2020-05-07 10:25:58 +02:00
|
|
|
package common
|
2020-05-06 19:05:04 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/gob"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2020-05-07 11:36:46 +02:00
|
|
|
// nodeMeta holds metadata sent over the cluster
|
|
|
|
type nodeMeta struct {
|
2020-05-06 19:05:04 +02:00
|
|
|
OverlayAddr net.IPNet
|
|
|
|
PubKey string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Node holds the memberlist node structure
|
2020-05-07 10:25:58 +02:00
|
|
|
type Node struct {
|
2020-05-06 19:05:04 +02:00
|
|
|
Name string
|
|
|
|
Addr net.IP
|
2020-05-06 19:27:21 +02:00
|
|
|
Meta []byte
|
2020-05-07 11:36:46 +02:00
|
|
|
nodeMeta
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|
|
|
|
|
2020-05-07 10:25:58 +02:00
|
|
|
func (n *Node) String() string {
|
2020-05-06 19:05:04 +02:00
|
|
|
return n.Addr.String()
|
|
|
|
}
|
|
|
|
|
2020-05-10 18:12:47 +02:00
|
|
|
// EncodeMeta the node metadata to bytes, in a deterministic reversible way
|
|
|
|
func (n *Node) EncodeMeta(limit int) ([]byte, error) {
|
2020-05-06 19:05:04 +02:00
|
|
|
buf := &bytes.Buffer{}
|
2020-05-07 11:36:46 +02:00
|
|
|
if err := gob.NewEncoder(buf).Encode(n.nodeMeta); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "could not encode local state")
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|
|
|
|
if buf.Len() > limit {
|
2020-05-07 11:36:46 +02:00
|
|
|
return nil, errors.Errorf("could not fit node metadata into %d bytes", limit)
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|
2020-05-07 11:36:46 +02:00
|
|
|
return buf.Bytes(), nil
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|
|
|
|
|
2020-05-10 18:12:47 +02:00
|
|
|
// DecodeMeta the node Meta field into its metadata
|
|
|
|
func (n *Node) DecodeMeta() error {
|
2020-05-06 19:05:04 +02:00
|
|
|
// TODO: we blindly trust the info we get from the peers; We should be more defensive to limit the damage a leaked
|
|
|
|
// PSK can cause.
|
2020-05-07 11:36:46 +02:00
|
|
|
nm := nodeMeta{}
|
|
|
|
if err := gob.NewDecoder(bytes.NewReader(n.Meta)).Decode(&nm); err != nil {
|
|
|
|
return errors.Wrap(err, "could not decode node meta")
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|
2020-05-07 11:36:46 +02:00
|
|
|
n.nodeMeta = nm
|
|
|
|
return nil
|
2020-05-06 19:05:04 +02:00
|
|
|
}
|