google

package
v0.0.0-...-9ec3720 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 6, 2021 License: AGPL-3.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OSEnvPrivateKey  = "GCE_PRIVATE_KEY"
	OSEnvClientID    = "GCE_CLIENT_ID"
	OSEnvClientEmail = "GCE_CLIENT_EMAIL"
	OSEnvRegion      = "GCE_REGION"
	OSEnvProjectID   = "GCE_PROJECT_ID"
)

The names of OS environment variables related to GCE.

Note that these are not specified by Google. Instead they are defined by juju for use with the GCE provider. If Google defines equivalent environment variables they should be used instead.

View Source
const (
	StatusDone         = "DONE"
	StatusDown         = "DOWN"
	StatusPending      = "PENDING"
	StatusProvisioning = "PROVISIONING"
	StatusRunning      = "RUNNING"
	StatusStaging      = "STAGING"
	StatusStopped      = "STOPPED"
	StatusStopping     = "STOPPING"
	StatusTerminated   = "TERMINATED"
	StatusUp           = "UP"
)

The various status values used by GCE.

View Source
const (
	NetworkAccessOneToOneNAT = "ONE_TO_ONE_NAT" // the default
)

The different kinds of network access.

Variables

View Source
var AuthorisationFailureStatusCodes = map[int][]string{
	http.StatusUnauthorized:      {"Unauthorized"},
	http.StatusPaymentRequired:   {"Payment Required"},
	http.StatusForbidden:         {"Forbidden", "Access Not Configured"},
	http.StatusProxyAuthRequired: {"Proxy Auth Required"},

	http.StatusBadRequest: {"Bad Request"},
}

AuthorisationFailureStatusCodes contains http status code and description that signify authorisation difficulties.

Google does not always use standard HTTP descriptions, which is why a single status code can map to multiple descriptions.

Functions

func HandleCredentialError

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

HandleCredentialError determines if a given error relates to an invalid credential. If it is, the credential is invalidated. Original error is returned untouched.

func HasDenialStatusCode

func HasDenialStatusCode(err error) bool

HasDenialStatusCode determines if the given error was caused by an invalid credential, i.e. whether it contains a response status code that indicates an authentication failure.

func IsInvalidConfigValueError

func IsInvalidConfigValueError(err error) bool

IsInvalidConfigValueError returns whether or not the cause of the provided error is a *InvalidConfigValueError.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports if given error is of 'not found' type.

func MinDiskSizeGB

func MinDiskSizeGB(ser string) uint64

MinDiskSizeGB is the minimum/default size (in megabytes) for GCE disks.

Note: GCE does not currently have an official minimum disk size. However, in testing we found the minimum size to be 10 GB for ubuntu and 50 GB for windows due to the image size. See gceapi message.

gceapi: Requested disk size cannot be smaller than the image size (10 GB)

func NewInvalidConfigValueError

func NewInvalidConfigValueError(key, value string, reason error) error

NewInvalidConfigValueError returns a new InvalidConfigValueError for the given info. If the provided reason is an error then Reason is set to that error. Otherwise a non-nil value is treated as a string and Reason is set to a non-nil value that wraps it.

func NewMissingConfigValue

func NewMissingConfigValue(key, field string) error

NewMissingConfigValue returns a new error for a missing config field.

func RandomSuffixNamer

func RandomSuffixNamer(fw *firewall, prefix string, existingNames set.Strings) (string, error)

RandomSuffixNamer tries to find a unique name for the firewall by appending a random suffix.

Types

type AttachedDisk

type AttachedDisk struct {
	// VolumeName is the name of the volume that is attached, this is unique
	// and used by gce as an identifier.
	VolumeName string
	// DeviceName is the name of the device in the instance, typycally
	// is reflected into the /dev/disk/by-id/google-*
	DeviceName string
	// Mode is the read/write mode of the disk.
	Mode DiskMode
}

AttachedDisk represents a disk that is attached to an instance.

type AvailabilityZone

type AvailabilityZone struct {
	// contains filtered or unexported fields
}

AvailabilityZone represents a single GCE zone. It satisfies the {provider/common}.AvailabilityZone interface.

func NewZone

func NewZone(name, status, state, replacement string) AvailabilityZone

NewZone build an availability zone from the provided name, status state, and replacement and returns it.

func (AvailabilityZone) Available

func (z AvailabilityZone) Available() bool

Available returns whether or not the zone is available for provisioning.

func (AvailabilityZone) Deprecated

func (z AvailabilityZone) Deprecated() bool

Deprecated returns true if the zone has been deprecated.

func (AvailabilityZone) Name

func (z AvailabilityZone) Name() string

Name returns the zone's name.

func (AvailabilityZone) Status

func (z AvailabilityZone) Status() string

Status returns the status string for the zone. It will match one of the Status* constants defined in the package.

type Connection

type Connection struct {
	// contains filtered or unexported fields
}

Connection provides methods for interacting with the GCE API. The methods are limited to those needed by the juju GCE provider.

Before calling any of the methods, the Connect method should be called to authenticate and open the raw connection to the GCE API. Otherwise a panic will result.

func Connect

func Connect(connCfg ConnectionConfig, creds *Credentials) (*Connection, error)

Connect authenticates using the provided credentials and opens a low-level connection to the GCE API for the Connection. Calling Connect after a successful connection has already been made will result in an error. All errors that happen while authenticating and connecting are returned by Connect.

func (*Connection) AddInstance

func (gce *Connection) AddInstance(spec InstanceSpec) (*Instance, error)

AddInstance creates a new instance based on the spec's data and returns it. The instance will be created using the provided connection and in the provided zone.

func (*Connection) AttachDisk

func (gce *Connection) AttachDisk(zone, volumeName, instanceId string, mode DiskMode) (*AttachedDisk, error)

AttachDisk implements storage section of gceConnection.

func (*Connection) AvailabilityZones

func (gc *Connection) AvailabilityZones(region string) ([]AvailabilityZone, error)

AvailabilityZones returns the list of availability zones for a given GCE region. If none are found the the list is empty. Any failure in the low-level request is returned as an error.

func (Connection) ClosePorts

func (gce Connection) ClosePorts(target string, rules corefirewall.IngressRules) error

ClosePorts sends a request to the GCE API to close the provided port ranges on the named firewall. If the firewall does not exist nothing happens. If the firewall is left with no ports then it is removed. Otherwise it will be left with just the open ports it has that do not match the provided port ranges. The call blocks until the ports are closed or the request fails.

func (*Connection) CreateDisks

func (gce *Connection) CreateDisks(zone string, disks []DiskSpec) ([]*Disk, error)

CreateDisks implements storage section of gceConnection.

func (*Connection) DetachDisk

func (gce *Connection) DetachDisk(zone, instanceId, volumeName string) error

DetachDisk implements storage section of gceConnection. disk existence is checked but not instance nor is attachment.

func (*Connection) Disk

func (gce *Connection) Disk(zone, name string) (*Disk, error)

Disk implements storage section of gceConnection.

func (*Connection) Disks

func (gce *Connection) Disks() ([]*Disk, error)

Disks implements storage section of gceConnection.

func (Connection) IngressRules

func (gce Connection) IngressRules(fwname string) (corefirewall.IngressRules, error)

IngressRules build a list of all open port ranges for a given firewall name (within the Connection's project) and returns it. If the firewall does not exist then the list will be empty and no error is returned.

func (*Connection) Instance

func (gce *Connection) Instance(id, zone string) (Instance, error)

Instance gets the up-to-date info about the given instance and returns it.

func (*Connection) InstanceDisks

func (gce *Connection) InstanceDisks(zone, instanceId string) ([]*AttachedDisk, error)

InstanceDisks implements storage section of gceConnection.

func (*Connection) Instances

func (gce *Connection) Instances(prefix string, statuses ...string) ([]Instance, error)

Instances sends a request to the GCE API for a list of all instances (in the Connection's project) for which the name starts with the provided prefix. The result is also limited to those instances with one of the specified statuses (if any).

func (*Connection) ListMachineTypes

func (gce *Connection) ListMachineTypes(zone string) ([]MachineType, error)

ListMachineTypes returns a list of MachineType available for the given zone.

func (Connection) Networks

func (gce Connection) Networks() ([]*compute.Network, error)

Networks returns the networks available.

func (Connection) OpenPorts

func (gce Connection) OpenPorts(target string, rules corefirewall.IngressRules) error

OpenPorts adds or updates GCE firewall rules so that traffic to the target ports is allowed from the source ranges specified by the ingress rules. If a rule matching a set of source ranges doesn't already exist, it will be created - the name will be made unique using a random suffix.

func (Connection) OpenPortsWithNamer

func (gce Connection) OpenPortsWithNamer(target string, namer FirewallNamer, rules corefirewall.IngressRules) error

OpenPortsWithNamer adds or creates firewall rules in the same way as OpenPorts, but uses the FirewallNamer passed in to generate the firewall name - this is mostly useful for getting predictable results in tests.

func (*Connection) RemoveDisk

func (gce *Connection) RemoveDisk(zone, name string) error

RemoveDisk implements storage section of gceConnection. TODO(perrito666) handle non existing disk, perhaps catch 404.

func (*Connection) RemoveInstances

func (gce *Connection) RemoveInstances(prefix string, ids ...string) error

RemoveInstances sends a request to the GCE API to terminate all instances (in the Connection's project) that match one of the provided IDs. If a prefix is provided, only IDs that start with the prefix will be considered. The call blocks until all the instances are removed or the request fails.

func (*Connection) SetDiskLabels

func (gce *Connection) SetDiskLabels(zone, name, labelFingerprint string, labels map[string]string) error

SetDiskLabels implements storage section of gceConnection.

func (Connection) Subnetworks

func (gce Connection) Subnetworks(region string) ([]*compute.Subnetwork, error)

Subnetworks returns the subnets available in this region.

func (*Connection) UpdateMetadata

func (gce *Connection) UpdateMetadata(key, value string, ids ...string) error

UpdateMetadata sets the metadata key to the specified value for all of the instance ids given. The call blocks until all of the instances are updated or the request fails.

func (Connection) VerifyCredentials

func (gc Connection) VerifyCredentials() error

VerifyCredentials ensures that the authentication credentials used to connect are valid for use in the project and region defined for the Connection. If they are not then an error is returned.

type ConnectionConfig

type ConnectionConfig struct {
	// Region is the GCE region in which to operate for the connection.
	Region string

	// ProjectID is the project ID to use in all GCE API requests for
	// the connection.
	ProjectID string
}

ConnectionConfig contains the config values used for a connection to the GCE API.

func (ConnectionConfig) Validate

func (gc ConnectionConfig) Validate() error

Validate checks the connection's fields for invalid values. If the values are not valid, it returns a config.InvalidConfigValueError error with the key set to the corresponding OS environment variable name.

To be considered valid, each of the connection's must be set to some non-empty value.

type Credentials

type Credentials struct {
	// JSONKey is the content of the JSON key file for these credentials.
	JSONKey []byte

	// ClientID is the GCE account's OAuth ID. It is part of the OAuth
	// config used in the OAuth-wrapping network transport.
	ClientID string

	// ProjectID is the GCE project's ID that these credentials relate to.
	ProjectID string

	// ClientEmail is the email address associatd with the GCE account.
	// It is used to generate a new OAuth token to use in the
	// OAuth-wrapping network transport.
	ClientEmail string

	// PrivateKey is the private key that matches the public key
	// associatd with the GCE account. It is used to generate a new
	// OAuth token to use in the OAuth-wrapping network transport.
	PrivateKey []byte
}

Credentials holds the OAuth2 credentials needed to authenticate on GCE.

func NewCredentials

func NewCredentials(values map[string]string) (*Credentials, error)

NewCredentials returns a new Credentials based on the provided values. The keys must be recognized OS env var names for the different credential fields.

func ParseJSONKey

func ParseJSONKey(jsonKeyFile io.Reader) (*Credentials, error)

ParseJSONKey returns a new Credentials with values based on the provided JSON key file contents.

func (Credentials) Validate

func (gc Credentials) Validate() error

Validate checks the credentials for invalid values. If the values are not valid, it returns errors.NotValid with the message set to the corresponding OS environment variable name.

To be considered valid, each of the credentials must be set to some non-empty value. Furthermore, ClientEmail must be a proper email address.

func (Credentials) Values

func (gc Credentials) Values() map[string]string

Values returns the credentials as a simple mapping with the corresponding OS env variable names as the keys.

type Disk

type Disk struct {
	// Id is an unique identifier google adds to the disk, it usually
	// is not used in the API.
	Id uint64

	// Name is a unique identifier string for each disk.
	Name string

	// Description holds the description field for a disk, we used to
	// store the model UUID here.
	Description string

	// Size is the size in mbit.
	Size uint64

	// Type is one of the available disk types supported by
	// gce (persistent or ephemeral).
	Type DiskType

	// Zone holds the name of the zone in which the disk lives.
	Zone string

	// DiskStatus holds the status of he aforementioned disk.
	Status DiskStatus

	// AttachedInstances holds the IDs of instances that have the disk
	// attached.
	AttachedInstances []string

	// Labels holds labels/metadata for the disk. Labels are used for
	// storing volume resource tags.
	Labels map[string]string

	// LabelFingerprint holds a hash of the labels, to be used to prevent
	// conflicting changes to labels.
	LabelFingerprint string
}

Disk represents a gce disk.

func NewDisk

func NewDisk(cd *compute.Disk) *Disk

type DiskMode

type DiskMode string
const (
	ModeRW DiskMode = "READ_WRITE"
	ModeRO DiskMode = "READ_ONLY"
)

The different disk modes supported by GCE.

type DiskSpec

type DiskSpec struct {
	// Series is the OS series on which the disk size depends
	Series string
	// SizeHintGB is the requested disk size in Gigabytes. It must be
	// greater than 0.
	SizeHintGB uint64
	// ImageURL is the location of the image to which the disk should
	// be initialized.
	ImageURL string
	// Boot indicates that this is a boot disk. An instance may only
	// have one boot disk. (attached only)
	Boot bool
	// Scratch indicates that the disk should be a "scratch" disk
	// instead of a "persistent" disk (the default).
	Scratch bool
	// Readonly indicates that the disk should not support writes.
	Readonly bool
	// AutoDelete indicates that the attached disk should be removed
	// when the instance to which it is attached is removed.
	AutoDelete bool
	// PersistenDiskType is exclusive to persistent disks and indicates which of the
	// persistent types available this disk should be.
	PersistentDiskType DiskType
	// Name: Name of the resource; provided by the client when the resource
	// is created. The name must be 1-63 characters long, and comply with
	// RFC1035. Specifically, the name must be 1-63 characters long and
	// match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means
	// the first character must be a lowercase letter, and all following
	// characters must be a dash, lowercase letter, or digit, except the
	// last character, which cannot be a dash.
	Name string
	// Labels holds labels/metadata for the disk. Labels are used for
	// storing volume resource tags.
	Labels map[string]string
}

DiskSpec holds all the data needed to request a new disk on GCE. Some fields are used only for attached disks (i.e. in association with instances).

func (*DiskSpec) SizeGB

func (ds *DiskSpec) SizeGB() uint64

SizeGB returns the disk size to use for a new disk. The size hint is returned if it isn't too small (otherwise the min size is returned).

func (*DiskSpec) TooSmall

func (ds *DiskSpec) TooSmall() bool

TooSmall checks the spec's size hint and indicates whether or not it is smaller than the minimum disk size.

type DiskStatus

type DiskStatus string
const (
	StatusCreating  DiskStatus = "CREATING"
	StatusFailed    DiskStatus = "FAILED"
	StatusReady     DiskStatus = "READY"
	StatusRestoring DiskStatus = "RESTORING"
)

type DiskType

type DiskType string
const (
	// persistent
	DiskPersistentStandard DiskType = "pd-standard"
	DiskPersistentSSD      DiskType = "pd-ssd"
	// scratch
	DiskLocalSSD DiskType = "local-ssd"
)

The types of disk supported by GCE

type FirewallNamer

type FirewallNamer func(fw *firewall, prefix string, existingNames set.Strings) (string, error)

FirewallNamer generates a unique name for a firewall given the firewall, a prefix and a set of current firewall rule names.

type Instance

type Instance struct {
	InstanceSummary
	// contains filtered or unexported fields
}

Instance represents a single realized GCE compute instance.

func NewInstance

func NewInstance(summary InstanceSummary, spec *InstanceSpec) *Instance

NewInstance builds an instance from the provided summary and spec and returns it.

func (Instance) Addresses

func (gi Instance) Addresses() network.ProviderAddresses

Addresses identifies information about the network addresses associated with the instance and returns it.

func (Instance) Metadata

func (gi Instance) Metadata() map[string]string

Metadata returns the user-specified metadata for the instance.

func (Instance) NetworkInterfaces

func (gi Instance) NetworkInterfaces() []compute.NetworkInterface

NetworkInterfaces returns the details of the network connection for this instance.

func (Instance) RootDisk

func (gi Instance) RootDisk() *compute.AttachedDisk

RootDisk returns an AttachedDisk

func (Instance) RootDiskGB

func (gi Instance) RootDiskGB() uint64

RootDiskGB returns the size of the instance's root disk. If it cannot be determined then 0 is returned.

func (Instance) Status

func (gi Instance) Status() string

Status returns a string identifying the status of the instance. The value will match one of the Status* constants in the package.

type InstanceSpec

type InstanceSpec struct {
	// ID is the "name" of the instance.
	ID string

	// Type is the name of the GCE instance type. The value is resolved
	// relative to an availability zone when the API request is sent.
	// The type must match one of the GCE-recognized types.
	Type string

	// Disks holds the information needed to request each of the disks
	// that should be attached to a new instance. This must include a
	// single root disk.
	Disks []DiskSpec

	// Network identifies the information for the network that a new
	// instance should use. If the network does not exist then it will
	// be added when the instance is. At least the network's name must
	// be set.
	Network NetworkSpec

	// NetworkInterfaces is the names of the network interfaces to
	// associate with the instance. They will be connected to the the
	// network identified by the instance spec. At least one name must
	// be provided.
	NetworkInterfaces []string

	// Metadata is the GCE instance "user-specified" metadata that will
	// be initialized on the new instance.
	Metadata map[string]string

	// Tags are the labels to associate with the instance. This is
	// useful when making bulk calls or in relation to some API methods
	// (e.g. related to firewalls access rules).
	Tags []string

	// AvailabilityZone holds the name of the availability zone in which
	// to create the instance.
	AvailabilityZone string

	// AllocatePublicIP is true if the instance should be assigned a public IP
	// address, exposing it to access from outside the internal network.
	AllocatePublicIP bool
}

InstanceSpec holds all the information needed to create a new GCE instance. TODO(ericsnow) Validate the invariants?

func (InstanceSpec) RootDisk

func (is InstanceSpec) RootDisk() *compute.AttachedDisk

RootDisk identifies the root disk for a given instance (or instance spec) and returns it. If the root disk could not be determined then nil is returned. TODO(ericsnow) Return an error?

func (InstanceSpec) Summary

func (is InstanceSpec) Summary() InstanceSummary

Summary builds an InstanceSummary based on the spec and returns it.

type InstanceSummary

type InstanceSummary struct {
	// ID is the "name" of the instance.
	ID string
	// ZoneName is the unqualified name of the zone in which the
	// instance was provisioned.
	ZoneName string
	// Status holds the status of the instance at a certain point in time.
	Status string
	// Metadata is the instance metadata.
	Metadata map[string]string
	// Addresses are the IP Addresses associated with the instance.
	Addresses network.ProviderAddresses
	// NetworkInterfaces are the network connections associated with
	// the instance.
	NetworkInterfaces []*compute.NetworkInterface
}

InstanceSummary captures all the data needed by Instance.

type InvalidConfigValueError

type InvalidConfigValueError struct {
	errors.Err

	// Key is the OS env var corresponding to the field with the bad value.
	Key string

	// Value is the invalid value.
	Value interface{}
}

InvalidConfigValueError indicates that one of the config values failed validation.

func (*InvalidConfigValueError) Cause

func (err *InvalidConfigValueError) Cause() error

Cause implements errors.Causer.Cause.

func (InvalidConfigValueError) Error

func (err InvalidConfigValueError) Error() string

Error implements error.

type MachineType

type MachineType struct {
	CreationTimestamp            string
	Deprecated                   bool
	Description                  string
	GuestCpus                    int64
	Id                           uint64
	ImageSpaceGb                 int64
	Kind                         string
	MaximumPersistentDisks       int64
	MaximumPersistentDisksSizeGb int64
	MemoryMb                     int64
	Name                         string
}

MachineType represents a gce Machine Type. this is basically a copy of compute.MachineType put here to satisfy an extra layer of abstraction.

type NetworkSpec

type NetworkSpec struct {
	// Name is the unqualified name of the network.
	Name string
}

NetworkSpec holds all the information needed to identify and create a GCE network.

func (*NetworkSpec) Path

func (ns *NetworkSpec) Path() string

Path returns the qualified name of the network.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL