2018-06-04 16:40:04 +00:00
|
|
|
package element
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/hashicorp/memberlist"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultInterval = time.Second * 10
|
|
|
|
nodeReconcileTimeout = defaultInterval * 3
|
|
|
|
nodeUpdateTimeout = defaultInterval / 2
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrUnknownConnectionType = errors.New("unknown connection type")
|
|
|
|
)
|
|
|
|
|
|
|
|
// Agent represents the node agent
|
|
|
|
type Agent struct {
|
|
|
|
config *Config
|
|
|
|
members *memberlist.Memberlist
|
|
|
|
peerUpdateChan chan bool
|
|
|
|
nodeEventChan chan *NodeEvent
|
|
|
|
registeredServices map[string]struct{}
|
2018-07-06 22:07:00 +00:00
|
|
|
memberConfig *memberlist.Config
|
2018-06-04 16:40:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewAgent returns a new node agent
|
|
|
|
func NewAgent(cfg *Config) (*Agent, error) {
|
|
|
|
updateCh := make(chan bool)
|
|
|
|
nodeEventCh := make(chan *NodeEvent)
|
2018-09-14 12:25:35 +00:00
|
|
|
mc, err := cfg.memberListConfig(updateCh, nodeEventCh)
|
2018-06-04 16:40:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ml, err := memberlist.Create(mc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Agent{
|
|
|
|
config: cfg,
|
|
|
|
members: ml,
|
|
|
|
peerUpdateChan: updateCh,
|
|
|
|
nodeEventChan: nodeEventCh,
|
2018-07-06 22:07:00 +00:00
|
|
|
memberConfig: mc,
|
2018-06-04 16:40:04 +00:00
|
|
|
}, nil
|
|
|
|
}
|
2018-06-09 17:28:25 +00:00
|
|
|
|
2018-07-06 22:07:00 +00:00
|
|
|
// SyncInterval returns the cluster sync interval
|
|
|
|
func (a *Agent) SyncInterval() time.Duration {
|
|
|
|
return a.memberConfig.PushPullInterval
|
|
|
|
}
|
|
|
|
|
2018-06-09 17:28:25 +00:00
|
|
|
// Subscribe subscribes to the node event channel
|
|
|
|
func (a *Agent) Subscribe(ch chan *NodeEvent) {
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case evt := <-a.nodeEventChan:
|
|
|
|
ch <- evt
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|