github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/facades/client/sshclient/shim.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package sshclient
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/names.v2"
     9  
    10  	"github.com/juju/juju/environs"
    11  	"github.com/juju/juju/environs/config"
    12  	"github.com/juju/juju/network"
    13  	"github.com/juju/juju/state"
    14  	"github.com/juju/juju/state/stateenvirons"
    15  )
    16  
    17  // Backend defines the State API used by the sshclient facade.
    18  type Backend interface {
    19  	ModelConfig() (*config.Config, error)
    20  	CloudSpec() (environs.CloudSpec, error)
    21  	GetMachineForEntity(tag string) (SSHMachine, error)
    22  	GetSSHHostKeys(names.MachineTag) (state.SSHHostKeys, error)
    23  	ModelTag() names.ModelTag
    24  }
    25  
    26  // SSHMachine specifies the methods on State.Machine of interest to
    27  // the SSHClient facade.
    28  type SSHMachine interface {
    29  	MachineTag() names.MachineTag
    30  	PublicAddress() (network.Address, error)
    31  	PrivateAddress() (network.Address, error)
    32  	Addresses() []network.Address
    33  	AllNetworkAddresses() ([]network.Address, error)
    34  }
    35  
    36  type backend struct {
    37  	stateenvirons.EnvironConfigGetter
    38  }
    39  
    40  // GetMachineForEntity takes a machine or unit tag (as a string) and
    41  // returns the associated SSHMachine.
    42  func (b *backend) GetMachineForEntity(tagString string) (SSHMachine, error) {
    43  	tag, err := names.ParseTag(tagString)
    44  	if err != nil {
    45  		return nil, errors.Trace(err)
    46  	}
    47  
    48  	switch tag := tag.(type) {
    49  	case names.MachineTag:
    50  		machine, err := b.State.Machine(tag.Id())
    51  		if err != nil {
    52  			return nil, errors.Trace(err)
    53  		}
    54  		return machine, nil
    55  	case names.UnitTag:
    56  		unit, err := b.State.Unit(tag.Id())
    57  		if err != nil {
    58  			return nil, errors.Trace(err)
    59  		}
    60  		machineId, err := unit.AssignedMachineId()
    61  		if err != nil {
    62  			return nil, errors.Trace(err)
    63  		}
    64  		machine, err := b.State.Machine(machineId)
    65  		if err != nil {
    66  			return nil, errors.Trace(err)
    67  		}
    68  		return machine, nil
    69  	default:
    70  		return nil, errors.Errorf("unsupported entity: %q", tagString)
    71  	}
    72  }