-
Notifications
You must be signed in to change notification settings - Fork 12
/
awareness.go
82 lines (69 loc) · 2.14 KB
/
awareness.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package swim
/*
* Copyright 2018 De-labtory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* https://github.com/hashicorp/memberlist
*
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed
* with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import (
"sync"
"time"
)
// Awareness manages health of the local node. This related to Lifeguard L1
// "self-awareness" concept. Expect to receive replies to probe messages we sent
// Start timeouts low, increase in response to absence of replies
type Awareness struct {
sync.RWMutex
// max is the upper threshold for the factor that increase the timeout value
// (the score will be constrained from 0 <= score < max)
max int
// score is the current awareness score. Lower values are healthier and
// zero is the minimum value
score int
}
func NewAwareness(max int) *Awareness {
return &Awareness{
max: max,
score: 0,
}
}
func (a *Awareness) GetHealthScore() int {
a.RLock()
defer a.RUnlock()
return a.score
}
// ApplyDelta with given delta applies it to the score in thread-safe manner
// score must be bound from 0 to max value
func (a *Awareness) ApplyDelta(delta int) {
a.RLock()
defer a.RUnlock()
a.score += delta
if a.score < 0 {
a.score = 0
} else if a.score > (a.max - 1) {
a.score = a.max - 1
}
}
// ScaleTimeout takes the given duration and scales it based on the current score.
// Less healthyness will lead to longer timeouts.
func (a *Awareness) ScaleTimeout(timeout time.Duration) time.Duration {
a.RLock()
defer a.RUnlock()
return timeout * (time.Duration(a.score) + 1)
}