/
nodeinfo.go
103 lines (87 loc) · 2.21 KB
/
nodeinfo.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
package swarm
import (
"fmt"
"net"
"strconv"
log "github.com/sirupsen/logrus"
)
// Self can return itself as NodeInfo
type Self interface {
Node() *NodeInfo
}
// EntryPoint knows its peers of nodes which contains itself
type EntryPoint interface {
Nodes() []*NodeInfo
}
// NodeInfo is a value object tat contains information about swarm
// cluster nodes, that is required to access member nodes.
type NodeInfo struct {
Name string
Addr net.IP
Port uint16
}
func NewStaticNodeInfo(name, addr string) (*NodeInfo, error) {
ipString, portString, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ip := net.ParseIP(ipString)
portInt, err := strconv.Atoi(portString)
if err != nil {
return nil, fmt.Errorf("invalid port in addr '%s': %v", portString, err)
}
return &NodeInfo{
Name: name,
Addr: ip,
Port: uint16(portInt),
}, nil
}
// NewFakeNodeInfo used to create a FakeSwarm
func NewFakeNodeInfo(name string, addr net.IP, port uint16) *NodeInfo {
return &NodeInfo{
Name: name,
Addr: addr,
Port: port,
}
}
// String will only show initial peers when created this peer
func (ni NodeInfo) String() string {
return fmt.Sprintf("NodeInfo{name: %s, %s:%d}", ni.Name, ni.Addr, ni.Port)
}
// initial peers when created this peer, only nic is up to date
type knownEntryPoint struct {
self *NodeInfo
nodes []*NodeInfo
nic nodeInfoClient
}
// newKnownEntryPoint returns a new knownEntryPoint that knows all
// initial peers and itself. If it can not get a list of peers it will
// fail fast.
func newKnownEntryPoint(o Options) (*knownEntryPoint, func()) {
nic, cleanupF := NewNodeInfoClient(o)
nodes, err := nic.GetNodeInfo()
if err != nil {
log.Fatalf("SWARM: Failed to get nodeinfo: %v", err)
}
self := nic.Self()
return &knownEntryPoint{self: self, nodes: nodes, nic: nic}, cleanupF
}
// Node return its self
func (e *knownEntryPoint) Node() *NodeInfo {
if e.nic == nil {
return e.self
}
return e.nic.Self()
}
// Nodes return the list of known peers including self
func (e *knownEntryPoint) Nodes() []*NodeInfo {
if e.nic == nil {
return e.nodes
}
nodes, err := e.nic.GetNodeInfo()
if err != nil {
log.Errorf("Failed to get nodeinfo: %v", err)
return nil
}
return nodes
}