-
Notifications
You must be signed in to change notification settings - Fork 38
/
managers.go
107 lines (87 loc) · 2.57 KB
/
managers.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package common
import (
"bytes"
"fmt"
"github.com/nspcc-dev/hrw"
apiNetmap "github.com/nspcc-dev/neofs-api-go/pkg/netmap"
netmapcore "github.com/nspcc-dev/neofs-node/pkg/core/netmap"
"github.com/nspcc-dev/neofs-node/pkg/services/reputation"
"github.com/nspcc-dev/neofs-node/pkg/util/logger"
"go.uber.org/zap"
)
// managerBuilder is implementation of reputation ManagerBuilder interface.
// It sorts nodes in NetMap with HRW algorithms and
// takes the next node after the current one as the only manager.
type managerBuilder struct {
log *logger.Logger
nmSrc netmapcore.Source
opts *mngOptions
}
// ManagersPrm groups the required parameters of the managerBuilder's constructor.
//
// All values must comply with the requirements imposed on them.
// Passing incorrect parameter values will result in constructor
// failure (error or panic depending on the implementation).
type ManagersPrm struct {
NetMapSource netmapcore.Source
}
// NewManagerBuilder creates a new instance of the managerBuilder.
//
// Panics if at least one value of the parameters is invalid.
//
// The created managerBuilder does not require additional
// initialization and is completely ready for work.
func NewManagerBuilder(prm ManagersPrm, opts ...MngOption) ManagerBuilder {
switch {
case prm.NetMapSource == nil:
panic(fmt.Sprintf("invalid NetMapSource (%T):%v", prm.NetMapSource, prm.NetMapSource))
}
o := defaultMngOpts()
for i := range opts {
opts[i](o)
}
return &managerBuilder{
log: o.log,
nmSrc: prm.NetMapSource,
opts: o,
}
}
// BuildManagers sorts nodes in NetMap with HRW algorithms and
// takes the next node after the current one as the only manager.
func (mb *managerBuilder) BuildManagers(epoch uint64, p reputation.PeerID) ([]ServerInfo, error) {
nm, err := mb.nmSrc.GetNetMapByEpoch(epoch)
if err != nil {
return nil, err
}
// make a copy to keep order consistency of the origin netmap after sorting
nodes := make([]*apiNetmap.Node, len(nm.Nodes))
copy(nodes, nm.Nodes)
hrw.SortSliceByValue(nodes, epoch)
for i := range nodes {
if bytes.Equal(nodes[i].PublicKey(), p.Bytes()) {
managerIndex := i + 1
if managerIndex == len(nodes) {
managerIndex = 0
}
return []ServerInfo{nodes[managerIndex]}, nil
}
}
return nil, nil
}
type mngOptions struct {
log *logger.Logger
}
type MngOption func(*mngOptions)
func defaultMngOpts() *mngOptions {
return &mngOptions{
log: zap.L(),
}
}
// WithLogger returns MngOption to specify logging component.
func WithLogger(l *logger.Logger) MngOption {
return func(o *mngOptions) {
if l != nil {
o.log = l
}
}
}