github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/api/firewaller/unit.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package firewaller 5 6 import ( 7 "github.com/juju/errors" 8 "gopkg.in/juju/names.v2" 9 10 "github.com/juju/juju/apiserver/params" 11 ) 12 13 // Unit represents a juju unit as seen by a firewaller worker. 14 type Unit struct { 15 st *State 16 tag names.UnitTag 17 life params.Life 18 } 19 20 // Name returns the name of the unit. 21 func (u *Unit) Name() string { 22 return u.tag.Id() 23 } 24 25 // Tag returns the unit tag. 26 func (u *Unit) Tag() names.UnitTag { 27 return u.tag 28 } 29 30 // Life returns the unit's life cycle value. 31 func (u *Unit) Life() params.Life { 32 return u.life 33 } 34 35 // Refresh updates the cached local copy of the unit's data. 36 func (u *Unit) Refresh() error { 37 life, err := u.st.life(u.tag) 38 if err != nil { 39 return err 40 } 41 u.life = life 42 return nil 43 } 44 45 // Application returns the application. 46 func (u *Unit) Application() (*Application, error) { 47 serviceName, err := names.UnitApplication(u.Name()) 48 if err != nil { 49 return nil, err 50 } 51 applicationTag := names.NewApplicationTag(serviceName) 52 service := &Application{ 53 st: u.st, 54 tag: applicationTag, 55 } 56 // Call Refresh() immediately to get the up-to-date 57 // life and other needed locally cached fields. 58 if err := service.Refresh(); err != nil { 59 return nil, err 60 } 61 return service, nil 62 } 63 64 // AssignedMachine returns the tag of this unit's assigned machine (if 65 // any), or a CodeNotAssigned error. 66 func (u *Unit) AssignedMachine() (names.MachineTag, error) { 67 var results params.StringResults 68 args := params.Entities{ 69 Entities: []params.Entity{{Tag: u.tag.String()}}, 70 } 71 emptyTag := names.NewMachineTag("") 72 err := u.st.facade.FacadeCall("GetAssignedMachine", args, &results) 73 if err != nil { 74 return emptyTag, err 75 } 76 if len(results.Results) != 1 { 77 return emptyTag, errors.Errorf("expected 1 result, got %d", len(results.Results)) 78 } 79 result := results.Results[0] 80 if result.Error != nil { 81 return emptyTag, result.Error 82 } 83 return names.ParseMachineTag(result.Result) 84 }