github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/jujud/agent/machine/servinginfo_setter.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package machine 5 6 import ( 7 "github.com/juju/errors" 8 "gopkg.in/juju/names.v2" 9 10 coreagent "github.com/juju/juju/agent" 11 apiagent "github.com/juju/juju/api/agent" 12 "github.com/juju/juju/api/base" 13 "github.com/juju/juju/worker" 14 "github.com/juju/juju/worker/dependency" 15 ) 16 17 // ServingInfoSetterConfig provides the dependencies for the 18 // servingInfoSetter manifold. 19 type ServingInfoSetterConfig struct { 20 AgentName string 21 APICallerName string 22 } 23 24 // ServingInfoSetterManifold defines a simple start function which 25 // runs after the API connection has come up. If the machine agent is 26 // a controller, it grabs the state serving info over the API and 27 // records it to agent configuration, and then stops. 28 func ServingInfoSetterManifold(config ServingInfoSetterConfig) dependency.Manifold { 29 return dependency.Manifold{ 30 Inputs: []string{ 31 config.AgentName, 32 config.APICallerName, 33 }, 34 Start: func(context dependency.Context) (worker.Worker, error) { 35 // Get the agent. 36 var agent coreagent.Agent 37 if err := context.Get(config.AgentName, &agent); err != nil { 38 return nil, err 39 } 40 41 // Grab the tag and ensure that it's for a machine. 42 tag, ok := agent.CurrentConfig().Tag().(names.MachineTag) 43 if !ok { 44 return nil, errors.New("agent's tag is not a machine tag") 45 } 46 47 // Get API connection. 48 var apiCaller base.APICaller 49 if err := context.Get(config.APICallerName, &apiCaller); err != nil { 50 return nil, err 51 } 52 apiState := apiagent.NewState(apiCaller) 53 54 // If the machine needs State, grab the state serving info 55 // over the API and write it to the agent configuration. 56 machine, err := apiState.Entity(tag) 57 if err != nil { 58 return nil, err 59 } 60 existing, hasInfo := agent.CurrentConfig().StateServingInfo() 61 for _, job := range machine.Jobs() { 62 if job.NeedsState() { 63 info, err := apiState.StateServingInfo() 64 if err != nil { 65 return nil, errors.Errorf("cannot get state serving info: %v", err) 66 } 67 if hasInfo { 68 // Use the existing Cert as it may have been updated already 69 // by the cert updater worker to have this machine's IP address 70 // as part of the cert. This changed cert is never put back into 71 // the database, so it isn't reflected in the copy we have got 72 // from apiState. 73 info.Cert = existing.Cert 74 } 75 err = agent.ChangeConfig(func(config coreagent.ConfigSetter) error { 76 config.SetStateServingInfo(info) 77 return nil 78 }) 79 if err != nil { 80 return nil, err 81 } 82 } 83 } 84 85 // All is well - we're done (no actual worker is actually returned). 86 return nil, dependency.ErrUninstall 87 }, 88 } 89 }