-
Notifications
You must be signed in to change notification settings - Fork 661
/
locked_calculator.go
87 lines (64 loc) · 1.92 KB
/
locked_calculator.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
83
84
85
86
87
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package uptime
import (
"errors"
"sync"
"time"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils"
)
var (
errNotReady = errors.New("should not be called")
_ LockedCalculator = &lockedCalculator{}
)
type LockedCalculator interface {
Calculator
SetCalculator(isBootstrapped *utils.AtomicBool, lock sync.Locker, newC Calculator)
}
type lockedCalculator struct {
lock sync.RWMutex
isBootstrapped *utils.AtomicBool
calculatorLock sync.Locker
c Calculator
}
func NewLockedCalculator() LockedCalculator {
return &lockedCalculator{}
}
func (c *lockedCalculator) CalculateUptime(nodeID ids.ShortID) (time.Duration, time.Time, error) {
c.lock.RLock()
defer c.lock.RUnlock()
if c.isBootstrapped == nil || !c.isBootstrapped.GetValue() {
return 0, time.Time{}, errNotReady
}
c.calculatorLock.Lock()
defer c.calculatorLock.Unlock()
return c.c.CalculateUptime(nodeID)
}
func (c *lockedCalculator) CalculateUptimePercent(nodeID ids.ShortID) (float64, error) {
c.lock.RLock()
defer c.lock.RUnlock()
if c.isBootstrapped == nil || !c.isBootstrapped.GetValue() {
return 0, errNotReady
}
c.calculatorLock.Lock()
defer c.calculatorLock.Unlock()
return c.c.CalculateUptimePercent(nodeID)
}
func (c *lockedCalculator) CalculateUptimePercentFrom(nodeID ids.ShortID, startTime time.Time) (float64, error) {
c.lock.RLock()
defer c.lock.RUnlock()
if c.isBootstrapped == nil || !c.isBootstrapped.GetValue() {
return 0, errNotReady
}
c.calculatorLock.Lock()
defer c.calculatorLock.Unlock()
return c.c.CalculateUptimePercentFrom(nodeID, startTime)
}
func (c *lockedCalculator) SetCalculator(isBootstrapped *utils.AtomicBool, lock sync.Locker, newC Calculator) {
c.lock.Lock()
defer c.lock.Unlock()
c.isBootstrapped = isBootstrapped
c.calculatorLock = lock
c.c = newC
}