github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/instancepoller/worker.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package instancepoller 5 6 import ( 7 "launchpad.net/tomb" 8 9 "github.com/juju/juju/state" 10 "github.com/juju/juju/worker" 11 ) 12 13 type updaterWorker struct { 14 st *state.State 15 tomb tomb.Tomb 16 *aggregator 17 18 observer *worker.EnvironObserver 19 } 20 21 // NewWorker returns a worker that keeps track of 22 // the machines in the state and polls their instance 23 // addresses and status periodically to keep them up to date. 24 func NewWorker(st *state.State) worker.Worker { 25 u := &updaterWorker{ 26 st: st, 27 } 28 // wait for environment 29 go func() { 30 defer u.tomb.Done() 31 u.tomb.Kill(u.loop()) 32 }() 33 return u 34 } 35 36 func (u *updaterWorker) Kill() { 37 u.tomb.Kill(nil) 38 } 39 40 func (u *updaterWorker) Wait() error { 41 return u.tomb.Wait() 42 } 43 44 func (u *updaterWorker) loop() (err error) { 45 u.observer, err = worker.NewEnvironObserver(u.st) 46 if err != nil { 47 return err 48 } 49 u.aggregator = newAggregator(u.observer.Environ()) 50 logger.Infof("instance poller received inital environment configuration") 51 defer func() { 52 obsErr := worker.Stop(u.observer) 53 if err == nil { 54 err = obsErr 55 } 56 }() 57 return watchMachinesLoop(u, u.st.WatchEnvironMachines()) 58 } 59 60 func (u *updaterWorker) newMachineContext() machineContext { 61 return u 62 } 63 64 func (u *updaterWorker) getMachine(id string) (machine, error) { 65 return u.st.Machine(id) 66 } 67 68 func (u *updaterWorker) dying() <-chan struct{} { 69 return u.tomb.Dying() 70 } 71 72 func (u *updaterWorker) killAll(err error) { 73 u.tomb.Kill(err) 74 }