peer_status.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 The etcd Authors
  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. since time.Time
  30. }
  31. func newPeerStatus(id types.ID) *peerStatus {
  32. return &peerStatus{
  33. id: id,
  34. }
  35. }
  36. func (s *peerStatus) activate() {
  37. s.mu.Lock()
  38. defer s.mu.Unlock()
  39. if !s.active {
  40. plog.Infof("peer %s became active", s.id)
  41. s.active = true
  42. s.since = time.Now()
  43. }
  44. }
  45. func (s *peerStatus) deactivate(failure failureType, reason string) {
  46. s.mu.Lock()
  47. defer s.mu.Unlock()
  48. msg := fmt.Sprintf("failed to %s %s on %s (%s)", failure.action, s.id, failure.source, reason)
  49. if s.active {
  50. plog.Errorf(msg)
  51. plog.Infof("peer %s became inactive", s.id)
  52. s.active = false
  53. s.since = time.Time{}
  54. return
  55. }
  56. plog.Debugf(msg)
  57. }
  58. func (s *peerStatus) isActive() bool {
  59. s.mu.Lock()
  60. defer s.mu.Unlock()
  61. return s.active
  62. }
  63. func (s *peerStatus) activeSince() time.Time {
  64. s.mu.Lock()
  65. defer s.mu.Unlock()
  66. return s.since
  67. }