github.com/jiasir/deis@v1.12.2/logger/publisher/publisher.go (about) 1 package publisher 2 3 import ( 4 "fmt" 5 "log" 6 "strconv" 7 "time" 8 9 "github.com/coreos/go-etcd/etcd" 10 ) 11 12 // Publisher takes responsibility for regularly updating etcd with the host and port where this 13 // logger component is running. This permits other components to discover it. 14 type Publisher struct { 15 etcdClient *etcd.Client 16 etcdPath string 17 publishTTL uint64 18 logHost string 19 logPort int 20 ticker *time.Ticker 21 running bool 22 } 23 24 // NewPublisher returns a pointer to a new Publisher instance. 25 func NewPublisher(etcdHost string, etcdPort int, etcdPath string, publishInterval int, 26 publishTTL int, logHost string, logPort int) (*Publisher, error) { 27 etcdClient := etcd.NewClient([]string{fmt.Sprintf("http://%s:%d", etcdHost, etcdPort)}) 28 ticker := time.NewTicker(time.Duration(publishInterval) * time.Second) 29 return &Publisher{ 30 etcdClient: etcdClient, 31 etcdPath: etcdPath, 32 publishTTL: uint64(time.Duration(publishTTL) * time.Second), 33 logHost: logHost, 34 logPort: logPort, 35 ticker: ticker, 36 }, nil 37 } 38 39 // Start begins the publisher's main loop. 40 func (p *Publisher) Start() { 41 // Should only ever be called once 42 if !p.running { 43 p.running = true 44 go p.publish() 45 log.Println("publisher running") 46 } 47 } 48 49 func (p *Publisher) publish() { 50 for { 51 <-p.ticker.C 52 p.setEtcd("/host", p.logHost) 53 p.setEtcd("/port", strconv.Itoa(p.logPort)) 54 } 55 } 56 57 func (p *Publisher) setEtcd(key string, value string) { 58 _, err := p.etcdClient.Set(fmt.Sprintf("%s%s", p.etcdPath, key), value, p.publishTTL) 59 if err != nil { 60 etcdErr, ok := err.(*etcd.EtcdError) 61 // Error code 105 is key already exists 62 if !ok || etcdErr.ErrorCode != 105 { 63 log.Println(err) 64 } 65 } 66 }