github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/clusterproviders/etcd/node.go (about) 1 package etcd 2 3 import ( 4 "encoding/json" 5 6 "github.com/asynkron/protoactor-go/cluster" 7 ) 8 9 type Node struct { 10 ID string `json:"id"` 11 Name string `json:"name"` 12 Host string `json:"host"` 13 Address string `json:"address"` 14 Port int `json:"port"` 15 Kinds []string `json:"kinds"` 16 Meta map[string]string `json:"-"` 17 Alive bool `json:"alive"` 18 } 19 20 func NewNode(name, host string, port int, kinds []string) *Node { 21 return &Node{ 22 ID: name, 23 Name: name, 24 Address: host, 25 Host: host, 26 Port: port, 27 Kinds: kinds, 28 Meta: map[string]string{}, 29 Alive: true, 30 } 31 } 32 33 func NewNodeFromBytes(data []byte) (*Node, error) { 34 n := Node{} 35 if err := json.Unmarshal(data, &n); err != nil { 36 return nil, err 37 } 38 return &n, nil 39 } 40 41 func (n *Node) GetAddress() (host string, port int) { 42 host = n.Host 43 port = n.Port 44 if host == "" { 45 host = n.Address 46 } 47 return 48 } 49 50 func (n *Node) Equal(other *Node) bool { 51 if n == nil || other == nil { 52 return false 53 } 54 if n == other { 55 return true 56 } 57 return n.ID == other.ID 58 } 59 60 func (n *Node) GetMeta(name string) (string, bool) { 61 if n.Meta == nil { 62 return "", false 63 } 64 val, ok := n.Meta[name] 65 return val, ok 66 } 67 68 func (n *Node) MemberStatus() *cluster.Member { 69 host, port := n.GetAddress() 70 kinds := n.Kinds 71 if kinds == nil { 72 kinds = []string{} 73 } 74 return &cluster.Member{ 75 Id: n.ID, 76 Host: host, 77 Port: int32(port), 78 Kinds: kinds, 79 } 80 } 81 82 func (n *Node) SetMeta(name string, val string) { 83 if n.Meta == nil { 84 n.Meta = map[string]string{} 85 } 86 n.Meta[name] = val 87 } 88 89 func (n *Node) Serialize() ([]byte, error) { 90 data, err := json.Marshal(n) 91 if err != nil { 92 return nil, err 93 } 94 return data, nil 95 } 96 97 func (n *Node) Deserialize(data []byte) error { 98 return json.Unmarshal(data, n) 99 } 100 101 func (n *Node) IsAlive() bool { 102 return n.Alive 103 } 104 105 func (n *Node) SetAlive(alive bool) { 106 n.Alive = alive 107 }