peer_status.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package rafthttp
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/pkg/types"
  20. )
  21. type failureType struct {
  22. source string
  23. action string
  24. }
  25. type peerStatus struct {
  26. id types.ID
  27. mu sync.Mutex // protect variables below
  28. active bool
  29. failureMap map[failureType]string
  30. activeSince time.Time
  31. }
  32. func newPeerStatus(id types.ID) *peerStatus {
  33. return &peerStatus{
  34. id: id,
  35. failureMap: make(map[failureType]string),
  36. }
  37. }
  38. func (s *peerStatus) activate() {
  39. s.mu.Lock()
  40. defer s.mu.Unlock()
  41. if !s.active {
  42. plog.Infof("the connection with %s became active", s.id)
  43. s.active = true
  44. s.activeSince = time.Now()
  45. s.failureMap = make(map[failureType]string)
  46. }
  47. }
  48. func (s *peerStatus) deactivate(failure failureType, reason string) {
  49. s.mu.Lock()
  50. defer s.mu.Unlock()
  51. if s.active {
  52. plog.Infof("the connection with %s became inactive", s.id)
  53. s.active = false
  54. s.activeSince = time.Time{}
  55. }
  56. logline := fmt.Sprintf("failed to %s %s on %s (%s)", failure.action, s.id, failure.source, reason)
  57. if r, ok := s.failureMap[failure]; ok && r == reason {
  58. plog.Debugf(logline)
  59. return
  60. }
  61. s.failureMap[failure] = reason
  62. plog.Errorf(logline)
  63. }
  64. func (s *peerStatus) isActive() bool {
  65. s.mu.Lock()
  66. defer s.mu.Unlock()
  67. return s.active
  68. }