peer_status.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "go.etcd.io/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. local types.ID
  30. id types.ID
  31. mu sync.Mutex // protect variables below
  32. active bool
  33. since time.Time
  34. }
  35. func newPeerStatus(lg *zap.Logger, local, id types.ID) *peerStatus {
  36. return &peerStatus{lg: lg, local: local, id: id}
  37. }
  38. func (s *peerStatus) activate() {
  39. s.mu.Lock()
  40. defer s.mu.Unlock()
  41. if !s.active {
  42. if s.lg != nil {
  43. s.lg.Info("peer became active", zap.String("peer-id", s.id.String()))
  44. } else {
  45. plog.Infof("peer %s became active", s.id)
  46. }
  47. s.active = true
  48. s.since = time.Now()
  49. activePeers.WithLabelValues(s.local.String(), s.id.String()).Inc()
  50. }
  51. }
  52. func (s *peerStatus) deactivate(failure failureType, reason string) {
  53. s.mu.Lock()
  54. defer s.mu.Unlock()
  55. msg := fmt.Sprintf("failed to %s %s on %s (%s)", failure.action, s.id, failure.source, reason)
  56. if s.active {
  57. if s.lg != nil {
  58. s.lg.Warn("peer became inactive (message send to peer failed)", zap.String("peer-id", s.id.String()), zap.Error(errors.New(msg)))
  59. } else {
  60. plog.Errorf(msg)
  61. plog.Infof("peer %s became inactive (message send to peer failed)", s.id)
  62. }
  63. s.active = false
  64. s.since = time.Time{}
  65. activePeers.WithLabelValues(s.local.String(), s.id.String()).Dec()
  66. disconnectedPeers.WithLabelValues(s.local.String(), s.id.String()).Inc()
  67. return
  68. }
  69. if s.lg != nil {
  70. s.lg.Debug("peer deactivated again", zap.String("peer-id", s.id.String()), zap.Error(errors.New(msg)))
  71. }
  72. }
  73. func (s *peerStatus) isActive() bool {
  74. s.mu.Lock()
  75. defer s.mu.Unlock()
  76. return s.active
  77. }
  78. func (s *peerStatus) activeSince() time.Time {
  79. s.mu.Lock()
  80. defer s.mu.Unlock()
  81. return s.since
  82. }