juju: github.com/juju/juju/provider/common Index | Files | Directories

package common

import "github.com/juju/juju/provider/common"

Index

Package Files

availabilityzones.go bootstrap.go destroy.go disk.go errors.go instance_configurator.go polling.go provider.go state.go util.go

Constants

const StateFile = "provider-state"

StateFile is the name of the file where the provider's state is stored.

Variables

var AuthorisationFailureStatusCodes = set.NewInts(
    http.StatusUnauthorized,
    http.StatusPaymentRequired,
    http.StatusForbidden,
    http.StatusProxyAuthRequired,
)

AuthorisationFailureStatusCodes contains http status code that signify authorisation difficulties.

var FinishBootstrap = func(
    ctx environs.BootstrapContext,
    client ssh.Client,
    env environs.Environ,
    callCtx context.ProviderCallContext,
    inst instances.Instance,
    instanceConfig *instancecfg.InstanceConfig,
    opts environs.BootstrapDialOpts,
) error {
    interrupted := make(chan os.Signal, 1)
    ctx.InterruptNotify(interrupted)
    defer ctx.StopInterruptNotify(interrupted)

    hostSSHOptions := bootstrapSSHOptionsFunc(instanceConfig)
    addr, err := WaitSSH(
        ctx.GetStderr(),
        interrupted,
        client,
        GetCheckNonceCommand(instanceConfig),
        &RefreshableInstance{inst, env},
        callCtx,
        opts,
        hostSSHOptions,
    )
    if err != nil {
        return err
    }
    ctx.Infof("Connected to %v", addr)

    sshOptions, cleanup, err := hostSSHOptions(addr)
    if err != nil {
        return err
    }
    defer cleanup()

    return ConfigureMachine(ctx, client, addr, instanceConfig, sshOptions)
}

FinishBootstrap completes the bootstrap process by connecting to the instance via SSH and carrying out the cloud-config.

Note: FinishBootstrap is exposed so it can be replaced for testing.

var LongAttempt = utils.AttemptStrategy{
    Total: 3 * time.Minute,
    Delay: 1 * time.Second,
}

A request may fail to due "eventual consistency" semantics, which should resolve fairly quickly. These delays are specific to the provider and best tuned there. Other requests fail due to a slow state transition (e.g. an instance taking a while to release a security group after termination). If you need to poll for the latter kind, use LongAttempt.

TODO(katco): 2016-08-09: lp:1611427

var ShortAttempt = utils.AttemptStrategy{
    Total: 5 * time.Second,
    Delay: 200 * time.Millisecond,
}

Use ShortAttempt to poll for short-term events. TODO: This may need tuning for different providers (or even environments).

TODO(katco): 2016-08-09: lp:1611427

func AddStateInstance Uses

func AddStateInstance(stor storage.Storage, id instance.Id) error

AddStateInstance adds a controller instance ID to the provider-state file in storage.

func Bootstrap Uses

func Bootstrap(
    ctx environs.BootstrapContext,
    env environs.Environ,
    callCtx context.ProviderCallContext,
    args environs.BootstrapParams,
) (*environs.BootstrapResult, error)

Bootstrap is a common implementation of the Bootstrap method defined on environs.Environ; we strongly recommend that this implementation be used when writing a new provider.

func BootstrapInstance Uses

func BootstrapInstance(
    ctx environs.BootstrapContext,
    env environs.Environ,
    callCtx context.ProviderCallContext,
    args environs.BootstrapParams,
) (_ *environs.StartInstanceResult, selectedSeries string, _ environs.CloudBootstrapFinalizer, err error)

BootstrapInstance creates a new instance with the series of its choice, constrained to those of the available tools, and returns the instance result, series, and a function that must be called to finalize the bootstrap process by transferring the tools and installing the initial Juju controller. This method is called by Bootstrap above, which implements environs.Bootstrap, but is also exported so that providers can manipulate the started instance.

func ConfigureExternalIpAddressCommands Uses

func ConfigureExternalIpAddressCommands(apiPort int) []string

ConfigureExternalIpAddressCommands returns the commands to run to configure the external IP address

func ConfigureMachine Uses

func ConfigureMachine(
    ctx environs.BootstrapContext,
    client ssh.Client,
    host string,
    instanceConfig *instancecfg.InstanceConfig,
    sshOptions *ssh.Options,
) error

func CreateStateFile Uses

func CreateStateFile(stor storage.Storage) (string, error)

CreateStateFile creates an empty state file on the given storage, and returns its URL.

func CredentialNotValid Uses

func CredentialNotValid(err error) error

CredentialNotValid returns an error which wraps err and satisfies IsCredentialNotValid().

func CredentialNotValidf Uses

func CredentialNotValidf(err error, message string) error

CredentialNotValidf returns a wrapped error with given message and satisfies IsCredentialNotValid().

func DefaultHostSSHOptions Uses

func DefaultHostSSHOptions(host string) (*ssh.Options, func(), error)

DefaultHostSSHOptions returns a a nil *ssh.Options, which means to use the defaults; and a no-op cleanup function.

func DeleteStateFile Uses

func DeleteStateFile(stor storage.Storage) error

DeleteStateFile deletes the state file on the given storage.

func Destroy Uses

func Destroy(env environs.Environ, ctx context.ProviderCallContext) error

Destroy is a common implementation of the Destroy method defined on environs.Environ; we strongly recommend that this implementation be used when writing a new provider.

func DistributeInstances Uses

func DistributeInstances(
    env ZonedEnviron, ctx context.ProviderCallContext, candidates, group []instance.Id, limitZones []string,
) ([]instance.Id, error)

DistributeInstances is a common function for implement the state.InstanceDistributor policy based on availability zone spread. TODO (manadart 2018-11-27) This method signature has grown to the point where the argument list should be replaced with a struct. At that time limitZones could be transformed to a map so that lookups in the filtering below are more efficient.

func EnvFullName Uses

func EnvFullName(modelUUID string) string

EnvFullName returns a string based on the provided model UUID that is suitable for identifying the env on a provider.

The resulting string clearly associates the value with juju, whereas the model's UUID alone isn't very distinctive for humans. This benefits users by helping them quickly identify in their hosting management tools which instances are juju related.

func GetCheckNonceCommand Uses

func GetCheckNonceCommand(instanceConfig *instancecfg.InstanceConfig) string

func HandleCredentialError Uses

func HandleCredentialError(isAuthError func(error) bool, err error, ctx context.ProviderCallContext)

HandleCredentialError determines if a given error relates to an invalid credential.

func IsCredentialNotValid Uses

func IsCredentialNotValid(err error) bool

IsCredentialNotValid reports whether err was created with CredentialNotValid().

func MaybeHandleCredentialError Uses

func MaybeHandleCredentialError(isAuthError func(error) bool, err error, ctx context.ProviderCallContext) bool

MaybeHandleCredentialError determines if a given error relates to an invalid credential. If it is, the credential is invalidated and the return bool is true.

func MiBToGiB Uses

func MiBToGiB(m uint64) uint64

MiBToGiB converts the provided megabytes (base-2) into the nearest gigabytes (base-2), rounding up. This is useful for providers that deal in gigabytes (while juju deals in megabytes).

func MinRootDiskSizeGiB Uses

func MinRootDiskSizeGiB(series string) uint64

MinRootDiskSizeGiB is the minimum size for the root disk of an instance, in Gigabytes. This value accommodates the anticipated size of the initial image, any updates, and future application data.

func NewCredentialNotValid Uses

func NewCredentialNotValid(message string) error

NewCredentialNotValid returns an error with given message and satisfies IsCredentialNotValid().

func ProviderStateInstances Uses

func ProviderStateInstances(stor storage.StorageReader) ([]instance.Id, error)

ProviderStateInstances extracts the instance IDs from provider-state.

func RemoveStateInstances Uses

func RemoveStateInstances(stor storage.Storage, ids ...instance.Id) error

RemoveStateInstances removes controller instance IDs from the provider-state file in storage. Instance IDs that are not found in the file are ignored.

func SaveState Uses

func SaveState(storage storage.StorageWriter, state *BootstrapState) error

SaveState writes the given state to the given storage.

func ValidateAvailabilityZone Uses

func ValidateAvailabilityZone(env ZonedEnviron, ctx context.ProviderCallContext, zone string) error

ValidateAvailabilityZone returns nil iff the availability zone exists and is available, otherwise returns a NotValid error.

func WaitSSH Uses

func WaitSSH(
    stdErr io.Writer,
    interrupted <-chan os.Signal,
    client ssh.Client,
    checkHostScript string,
    inst InstanceRefresher,
    ctx context.ProviderCallContext,
    opts environs.BootstrapDialOpts,
    hostSSHOptions HostSSHOptionsFunc,
) (addr string, err error)

WaitSSH waits for the instance to be assigned a routable address, then waits until we can connect to it via SSH.

waitSSH attempts on all addresses returned by the instance in parallel; the first succeeding one wins. We ensure that private addresses are for the correct machine by checking the presence of a file on the machine that contains the machine's nonce. The "checkHostScript" is a bash script that performs this file check.

func ZoneIndependentError Uses

func ZoneIndependentError(err error) error

ZoneIndependentError wraps the given error such that it satisfies environs.IsAvailabilityZoneIndependent.

type AvailabilityZone Uses

type AvailabilityZone interface {
    // Name returns the name of the availability zone.
    Name() string

    // Available reports whether the availability zone is currently available.
    Available() bool
}

AvailabilityZone describes a provider availability zone. go:generate mockgen -package mocks -destination mocks/availability_zone.go github.com/juju/juju/provider/common AvailabilityZone

type AvailabilityZoneInstances Uses

type AvailabilityZoneInstances struct {
    // ZoneName is the name of the availability zone.
    ZoneName string

    // Instances is a set of instances within the availability zone.
    Instances []instance.Id
}

AvailabilityZoneInstances describes an availability zone and a set of instances in that zone.

func AvailabilityZoneAllocations Uses

func AvailabilityZoneAllocations(
    env ZonedEnviron, ctx context.ProviderCallContext, group []instance.Id,
) ([]AvailabilityZoneInstances, error)

AvailabilityZoneAllocations returns the availability zones and their instance allocations from the specified group, in ascending order of population. Availability zones with the same population size are ordered by name.

If the specified group is empty, then it will behave as if the result of AllRunningInstances were provided.

type BootstrapState Uses

type BootstrapState struct {
    // StateInstances are the controllers.
    StateInstances []instance.Id `yaml:"state-instances"`
}

BootstrapState is the state information that is stored in StateFile.

Individual providers may define their own state structures instead of this one, and use their own code for loading and saving those, but this is the definition that most practically useful providers share unchanged.

func LoadState Uses

func LoadState(stor storage.StorageReader) (*BootstrapState, error)

LoadState reads state from the given storage.

type DefaultProvider Uses

type DefaultProvider struct {
    // Env is the Juju environment that methods target.
    Env environs.Environ
}

DefaultProvider exposes the various common implementations found in this package as methods of a single type. This facilitates treating the implementations as a bundle, e.g. satisfying interfaces.

func (DefaultProvider) BootstrapEnv Uses

func (dp DefaultProvider) BootstrapEnv(ctx environs.BootstrapContext, callCtx context.ProviderCallContext, args environs.BootstrapParams) (*environs.BootstrapResult, error)

BootstrapEnv bootstraps the Juju environment.

func (DefaultProvider) DestroyEnv Uses

func (dp DefaultProvider) DestroyEnv(ctx context.ProviderCallContext) error

DestroyEnv destroys the Juju environment.

type HostSSHOptionsFunc Uses

type HostSSHOptionsFunc func(host string) (*ssh.Options, func(), error)

HostSSHOptionsFunc is a function that, given a hostname, returns an ssh.Options and a cleanup function, or an error.

type InstanceConfigurator Uses

type InstanceConfigurator interface {

    // Close all ports.
    DropAllPorts(exceptPorts []int, addr string) error

    // Add network interface and allocate external IP address.
    // Implementations should also configure this interface and initialise  ports state.
    ConfigureExternalIpAddress(apiPort int) error

    // Open or close ports.
    ChangeIngressRules(ipAddress string, insert bool, rules []network.IngressRule) error

    // List all ingress rules.
    FindIngressRules() ([]network.IngressRule, error)
}

Implementations of this interface should provide a way to configure external IP allocation and add firewall functionality. go:generate mockgen -package mocks -destination mocks/instance_configurator.go github.com/juju/juju/provider/common InstanceConfigurator

func NewSshInstanceConfigurator Uses

func NewSshInstanceConfigurator(host string) InstanceConfigurator

NewSshInstanceConfigurator creates new sshInstanceConfigurator.

type InstanceRefresher Uses

type InstanceRefresher interface {
    // Refresh refreshes the addresses for the instance.
    Refresh(ctx context.ProviderCallContext) error

    // Addresses returns the addresses for the instance.
    // To ensure that the results are up to date, call
    // Refresh first.
    Addresses(ctx context.ProviderCallContext) (network.ProviderAddresses, error)

    // Status returns the provider-specific status for the
    // instance.
    Status(ctx context.ProviderCallContext) instance.Status
}

InstanceRefresher is the subet of the Instance interface required for waiting for SSH access to become available.

type RefreshableInstance Uses

type RefreshableInstance struct {
    instances.Instance
    Env environs.Environ
}

func (*RefreshableInstance) Refresh Uses

func (i *RefreshableInstance) Refresh(ctx context.ProviderCallContext) error

Refresh refreshes the addresses for the instance.

type ZonedEnviron Uses

type ZonedEnviron interface {
    environs.Environ

    // AvailabilityZones returns all availability zones in the environment.
    AvailabilityZones(ctx context.ProviderCallContext) ([]AvailabilityZone, error)

    // InstanceAvailabilityZoneNames returns the names of the availability
    // zones for the specified instances. The error returned follows the same
    // rules as Environ.Instances.
    InstanceAvailabilityZoneNames(ctx context.ProviderCallContext, ids []instance.Id) ([]string, error)

    // DeriveAvailabilityZones attempts to derive availability zones from
    // the specified StartInstanceParams.
    //
    // The parameters for starting an instance may imply (or explicitly
    // specify) availability zones, e.g. due to placement, or due to the
    // attachment of existing volumes, or due to subnet placement. If
    // there is no such restriction, then DeriveAvailabilityZones should
    // return an empty string slice to indicate that the caller should
    // choose an availability zone.
    DeriveAvailabilityZones(ctx context.ProviderCallContext, args environs.StartInstanceParams) ([]string, error)
}

ZonedEnviron is an environs.Environ that has support for availability zones. go:generate mockgen -package mocks -destination mocks/zoned_environ.go github.com/juju/juju/provider/common ZonedEnviron

Directories

PathSynopsis
mocksPackage mocks is a generated GoMock package.

Package common imports 43 packages (graph) and is imported by 603 packages. Updated 2019-09-24. Refresh now. Tools for package owners.