launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/state/api/agent/state.go (about) 1 // Copyright 2012, 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package agent 5 6 import ( 7 "launchpad.net/errgo/errors" 8 "launchpad.net/juju-core/instance" 9 "launchpad.net/juju-core/state/api/base" 10 "launchpad.net/juju-core/state/api/params" 11 ) 12 13 // State provides access to an agent's view of the state. 14 type State struct { 15 caller base.Caller 16 } 17 18 // NewState returns a version of the state that provides functionality 19 // required by agent code. 20 func NewState(caller base.Caller) *State { 21 return &State{caller} 22 } 23 24 func (st *State) getEntity(tag string) (*params.AgentGetEntitiesResult, error) { 25 var results params.AgentGetEntitiesResults 26 args := params.Entities{ 27 Entities: []params.Entity{{Tag: tag}}, 28 } 29 err := st.caller.Call("Agent", "", "GetEntities", args, &results) 30 if err != nil { 31 return nil, base.WrapError(err) 32 } 33 if len(results.Entities) != 1 { 34 return nil, errors.Newf("expected one result, got %d", len(results.Entities)) 35 } 36 if err := results.Entities[0].Error; err != nil { 37 return nil, base.WrapError(err) 38 } 39 return &results.Entities[0], nil 40 } 41 42 type Entity struct { 43 st *State 44 tag string 45 doc params.AgentGetEntitiesResult 46 } 47 48 func (st *State) Entity(tag string) (*Entity, error) { 49 doc, err := st.getEntity(tag) 50 if err != nil { 51 return nil, base.WrapError(err) 52 } 53 return &Entity{ 54 st: st, 55 tag: tag, 56 doc: *doc, 57 }, nil 58 } 59 60 // Tag returns the entity's tag. 61 func (m *Entity) Tag() string { 62 return m.tag 63 } 64 65 // Life returns the current life cycle state of the entity. 66 func (m *Entity) Life() params.Life { 67 return m.doc.Life 68 } 69 70 // Jobs returns the set of configured jobs 71 // if the API is running on behalf of a machine agent. 72 // When running for other agents, it will return 73 // the empty list. 74 func (m *Entity) Jobs() []params.MachineJob { 75 return m.doc.Jobs 76 } 77 78 // ContainerType returns the type of container hosting this entity. 79 // If the entity is not a machine, it returns an empty string. 80 func (m *Entity) ContainerType() instance.ContainerType { 81 return m.doc.ContainerType 82 } 83 84 // SetPassword sets the password associated with the agent's entity. 85 func (m *Entity) SetPassword(password string) error { 86 var results params.ErrorResults 87 args := params.PasswordChanges{ 88 Changes: []params.PasswordChange{{ 89 Tag: m.tag, 90 Password: password, 91 }}, 92 } 93 err := m.st.caller.Call("Agent", "", "SetPasswords", args, &results) 94 if err != nil { 95 return base.WrapError(err) 96 } 97 return results.OneError() 98 }