github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/apiserver/machine/machiner.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 // The machiner package implements the API interface 5 // used by the machiner worker. 6 package machine 7 8 import ( 9 "github.com/juju/errors" 10 "github.com/juju/names" 11 12 "github.com/juju/juju/apiserver/common" 13 "github.com/juju/juju/apiserver/params" 14 "github.com/juju/juju/state" 15 ) 16 17 func init() { 18 common.RegisterStandardFacade("Machiner", 0, NewMachinerAPI) 19 } 20 21 // MachinerAPI implements the API used by the machiner worker. 22 type MachinerAPI struct { 23 *common.LifeGetter 24 *common.StatusSetter 25 *common.DeadEnsurer 26 *common.AgentEntityWatcher 27 *common.APIAddresser 28 29 st *state.State 30 auth common.Authorizer 31 getCanModify common.GetAuthFunc 32 getCanRead common.GetAuthFunc 33 } 34 35 // NewMachinerAPI creates a new instance of the Machiner API. 36 func NewMachinerAPI(st *state.State, resources *common.Resources, authorizer common.Authorizer) (*MachinerAPI, error) { 37 if !authorizer.AuthMachineAgent() { 38 return nil, common.ErrPerm 39 } 40 getCanModify := func() (common.AuthFunc, error) { 41 return authorizer.AuthOwner, nil 42 } 43 getCanRead := func() (common.AuthFunc, error) { 44 return authorizer.AuthOwner, nil 45 } 46 return &MachinerAPI{ 47 LifeGetter: common.NewLifeGetter(st, getCanRead), 48 StatusSetter: common.NewStatusSetter(st, getCanModify), 49 DeadEnsurer: common.NewDeadEnsurer(st, getCanModify), 50 AgentEntityWatcher: common.NewAgentEntityWatcher(st, resources, getCanRead), 51 APIAddresser: common.NewAPIAddresser(st, resources), 52 st: st, 53 auth: authorizer, 54 getCanModify: getCanModify, 55 }, nil 56 } 57 58 func (api *MachinerAPI) getMachine(tag names.Tag) (*state.Machine, error) { 59 entity, err := api.st.FindEntity(tag) 60 if err != nil { 61 return nil, err 62 } 63 return entity.(*state.Machine), nil 64 } 65 66 func (api *MachinerAPI) SetMachineAddresses(args params.SetMachinesAddresses) (params.ErrorResults, error) { 67 results := params.ErrorResults{ 68 Results: make([]params.ErrorResult, len(args.MachineAddresses)), 69 } 70 canModify, err := api.getCanModify() 71 if err != nil { 72 return results, err 73 } 74 for i, arg := range args.MachineAddresses { 75 tag, err := names.ParseMachineTag(arg.Tag) 76 if err != nil { 77 results.Results[i].Error = common.ServerError(common.ErrPerm) 78 continue 79 } 80 err = common.ErrPerm 81 if canModify(tag) { 82 var m *state.Machine 83 m, err = api.getMachine(tag) 84 if err == nil { 85 err = m.SetMachineAddresses(arg.Addresses...) 86 } else if errors.IsNotFound(err) { 87 err = common.ErrPerm 88 } 89 } 90 results.Results[i].Error = common.ServerError(err) 91 } 92 return results, nil 93 }