peer_status.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. "errors"
  17. "fmt"
  18. "sync"
  19. "time"
  20. "github.com/coreos/etcd/pkg/types"
  21. "go.uber.org/zap"
  22. )
  23. type failureType struct {
  24. source string
  25. action string
  26. }
  27. type peerStatus struct {
  28. lg *zap.Logger
  29. id types.ID
  30. mu sync.Mutex // protect variables below
  31. active bool
  32. since time.Time
  33. }
  34. func newPeerStatus(lg *zap.Logger, id types.ID) *peerStatus {
  35. return &peerStatus{lg: lg, id: id}
  36. }
  37. func (s *peerStatus) activate() {
  38. s.mu.Lock()
  39. defer s.mu.Unlock()
  40. if !s.active {
  41. if s.lg != nil {
  42. s.lg.Info("peer became active", zap.String("peer-id", s.id.String()))
  43. } else {
  44. plog.Infof("peer %s became active", s.id)
  45. }
  46. s.active = true
  47. s.since = time.Now()
  48. }
  49. }
  50. func (s *peerStatus) deactivate(failure failureType, reason string) {
  51. s.mu.Lock()
  52. defer s.mu.Unlock()
  53. msg := fmt.Sprintf("failed to %s %s on %s (%s)", failure.action, s.id, failure.source, reason)
  54. if s.active {
  55. if s.lg != nil {
  56. s.lg.Warn("peer became inactive", zap.String("peer-id", s.id.String()), zap.Error(errors.New(msg)))
  57. } else {
  58. plog.Errorf(msg)
  59. plog.Infof("peer %s became inactive", s.id)
  60. }
  61. s.active = false
  62. s.since = time.Time{}
  63. return
  64. }
  65. if s.lg != nil {
  66. s.lg.Debug("peer deactivated again", zap.String("peer-id", s.id.String()), zap.Error(errors.New(msg)))
  67. }
  68. }
  69. func (s *peerStatus) isActive() bool {
  70. s.mu.Lock()
  71. defer s.mu.Unlock()
  72. return s.active
  73. }
  74. func (s *peerStatus) activeSince() time.Time {
  75. s.mu.Lock()
  76. defer s.mu.Unlock()
  77. return s.since
  78. }