github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/state/apiserver/agent/agent.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 // The machine package implements the API interfaces 5 // used by the machine agent. 6 package agent 7 8 import ( 9 "launchpad.net/juju-core/state" 10 "launchpad.net/juju-core/state/api/params" 11 "launchpad.net/juju-core/state/apiserver/common" 12 ) 13 14 // API implements the API provided to an agent. 15 type API struct { 16 *common.PasswordChanger 17 18 st *state.State 19 auth common.Authorizer 20 } 21 22 // NewAPI returns an object implementing an agent API 23 // with the given authorizer representing the currently logged in client. 24 func NewAPI(st *state.State, auth common.Authorizer) (*API, error) { 25 // Agents are defined to be any user that's not a client user. 26 if !auth.AuthMachineAgent() && !auth.AuthUnitAgent() { 27 return nil, common.ErrPerm 28 } 29 getCanChange := func() (common.AuthFunc, error) { 30 return auth.AuthOwner, nil 31 } 32 return &API{ 33 PasswordChanger: common.NewPasswordChanger(st, getCanChange), 34 st: st, 35 auth: auth, 36 }, nil 37 } 38 39 func (api *API) GetEntities(args params.Entities) params.AgentGetEntitiesResults { 40 results := params.AgentGetEntitiesResults{ 41 Entities: make([]params.AgentGetEntitiesResult, len(args.Entities)), 42 } 43 for i, entity := range args.Entities { 44 result, err := api.getEntity(entity.Tag) 45 result.Error = common.ServerError(err) 46 results.Entities[i] = result 47 } 48 return results 49 } 50 51 func (api *API) getEntity(tag string) (result params.AgentGetEntitiesResult, err error) { 52 // Allow only for the owner agent. 53 // Note: having a bulk API call for this is utter madness, given that 54 // this check means we can only ever return a single object. 55 if !api.auth.AuthOwner(tag) { 56 err = common.ErrPerm 57 return 58 } 59 entity0, err := api.st.FindEntity(tag) 60 if err != nil { 61 return 62 } 63 entity, ok := entity0.(state.Lifer) 64 if !ok { 65 err = common.NotSupportedError(tag, "life cycles") 66 return 67 } 68 result.Life = params.Life(entity.Life().String()) 69 if machine, ok := entity.(*state.Machine); ok { 70 result.Jobs = stateJobsToAPIParamsJobs(machine.Jobs()) 71 result.ContainerType = machine.ContainerType() 72 } 73 return 74 } 75 76 func stateJobsToAPIParamsJobs(jobs []state.MachineJob) []params.MachineJob { 77 pjobs := make([]params.MachineJob, len(jobs)) 78 for i, job := range jobs { 79 pjobs[i] = params.MachineJob(job.String()) 80 } 81 return pjobs 82 }