github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/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   *Client
    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  	appName, err := names.UnitApplication(u.Name())
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	applicationTag := names.NewApplicationTag(appName)
    52  	app := &Application{
    53  		st:  u.st,
    54  		tag: applicationTag,
    55  	}
    56  	return app, nil
    57  }
    58  
    59  // AssignedMachine returns the tag of this unit's assigned machine (if
    60  // any), or a CodeNotAssigned error.
    61  func (u *Unit) AssignedMachine() (names.MachineTag, error) {
    62  	var results params.StringResults
    63  	args := params.Entities{
    64  		Entities: []params.Entity{{Tag: u.tag.String()}},
    65  	}
    66  	emptyTag := names.NewMachineTag("")
    67  	err := u.st.facade.FacadeCall("GetAssignedMachine", args, &results)
    68  	if err != nil {
    69  		return emptyTag, err
    70  	}
    71  	if len(results.Results) != 1 {
    72  		return emptyTag, errors.Errorf("expected 1 result, got %d", len(results.Results))
    73  	}
    74  	result := results.Results[0]
    75  	if result.Error != nil {
    76  		return emptyTag, result.Error
    77  	}
    78  	return names.ParseMachineTag(result.Result)
    79  }