state

package
v0.0.0-...-4bd6544 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2016 License: AGPL-3.0 Imports: 83 Imported by: 0

Documentation

Overview

Package state enables reading, observing, and changing the state stored in MongoDB of a whole model managed by juju.

Index

Constants

View Source
const (
	ItemAdded = iota
	ItemModified
	ItemDeleted
)
View Source
const (
	CleanupAge = time.Hour * 24
)
View Source
const (
	// CleanupKindResourceBlob identifies the cleanup kind
	// for resource blobs.
	CleanupKindResourceBlob = "resourceBlob"
)

Variables

View Source
var AddServicePostFuncs = map[string]func(*State, AddApplicationArgs) error{}

TODO(natefinch) DEMO code, revisit after demo!

View Source
var ErrCannotEnterScope = stderrors.New("cannot enter scope: unit or relation is not alive")

ErrCannotEnterScope indicates that a relation unit failed to enter its scope due to either the unit or the relation not being Alive.

View Source
var ErrCannotEnterScopeYet = stderrors.New("cannot enter scope yet: non-alive subordinate unit has not been removed")

ErrCannotEnterScopeYet indicates that a relation unit failed to enter its scope due to a required and pre-existing subordinate unit that is not Alive. Once that subordinate has been removed, a new one can be created.

View Source
var ErrChangeComplete = errors.New("change complete")

ErrChangeComplete can be returned from Prepare to finish an Apply attempt and report success without taking any further action.

View Source
var ErrCharmRevisionAlreadyModified = fmt.Errorf("charm revision already modified")

ErrCharmRevisionAlreadyModified is returned when a pending or placeholder charm is no longer pending or a placeholder, signaling the charm is available in state with its full information.

View Source
var ErrDead = fmt.Errorf("not found or dead")
View Source
var ErrModelNotDying = errors.New("model is not dying")
View Source
var ErrNeverForwarded = errors.Errorf("cannot find ID of the last forwarded record")

ErrNeverForwarded signals to the caller that the ID of a previously forwarded log record could not be found.

View Source
var ErrNoBackingVolume = errors.New("filesystem has no backing volume")

ErrNoBackingVolume is returned by Filesystem.Volume() for filesystems without a backing volume.

View Source
var ErrNoDefaultStoragePool = fmt.Errorf("no storage pool specifed and no default available")

ErrNoDefaultStoragePool is returned when a storage pool is required but none is specified nor available as a default.

View Source
var ErrStateClosed = fmt.Errorf("state has been closed")

ErrStateClosed is returned from watchers if their underlying state connection has been closed.

View Source
var ErrStopped = stderrors.New("watcher was stopped")
View Source
var ErrSubordinateConstraints = stderrors.New("constraints do not apply to subordinate services")
View Source
var ErrUnitHasStorageAttachments = errors.New("unit has storage attachments")

ErrUnitHasStorageAttachments is a standard error to indicate that a Unit cannot complete an operation to end its life because it still has storage attachments.

View Source
var ErrUnitHasSubordinates = errors.New("unit has subordinates")

ErrUnitHasSubordinates is a standard error to indicate that a Unit cannot complete an operation to end its life because it still has subordinate services

View Source
var (

	// NewUUID wraps the utils.NewUUID() call, and exposes it as a var to
	// facilitate patching.
	NewUUID = func() (utils.UUID, error) { return utils.NewUUID() }
)

Functions

func AddDefaultEndpointBindingsToServices

func AddDefaultEndpointBindingsToServices(st *State) error

AddDefaultEndpointBindingsToServices adds default endpoint bindings for each service. As long as the service has a charm URL set, each charm endpoint will be bound to the default space.

func AddFilesystemStatus

func AddFilesystemStatus(st *State) error

AddFilesystemStatus ensures each filesystem has a status doc.

func AddPreferredAddressesToMachines

func AddPreferredAddressesToMachines(st *State) error

func Apply

func Apply(db Database, change Change) error

Apply runs the supplied Change against the supplied Database. If it returns no error, the change succeeded.

func ContainerTypeFromId

func ContainerTypeFromId(machineId string) instance.ContainerType

ContainerTypeFromId returns the container type if machineId is a container id, or "" if machineId is not for a container.

func ControllerAccess

func ControllerAccess(st *State, tag names.Tag) (permission.UserAccess, error)

func DefaultEndpointBindingsForCharm

func DefaultEndpointBindingsForCharm(charmMeta *charm.Meta) map[string]string

DefaultEndpointBindingsForCharm populates a bindings map containing each endpoint of the given charm metadata (relation name or extra-binding name) bound to an empty space.

func HostedModelCountOp

func HostedModelCountOp(amount int) txn.Op

func InitDbLogs

func InitDbLogs(session *mgo.Session) error

InitDbLogs sets up the indexes for the logs collection. It should be called as state is opened. It is idempotent.

func IsCharmAlreadyUploadedError

func IsCharmAlreadyUploadedError(err interface{}) bool

IsCharmAlreadyUploadedError returns if the given error is ErrCharmAlreadyUploaded.

func IsContainsFilesystem

func IsContainsFilesystem(err error) bool

func IsHasAssignedUnitsError

func IsHasAssignedUnitsError(err error) bool

func IsHasAttachmentsError

func IsHasAttachmentsError(err error) bool

IsHasAttachmentsError reports whether or not the error is a HasAttachmentsError, indicating that an attempt to destroy a machine failed due to it having storage attachments.

func IsHasContainersError

func IsHasContainersError(err error) bool

IsHasContainersError reports whether or not the error is a HasContainersError, indicating that an attempt to destroy a machine failed due to it having containers.

func IsHasHostedModelsError

func IsHasHostedModelsError(err error) bool

func IsMigrationActive

func IsMigrationActive(st *State, modelUUID string) (bool, error)

IsMigrationActive returns true if a migration is in progress for the model with the given UUID. The State provided need not be for the model in question.

func IsNeverConnectedError

func IsNeverConnectedError(err error) bool

IsNeverConnectedError returns true if err is of type NeverConnectedError.

func IsNeverLoggedInError

func IsNeverLoggedInError(err error) bool

IsNeverLoggedInError returns true if err is of type NeverLoggedInError.

func IsParentDeviceHasChildrenError

func IsParentDeviceHasChildrenError(err interface{}) bool

IsParentDeviceHasChildrenError returns if the given error or its cause is ErrParentDeviceHasChildren.

func IsProviderIDNotUniqueError

func IsProviderIDNotUniqueError(err interface{}) bool

IsProviderIDNotUniqueError returns if the given error or its cause is ErrProviderIDNotUnique.

func IsUpgradeInProgressError

func IsUpgradeInProgressError(err error) bool

IsUpgradeInProgressError returns true if the error is caused by an in-progress upgrade.

func IsValidAddressConfigMethod

func IsValidAddressConfigMethod(value string) bool

IsValidAddressConfigMethod returns whether the given value is a valid method to configure a link-layer network device's IP address.

func IsValidLinkLayerDeviceName

func IsValidLinkLayerDeviceName(name string) bool

IsValidLinkLayerDeviceName returns whether the given name is a valid network link-layer device name, depending on the runtime.GOOS value.

func IsValidLinkLayerDeviceType

func IsValidLinkLayerDeviceType(value string) bool

IsValidLinkLayerDeviceType returns whether the given value is a valid link-layer network device type.

func IsVersionInconsistentError

func IsVersionInconsistentError(e interface{}) bool

IsVersionInconsistentError returns if the given error is versionInconsistentError.

func MigrateSettingsSchema

func MigrateSettingsSchema(st *State) error

MigrateSettingsSchema migrates the schema of the settings collection, moving non-reserved keys at the top-level into a subdoc, and introducing a top-level "version" field with the initial value matching txn-revno.

This migration takes place both before and after model-uuid migration, to get the correct txn-revno value.

func NestingLevel

func NestingLevel(machineId string) int

NestingLevel returns how many levels of nesting exist for a machine id.

func NewControllerUserAccess

func NewControllerUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error)

NewControllerUserAccess returns a new permission.UserAccess for the given userDoc and current Controller.

func NewModelUserAccess

func NewModelUserAccess(st *State, userDoc userAccessDoc) (permission.UserAccess, error)

NewModelUserAccess returns a new permission.UserAccess for the given userDoc and current Model.

func NewProviderIDNotUniqueError

func NewProviderIDNotUniqueError(providerIDs ...network.Id) error

NewProviderIDNotUniqueError returns an instance of ErrProviderIDNotUnique initialized with the given duplicate provider IDs.

func ParentId

func ParentId(machineId string) string

ParentId returns the id of the host machine if machineId a container id, or "" if machineId is not for a container.

func ParseFilesystemAttachmentId

func ParseFilesystemAttachmentId(id string) (names.MachineTag, names.FilesystemTag, error)

ParseFilesystemAttachmentId parses a string as a filesystem attachment ID, returning the machine and filesystem components.

func ParseVolumeAttachmentId

func ParseVolumeAttachmentId(id string) (names.MachineTag, names.VolumeTag, error)

ParseVolumeAttachmentId parses a string as a volume attachment ID, returning the machine and volume components.

func PruneLogs

func PruneLogs(st MongoSessioner, minLogTime time.Time, maxLogsMB int) error

PruneLogs removes old log documents in order to control the size of logs collection. All logs older than minLogTime are removed. Further removal is also performed if the logs collection size is greater than maxLogsMB.

func PruneStatusHistory

func PruneStatusHistory(st *State, maxHistoryTime time.Duration, maxHistoryMB int) error

PruneStatusHistory removes status history entries until only logs newer than <maxLogTime> remain and also ensures that the collection is smaller than <maxLogsMB> after the deletion.

func RegisterCleanupHandler

func RegisterCleanupHandler(kindStr string, handler CleanupHandler) error

RegisterCleanupHandler identifies the handler to use a given cleanup kind.

func RemoveModelBlock

func RemoveModelBlock(st *State, t BlockType) error

func RemoveModelBlockOps

func RemoveModelBlockOps(st *State, t BlockType) ([]txn.Op, error)

func ServiceInstances

func ServiceInstances(st *State, application string) ([]instance.Id, error)

ServiceInstances returns the instance IDs of provisioned machines that are assigned units of the specified application.

func SetResourcesComponent

func SetResourcesComponent(fn func(Persistence, *State) Resources)

SetResourcesComponent registers the function that provide the state functionality related to resources.

func SetResourcesPersistence

func SetResourcesPersistence(fn func(Persistence) ResourcesPersistence)

SetResourcesPersistence registers the function that provides the state persistence functionality related to resources.

func SetSystemIdentity

func SetSystemIdentity(st *State, identity string) error

SetSystemIdentity sets the system identity value in the database if and only iff it is empty.

func TopParentId

func TopParentId(machineId string) string

TopParentId returns the id of the top level host machine for a container id.

Types

type Action

type Action interface {
	Entity

	// Id returns the local id of the Action.
	Id() string

	// Receiver returns the Name of the ActionReceiver for which this action
	// is enqueued.  Usually this is a Unit Name().
	Receiver() string

	// Name returns the name of the action, as defined in the charm.
	Name() string

	// Parameters will contain a structure representing arguments or parameters to
	// an action, and is expected to be validated by the Unit using the Charm
	// definition of the Action.
	Parameters() map[string]interface{}

	// Enqueued returns the time the action was added to state as a pending
	// Action.
	Enqueued() time.Time

	// Started returns the time that the Action execution began.
	Started() time.Time

	// Completed returns the completion time of the Action.
	Completed() time.Time

	// Status returns the final state of the action.
	Status() ActionStatus

	// Results returns the structured output of the action and any error.
	Results() (map[string]interface{}, string)

	// ActionTag returns an ActionTag constructed from this action's
	// Prefix and Sequence.
	ActionTag() names.ActionTag

	// Begin marks an action as running, and logs the time it was started.
	// It asserts that the action is currently pending.
	Begin() (Action, error)

	// Finish removes action from the pending queue and captures the output
	// and end state of the action.
	Finish(results ActionResults) (Action, error)
}

Action represents an instance of an action designated for a unit or machine in the model.

type ActionReceiver

type ActionReceiver interface {
	Entity

	// AddAction queues an action with the given name and payload for this
	// ActionReceiver.
	AddAction(name string, payload map[string]interface{}) (Action, error)

	// CancelAction removes a pending Action from the queue for this
	// ActionReceiver and marks it as cancelled.
	CancelAction(action Action) (Action, error)

	// WatchActionNotifications returns a StringsWatcher that will notify
	// on changes to the queued actions for this ActionReceiver.
	WatchActionNotifications() StringsWatcher

	// Actions returns the list of Actions queued and completed for this
	// ActionReceiver.
	Actions() ([]Action, error)

	// CompletedActions returns the list of Actions completed for this
	// ActionReceiver.
	CompletedActions() ([]Action, error)

	// PendingActions returns the list of Actions queued for this
	// ActionReceiver.
	PendingActions() ([]Action, error)

	// RunningActions returns the list of Actions currently running for
	// this ActionReceiver.
	RunningActions() ([]Action, error)
}

ActionReceiver describes Entities that can have Actions queued for them, and that can get ActionRelated information about those actions. TODO(jcw4) consider implementing separate Actor classes for this interface; for example UnitActor that implements this interface, and takes a Unit and performs all these actions.

type ActionResults

type ActionResults struct {
	Status  ActionStatus           `json:"status"`
	Results map[string]interface{} `json:"results"`
	Message string                 `json:"message"`
}

ActionResults is a data transfer object that holds the key Action output and results information.

type ActionSpecsByName

type ActionSpecsByName map[string]charm.ActionSpec

ActionSpecsByName is a map of action names to their respective ActionSpec.

type ActionStatus

type ActionStatus string

ActionStatus represents the possible end states for an action.

const (
	// ActionFailed signifies that the action did not complete successfully.
	ActionFailed ActionStatus = "failed"

	// ActionCompleted indicates that the action ran to completion as intended.
	ActionCompleted ActionStatus = "completed"

	// ActionCancelled means that the Action was cancelled before being run.
	ActionCancelled ActionStatus = "cancelled"

	// ActionPending is the default status when an Action is first queued.
	ActionPending ActionStatus = "pending"

	// ActionRunning indicates that the Action is currently running.
	ActionRunning ActionStatus = "running"
)

type ActionsWatcher

type ActionsWatcher interface {
	Entity
	WatchActionNotifications() StringsWatcher
}

ActionsWatcher defines the methods an entity exposes to watch Actions queued up for itself

type AddApplicationArgs

type AddApplicationArgs struct {
	Name             string
	Series           string
	Charm            *Charm
	Channel          csparams.Channel
	Storage          map[string]StorageConstraints
	EndpointBindings map[string]string
	Settings         charm.Settings
	NumUnits         int
	Placement        []*instance.Placement
	Constraints      constraints.Value
	Resources        map[string]string
}

type Address

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

Address represents the state of an IP address assigned to a link-layer network device on a machine.

func (*Address) ConfigMethod

func (addr *Address) ConfigMethod() AddressConfigMethod

ConfigMethod returns the AddressConfigMethod used for this IP address.

func (*Address) DNSSearchDomains

func (addr *Address) DNSSearchDomains() []string

DNSSearchDomains returns the list of DNS domains to use for qualifying hostnames. Can be empty.

func (*Address) DNSServers

func (addr *Address) DNSServers() []string

DNSServers returns the list of DNS nameservers to use, which can be empty.

func (*Address) Device

func (addr *Address) Device() (*LinkLayerDevice, error)

Device returns the LinkLayeyDevice this IP address is assigned to.

func (*Address) DeviceName

func (addr *Address) DeviceName() string

DeviceName returns the name of the link-layer device this IP address is assigned to.

func (*Address) DocID

func (addr *Address) DocID() string

DocID returns the globally unique ID of the IP address, including the model UUID as prefix.

func (*Address) GatewayAddress

func (addr *Address) GatewayAddress() string

GatewayAddress returns the gateway address to use, which can be empty.

func (*Address) Machine

func (addr *Address) Machine() (*Machine, error)

Machine returns the Machine this IP address belongs to.

func (*Address) MachineID

func (addr *Address) MachineID() string

MachineID returns the ID of the machine this IP address belongs to.

func (*Address) ProviderID

func (addr *Address) ProviderID() network.Id

ProviderID returns the provider-specific IP address ID, if set.

func (*Address) Remove

func (addr *Address) Remove() (err error)

Remove removes the IP address, if it exists. No error is returned when the address was already removed.

func (*Address) String

func (addr *Address) String() string

String returns a human-readable representation of the IP address.

func (*Address) Subnet

func (addr *Address) Subnet() (*Subnet, error)

Subnet returns the Subnet this IP address comes from. Returns nil and errors.NotFoundError if the address comes from an unknown subnet (i.e. machine-local one).

func (*Address) SubnetCIDR

func (addr *Address) SubnetCIDR() string

SubnetCIDR returns the CIDR of the subnet this IP address comes from.

func (*Address) Value

func (addr *Address) Value() string

Value returns the value of this IP address.

type AddressConfigMethod

type AddressConfigMethod string

AddressConfigMethod is the method used to configure a link-layer device's IP address.

const (
	// LoopbackAddress is used for IP addresses of LoopbackDevice types.
	LoopbackAddress AddressConfigMethod = "loopback"

	// StaticAddress is used for statically configured addresses.
	StaticAddress AddressConfigMethod = "static"

	// DynamicAddress is used for addresses dynamically configured via DHCP.
	DynamicAddress AddressConfigMethod = "dynamic"

	// ManualAddress is used for manually configured addresses.
	ManualAddress AddressConfigMethod = "manual"
)

type AgentEntity

AgentEntity represents an entity that can have an agent responsible for it.

type AgentLiving

type AgentLiving interface {
	Living
	EnsureDead() error
	Remove() error
}

AgentLiving describes state entities with a lifecycle and an agent that manages it.

type AgentTooler

type AgentTooler interface {
	AgentTools() (*tools.Tools, error)
	SetAgentVersion(version.Binary) error
}

AgentTooler is implemented by entities that have associated agent tools.

type Application

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

Application represents the state of an application.

func (*Application) AddUnit

func (a *Application) AddUnit() (unit *Unit, err error)

AddUnit adds a new principal unit to the service.

func (*Application) AllUnits

func (a *Application) AllUnits() (units []*Unit, err error)

AllUnits returns all units of the service.

func (*Application) ApplicationTag

func (a *Application) ApplicationTag() names.ApplicationTag

ApplicationTag returns the more specific ApplicationTag rather than the generic Tag.

func (*Application) Channel

func (a *Application) Channel() csparams.Channel

Channel identifies the charm store channel from which the service's charm was deployed. It is only needed when interacting with the charm store.

func (*Application) Charm

func (a *Application) Charm() (ch *Charm, force bool, err error)

Charm returns the service's charm and whether units should upgrade to that charm even if they are in an error state.

func (*Application) CharmModifiedVersion

func (a *Application) CharmModifiedVersion() int

CharmModifiedVersion increases whenever the service's charm is changed in any way.

func (*Application) CharmURL

func (a *Application) CharmURL() (curl *charm.URL, force bool)

CharmURL returns the service's charm URL, and whether units should upgrade to the charm with that URL even if they are in an error state.

func (*Application) ClearExposed

func (a *Application) ClearExposed() error

ClearExposed removes the exposed flag from the service. See SetExposed and IsExposed.

func (*Application) ConfigSettings

func (a *Application) ConfigSettings() (charm.Settings, error)

ConfigSettings returns the raw user configuration for the application's charm. Unset values are omitted.

func (*Application) Constraints

func (a *Application) Constraints() (constraints.Value, error)

Constraints returns the current application constraints.

func (*Application) Destroy

func (a *Application) Destroy() (err error)

Destroy ensures that the application and all its relations will be removed at some point; if the application has no units, and no relation involving the application has any units in scope, they are all removed immediately.

func (*Application) Endpoint

func (a *Application) Endpoint(relationName string) (Endpoint, error)

Endpoint returns the relation endpoint with the supplied name, if it exists.

func (*Application) EndpointBindings

func (a *Application) EndpointBindings() (map[string]string, error)

EndpointBindings returns the mapping for each endpoint name and the space name it is bound to (or empty if unspecified). When no bindings are stored for the application, defaults are returned.

func (*Application) Endpoints

func (a *Application) Endpoints() (eps []Endpoint, err error)

Endpoints returns the service's currently available relation endpoints.

func (*Application) EnsureMinUnits

func (s *Application) EnsureMinUnits() (err error)

EnsureMinUnits adds new units if the service's MinUnits value is greater than the number of alive units.

func (*Application) IsExposed

func (a *Application) IsExposed() bool

IsExposed returns whether this application is exposed. The explicitly open ports (with open-port) for exposed services may be accessed from machines outside of the local deployment network. See SetExposed and ClearExposed.

func (*Application) IsPrincipal

func (a *Application) IsPrincipal() bool

IsPrincipal returns whether units of the application can have subordinate units.

func (*Application) LeaderSettings

func (a *Application) LeaderSettings() (map[string]string, error)

LeaderSettings returns a service's leader settings. If nothing has been set yet, it will return an empty map; this is not an error.

func (*Application) Life

func (a *Application) Life() Life

Life returns whether the application is Alive, Dying or Dead.

func (*Application) MetricCredentials

func (a *Application) MetricCredentials() []byte

MetricCredentials returns any metric credentials associated with this service.

func (*Application) MinUnits

func (s *Application) MinUnits() int

MinUnits returns the minimum units count for the application.

func (*Application) Name

func (a *Application) Name() string

Name returns the application name.

func (*Application) Refresh

func (a *Application) Refresh() error

Refresh refreshes the contents of the Service from the underlying state. It returns an error that satisfies errors.IsNotFound if the application has been removed.

func (*Application) Relations

func (a *Application) Relations() (relations []*Relation, err error)

Relations returns a Relation for every relation the application is in.

func (*Application) Series

func (a *Application) Series() string

Series returns the specified series for this charm.

func (*Application) ServiceAndUnitsStatus

func (a *Application) ServiceAndUnitsStatus() (status.StatusInfo, map[string]status.StatusInfo, error)

ServiceAndUnitsStatus returns the status for this application and all its units.

func (*Application) SetCharm

func (a *Application) SetCharm(cfg SetCharmConfig) (err error)

SetCharm changes the charm for the application.

func (*Application) SetConstraints

func (a *Application) SetConstraints(cons constraints.Value) (err error)

SetConstraints replaces the current application constraints.

func (*Application) SetExposed

func (a *Application) SetExposed() error

SetExposed marks the application as exposed. See ClearExposed and IsExposed.

func (*Application) SetMetricCredentials

func (a *Application) SetMetricCredentials(b []byte) error

SetMetricCredentials updates the metric credentials associated with this service.

func (*Application) SetMinUnits

func (s *Application) SetMinUnits(minUnits int) (err error)

SetMinUnits changes the number of minimum units required by the service.

func (*Application) SetStatus

func (a *Application) SetStatus(statusInfo status.StatusInfo) error

SetStatus sets the status for the application.

func (*Application) Status

func (a *Application) Status() (status.StatusInfo, error)

Status returns the status of the service. Only unit leaders are allowed to set the status of the service. If no status is recorded, then there are no unit leaders and the status is derived from the unit status values.

func (*Application) StatusHistory

func (a *Application) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

StatusHistory returns a slice of at most filter.Size StatusInfo items or items as old as filter.Date or items newer than now - filter.Delta time representing past statuses for this service.

func (*Application) StorageConstraints

func (a *Application) StorageConstraints() (map[string]StorageConstraints, error)

StorageConstraints returns the storage constraints for the application.

func (*Application) String

func (a *Application) String() string

String returns the application name.

func (*Application) Tag

func (a *Application) Tag() names.Tag

Tag returns a name identifying the service. The returned name will be different from other Tag values returned by any other entities from the same state.

func (*Application) UpdateConfigSettings

func (a *Application) UpdateConfigSettings(changes charm.Settings) error

UpdateConfigSettings changes a service's charm config settings. Values set to nil will be deleted; unknown and invalid values will return an error.

func (*Application) UpdateLeaderSettings

func (a *Application) UpdateLeaderSettings(token leadership.Token, updates map[string]string) error

UpdateLeaderSettings updates the service's leader settings with the supplied values, but will fail (with a suitable error) if the supplied Token loses validity. Empty values in the supplied map will be cleared in the database.

func (*Application) Watch

func (s *Application) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a service.

func (*Application) WatchLeaderSettings

func (s *Application) WatchLeaderSettings() NotifyWatcher

WatchLeaderSettings returns a watcher for observing changed to a service's leader settings.

func (*Application) WatchRelations

func (s *Application) WatchRelations() StringsWatcher

WatchRelations returns a StringsWatcher that notifies of changes to the lifecycles of relations involving s.

func (*Application) WatchUnits

func (s *Application) WatchUnits() StringsWatcher

WatchUnits returns a StringsWatcher that notifies of changes to the lifecycles of units of s.

type AssignmentPolicy

type AssignmentPolicy string

AssignmentPolicy controls what machine a unit will be assigned to.

const (
	// AssignLocal indicates that all service units should be assigned
	// to machine 0.
	AssignLocal AssignmentPolicy = "local"

	// AssignClean indicates that every service unit should be assigned
	// to a machine which never previously has hosted any units, and that
	// new machines should be launched if required.
	AssignClean AssignmentPolicy = "clean"

	// AssignCleanEmpty indicates that every service unit should be assigned
	// to a machine which never previously has hosted any units, and which is not
	// currently hosting any containers, and that new machines should be launched if required.
	AssignCleanEmpty AssignmentPolicy = "clean-empty"

	// AssignNew indicates that every service unit should be assigned to a new
	// dedicated machine.  A new machine will be launched for each new unit.
	AssignNew AssignmentPolicy = "new"
)

type Authenticator

type Authenticator interface {
	Refresh() error
	SetPassword(pass string) error
	PasswordValid(pass string) bool
}

Authenticator represents entites capable of handling password authentication.

type Backing

type Backing interface {

	// GetAll retrieves information about all information
	// known to the Backing and stashes it in the Store.
	GetAll(all *multiwatcherStore) error

	// Changed informs the backing about a change received
	// from a watcher channel.  The backing is responsible for
	// updating the Store to reflect the change.
	Changed(all *multiwatcherStore, change watcher.Change) error

	// Watch watches for any changes and sends them
	// on the given channel.
	Watch(in chan<- watcher.Change)

	// Unwatch stops watching for changes on the
	// given channel.
	Unwatch(in chan<- watcher.Change)

	// Release cleans up resources opened by the Backing.
	Release() error
}

Backing is the interface required by the storeManager to access the underlying state.

func NewAllModelWatcherStateBacking

func NewAllModelWatcherStateBacking(st *State) Backing

type BatchParam

type BatchParam struct {
	UUID     string
	CharmURL string
	Created  time.Time
	Metrics  []Metric
	Unit     names.UnitTag
}

BatchParam contains the properties of the metrics batch used when creating a metrics batch.

type Block

type Block interface {
	// Id returns this block's id.
	Id() string

	// ModelUUID returns the model UUID associated with this block.
	ModelUUID() string

	// Tag returns tag for the entity that is being blocked
	Tag() (names.Tag, error)

	// Type returns block type
	Type() BlockType

	// Message returns explanation that accompanies this block.
	Message() string
	// contains filtered or unexported methods
}

Customers and stakeholders want to be able to prevent accidental damage to their Juju deployments. To prevent running some operations, we want to have blocks that can be switched on/off.

type BlockDevice

type BlockDevice interface {
	// Machine returns the ID of the machine the block device is attached to.
	Machine() string

	// Info returns the block device's BlockDeviceInfo.
	Info() BlockDeviceInfo
}

BlockDevice represents the state of a block device in the model.

type BlockDeviceInfo

type BlockDeviceInfo struct {
	DeviceName     string   `bson:"devicename"`
	DeviceLinks    []string `bson:"devicelinks,omitempty"`
	Label          string   `bson:"label,omitempty"`
	UUID           string   `bson:"uuid,omitempty"`
	HardwareId     string   `bson:"hardwareid,omitempty"`
	BusAddress     string   `bson:"busaddress,omitempty"`
	Size           uint64   `bson:"size"`
	FilesystemType string   `bson:"fstype,omitempty"`
	InUse          bool     `bson:"inuse"`
	MountPoint     string   `bson:"mountpoint,omitempty"`
}

BlockDeviceInfo describes information about a block device.

type BlockType

type BlockType int8

BlockType specifies block type for enum benefit.

const (
	// DestroyBlock type identifies block that prevents model destruction.
	DestroyBlock BlockType = iota

	// RemoveBlock type identifies block that prevents
	// removal of machines, services, units or relations.
	RemoveBlock

	// ChangeBlock type identifies block that prevents model changes such
	// as additions, modifications, removals of model entities.
	ChangeBlock
)

func AllTypes

func AllTypes() []BlockType

AllTypes returns all supported block types.

func ParseBlockType

func ParseBlockType(str string) BlockType

ParseBlockType returns BlockType from humanly readable type representation.

func (BlockType) MigrationValue

func (t BlockType) MigrationValue() string

MigrationValue converts the block type value into a useful human readable string for model migration.

func (BlockType) String

func (t BlockType) String() string

String returns humanly readable type representation.

func (BlockType) ToParams

func (t BlockType) ToParams() multiwatcher.BlockType

ToParams returns the type as multiwatcher.BlockType.

type Change

type Change interface {

	// Prepare ensures that db is in a valid base state for applying
	// the change, and returns mgo/txn operations that will fail any
	// enclosing transaction if the state has materially changed; or
	// returns an error.
	Prepare(db Database) ([]txn.Op, error)
}

Change represents any mgo/txn-representable change to a Database.

type Charm

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

Charm represents the state of a charm in the model.

func (*Charm) Actions

func (c *Charm) Actions() *charm.Actions

Actions returns the actions definition of the charm.

func (*Charm) BundleSha256

func (c *Charm) BundleSha256() string

BundleSha256 returns the SHA256 digest of the charm bundle bytes.

func (*Charm) Config

func (c *Charm) Config() *charm.Config

Config returns the configuration of the charm.

func (*Charm) Destroy

func (c *Charm) Destroy() error

Destroy sets the charm to Dying and prevents it from being used by applications or units. It only works on local charms, and only when the charm is not referenced by any application.

func (*Charm) IsPlaceholder

func (c *Charm) IsPlaceholder() bool

IsPlaceholder returns whether the charm record is just a placeholder rather than representing a deployed charm.

func (*Charm) IsUploaded

func (c *Charm) IsUploaded() bool

IsUploaded returns whether the charm has been uploaded to the model storage.

func (*Charm) Life

func (c *Charm) Life() Life

Life returns the charm's life state.

func (*Charm) Macaroon

func (c *Charm) Macaroon() (macaroon.Slice, error)

Macaroon return the macaroon that can be used to request data about the charm from the charmstore, or nil if the charm is not private.

func (*Charm) Meta

func (c *Charm) Meta() *charm.Meta

Meta returns the metadata of the charm.

func (*Charm) Metrics

func (c *Charm) Metrics() *charm.Metrics

Metrics returns the metrics declared for the charm.

func (*Charm) Refresh

func (c *Charm) Refresh() error

Refresh loads fresh charm data from the database. In practice, the only observable change should be to its Life value.

func (*Charm) Remove

func (c *Charm) Remove() error

Remove will delete the charm's stored archive and render the charm inaccessible to future clients. It will fail unless the charm is already Dying (indicating that someone has called Destroy).

func (*Charm) Revision

func (c *Charm) Revision() int

Revision returns the monotonically increasing charm revision number.

func (*Charm) StoragePath

func (c *Charm) StoragePath() string

StoragePath returns the storage path of the charm bundle.

func (*Charm) String

func (c *Charm) String() string

func (*Charm) Tag

func (c *Charm) Tag() names.Tag

Tag returns a tag identifying the charm. Implementing state.GlobalEntity interface.

func (*Charm) URL

func (c *Charm) URL() *charm.URL

URL returns the URL that identifies the charm.

func (*Charm) UpdateMacaroon

func (c *Charm) UpdateMacaroon(m macaroon.Slice) error

UpdateMacaroon updates the stored macaroon for this charm.

type CharmInfo

type CharmInfo struct {
	Charm       charm.Charm
	ID          *charm.URL
	StoragePath string
	SHA256      string
	Macaroon    macaroon.Slice
}

CharmInfo contains all the data necessary to store a charm's metadata.

type CleanupHandler

type CleanupHandler func(st *State, persist Persistence, prefix string) error

CleanupHandler is a function that state may call during cleanup to perform cleanup actions for some cleanup type.

type CloudAccessor

type CloudAccessor interface {
	Cloud(cloud string) (cloud.Cloud, error)
	Clouds() (map[names.CloudTag]cloud.Cloud, error)
	CloudCredential(tag names.CloudCredentialTag) (cloud.Credential, error)
}

CloudAccessor defines the methods needed to obtain information about clouds and credentials.

type ControllerAccessor

type ControllerAccessor interface {
	ControllerConfig() (controller.Config, error)
}

ControllerAccessor defines the methods needed to access controller information.

type ControllerInfo

type ControllerInfo struct {
	// CloudName is the name of the cloud to which this controller is deployed.
	CloudName string

	// ModelTag identifies the initial model. Only the initial
	// model is able to have machines that manage state. The initial
	// model is the model that is created when bootstrapping.
	ModelTag names.ModelTag

	// MachineIds holds the ids of all machines configured
	// to run a controller. It includes all the machine
	// ids in VotingMachineIds.
	MachineIds []string

	// VotingMachineIds holds the ids of all machines
	// configured to run a controller and to have a vote
	// in peer election.
	VotingMachineIds []string

	// MongoSpaceName is the space that contains all Mongo servers.
	MongoSpaceName string

	// MongoSpaceState records the state of the mongo space selection state machine. Valid states are:
	// * We haven't looked for a Mongo space yet (MongoSpaceUnknown)
	// * We have looked for a Mongo space, but we didn't find one (MongoSpaceInvalid)
	// * We have looked for and found a Mongo space (MongoSpaceValid)
	// * We didn't try to find a Mongo space because the provider doesn't support spaces (MongoSpaceUnsupported)
	MongoSpaceState MongoSpaceStates
}

ControllerInfo holds information about currently configured controller machines.

type ControllerSessioner

type ControllerSessioner interface {
	MongoSessioner

	// IsController indicates if current state is controller.
	IsController() bool
}

ModelSessioner supports creating new mongo sessions for the controller.

type ControllersChanges

type ControllersChanges struct {
	Added      []string
	Removed    []string
	Maintained []string
	Promoted   []string
	Demoted    []string
	Converted  []string
}

Change in controllers after the ensure availability txn has committed.

type Database

type Database interface {

	// Copy returns a matching Database with its own session, and a
	// func that must be called when the Database is no longer needed.
	//
	// GetCollection and TransactionRunner results from the resulting Database
	// will all share a session; this does not absolve you of responsibility
	// for calling those collections' closers.
	Copy() (Database, SessionCloser)

	// CopyForModel returns a matching Database with its own session and
	// its own modelUUID and a func that must be called when the Database is no
	// longer needed.
	//
	// Same warnings apply for CopyForModel than for Copy.
	CopyForModel(modelUUID string) (Database, SessionCloser)

	// GetCollection returns the named Collection, and a func that must be
	// called when the Collection is no longer needed. The returned Collection
	// might or might not have its own session, depending on the Database; the
	// closer must always be called regardless.
	//
	// If the schema specifies model-filtering for the named collection,
	// the returned collection will automatically filter queries; for details,
	// see modelStateCollection.
	GetCollection(name string) (mongo.Collection, SessionCloser)

	// TransactionRunner() returns a runner responsible for making changes to
	// the database, and a func that must be called when the runner is no longer
	// needed. The returned Runner might or might not have its own session,
	// depending on the Database; the closer must always be called regardless.
	//
	// It will reject transactions that reference raw-access (or unknown)
	// collections; it will automatically rewrite operations that reference
	// non-global collections; and it will ensure that non-global documents can
	// only be inserted while the corresponding model is still Alive.
	TransactionRunner() (jujutxn.Runner, SessionCloser)

	// Schema returns the schema used to load the database. The returned schema
	// is not a copy and must not be modified.
	Schema() collectionSchema
}

Database exposes the mongodb capabilities that most of state should see.

type DbLogger

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

func NewDbLogger

func NewDbLogger(st ModelSessioner, entity names.Tag, ver version.Number) *DbLogger

NewDbLogger returns a DbLogger instance which is used to write logs to the database.

func (*DbLogger) Close

func (logger *DbLogger) Close()

Close cleans up resources used by the DbLogger instance.

func (*DbLogger) Log

func (logger *DbLogger) Log(t time.Time, module string, location string, level loggo.Level, msg string) error

Log writes a log message to the database.

type DeletedUserError

type DeletedUserError struct {
	UserName string
}

DeletedUserError is used to indicate when an attempt to mutate a deleted user is attempted.

func (DeletedUserError) Error

func (e DeletedUserError) Error() string

Error implements the error interface.

type Endpoint

type Endpoint struct {
	ApplicationName string
	// TODO: thumper 2016-06-27
	// This is pure evil and we should not be storing structures from
	// external packages directly in mongo.
	charm.Relation
}

Endpoint represents one endpoint of a relation.

func (Endpoint) CanRelateTo

func (ep Endpoint) CanRelateTo(other Endpoint) bool

CanRelateTo returns whether a relation may be established between e and other.

func (Endpoint) String

func (ep Endpoint) String() string

String returns the unique identifier of the relation endpoint.

type EnsureDeader

type EnsureDeader interface {
	EnsureDead() error
}

EnsureDeader with an EnsureDead method.

type Entity

type Entity interface {
	Tag() names.Tag
}

Entity represents any entity that can be returned by State.FindEntity. All entities have a tag.

type EntityFinder

type EntityFinder interface {
	FindEntity(tag names.Tag) (Entity, error)
}

EntityFinder is implemented by *State. See State.FindEntity for documentation on the method.

type EntityWithApplication

type EntityWithApplication interface {
	Application() (*Application, error)
}

EntityWithApplication is implemented by Units it is intended for anything that can return its Application.

type ErrCharmAlreadyUploaded

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

ErrCharmAlreadyUploaded is returned by UpdateUploadedCharm() when the given charm is already uploaded and marked as not pending in state.

func (*ErrCharmAlreadyUploaded) Error

func (e *ErrCharmAlreadyUploaded) Error() string

type ErrParentDeviceHasChildren

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

ErrParentDeviceHasChildren is a standard error to indicate a network link-layer device cannot be removed because other existing devices refer to it as their parent.

func (*ErrParentDeviceHasChildren) Error

type ErrProviderIDNotUnique

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

ErrProviderIDNotUnique is a standard error to indicate the value specified for a ProviderID field is not unique within the current model.

func (*ErrProviderIDNotUnique) Error

func (e *ErrProviderIDNotUnique) Error() string

type Filesystem

type Filesystem interface {
	GlobalEntity
	LifeBinder
	status.StatusGetter
	status.StatusSetter

	// FilesystemTag returns the tag for the filesystem.
	FilesystemTag() names.FilesystemTag

	// Storage returns the tag of the storage instance that this
	// filesystem is assigned to, if any. If the filesystem is not
	// assigned to a storage instance, an error satisfying
	// errors.IsNotAssigned will be returned.
	//
	// A filesystem can be assigned to at most one storage instance, and
	// a storage instance can have at most one associated filesystem.
	Storage() (names.StorageTag, error)

	// Volume returns the tag of the volume backing this filesystem,
	// or ErrNoBackingVolume if the filesystem is not backed by a volume
	// managed by Juju.
	Volume() (names.VolumeTag, error)

	// Info returns the filesystem's FilesystemInfo, or a NotProvisioned
	// error if the filesystem has not yet been provisioned.
	Info() (FilesystemInfo, error)

	// Params returns the parameters for provisioning the filesystem,
	// if it needs to be provisioned. Params returns true if the returned
	// parameters are usable for provisioning, otherwise false.
	Params() (FilesystemParams, bool)
}

Filesystem describes a filesystem in the model. Filesystems may be backed by a volume, and managed by Juju; otherwise they are first-class entities managed by a filesystem provider.

type FilesystemAttachment

type FilesystemAttachment interface {
	Lifer

	// Filesystem returns the tag of the related Filesystem.
	Filesystem() names.FilesystemTag

	// Machine returns the tag of the related Machine.
	Machine() names.MachineTag

	// Info returns the filesystem attachment's FilesystemAttachmentInfo, or a
	// NotProvisioned error if the attachment has not yet been made.
	//
	// Note that the presence of FilesystemAttachmentInfo does not necessarily
	// imply that the filesystem is mounted; model storage providers may
	// need to prepare a filesystem for attachment to a machine before it can
	// be mounted.
	Info() (FilesystemAttachmentInfo, error)

	// Params returns the parameters for creating the filesystem attachment,
	// if it has not already been made. Params returns true if the returned
	// parameters are usable for creating an attachment, otherwise false.
	Params() (FilesystemAttachmentParams, bool)
}

FilesystemAttachment describes an attachment of a filesystem to a machine.

type FilesystemAttachmentInfo

type FilesystemAttachmentInfo struct {
	// MountPoint is the path at which the filesystem is mounted on the
	// machine. MountPoint may be empty, meaning that the filesystem is
	// not mounted yet.
	MountPoint string `bson:"mountpoint"`
	ReadOnly   bool   `bson:"read-only"`
}

FilesystemAttachmentInfo describes information about a filesystem attachment.

type FilesystemAttachmentParams

type FilesystemAttachmentParams struct {
	Location string `bson:"location"`
	ReadOnly bool   `bson:"read-only"`
	// contains filtered or unexported fields
}

FilesystemAttachmentParams records parameters for attaching a filesystem to a machine.

type FilesystemInfo

type FilesystemInfo struct {
	Size uint64 `bson:"size"`
	Pool string `bson:"pool"`

	// FilesystemId is the provider-allocated unique ID of the
	// filesystem. This will be unspecified for filesystems
	// backed by volumes.
	FilesystemId string `bson:"filesystemid"`
}

FilesystemInfo describes information about a filesystem.

type FilesystemParams

type FilesystemParams struct {
	Pool string `bson:"pool"`
	Size uint64 `bson:"size"`
	// contains filtered or unexported fields
}

FilesystemParams records parameters for provisioning a new filesystem.

type GlobalEntity

type GlobalEntity interface {
	Tag() names.Tag
	// contains filtered or unexported methods
}

GlobalEntity specifies entity.

type HAMember

type HAMember struct {
	Tag           string
	PublicAddress network.Address
	Series        string
}

HAMember holds information that identifies one member of HA.

type HasAssignedUnitsError

type HasAssignedUnitsError struct {
	MachineId string
	UnitNames []string
}

func (*HasAssignedUnitsError) Error

func (e *HasAssignedUnitsError) Error() string

type HasAttachmentsError

type HasAttachmentsError struct {
	MachineId   string
	Attachments []names.Tag
}

HasAttachmentsError is the error returned by EnsureDead if the machine has attachments to resources that must be cleaned up first.

func (*HasAttachmentsError) Error

func (e *HasAttachmentsError) Error() string

type HasContainersError

type HasContainersError struct {
	MachineId    string
	ContainerIds []string
}

func (*HasContainersError) Error

func (e *HasContainersError) Error() string

type HistoryGetter

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

HistoryGetter allows getting the status history based on some identifying key.

func (*HistoryGetter) StatusHistory

func (g *HistoryGetter) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

StatusHistory implements status.StatusHistoryGetter.

type InitializeParams

type InitializeParams struct {
	// Clock wraps all calls time. Real uses use clock.WallClock,
	// tests may override with a testing clock.
	Clock clock.Clock

	// ControllerModelArgs contains the arguments for creating
	// the controller model.
	ControllerModelArgs ModelArgs

	// CloudName is the name of the cloud that the controller
	// runs in.
	CloudName string

	// Cloud contains the properties of the cloud that the
	// controller runs in.
	Cloud cloud.Cloud

	// CloudCredentials contains the credentials for the owner of
	// the controller model to store in the controller.
	CloudCredentials map[names.CloudCredentialTag]cloud.Credential

	// ControllerConfig contains config attributes for
	// the controller.
	ControllerConfig controller.Config

	// ControllerInheritedConfig contains default config attributes for
	// models on the specified cloud.
	ControllerInheritedConfig map[string]interface{}

	// RegionInheritedConfig contains region specific configuration for
	// models running on specific cloud regions.
	RegionInheritedConfig cloud.RegionConfig

	// NewPolicy is a function that returns the set of state policies
	// to apply.
	NewPolicy NewPolicyFunc

	// MongoInfo contains the information required to address and
	// authenticate with Mongo.
	MongoInfo *mongo.MongoInfo

	// MongoDialOpts contains the dial options for connecting to
	// Mongo.
	MongoDialOpts mongo.DialOpts
}

InitializeParams contains the parameters for initializing the state database.

func (InitializeParams) Validate

func (p InitializeParams) Validate() error

Validate checks that the state initialization parameters are valid.

type InstanceIdGetter

type InstanceIdGetter interface {
	InstanceId() (instance.Id, error)
}

InstanceIdGetter defines a single method - InstanceId.

type ItemChange

type ItemChange struct {
	Type     int
	Key      string
	OldValue interface{}
	NewValue interface{}
}

ItemChange represents the change of an item in a settings.

func (*ItemChange) String

func (ic *ItemChange) String() string

String returns the item change in a readable format.

type LastSentLogTracker

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

LastSentLogTracker records and retrieves timestamps of the most recent log records forwarded to a log sink for a model.

func NewAllLastSentLogTracker

func NewAllLastSentLogTracker(st ControllerSessioner, sink string) (*LastSentLogTracker, error)

NewAllLastSentLogTracker returns a new tracker that records and retrieves the timestamps of the most recent log records forwarded to the identified log sink for *all* models.

func NewLastSentLogTracker

func NewLastSentLogTracker(st ModelSessioner, modelUUID, sink string) *LastSentLogTracker

NewLastSentLogTracker returns a new tracker that records and retrieves the timestamps of the most recent log records forwarded to the identified log sink for the current model.

func (*LastSentLogTracker) Close

func (logger *LastSentLogTracker) Close() error

Close implements io.Closer

func (*LastSentLogTracker) Get

func (logger *LastSentLogTracker) Get() (int64, int64, error)

Get retrieves the id and timestamp.

func (*LastSentLogTracker) Set

func (logger *LastSentLogTracker) Set(recID, recTimestamp int64) error

Set records the timestamp.

type Life

type Life int8

Life represents the lifecycle state of the entities Relation, Unit, Service and Machine.

const (
	Alive Life = iota
	Dying
	Dead
)

func (Life) String

func (l Life) String() string

type LifeBinder

type LifeBinder interface {
	Lifer

	// LifeBinding either returns the tag of an entity to which this
	// entity's lifespan is bound; the result may be nil, indicating
	// that the entity's lifespan is not bound to anything.
	//
	// The types of tags that may be returned are depdendent on the
	// entity type. For example, a Volume may be bound to a Filesystem,
	// but a Filesystem may not be bound to a Filesystem.
	LifeBinding() names.Tag
}

LifeBinder represents an entity whose lifespan is bindable to that of another entity.

type Lifer

type Lifer interface {
	Life() Life
}

Lifer represents an entity with a life.

type LinkLayerDevice

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

LinkLayerDevice represents the state of a link-layer network device for a machine.

func (*LinkLayerDevice) Addresses

func (dev *LinkLayerDevice) Addresses() ([]*Address, error)

Addresses returns all IP addresses assigned to the device.

func (*LinkLayerDevice) DocID

func (dev *LinkLayerDevice) DocID() string

DocID returns the globally unique ID of the link-layer device, including the model UUID as prefix.

func (*LinkLayerDevice) IsAutoStart

func (dev *LinkLayerDevice) IsAutoStart() bool

IsAutoStart returns whether the device is set to automatically start on boot.

func (*LinkLayerDevice) IsUp

func (dev *LinkLayerDevice) IsUp() bool

IsUp returns whether the device is currently up.

func (*LinkLayerDevice) MACAddress

func (dev *LinkLayerDevice) MACAddress() string

MACAddress returns the media access control (MAC) address of the device.

func (*LinkLayerDevice) MTU

func (dev *LinkLayerDevice) MTU() uint

MTU returns the maximum transmission unit the device can handle.

func (*LinkLayerDevice) Machine

func (dev *LinkLayerDevice) Machine() (*Machine, error)

Machine returns the Machine this device belongs to.

func (*LinkLayerDevice) MachineID

func (dev *LinkLayerDevice) MachineID() string

MachineID returns the ID of the machine this device belongs to.

func (*LinkLayerDevice) Name

func (dev *LinkLayerDevice) Name() string

Name returns the name of the device, as it appears on the machine.

func (*LinkLayerDevice) ParentDevice

func (dev *LinkLayerDevice) ParentDevice() (*LinkLayerDevice, error)

ParentDevice returns the LinkLayerDevice corresponding to the parent device of this device, if set. When no parent device name is set, it returns nil and no error.

func (*LinkLayerDevice) ParentName

func (dev *LinkLayerDevice) ParentName() string

ParentName returns the name of this device's parent device, if set. The parent device is almost always on the same machine as the child device, but as a special case a child device on a container machine can have a parent BridgeDevice on the container's host machine. In the last case ParentName() returns the global key of the parent device, not just its name.

func (*LinkLayerDevice) ProviderID

func (dev *LinkLayerDevice) ProviderID() network.Id

ProviderID returns the provider-specific device ID, if set.

func (*LinkLayerDevice) Remove

func (dev *LinkLayerDevice) Remove() (err error)

Remove removes the device, if it exists. No error is returned when the device was already removed. ErrParentDeviceHasChildren is returned if this device is a parent to one or more existing devices and therefore cannot be removed.

func (*LinkLayerDevice) RemoveAddresses

func (dev *LinkLayerDevice) RemoveAddresses() error

RemoveAddresses removes all IP addresses assigned to the device.

func (*LinkLayerDevice) String

func (dev *LinkLayerDevice) String() string

String returns a human-readable representation of the device.

func (*LinkLayerDevice) Type

Type returns this device's underlying type.

type LinkLayerDeviceAddress

type LinkLayerDeviceAddress struct {
	// DeviceName is the name of the link-layer device that has this address.
	DeviceName string

	// ConfigMethod is the method used to configure this address.
	ConfigMethod AddressConfigMethod

	// ProviderID is the provider-specific ID of the address. Empty when not
	// supported. Cannot be changed once set to non-empty.
	ProviderID network.Id

	// CIDRAddress is the IP address assigned to the device, in CIDR format
	// (e.g. 10.20.30.5/24 or fc00:1234::/64).
	CIDRAddress string

	// DNSServers contains a list of DNS nameservers to use, which can be empty.
	DNSServers []string

	// DNSSearchDomains contains a list of DNS domain names to qualify
	// hostnames, and can be empty.
	DNSSearchDomains []string

	// GatewayAddress is the address of the gateway to use, which can be empty.
	GatewayAddress string
}

LinkLayerDeviceAddress contains an IP address assigned to a link-layer device.

type LinkLayerDeviceArgs

type LinkLayerDeviceArgs struct {
	// Name is the name of the device as it appears on the machine.
	Name string

	// MTU is the maximum transmission unit the device can handle.
	MTU uint

	// ProviderID is a provider-specific ID of the device. Empty when not
	// supported by the provider. Cannot be cleared once set.
	ProviderID network.Id

	// Type is the type of the underlying link-layer device.
	Type LinkLayerDeviceType

	// MACAddress is the media access control address for the device.
	MACAddress string

	// IsAutoStart is true if the device should be activated on boot.
	IsAutoStart bool

	// IsUp is true when the device is up (enabled).
	IsUp bool

	// ParentName is the name of the parent device, which may be empty. If set,
	// it needs to be an existing device on the same machine, unless the current
	// device is inside a container, in which case ParentName can be a global
	// key of a BridgeDevice on the host machine of the container. Traffic
	// originating from a device egresses from its parent device.
	ParentName string
}

LinkLayerDeviceArgs contains the arguments accepted by Machine.SetLinkLayerDevices().

type LinkLayerDeviceType

type LinkLayerDeviceType string

LinkLayerDeviceType defines the type of a link-layer network device.

const (
	// LoopbackDevice is used for loopback devices.
	LoopbackDevice LinkLayerDeviceType = "loopback"

	// EthernetDevice is used for Ethernet (IEEE 802.3) devices.
	EthernetDevice LinkLayerDeviceType = "ethernet"

	// VLAN_8021QDevice is used for IEEE 802.1Q VLAN devices.
	VLAN_8021QDevice LinkLayerDeviceType = "802.1q"

	// BondDevice is used for bonding devices.
	BondDevice LinkLayerDeviceType = "bond"

	// BridgeDevice is used for OSI layer-2 bridge devices.
	BridgeDevice LinkLayerDeviceType = "bridge"
)

type Living

type Living interface {
	Life() Life
	Destroy() error
	Refresh() error
}

Living describes state entities with a lifecycle.

type LogRecord

type LogRecord struct {
	// universal fields
	ID   int64
	Time time.Time

	// origin fields
	ModelUUID string
	Entity    names.Tag
	Version   version.Number

	// logging-specific fields
	Level    loggo.Level
	Module   string
	Location string
	Message  string
}

LogRecord defines a single Juju log message as returned by LogTailer.

type LogTailer

type LogTailer interface {
	// Logs returns the channel through which the LogTailer returns
	// Juju logs. It will be closed when the tailer stops.
	Logs() <-chan *LogRecord

	// Dying returns a channel which will be closed as the LogTailer
	// stops.
	Dying() <-chan struct{}

	// Stop is used to request that the LogTailer stops. It blocks
	// unil the LogTailer has stopped.
	Stop() error

	// Err returns the error that caused the LogTailer to stopped. If
	// it hasn't stopped or stopped without error nil will be
	// returned.
	Err() error
}

LogTailer allows for retrieval of Juju's logs from MongoDB. It first returns any matching already recorded logs and then waits for additional matching logs as they appear.

func NewLogTailer

func NewLogTailer(st LogTailerState, params *LogTailerParams) (LogTailer, error)

NewLogTailer returns a LogTailer which filters according to the parameters given.

type LogTailerParams

type LogTailerParams struct {
	StartID       int64
	StartTime     time.Time
	MinLevel      loggo.Level
	InitialLines  int
	NoTail        bool
	IncludeEntity []string
	ExcludeEntity []string
	IncludeModule []string
	ExcludeModule []string
	Oplog         *mgo.Collection // For testing only
	AllModels     bool
}

LogTailerParams specifies the filtering a LogTailer should apply to logs in order to decide which to return.

type LogTailerState

type LogTailerState interface {
	ModelSessioner

	// IsController indicates whether or not the model is the admin model.
	IsController() bool
}

LogTailerState describes the methods on State required for logging to the database.

type MacaroonCache

type MacaroonCache struct {
	*State
}

MacaroonCache is a type that wraps State and implements charmstore.MacaroonCache.

func (MacaroonCache) Get

func (m MacaroonCache) Get(u *charm.URL) (macaroon.Slice, error)

Get retrieves the macaroon for the charm (if any).

func (MacaroonCache) Set

func (m MacaroonCache) Set(u *charm.URL, ms macaroon.Slice) error

Set stores the macaroon on the charm.

type Machine

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

Machine represents the state of a machine.

func (*Machine) Actions

func (m *Machine) Actions() ([]Action, error)

Actions is part of the ActionReceiver interface.

func (*Machine) AddAction

func (m *Machine) AddAction(name string, payload map[string]interface{}) (Action, error)

AddAction is part of the ActionReceiver interface.

func (*Machine) Addresses

func (m *Machine) Addresses() (addresses []network.Address)

Addresses returns any hostnames and ips associated with a machine, determined both by the machine itself, and by asking the provider.

The addresses returned by the provider shadow any of the addresses that the machine reported with the same address value. Provider-reported addresses always come before machine-reported addresses. Duplicates are removed.

func (*Machine) AgentPresence

func (m *Machine) AgentPresence() (bool, error)

AgentPresence returns whether the respective remote agent is alive.

func (*Machine) AgentTools

func (m *Machine) AgentTools() (*tools.Tools, error)

AgentTools returns the tools that the agent is currently running. It returns an error that satisfies errors.IsNotFound if the tools have not yet been set.

func (*Machine) AllAddresses

func (m *Machine) AllAddresses() ([]*Address, error)

AllAddresses returns the all addresses assigned to all devices of the machine.

func (*Machine) AllLinkLayerDevices

func (m *Machine) AllLinkLayerDevices() ([]*LinkLayerDevice, error)

AllLinkLayerDevices returns all exiting link-layer devices of the machine.

func (*Machine) AllPorts

func (m *Machine) AllPorts() ([]*Ports, error)

AllPorts returns all opened ports for this machine (on all networks).

func (*Machine) AllProviderInterfaceInfos

func (m *Machine) AllProviderInterfaceInfos() ([]network.ProviderInterfaceInfo, error)

AllProviderInterfaceInfos returns the provider details for all of the link layer devices belonging to this machine. These can be used to identify the devices when interacting with the provider directly (for example, releasing container addresses).

func (*Machine) AvailabilityZone

func (m *Machine) AvailabilityZone() (string, error)

AvailabilityZone returns the provier-specific instance availability zone in which the machine was provisioned.

func (*Machine) CancelAction

func (m *Machine) CancelAction(action Action) (Action, error)

CancelAction is part of the ActionReceiver interface.

func (*Machine) CheckProvisioned

func (m *Machine) CheckProvisioned(nonce string) bool

CheckProvisioned returns true if the machine was provisioned with the given nonce.

func (*Machine) Clean

func (m *Machine) Clean() bool

Clean returns true if the machine does not have any deployed units or containers.

func (*Machine) CompletedActions

func (m *Machine) CompletedActions() ([]Action, error)

CompletedActions is part of the ActionReceiver interface.

func (*Machine) Constraints

func (m *Machine) Constraints() (constraints.Value, error)

Constraints returns the exact constraints that should apply when provisioning an instance for the machine.

func (*Machine) ContainerType

func (m *Machine) ContainerType() instance.ContainerType

ContainerType returns the type of container hosting this machine.

func (*Machine) Containers

func (m *Machine) Containers() ([]string, error)

Containers returns the container ids belonging to a parent machine. TODO(wallyworld): move this method to a service

func (*Machine) Destroy

func (m *Machine) Destroy() error

Destroy sets the machine lifecycle to Dying if it is Alive. It does nothing otherwise. Destroy will fail if the machine has principal units assigned, or if the machine has JobManageModel. If the machine has assigned units, Destroy will return a HasAssignedUnitsError.

func (*Machine) EnsureDead

func (m *Machine) EnsureDead() error

EnsureDead sets the machine lifecycle to Dead if it is Alive or Dying. It does nothing otherwise. EnsureDead will fail if the machine has principal units assigned, or if the machine has JobManageModel. If the machine has assigned units, EnsureDead will return a HasAssignedUnitsError.

func (*Machine) ForceDestroy

func (m *Machine) ForceDestroy() error

ForceDestroy queues the machine for complete removal, including the destruction of all units and containers on the machine.

func (*Machine) GetRebootFlag

func (m *Machine) GetRebootFlag() (bool, error)

GetRebootFlag returns the reboot flag for this machine.

func (*Machine) HardwareCharacteristics

func (m *Machine) HardwareCharacteristics() (*instance.HardwareCharacteristics, error)

TODO(wallyworld): move this method to a service.

func (*Machine) HasVote

func (m *Machine) HasVote() bool

HasVote reports whether that machine is currently a voting member of the replica set.

func (*Machine) Id

func (m *Machine) Id() string

Id returns the machine id.

func (*Machine) InstanceId

func (m *Machine) InstanceId() (instance.Id, error)

InstanceId returns the provider specific instance id for this machine, or a NotProvisionedError, if not set.

func (*Machine) InstanceStatus

func (m *Machine) InstanceStatus() (status.StatusInfo, error)

InstanceStatus returns the provider specific instance status for this machine, or a NotProvisionedError if instance is not yet provisioned.

func (*Machine) InstanceStatusHistory

func (m *Machine) InstanceStatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

InstanceStatusHistory returns a slice of at most filter.Size StatusInfo items or items as old as filter.Date or items newer than now - filter.Delta time representing past statuses for this machine instance. Instance represents the provider underlying [v]hardware or container where this juju machine is deployed.

func (*Machine) IsContainer

func (m *Machine) IsContainer() bool

IsContainer returns true if the machine is a container.

func (*Machine) IsManager

func (m *Machine) IsManager() bool

IsManager returns true if the machine has JobManageModel.

func (*Machine) IsManual

func (m *Machine) IsManual() (bool, error)

IsManual returns true if the machine was manually provisioned.

func (*Machine) Jobs

func (m *Machine) Jobs() []MachineJob

Jobs returns the responsibilities that must be fulfilled by m's agent.

func (*Machine) Life

func (m *Machine) Life() Life

Life returns whether the machine is Alive, Dying or Dead.

func (*Machine) LinkLayerDevice

func (m *Machine) LinkLayerDevice(name string) (*LinkLayerDevice, error)

LinkLayerDevice returns the link-layer device matching the given name. An error satisfying errors.IsNotFound() is returned when no such device exists on the machine.

func (*Machine) MachineAddresses

func (m *Machine) MachineAddresses() (addresses []network.Address)

MachineAddresses returns any hostnames and ips associated with a machine, determined by asking the machine itself.

func (*Machine) MachineTag

func (m *Machine) MachineTag() names.MachineTag

MachineTag returns the more specific MachineTag type as opposed to the more generic Tag type.

func (*Machine) MarkForRemoval

func (m *Machine) MarkForRemoval() (err error)

MarkForRemoval requests that this machine be removed after any needed provider-level cleanup is done.

func (*Machine) OpenedPorts

func (m *Machine) OpenedPorts(subnetID string) (*Ports, error)

OpenedPorts returns this machine ports document for the given subnetID.

func (*Machine) ParentId

func (m *Machine) ParentId() (string, bool)

ParentId returns the Id of the host machine if this machine is a container.

func (*Machine) PasswordValid

func (m *Machine) PasswordValid(password string) bool

PasswordValid returns whether the given password is valid for the given machine.

func (*Machine) PendingActions

func (m *Machine) PendingActions() ([]Action, error)

PendingActions is part of the ActionReceiver interface.

func (*Machine) Placement

func (m *Machine) Placement() string

Placement returns the machine's Placement structure that should be used when provisioning an instance for the machine.

func (*Machine) Principals

func (m *Machine) Principals() []string

Principals returns the principals for the machine.

func (*Machine) PrivateAddress

func (m *Machine) PrivateAddress() (network.Address, error)

PrivateAddress returns a private address for the machine. If no address is available it returns an error that satisfies network.IsNoAddressError().

func (*Machine) ProviderAddresses

func (m *Machine) ProviderAddresses() (addresses []network.Address)

ProviderAddresses returns any hostnames and ips associated with a machine, as determined by asking the provider.

func (*Machine) PublicAddress

func (m *Machine) PublicAddress() (network.Address, error)

PublicAddress returns a public address for the machine. If no address is available it returns an error that satisfies network.IsNoAddressError().

func (*Machine) Refresh

func (m *Machine) Refresh() error

Refresh refreshes the contents of the machine from the underlying state. It returns an error that satisfies errors.IsNotFound if the machine has been removed.

func (*Machine) Remove

func (m *Machine) Remove() (err error)

Remove removes the machine from state. It will fail if the machine is not Dead.

func (*Machine) RemoveAllAddresses

func (m *Machine) RemoveAllAddresses() error

RemoveAllAddresses removes all assigned addresses to all devices of the machine, in a single transaction. No error is returned when some or all of the addresses were already removed.

func (*Machine) RemoveAllLinkLayerDevices

func (m *Machine) RemoveAllLinkLayerDevices() error

RemoveAllLinkLayerDevices removes all existing link-layer devices of the machine in a single transaction. No error is returned when some or all of the devices were already removed.

func (*Machine) RunningActions

func (m *Machine) RunningActions() ([]Action, error)

RunningActions is part of the ActionReceiver interface.

func (*Machine) Series

func (m *Machine) Series() string

Series returns the operating system series running on the machine.

func (*Machine) SetAgentPresence

func (m *Machine) SetAgentPresence() (*presence.Pinger, error)

SetAgentPresence signals that the agent for machine m is alive. It returns the started pinger.

func (*Machine) SetAgentVersion

func (m *Machine) SetAgentVersion(v version.Binary) (err error)

SetAgentVersion sets the version of juju that the agent is currently running.

func (*Machine) SetConstraints

func (m *Machine) SetConstraints(cons constraints.Value) (err error)

SetConstraints sets the exact constraints to apply when provisioning an instance for the machine. It will fail if the machine is Dead, or if it is already provisioned.

func (*Machine) SetContainerLinkLayerDevices

func (m *Machine) SetContainerLinkLayerDevices(containerMachine *Machine) error

SetContainerLinkLayerDevices sets the link-layer devices of the given containerMachine, setting each device linked to the corresponding BridgeDevice of the host machine m.

func (*Machine) SetDevicesAddresses

func (m *Machine) SetDevicesAddresses(devicesAddresses ...LinkLayerDeviceAddress) (err error)

SetDevicesAddresses sets the addresses of all devices in devicesAddresses, adding new or updating existing assignments as needed, in a single transaction. ProviderID field can be empty if not supported by the provider, but when set must be unique within the model. Errors are returned in the following cases:

  • Machine is no longer alive or is missing;
  • Subnet inferred from any CIDRAddress field in args is known but no longer alive (no error reported if the CIDRAddress does not match a known subnet);
  • Model no longer alive;
  • errors.NotValidError, when any of the fields in args contain invalid values;
  • errors.NotFoundError, when any DeviceName in args refers to unknown device;
  • ErrProviderIDNotUnique, when one or more specified ProviderIDs are not unique.

func (*Machine) SetDevicesAddressesIdempotently

func (m *Machine) SetDevicesAddressesIdempotently(devicesAddresses []LinkLayerDeviceAddress) error

SetDevicesAddressesIdempotently calls SetDevicesAddresses() and if it fails with ErrProviderIDNotUnique, retries the call with all ProviderID fields in devicesAddresses set to empty.

func (*Machine) SetHasVote

func (m *Machine) SetHasVote(hasVote bool) error

SetHasVote sets whether the machine is currently a voting member of the replica set. It should only be called from the worker that maintains the replica set.

func (*Machine) SetInstanceInfo

func (m *Machine) SetInstanceInfo(
	id instance.Id, nonce string, characteristics *instance.HardwareCharacteristics,
	devicesArgs []LinkLayerDeviceArgs, devicesAddrs []LinkLayerDeviceAddress,
	volumes map[names.VolumeTag]VolumeInfo,
	volumeAttachments map[names.VolumeTag]VolumeAttachmentInfo,
) error

SetInstanceInfo is used to provision a machine and in one steps set it's instance id, nonce, hardware characteristics, add link-layer devices and set their addresses as needed.

func (*Machine) SetInstanceStatus

func (m *Machine) SetInstanceStatus(sInfo status.StatusInfo) (err error)

SetInstanceStatus sets the provider specific instance status for a machine.

func (*Machine) SetLinkLayerDevices

func (m *Machine) SetLinkLayerDevices(devicesArgs ...LinkLayerDeviceArgs) (err error)

SetLinkLayerDevices sets link-layer devices on the machine, adding or updating existing devices as needed, in a single transaction. ProviderID field can be empty if not supported by the provider, but when set must be unique within the model, and cannot be unset once set. Errors are returned in the following cases: - Machine is no longer alive or is missing; - Model no longer alive; - errors.NotValidError, when any of the fields in args contain invalid values; - ErrProviderIDNotUnique, when one or more specified ProviderIDs are not unique; Setting new parent devices must be done in a separate call than setting their children on the same machine.

func (*Machine) SetMachineAddresses

func (m *Machine) SetMachineAddresses(addresses ...network.Address) (err error)

SetMachineAddresses records any addresses related to the machine, sourced by asking the machine.

func (*Machine) SetMachineBlockDevices

func (m *Machine) SetMachineBlockDevices(info ...BlockDeviceInfo) error

SetMachineBlockDevices sets the block devices visible on the machine.

func (*Machine) SetMongoPassword

func (m *Machine) SetMongoPassword(password string) error

SetMongoPassword sets the password the agent responsible for the machine should use to communicate with the controllers. Previous passwords are invalidated.

func (*Machine) SetParentLinkLayerDevicesBeforeTheirChildren

func (m *Machine) SetParentLinkLayerDevicesBeforeTheirChildren(devicesArgs []LinkLayerDeviceArgs) error

SetParentLinkLayerDevicesBeforeTheirChildren splits the given devicesArgs into multiple sets of args and calls SetLinkLayerDevices() for each set, such that child devices are set only after their parents.

func (*Machine) SetPassword

func (m *Machine) SetPassword(password string) error

SetPassword sets the password for the machine's agent.

func (*Machine) SetProviderAddresses

func (m *Machine) SetProviderAddresses(addresses ...network.Address) (err error)

SetProviderAddresses records any addresses related to the machine, sourced by asking the provider.

func (*Machine) SetProvisioned

func (m *Machine) SetProvisioned(id instance.Id, nonce string, characteristics *instance.HardwareCharacteristics) (err error)

SetProvisioned sets the provider specific machine id, nonce and also metadata for this machine. Once set, the instance id cannot be changed.

When provisioning an instance, a nonce should be created and passed when starting it, before adding the machine to the state. This means that if the provisioner crashes (or its connection to the state is lost) after starting the instance, we can be sure that only a single instance will be able to act for that machine.

func (*Machine) SetRebootFlag

func (m *Machine) SetRebootFlag(flag bool) error

SetRebootFlag sets the reboot flag of a machine to a boolean value. It will also do a lazy create of a reboot document if needed; i.e. If a document does not exist yet for this machine, it will create it.

func (*Machine) SetStatus

func (m *Machine) SetStatus(statusInfo status.StatusInfo) error

SetStatus sets the status of the machine.

func (*Machine) SetStopMongoUntilVersion

func (m *Machine) SetStopMongoUntilVersion(v mongo.Version) error

SetStopMongoUntilVersion sets a version that is to be checked against the agent config before deciding if mongo must be started on a state server.

func (*Machine) SetSupportedContainers

func (m *Machine) SetSupportedContainers(containers []instance.ContainerType) (err error)

SetSupportedContainers sets the list of containers supported by this machine.

func (*Machine) ShouldRebootOrShutdown

func (m *Machine) ShouldRebootOrShutdown() (RebootAction, error)

ShouldRebootOrShutdown check if the current node should reboot or shutdown If we are a container, and our parent needs to reboot, this should return: ShouldShutdown

func (*Machine) Status

func (m *Machine) Status() (status.StatusInfo, error)

Status returns the status of the machine.

func (*Machine) StatusHistory

func (m *Machine) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

StatusHistory returns a slice of at most filter.Size StatusInfo items or items as old as filter.Date or items newer than now - filter.Delta time representing past statuses for this machine.

func (*Machine) StopMongoUntilVersion

func (m *Machine) StopMongoUntilVersion() (mongo.Version, error)

StopMongoUntilVersion returns the current minimum version that is required for this machine to have mongo running.

func (*Machine) String

func (m *Machine) String() string

String returns a unique description of this machine.

func (*Machine) SupportedContainers

func (m *Machine) SupportedContainers() ([]instance.ContainerType, bool)

SupportedContainers returns any containers this machine is capable of hosting, and a bool indicating if the supported containers have been determined or not.

func (*Machine) SupportsNoContainers

func (m *Machine) SupportsNoContainers() (err error)

SupportsNoContainers records the fact that this machine doesn't support any containers.

func (*Machine) Tag

func (m *Machine) Tag() names.Tag

Tag returns a tag identifying the machine. The String method provides a string representation that is safe to use as a file name. The returned name will be different from other Tag values returned by any other entities from the same state.

func (*Machine) Units

func (m *Machine) Units() (units []*Unit, err error)

Units returns all the units that have been assigned to the machine.

func (*Machine) VolumeAttachments

func (m *Machine) VolumeAttachments() ([]VolumeAttachment, error)

VolumeAttachments returns the machine's volume attachments.

func (*Machine) WaitAgentPresence

func (m *Machine) WaitAgentPresence(timeout time.Duration) (err error)

WaitAgentPresence blocks until the respective agent is alive.

func (*Machine) WantsVote

func (m *Machine) WantsVote() bool

WantsVote reports whether the machine is a controller that wants to take part in peer voting.

func (*Machine) Watch

func (m *Machine) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a machine.

func (*Machine) WatchActionNotifications

func (m *Machine) WatchActionNotifications() StringsWatcher

WatchActionNotifications is part of the ActionReceiver interface.

func (*Machine) WatchAddresses

func (m *Machine) WatchAddresses() NotifyWatcher

WatchAddresses returns a new NotifyWatcher watching m's addresses.

func (*Machine) WatchAllContainers

func (m *Machine) WatchAllContainers() StringsWatcher

WatchAllContainers returns a StringsWatcher that notifies of changes to the lifecycles of all containers on a machine.

func (*Machine) WatchContainers

func (m *Machine) WatchContainers(ctype instance.ContainerType) StringsWatcher

WatchContainers returns a StringsWatcher that notifies of changes to the lifecycles of containers of the specified type on a machine.

func (*Machine) WatchForRebootEvent

func (m *Machine) WatchForRebootEvent() NotifyWatcher

WatchForRebootEvent returns a notify watcher that will trigger an event when the reboot flag is set on our machine agent, our parent machine agent or grandparent machine agent

func (*Machine) WatchHardwareCharacteristics

func (m *Machine) WatchHardwareCharacteristics() NotifyWatcher

WatchHardwareCharacteristics returns a watcher for observing changes to a machine's hardware characteristics.

func (*Machine) WatchPrincipalUnits

func (m *Machine) WatchPrincipalUnits() StringsWatcher

WatchPrincipalUnits returns a StringsWatcher tracking the machine's principal units.

func (*Machine) WatchUnits

func (m *Machine) WatchUnits() StringsWatcher

WatchUnits returns a new StringsWatcher watching m's units.

type MachineFilesystemParams

type MachineFilesystemParams struct {
	Filesystem FilesystemParams
	Attachment FilesystemAttachmentParams
}

MachineFilesystemParams holds the parameters for creating a filesystem and attaching it to a new machine.

type MachineJob

type MachineJob int

MachineJob values define responsibilities that machines may be expected to fulfil.

const (
	JobHostUnits MachineJob
	JobManageModel
)

func AllJobs

func AllJobs() []MachineJob

AllJobs returns all supported machine jobs.

func (MachineJob) MigrationValue

func (job MachineJob) MigrationValue() string

MigrationValue converts the state job into a useful human readable string for model migration.

func (MachineJob) String

func (job MachineJob) String() string

func (MachineJob) ToParams

func (job MachineJob) ToParams() multiwatcher.MachineJob

ToParams returns the job as multiwatcher.MachineJob.

type MachineTemplate

type MachineTemplate struct {
	// Series is the series to be associated with the new machine.
	Series string

	// Constraints are the constraints to be used when finding
	// an instance for the machine.
	Constraints constraints.Value

	// Jobs holds the jobs to run on the machine's instance.
	// A machine must have at least one job to do.
	// JobManageModel can only be part of the jobs
	// when the first (bootstrap) machine is added.
	Jobs []MachineJob

	// NoVote holds whether a machine running
	// a controller should abstain from peer voting.
	// It is ignored if Jobs does not contain JobManageModel.
	NoVote bool

	// Addresses holds the addresses to be associated with the
	// new machine.
	//
	// TODO(dimitern): This should be removed once all addresses
	// come from link-layer device addresses.
	Addresses []network.Address

	// InstanceId holds the instance id to associate with the machine.
	// If this is empty, the provisioner will try to provision the machine.
	// If this is non-empty, the HardwareCharacteristics and Nonce
	// fields must be set appropriately.
	InstanceId instance.Id

	// HardwareCharacteristics holds the h/w characteristics to
	// be associated with the machine.
	HardwareCharacteristics instance.HardwareCharacteristics

	// LinkLayerDevices holds a list of arguments for setting link-layer devices
	// on the machine.
	LinkLayerDevices []LinkLayerDeviceArgs

	// Volumes holds the parameters for volumes that are to be created
	// and attached to the machine.
	Volumes []MachineVolumeParams

	// VolumeAttachments holds the parameters for attaching existing
	// volumes to the machine.
	VolumeAttachments map[names.VolumeTag]VolumeAttachmentParams

	// Filesystems holds the parameters for filesystems that are to be
	// created and attached to the machine.
	Filesystems []MachineFilesystemParams

	// FilesystemAttachments holds the parameters for attaching existing
	// filesystems to the machine.
	FilesystemAttachments map[names.FilesystemTag]FilesystemAttachmentParams

	// Nonce holds a unique value that can be used to check
	// if a new instance was really started for this machine.
	// See Machine.SetProvisioned. This must be set if InstanceId is set.
	Nonce string

	// Dirty signifies whether the new machine will be treated
	// as unclean for unit-assignment purposes.
	Dirty bool

	// Placement holds the placement directive that will be associated
	// with the machine.
	Placement string
	// contains filtered or unexported fields
}

MachineTemplate holds attributes that are to be associated with a newly created machine.

type MachineVolumeParams

type MachineVolumeParams struct {
	Volume     VolumeParams
	Attachment VolumeAttachmentParams
}

MachineVolumeParams holds the parameters for creating a volume and attaching it to a new machine.

type MeterStatus

type MeterStatus struct {
	Code MeterStatusCode
	Info string
}

MeterStatus represents the metering status of a unit.

func (*MeterStatus) Severity

func (m *MeterStatus) Severity() int

Severity returns relative severity of the meter status.

type MeterStatusCode

type MeterStatusCode int

MeterStatusCode represents the meter status code of a unit. The int value represents its relative severity when compared to other MeterStatusCodes.

const (
	MeterNotAvailable MeterStatusCode = iota
	MeterRed
	MeterAmber
	MeterNotSet
	MeterGreen
)

This const block defines the relative severities of the valid MeterStatusCodes in ascending order.

func MeterStatusFromString

func MeterStatusFromString(str string) MeterStatusCode

MeterStatusFromString returns a valid MeterStatusCode given a string representation.

func (MeterStatusCode) Severity

func (m MeterStatusCode) Severity() int

Severity returns the relative severity.

func (MeterStatusCode) String

func (m MeterStatusCode) String() string

String returns a human readable string representation of the meter status.

type Metric

type Metric struct {
	Key   string    `bson:"key"`
	Value string    `bson:"value"`
	Time  time.Time `bson:"time"`
}

Metric represents a single Metric.

type MetricBatch

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

MetricBatch represents a batch of metrics reported from a unit. These will be received from the unit in batches. The main contents of the metric (key, value) is defined by the charm author and sent from the unit via a call to add-metric

func (*MetricBatch) CharmURL

func (m *MetricBatch) CharmURL() string

CharmURL returns the charm url for the charm this metric was generated in.

func (*MetricBatch) Created

func (m *MetricBatch) Created() time.Time

Created returns the time this metric batch was created.

func (*MetricBatch) Credentials

func (m *MetricBatch) Credentials() []byte

Credentials returns any credentials associated with the metric batch.

func (*MetricBatch) MarshalJSON

func (m *MetricBatch) MarshalJSON() ([]byte, error)

MarshalJSON defines how the MetricBatch type should be converted to json.

func (*MetricBatch) Metrics

func (m *MetricBatch) Metrics() []Metric

Metrics returns the metrics in this batch.

func (*MetricBatch) ModelUUID

func (m *MetricBatch) ModelUUID() string

ModelUUID returns the model UUID this metric applies to.

func (*MetricBatch) Sent

func (m *MetricBatch) Sent() bool

Sent returns a flag to tell us if this metric has been sent to the metric collection service

func (*MetricBatch) SetSent

func (m *MetricBatch) SetSent(t time.Time) error

SetSent marks the metric has having been sent at the specified time.

func (*MetricBatch) UUID

func (m *MetricBatch) UUID() string

UUID returns to uuid of the metric.

func (*MetricBatch) UniqueMetrics

func (m *MetricBatch) UniqueMetrics() []Metric

UniqueMetrics returns only the last value for each metric key in this batch.

func (*MetricBatch) Unit

func (m *MetricBatch) Unit() string

Unit returns the name of the unit this metric was generated in.

type MetricsManager

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

MetricsManager stores data about the state of the metrics manager

func (*MetricsManager) ConsecutiveErrors

func (m *MetricsManager) ConsecutiveErrors() int

ConsecutiveErrors returns the number of consecutive failures.

func (*MetricsManager) GracePeriod

func (m *MetricsManager) GracePeriod() time.Duration

GracePeriod returns the current grace period.

func (*MetricsManager) IncrementConsecutiveErrors

func (m *MetricsManager) IncrementConsecutiveErrors() error

IncrementConsecutiveErrors adds 1 to the consecutive errors count.

func (*MetricsManager) LastSuccessfulSend

func (m *MetricsManager) LastSuccessfulSend() time.Time

LastSuccessfulSend returns the time of the last successful send.

func (*MetricsManager) MeterStatus

func (m *MetricsManager) MeterStatus() MeterStatus

MeterStatus returns the overall state of the MetricsManager as a meter status summary.

func (*MetricsManager) SetGracePeriod

func (m *MetricsManager) SetGracePeriod(t time.Duration) error

func (*MetricsManager) SetLastSuccessfulSend

func (m *MetricsManager) SetLastSuccessfulSend(t time.Time) error

SetLastSuccessfulSend sets the last successful send time to the input time.

type MigrationMode

type MigrationMode string

MigrationMode specifies where the Model is with respect to migration.

const (
	// MigrationModeNone is the default mode for a model and reflects
	// that it isn't involved with a model migration.
	MigrationModeNone MigrationMode = ""

	// MigrationModeExporting reflects a model that is in the process of being
	// exported from one controller to another.
	MigrationModeExporting MigrationMode = "exporting"

	// MigrationModeImporting reflects a model that is being imported into a
	// controller, but is not yet fully active.
	MigrationModeImporting MigrationMode = "importing"
)

type MigrationSpec

type MigrationSpec struct {
	InitiatedBy     names.UserTag
	TargetInfo      migration.TargetInfo
	ExternalControl bool
}

MigrationSpec holds the information required to create a ModelMigration instance.

func (*MigrationSpec) Validate

func (spec *MigrationSpec) Validate() error

Validate returns an error if the MigrationSpec contains bad data. Nil is returned otherwise.

type MinionReports

type MinionReports struct {
	Succeeded []names.Tag
	Failed    []names.Tag
	Unknown   []names.Tag
}

MinionReports indicates the sets of agents whose migration minion workers have completed the current migration phase, have failed to complete the current migration phase, or are yet to report regarding the current migration phase.

type Model

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

Model represents the state of a model.

func (*Model) Cloud

func (m *Model) Cloud() string

Cloud returns the name of the cloud to which the model is deployed.

func (*Model) CloudCredential

func (m *Model) CloudCredential() (names.CloudCredentialTag, bool)

CloudCredential returns the tag of the cloud credential used for managing the model's cloud resources, and a boolean indicating whether a credential is set.

func (*Model) CloudRegion

func (m *Model) CloudRegion() string

CloudRegion returns the name of the cloud region to which the model is deployed.

func (*Model) Config

func (m *Model) Config() (*config.Config, error)

Config returns the config for the model.

func (*Model) ConfigValues

func (m *Model) ConfigValues() (config.ConfigValues, error)

ConfigValues returns the config values for the model.

func (*Model) ControllerTag

func (m *Model) ControllerTag() names.ControllerTag

ControllerTag is the tag for the controller that the model is running within.

func (*Model) ControllerUUID

func (m *Model) ControllerUUID() string

ControllerUUID returns the universally unique identifier of the controller in which the model is running.

func (*Model) Destroy

func (m *Model) Destroy() error

Destroy sets the models's lifecycle to Dying, preventing addition of services or machines to state. If called on an empty hosted model, the lifecycle will be advanced straight to Dead.

If called on a controller model, and that controller is hosting any non-Dead models, this method will return an error satisfying IsHasHostedsError.

func (*Model) DestroyIncludingHosted

func (m *Model) DestroyIncludingHosted() error

DestroyIncludingHosted sets the model's lifecycle to Dying, preventing addition of services or machines to state. If this model is a controller hosting other models, they will also be destroyed.

func (*Model) LatestToolsVersion

func (m *Model) LatestToolsVersion() version.Number

LatestToolsVersion returns the newest version found in the last check in the streams. Bear in mind that the check was performed filtering only new patches for the current major.minor. (major.minor.patch)

func (*Model) Life

func (m *Model) Life() Life

Life returns whether the model is Alive, Dying or Dead.

func (*Model) MigrationMode

func (m *Model) MigrationMode() MigrationMode

MigrationMode returns whether the model is active or being migrated.

func (*Model) ModelTag

func (m *Model) ModelTag() names.ModelTag

ModelTag is the concrete model tag for this model.

func (*Model) Name

func (m *Model) Name() string

Name returns the human friendly name of the model.

func (*Model) Owner

func (m *Model) Owner() names.UserTag

Owner returns tag representing the owner of the model. The owner is the user that created the model.

func (*Model) Refresh

func (m *Model) Refresh() error

func (*Model) SetMigrationMode

func (m *Model) SetMigrationMode(mode MigrationMode) error

SetMigrationMode updates the migration mode of the model.

func (*Model) SetStatus

func (m *Model) SetStatus(sInfo status.StatusInfo) error

SetStatus sets the status of the model.

func (*Model) Status

func (m *Model) Status() (status.StatusInfo, error)

Status returns the status of the model.

func (*Model) Tag

func (m *Model) Tag() names.Tag

Tag returns a name identifying the model. The returned name will be different from other Tag values returned by any other entities from the same state.

func (*Model) UUID

func (m *Model) UUID() string

UUID returns the universally unique identifier of the model.

func (*Model) UpdateLatestToolsVersion

func (m *Model) UpdateLatestToolsVersion(ver version.Number) error

UpdateLatestToolsVersion looks up for the latest available version of juju tools and updates environementDoc with it.

func (*Model) Users

func (m *Model) Users() ([]permission.UserAccess, error)

Users returns a slice of all users for this model.

func (*Model) Watch

func (e *Model) Watch() NotifyWatcher

Watch returns a watcher for observing changes to an model.

type ModelAccessor

type ModelAccessor interface {
	WatchForModelConfigChanges() NotifyWatcher
	ModelConfig() (*config.Config, error)
}

ModelAccessor defines the methods needed to watch for model config changes, and read the model config.

type ModelArgs

type ModelArgs struct {
	// CloudName is the name of the cloud to which the model is deployed.
	CloudName string

	// CloudRegion is the name of the cloud region to which the model is
	// deployed. This will be empty for clouds that do not support regions.
	CloudRegion string

	// CloudCredential is the tag of the cloud credential that will be
	// used for managing cloud resources for this model. This will be
	// empty for clouds that do not require credentials.
	CloudCredential names.CloudCredentialTag

	// Config is the model config.
	Config *config.Config

	// Constraints contains the initial constraints for the model.
	Constraints constraints.Value

	// StorageProviderRegistry is used to determine and store the
	// details of the default storage pools.
	StorageProviderRegistry storage.ProviderRegistry

	// Owner is the user that owns the model.
	Owner names.UserTag

	// MigrationMode is the initial migration mode of the model.
	MigrationMode MigrationMode
}

ModelArgs is a params struct for creating a new model.

func (ModelArgs) Validate

func (m ModelArgs) Validate() error

Validate validates the ModelArgs.

type ModelMachinesWatcher

type ModelMachinesWatcher interface {
	WatchModelMachines() StringsWatcher
}

ModelMachinesWatcher defines a single method - WatchModelMachines.

type ModelMigration

type ModelMigration interface {
	// Id returns a unique identifier for the model migration.
	Id() string

	// ModelUUID returns the UUID for the model being migrated.
	ModelUUID() string

	// ExternalControl returns true if the model migration should be
	// managed by an external process.
	ExternalControl() bool

	// Attempt returns the migration attempt identifier. This
	// increments for each migration attempt for the model.
	Attempt() (int, error)

	// StartTime returns the time when the migration was started.
	StartTime() time.Time

	// SuccessTime returns the time when the migration reached
	// SUCCESS.
	SuccessTime() time.Time

	// EndTime returns the time when the migration reached DONE or
	// REAPFAILED.
	EndTime() time.Time

	// Phase returns the migration's phase.
	Phase() (migration.Phase, error)

	// PhaseChangedTime returns the time when the migration's phase
	// last changed.
	PhaseChangedTime() time.Time

	// StatusMessage returns human readable text about the current
	// progress of the migration.
	StatusMessage() string

	// InitiatedBy returns username the initiated the migration.
	InitiatedBy() string

	// TargetInfo returns the details required to connect to the
	// migration's target controller.
	TargetInfo() (*migration.TargetInfo, error)

	// SetPhase sets the phase of the migration. An error will be
	// returned if the new phase does not follow the current phase or
	// if the migration is no longer active.
	SetPhase(nextPhase migration.Phase) error

	// SetStatusMessage sets some human readable text about the
	// current progress of the migration.
	SetStatusMessage(text string) error

	// SubmitMinionReport records a report from a migration minion
	// worker about the success or failure to complete its actions for
	// a given migration phase.
	SubmitMinionReport(tag names.Tag, phase migration.Phase, success bool) error

	// MinionReports returns details of the minions that have reported
	// success or failure for the current migration phase, as well as
	// those which are yet to report.
	MinionReports() (*MinionReports, error)

	// WatchMinionReports returns a notify watcher which triggers when
	// a migration minion has reported back about the success or failure
	// of its actions for the current migration phase.
	WatchMinionReports() (NotifyWatcher, error)

	// Refresh updates the contents of the ModelMigration from the
	// underlying state.
	Refresh() error
}

ModelMigration represents the state of an migration attempt for a model.

type ModelPayloads

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

ModelPayloads lets you read all unit payloads in a model.

func (ModelPayloads) ListAll

func (mp ModelPayloads) ListAll() ([]payload.FullPayloadInfo, error)

ListAll builds the list of payload information that is registered in state.

type ModelSessioner

type ModelSessioner interface {
	MongoSessioner

	// ModelUUID returns the ID of the current model.
	ModelUUID() string
}

ModelSessioner supports creating new mongo sessions for a model.

type MongoSessioner

type MongoSessioner interface {
	// MongoSession creates a new Mongo session.
	MongoSession() *mgo.Session
}

MongoSessioner supports creating new mongo sessions.

type MongoSpaceStates

type MongoSpaceStates string
const (
	MongoSpaceUnknown     MongoSpaceStates = ""
	MongoSpaceValid       MongoSpaceStates = "valid"
	MongoSpaceInvalid     MongoSpaceStates = "invalid"
	MongoSpaceUnsupported MongoSpaceStates = "unsupported"
)

type Multiwatcher

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

Multiwatcher watches any changes to the state.

func NewMultiwatcher

func NewMultiwatcher(all *storeManager) *Multiwatcher

NewMultiwatcher creates a new watcher that can observe changes to an underlying store manager.

func (*Multiwatcher) Next

func (w *Multiwatcher) Next() ([]multiwatcher.Delta, error)

Next retrieves all changes that have happened since the last time it was called, blocking until there are some changes available.

The result from the initial call to Next() is different from subsequent calls. The latter will reflect changes that have happened since the last Next() call. In contrast, the initial Next() call will return the deltas that represent the model's complete state at that moment, even when the model is empty. In that empty model case an empty set of deltas is returned.

func (*Multiwatcher) Stop

func (w *Multiwatcher) Stop() error

Stop stops the watcher.

type NeverConnectedError

type NeverConnectedError string

NeverConnectedError is used to indicate that a user has never connected to an model.

func (NeverConnectedError) Error

func (e NeverConnectedError) Error() string

Error returns the error string for a user who has never connected to an model.

type NeverLoggedInError

type NeverLoggedInError string

NeverLoggedInError is used to indicate that a user has never logged in.

func (NeverLoggedInError) Error

func (e NeverLoggedInError) Error() string

Error returns the error string for a user who has never logged in.

type NewPolicyFunc

type NewPolicyFunc func(*State) Policy

NewPolicyFunc is the type of a function that, given a *State, returns a Policy for that State.

type NotifyWatcher

type NotifyWatcher interface {
	Watcher
	Changes() <-chan struct{}
}

NotifyWatcher generates signals when something changes, but it does not return any content for those changes

type NotifyWatcherFactory

type NotifyWatcherFactory interface {
	Watch() NotifyWatcher
}

NotifyWatcherFactory represents an entity that can be watched.

type Origin

type Origin string

Origin specifies where an address comes from, whether it was reported by a provider or by a machine.

const (
	// Address origin unknown.
	OriginUnknown Origin = ""
	// Address comes from a provider.
	OriginProvider Origin = "provider"
	// Address comes from a machine.
	OriginMachine Origin = "machine"
)

type Persistence

type Persistence interface {
	// One populates doc with the document corresponding to the given
	// ID. Missing documents result in errors.NotFound.
	One(collName, id string, doc interface{}) error

	// All populates docs with the list of the documents corresponding
	// to the provided query.
	All(collName string, query, docs interface{}) error

	// Run runs the transaction generated by the provided factory
	// function. It may be retried several times.
	Run(transactions jujutxn.TransactionSource) error

	// NewStorage returns a new blob storage for the environment.
	NewStorage() storage.Storage

	// ApplicationExistsOps returns the operations that verify that the
	// identified application exists.
	ApplicationExistsOps(applicationID string) []txn.Op

	// IncCharmModifiedVersionOps returns the operations necessary to increment
	// the CharmModifiedVersion field for the given application.
	IncCharmModifiedVersionOps(applicationID string) []txn.Op

	// NewCleanupOp creates a mgo transaction operation that queues up
	// some cleanup action in state.
	NewCleanupOp(kind, prefix string) txn.Op
}

Persistence exposes persistence-layer functionality of State.

type Policy

type Policy interface {
	// Prechecker returns a Prechecker or an error.
	Prechecker() (Prechecker, error)

	// ProviderConfigSchemaSource returns a config.ConfigSchemaSource
	// for the environ provider, or an error.
	ProviderConfigSchemaSource() (config.ConfigSchemaSource, error)

	// ConfigValidator returns a config.Validator or an error.
	ConfigValidator() (config.Validator, error)

	// ConstraintsValidator returns a constraints.Validator or an error.
	ConstraintsValidator() (constraints.Validator, error)

	// InstanceDistributor returns an instance.Distributor or an error.
	InstanceDistributor() (instance.Distributor, error)

	// StorageProviderRegistry returns a storage.ProviderRegistry or an error.
	StorageProviderRegistry() (storage.ProviderRegistry, error)
}

Policy is an interface provided to State that may be consulted by State to validate or modify the behaviour of certain operations.

If a Policy implementation does not implement one of the methods, it must return an error that satisfies errors.IsNotImplemented, and will thus be ignored. Any other error will cause an error in the use of the policy.

type PortRange

type PortRange struct {
	UnitName string
	FromPort int
	ToPort   int
	Protocol string
}

PortRange represents a single range of ports opened by one unit.

func NewPortRange

func NewPortRange(unitName string, fromPort, toPort int, protocol string) (PortRange, error)

NewPortRange create a new port range and validate it.

func PortRangeFromNetworkPortRange

func PortRangeFromNetworkPortRange(unitName string, portRange network.PortRange) (PortRange, error)

PortRangeFromNetworkPortRange constructs a state.PortRange from the given unitName and network.PortRange.

func (PortRange) CheckConflicts

func (prA PortRange) CheckConflicts(prB PortRange) error

CheckConflicts determines if the two port ranges conflict.

func (PortRange) Length

func (a PortRange) Length() int

Length returns the number of ports in the range. If the range is not valid, it returns 0.

func (PortRange) SanitizeBounds

func (a PortRange) SanitizeBounds() PortRange

Sanitize returns a copy of the port range, which is guaranteed to have FromPort >= ToPort and both FromPort and ToPort fit into the valid range from 1 to 65535, inclusive.

func (PortRange) String

func (p PortRange) String() string

Strings returns the port range as a string.

func (PortRange) Validate

func (p PortRange) Validate() error

Validate checks if the port range is valid.

type Ports

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

Ports represents the state of ports on a machine.

func (*Ports) AllPortRanges

func (p *Ports) AllPortRanges() map[network.PortRange]string

AllPortRanges returns a map with network.PortRange as keys and unit names as values.

func (*Ports) ClosePorts

func (p *Ports) ClosePorts(portRange PortRange) (err error)

ClosePorts removes the specified port range from the list of ports maintained by this document.

func (*Ports) OpenPorts

func (p *Ports) OpenPorts(portRange PortRange) (err error)

OpenPorts adds the specified port range to the list of ports maintained by this document.

func (*Ports) PortsForUnit

func (p *Ports) PortsForUnit(unitName string) []PortRange

PortsForUnit returns the ports associated with specified unitName that are maintained on this document (i.e. are open on this unit's assigned machine).

func (*Ports) Refresh

func (p *Ports) Refresh() error

Refresh refreshes the port document from state.

func (*Ports) Remove

func (p *Ports) Remove() error

Remove removes the ports document from state.

func (*Ports) String

func (p *Ports) String() string

String returns p as a user-readable string.

func (*Ports) SubnetID

func (p *Ports) SubnetID() string

SubnetID returns the subnet ID associated with this ports document.

type Prechecker

type Prechecker interface {
	// PrecheckInstance performs a preflight check on the specified
	// series and constraints, ensuring that they are possibly valid for
	// creating an instance in this model.
	//
	// PrecheckInstance is best effort, and not guaranteed to eliminate
	// all invalid parameters. If PrecheckInstance returns nil, it is not
	// guaranteed that the constraints are valid; if a non-nil error is
	// returned, then the constraints are definitely invalid.
	PrecheckInstance(series string, cons constraints.Value, placement string) error
}

Prechecker is a policy interface that is provided to State to perform pre-flight checking of instance creation.

type RebootAction

type RebootAction string

RebootAction defines the action a machine should take when a hook needs to reboot

const (
	// ShouldDoNothing instructs a machine agent that no action
	// is required on its part
	ShouldDoNothing RebootAction = "noop"
	// ShouldReboot instructs a machine to reboot
	// this happens when a hook running on a machine, requests
	// a reboot
	ShouldReboot RebootAction = "reboot"
	// ShouldShutdown instructs a machine to shut down. This usually
	// happens when running inside a container, and a hook on the parent
	// machine requests a reboot
	ShouldShutdown RebootAction = "shutdown"
)

type RebootActionGetter

type RebootActionGetter interface {
	ShouldRebootOrShutdown() (RebootAction, error)
}

type RebootFlagSetter

type RebootFlagSetter interface {
	SetRebootFlag(flag bool) error
}

type Relation

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

Relation represents a relation between one or two service endpoints.

func (*Relation) Destroy

func (r *Relation) Destroy() (err error)

Destroy ensures that the relation will be removed at some point; if no units are currently in scope, it will be removed immediately.

func (*Relation) Endpoint

func (r *Relation) Endpoint(applicationname string) (Endpoint, error)

Endpoint returns the endpoint of the relation for the named service. If the service is not part of the relation, an error will be returned.

func (*Relation) Endpoints

func (r *Relation) Endpoints() []Endpoint

Endpoints returns the endpoints for the relation.

func (*Relation) Id

func (r *Relation) Id() int

Id returns the integer internal relation key. This is exposed because the unit agent needs to expose a value derived from this (as JUJU_RELATION_ID) to allow relation hooks to differentiate between relations with different services.

func (*Relation) Life

func (r *Relation) Life() Life

Life returns the relation's current life state.

func (*Relation) Refresh

func (r *Relation) Refresh() error

Refresh refreshes the contents of the relation from the underlying state. It returns an error that satisfies errors.IsNotFound if the relation has been removed.

func (*Relation) RelatedEndpoints

func (r *Relation) RelatedEndpoints(applicationname string) ([]Endpoint, error)

RelatedEndpoints returns the endpoints of the relation r with which units of the named service will establish relations. If the service is not part of the relation r, an error will be returned.

func (*Relation) String

func (r *Relation) String() string

func (*Relation) Tag

func (r *Relation) Tag() names.Tag

Tag returns a name identifying the relation.

func (*Relation) Unit

func (r *Relation) Unit(u *Unit) (*RelationUnit, error)

Unit returns a RelationUnit for the supplied unit.

type RelationScopeChange

type RelationScopeChange struct {
	Entered []string
	Left    []string
}

RelationScopeChange contains information about units that have entered or left a particular scope.

type RelationScopeWatcher

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

RelationScopeWatcher observes changes to the set of units in a particular relation scope.

func (*RelationScopeWatcher) Changes

func (w *RelationScopeWatcher) Changes() <-chan *RelationScopeChange

Changes returns a channel that will receive changes when units enter and leave a relation scope. The Entered field in the first event on the channel holds the initial state.

func (*RelationScopeWatcher) Err

func (w *RelationScopeWatcher) Err() error

Err returns any error encountered while running or shutting down, or tomb.ErrStillAlive if the watcher is still running.

func (*RelationScopeWatcher) Kill

func (w *RelationScopeWatcher) Kill()

Kill kills the watcher without waiting for it to shut down.

func (*RelationScopeWatcher) Stop

func (w *RelationScopeWatcher) Stop() error

Stop stops the watcher, and returns any error encountered while running or shutting down.

func (*RelationScopeWatcher) Wait

func (w *RelationScopeWatcher) Wait() error

Wait waits for the watcher to die and returns any error encountered when it was running.

type RelationUnit

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

RelationUnit holds information about a single unit in a relation, and allows clients to conveniently access unit-specific functionality.

func (*RelationUnit) Endpoint

func (ru *RelationUnit) Endpoint() Endpoint

Endpoint returns the relation endpoint that defines the unit's participation in the relation.

func (*RelationUnit) EnterScope

func (ru *RelationUnit) EnterScope(settings map[string]interface{}) error

EnterScope ensures that the unit has entered its scope in the relation. When the unit has already entered its relation scope, EnterScope will report success but make no changes to state.

Otherwise, assuming both the relation and the unit are alive, it will enter scope and create or overwrite the unit's settings in the relation according to the supplied map.

If the unit is a principal and the relation has container scope, EnterScope will also create the required subordinate unit, if it does not already exist; this is because there's no point having a principal in scope if there is no corresponding subordinate to join it.

Once a unit has entered a scope, it stays in scope without further intervention; the relation will not be able to become Dead until all units have departed its scopes.

func (*RelationUnit) InScope

func (ru *RelationUnit) InScope() (bool, error)

InScope returns whether the relation unit has entered scope and not left it.

func (*RelationUnit) Joined

func (ru *RelationUnit) Joined() (bool, error)

Joined returns whether the relation unit has entered scope and neither left it nor prepared to leave it.

func (*RelationUnit) LeaveScope

func (ru *RelationUnit) LeaveScope() error

LeaveScope signals that the unit has left its scope in the relation. After the unit has left its relation scope, it is no longer a member of the relation; if the relation is dying when its last member unit leaves, it is removed immediately. It is not an error to leave a scope that the unit is not, or never was, a member of.

func (*RelationUnit) PrepareLeaveScope

func (ru *RelationUnit) PrepareLeaveScope() error

PrepareLeaveScope causes the unit to be reported as departed by watchers, but does not *actually* leave the scope, to avoid triggering relation cleanup.

func (*RelationUnit) PrivateAddress

func (ru *RelationUnit) PrivateAddress() (network.Address, error)

PrivateAddress returns the private address of the unit.

func (*RelationUnit) ReadSettings

func (ru *RelationUnit) ReadSettings(uname string) (m map[string]interface{}, err error)

ReadSettings returns a map holding the settings of the unit with the supplied name within this relation. An error will be returned if the relation no longer exists, or if the unit's service is not part of the relation, or the settings are invalid; but mere non-existence of the unit is not grounds for an error, because the unit settings are guaranteed to persist for the lifetime of the relation, regardless of the lifetime of the unit.

func (*RelationUnit) Relation

func (ru *RelationUnit) Relation() *Relation

Relation returns the relation associated with the unit.

func (*RelationUnit) Settings

func (ru *RelationUnit) Settings() (*Settings, error)

Settings returns a Settings which allows access to the unit's settings within the relation.

func (*RelationUnit) Watch

func (ru *RelationUnit) Watch() RelationUnitsWatcher

Watch returns a watcher that notifies of changes to conterpart units in the relation.

func (*RelationUnit) WatchScope

func (ru *RelationUnit) WatchScope() *RelationScopeWatcher

WatchScope returns a watcher which notifies of counterpart units entering and leaving the unit's scope.

type RelationUnitsWatcher

type RelationUnitsWatcher interface {
	Watcher

	// Note that it's not very nice exposing a params type directly here. This
	// is a continuation of existing bad behaviour and not good practice; do
	// not use this as a model. (FWIW, it used to be in multiwatcher; which is
	// also api-ey; and the multiwatcher type was used directly in params
	// anyway.)
	Changes() <-chan params.RelationUnitsChange
}

RelationUnitsWatcher generates signals when units enter or leave the scope of a RelationUnit, and changes to the settings of those units known to have entered.

type Remover

type Remover interface {
	Remove() error
}

Remover represents entities with a Remove method.

type ResolvedMode

type ResolvedMode string

ResolvedMode describes the way state transition errors are resolved.

const (
	ResolvedNone       ResolvedMode = ""
	ResolvedRetryHooks ResolvedMode = "retry-hooks"
	ResolvedNoHooks    ResolvedMode = "no-hooks"
)

These are available ResolvedMode values.

type ResourcePersistence

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

ResourcePersistence provides the persistence functionality for the Juju environment as a whole.

func NewResourcePersistence

func NewResourcePersistence(base ResourcePersistenceBase) *ResourcePersistence

NewResourcePersistence wraps the base in a new ResourcePersistence.

func (ResourcePersistence) GetResource

func (p ResourcePersistence) GetResource(id string) (res resource.Resource, storagePath string, _ error)

GetResource returns the extended, model-related info for the non-pending resource.

func (ResourcePersistence) ListPendingResources

func (p ResourcePersistence) ListPendingResources(applicationID string) ([]resource.Resource, error)

ListPendingResources returns the extended, model-related info for each pending resource of the identifies service.

func (ResourcePersistence) ListResources

func (p ResourcePersistence) ListResources(applicationID string) (resource.ServiceResources, error)

ListResources returns the info for each non-pending resource of the identified service.

func (ResourcePersistence) NewRemoveResourcesOps

func (p ResourcePersistence) NewRemoveResourcesOps(applicationID string) ([]txn.Op, error)

NewRemoveResourcesOps returns mgo transaction operations that remove all the service's resources from state.

func (ResourcePersistence) NewRemoveUnitResourcesOps

func (p ResourcePersistence) NewRemoveUnitResourcesOps(unitID string) ([]txn.Op, error)

NewRemoveUnitResourcesOps returns mgo transaction operations that remove resource information specific to the unit from state.

func (ResourcePersistence) NewResolvePendingResourceOps

func (p ResourcePersistence) NewResolvePendingResourceOps(resID, pendingID string) ([]txn.Op, error)

NewResolvePendingResourceOps generates mongo transaction operations to set the identified resource as active.

Leaking mongo details (transaction ops) is a necessary evil since we do not have any machinery to facilitate transactions between different components.

func (ResourcePersistence) SetCharmStoreResource

func (p ResourcePersistence) SetCharmStoreResource(id, applicationID string, res charmresource.Resource, lastPolled time.Time) error

SetCharmStoreResource stores the resource info that was retrieved from the charm store.

func (ResourcePersistence) SetResource

func (p ResourcePersistence) SetResource(res resource.Resource) error

SetResource sets the info for the resource.

func (ResourcePersistence) SetUnitResource

func (p ResourcePersistence) SetUnitResource(unitID string, res resource.Resource) error

SetUnitResource stores the resource info for a particular unit. The resource must already be set for the application.

func (ResourcePersistence) SetUnitResourceProgress

func (p ResourcePersistence) SetUnitResourceProgress(unitID string, res resource.Resource, progress int64) error

SetUnitResource stores the resource info for a particular unit. The resource must already be set for the application. The provided progress is stored in the DB.

func (ResourcePersistence) StageResource

func (p ResourcePersistence) StageResource(res resource.Resource, storagePath string) (*StagedResource, error)

StageResource adds the resource in a separate staging area if the resource isn't already staged. If it is then errors.AlreadyExists is returned. A wrapper around the staged resource is returned which supports both finalizing and removing the staged resource.

type ResourcePersistenceBase

type ResourcePersistenceBase interface {
	// One populates doc with the document corresponding to the given
	// ID. Missing documents result in errors.NotFound.
	One(collName, id string, doc interface{}) error

	// All populates docs with the list of the documents corresponding
	// to the provided query.
	All(collName string, query, docs interface{}) error

	// Run runs the transaction generated by the provided factory
	// function. It may be retried several times.
	Run(transactions jujutxn.TransactionSource) error

	// ApplicationExistsOps returns the operations that verify that the
	// identified application exists.
	ApplicationExistsOps(applicationID string) []txn.Op

	// IncCharmModifiedVersionOps returns the operations necessary to increment
	// the CharmModifiedVersion field for the given application.
	IncCharmModifiedVersionOps(applicationID string) []txn.Op

	// NewCleanupOp creates a mgo transaction operation that queues up
	// some cleanup action in state.
	NewCleanupOp(kind, prefix string) txn.Op
}

ResourcePersistenceBase exposes the core persistence functionality needed for resources.

type Resources

type Resources interface {
	// ListResources returns the list of resources for the given service.
	ListResources(applicationID string) (resource.ServiceResources, error)

	// AddPendingResource adds the resource to the data store in a
	// "pending" state. It will stay pending (and unavailable) until
	// it is resolved. The returned ID is used to identify the pending
	// resources when resolving it.
	AddPendingResource(applicationID, userID string, chRes charmresource.Resource, r io.Reader) (string, error)

	// GetResource returns the identified resource.
	GetResource(applicationID, name string) (resource.Resource, error)

	// GetPendingResource returns the identified resource.
	GetPendingResource(applicationID, name, pendingID string) (resource.Resource, error)

	// SetResource adds the resource to blob storage and updates the metadata.
	SetResource(applicationID, userID string, res charmresource.Resource, r io.Reader) (resource.Resource, error)

	// UpdatePendingResource adds the resource to blob storage and updates the metadata.
	UpdatePendingResource(applicationID, pendingID, userID string, res charmresource.Resource, r io.Reader) (resource.Resource, error)

	// OpenResource returns the metadata for a resource and a reader for the resource.
	OpenResource(applicationID, name string) (resource.Resource, io.ReadCloser, error)

	// OpenResourceForUniter returns the metadata for a resource and a reader for the resource.
	OpenResourceForUniter(unit resource.Unit, name string) (resource.Resource, io.ReadCloser, error)

	// SetCharmStoreResources sets the "polled" resources for the
	// service to the provided values.
	SetCharmStoreResources(applicationID string, info []charmresource.Resource, lastPolled time.Time) error

	// NewResolvePendingResourcesOps generates mongo transaction operations
	// to set the identified resources as active.
	NewResolvePendingResourcesOps(applicationID string, pendingIDs map[string]string) ([]txn.Op, error)
}

Resources describes the state functionality for resources.

type ResourcesPersistence

type ResourcesPersistence interface {
	// NewRemoveUnitResourcesOps returns mgo transaction operations
	// that remove resource information specific to the unit from state.
	NewRemoveUnitResourcesOps(unitID string) ([]txn.Op, error)

	// NewRemoveResourcesOps returns mgo transaction operations that
	// remove all the service's resources from state.
	NewRemoveResourcesOps(applicationID string) ([]txn.Op, error)
}

ResourcesPersistence exposes the resources persistence functionality needed by state.

type RestoreInfo

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

RestoreInfo exposes restore status.

func (*RestoreInfo) PurgeTxn

func (info *RestoreInfo) PurgeTxn() error

PurgeTxn purges missing transation from restoreInfoC collection. These can be caused because this collection is heavy use while backing up and mongo 3.2 does not like this.

func (*RestoreInfo) SetStatus

func (info *RestoreInfo) SetStatus(status RestoreStatus) error

SetStatus sets the status of the current restore. Checks are made to ensure that status changes are performed in the correct order.

func (*RestoreInfo) Status

func (info *RestoreInfo) Status() (RestoreStatus, error)

Status returns the current Restore doc status

type RestoreStatus

type RestoreStatus string

RestoreStatus is the type of the statuses

const (

	// RestoreNotActive is not persisted in the database, and is
	// used to indicate the absence of a current restore doc.
	RestoreNotActive RestoreStatus = "NOT-RESTORING"

	// RestorePending is a status to signal that a restore is about
	// to start any change done in this status will be lost.
	RestorePending RestoreStatus = "PENDING"

	// RestoreInProgress indicates that a Restore is in progress.
	RestoreInProgress RestoreStatus = "RESTORING"

	// RestoreFinished it is set by restore upon a succesful run.
	RestoreFinished RestoreStatus = "RESTORED"

	// RestoreChecked is set when the server comes up after a
	// succesful restore.
	RestoreChecked RestoreStatus = "CHECKED"

	// RestoreFailed indicates that the process failed in a
	// recoverable step.
	RestoreFailed RestoreStatus = "FAILED"
)

func (RestoreStatus) Validate

func (status RestoreStatus) Validate() error

Validate returns an errors if status' value is not known.

type SSHHostKeys

type SSHHostKeys []string

SSHHostKeys holds the public SSH host keys for an entity (almost certainly a machine).

The host keys are one line each and are stored in the same format as the SSH authorized_keys and ssh_host_key*.pub files.

type SessionCloser

type SessionCloser func()

type SetCharmConfig

type SetCharmConfig struct {
	// Charm is the new charm to use for the application. New units
	// will be started with this charm, and existing units will be
	// upgraded to use it.
	Charm *Charm

	// Channel is the charm store channel from which charm was pulled.
	Channel csparams.Channel

	// ConfigSettings is the charm config settings to apply when upgrading
	// the charm.
	ConfigSettings charm.Settings

	// ForceUnits forces the upgrade on units in an error state.
	ForceUnits bool

	// ForceSeries forces the use of the charm even if it is not one of
	// the charm's supported series.
	ForceSeries bool

	// ResourceIDs is a map of resource names to resource IDs to activate during
	// the upgrade.
	ResourceIDs map[string]string

	// StorageConstraints contains the constraints to add or update when
	// upgrading the charm.
	//
	// Any existing storage instances for the named stores will be
	// unaffected; the storage constraints will only be used for
	// provisioning new storage instances.
	StorageConstraints map[string]StorageConstraints
}

SetCharmConfig contains the parameters for Application.SetCharm.

type Settings

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

A Settings manages changes to settings as a delta in memory and merges them back in the database when explicitly requested.

func (*Settings) Delete

func (s *Settings) Delete(key string)

Delete removes key.

func (*Settings) Get

func (s *Settings) Get(key string) (value interface{}, found bool)

Get returns the value of key and whether it was found.

func (*Settings) Keys

func (s *Settings) Keys() []string

Keys returns the current keys in alphabetical order.

func (*Settings) Map

func (s *Settings) Map() map[string]interface{}

Map returns all keys and values of the node.

func (*Settings) Read

func (s *Settings) Read() error

Read (re)reads the node data into c.

func (*Settings) Set

func (s *Settings) Set(key string, value interface{})

Set sets key to value

func (*Settings) Update

func (s *Settings) Update(kv map[string]interface{})

Update sets multiple key/value pairs.

func (*Settings) Write

func (s *Settings) Write() ([]ItemChange, error)

Write writes changes made to c back onto its node. Changes are written as a delta applied on top of the latest version of the node, to prevent overwriting unrelated changes made to the node since it was last read.

type Space

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

Space represents the state of a juju network space.

func (*Space) EnsureDead

func (s *Space) EnsureDead() (err error)

EnsureDead sets the Life of the space to Dead, if it's Alive. If the space is already Dead, no error is returned. When the space is no longer Alive or already removed, errNotAlive is returned.

func (*Space) IsPublic

func (s *Space) IsPublic() bool

IsPublic returns whether the space is public or not.

func (*Space) Life

func (s *Space) Life() Life

Life returns whether the space is Alive, Dying or Dead.

func (*Space) Name

func (s *Space) Name() string

Name returns the name of the Space.

func (*Space) ProviderId

func (s *Space) ProviderId() network.Id

ProviderId returns the provider id of the space. This will be the empty string except on substrates that directly support spaces.

func (*Space) Refresh

func (s *Space) Refresh() error

Refresh: refreshes the contents of the Space from the underlying state. It returns an error that satisfies errors.IsNotFound if the Space has been removed.

func (*Space) Remove

func (s *Space) Remove() (err error)

Remove removes a Dead space. If the space is not Dead or it is already removed, an error is returned.

func (*Space) String

func (s *Space) String() string

String implements fmt.Stringer.

func (*Space) Subnets

func (s *Space) Subnets() (results []*Subnet, err error)

Subnets returns all the subnets associated with the Space.

type StagedResource

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

StagedResource represents resource info that has been added to the "staging" area of the underlying data store. It remains unavailable until finalized, at which point it moves out of the staging area and replaces the current active resource info.

func (StagedResource) Activate

func (staged StagedResource) Activate() error

Activate makes the staged resource the active resource.

func (StagedResource) Unstage

func (staged StagedResource) Unstage() error

Unstage ensures that the resource is removed from the staging area. If it isn't in the staging area then this is a noop.

type State

type State struct {

	// TODO(anastasiamac 2015-07-16) As state gets broken up, remove this.
	CloudImageMetadataStorage cloudimagemetadata.Storage
	// contains filtered or unexported fields
}

State represents the state of an model managed by juju.

func Initialize

func Initialize(args InitializeParams) (_ *State, err error)

Initialize sets up an initial empty state and returns it. This needs to be performed only once for the initial controller model. It returns unauthorizedError if access is unauthorized.

func Open

func Open(
	controllerModelTag names.ModelTag,
	controllerTag names.ControllerTag,
	info *mongo.MongoInfo, opts mongo.DialOpts,
	newPolicy NewPolicyFunc,
) (*State, error)

Open connects to the server described by the given info, waits for it to be initialized, and returns a new State representing the model connected to.

A policy may be provided, which will be used to validate and modify behaviour of certain operations in state. A nil policy may be provided.

Open returns unauthorizedError if access is unauthorized.

func (*State) APIAddressesFromMachines

func (st *State) APIAddressesFromMachines() ([]string, error)

APIAddressesFromMachines returns the list of cloud-internal addresses that can be used to connect to the state API server. This method will be deprecated when API addresses are stored independently in their own document.

func (*State) APIHostPorts

func (st *State) APIHostPorts() ([][]network.HostPort, error)

APIHostPorts returns the API addresses as set by SetAPIHostPorts.

func (*State) AbortCurrentUpgrade

func (st *State) AbortCurrentUpgrade() error

AbortCurrentUpgrade archives any current UpgradeInfo and sets its status to UpgradeAborted. Nothing happens if there's no current UpgradeInfo.

func (*State) Action

func (st *State) Action(id string) (Action, error)

Action returns an Action by Id, which is a UUID.

func (*State) ActionByTag

func (st *State) ActionByTag(tag names.ActionTag) (Action, error)

ActionByTag returns an Action given an ActionTag.

func (*State) AddApplication

func (st *State) AddApplication(args AddApplicationArgs) (_ *Application, err error)

AddApplication creates a new application, running the supplied charm, with the supplied name (which must be unique). If the charm defines peer relations, they will be created automatically.

func (*State) AddCharm

func (st *State) AddCharm(info CharmInfo) (stch *Charm, err error)

AddCharm adds the ch charm with curl to the state. On success the newly added charm state is returned.

func (*State) AddCloud

func (st *State) AddCloud(name string, c cloud.Cloud) error

AddCloud creates a cloud with the given name and details. Note that the Config is deliberately ignored - it's only relevant when bootstrapping.

func (*State) AddControllerUser

func (st *State) AddControllerUser(spec UserAccessSpec) (permission.UserAccess, error)

AddControllerUser adds a new user for the curent controller to the database.

func (*State) AddMachine

func (st *State) AddMachine(series string, jobs ...MachineJob) (*Machine, error)

AddMachine adds a machine with the given series and jobs. It is deprecated and around for testing purposes only.

func (*State) AddMachineInsideMachine

func (st *State) AddMachineInsideMachine(template MachineTemplate, parentId string, containerType instance.ContainerType) (*Machine, error)

AddMachineInsideMachine adds a machine inside a container of the given type on the existing machine with id=parentId.

func (*State) AddMachineInsideNewMachine

func (st *State) AddMachineInsideNewMachine(template, parentTemplate MachineTemplate, containerType instance.ContainerType) (*Machine, error)

AddMachineInsideNewMachine creates a new machine within a container of the given type inside another new machine. The two given templates specify the form of the child and parent respectively.

func (*State) AddMachines

func (st *State) AddMachines(templates ...MachineTemplate) (_ []*Machine, err error)

AddMachines adds new machines configured according to the given templates.

func (*State) AddMetrics

func (st *State) AddMetrics(batch BatchParam) (*MetricBatch, error)

AddMetrics adds a new batch of metrics to the database.

func (*State) AddModelUser

func (st *State) AddModelUser(modelUUID string, spec UserAccessSpec) (permission.UserAccess, error)

AddModelUser adds a new user for the model identified by modelUUID to the database.

func (*State) AddOneMachine

func (st *State) AddOneMachine(template MachineTemplate) (*Machine, error)

AddOneMachine machine adds a new machine configured according to the given template.

func (*State) AddRelation

func (st *State) AddRelation(eps ...Endpoint) (r *Relation, err error)

AddRelation creates a new relation with the given endpoints.

func (*State) AddSpace

func (st *State) AddSpace(name string, providerId network.Id, subnets []string, isPublic bool) (newSpace *Space, err error)

AddSpace creates and returns a new space.

func (*State) AddStorageForUnit

func (st *State) AddStorageForUnit(
	tag names.UnitTag, name string, cons StorageConstraints,
) error

AddStorageForUnit adds storage instances to given unit as specified.

Missing storage constraints are populated based on model defaults. Storage store name is used to retrieve existing storage instances for this store. Combination of existing storage instances and anticipated additional storage instances is validated against the store as specified in the charm.

func (*State) AddStoreCharmPlaceholder

func (st *State) AddStoreCharmPlaceholder(curl *charm.URL) (err error)

AddStoreCharmPlaceholder creates a charm document in state for the given charm URL which must reference a charm from the store. The charm document is marked as a placeholder which means that if the charm is to be deployed, it will need to first be uploaded to env storage.

func (*State) AddSubnet

func (st *State) AddSubnet(args SubnetInfo) (subnet *Subnet, err error)

AddSubnet creates and returns a new subnet

func (*State) AddUser

func (st *State) AddUser(name, displayName, password, creator string) (*User, error)

AddUser adds a user to the database.

func (*State) AddUserWithSecretKey

func (st *State) AddUserWithSecretKey(name, displayName, creator string) (*User, error)

AddUserWithSecretKey adds the user with the specified name, and assigns it a randomly generated secret key. This secret key may be used for the user and controller to mutually authenticate one another, without without relying on TLS certificates.

The new user will not have a password. A password must be set, clearing the secret key in the process, before the user can login normally.

func (*State) Addresses

func (st *State) Addresses() ([]string, error)

Addresses returns the list of cloud-internal addresses that can be used to connect to the state.

func (*State) AllActions

func (st *State) AllActions() ([]Action, error)

AllActions returns all Actions.

func (*State) AllApplications

func (st *State) AllApplications() (applications []*Application, err error)

AllApplications returns all deployed services in the model.

func (*State) AllBlocks

func (st *State) AllBlocks() ([]Block, error)

AllBlocks returns all blocks in the model.

func (*State) AllBlocksForController

func (st *State) AllBlocksForController() ([]Block, error)

AllBlocksForController returns all blocks in any models on the controller.

func (*State) AllCharms

func (st *State) AllCharms() ([]*Charm, error)

AllCharms returns all charms in state.

func (*State) AllFilesystems

func (st *State) AllFilesystems() ([]Filesystem, error)

AllFilesystems returns all Filesystems for this state.

func (*State) AllIPAddresses

func (st *State) AllIPAddresses() (addresses []*Address, err error)

AllIPAddresses returns all ip addresses in the model.

func (*State) AllLinkLayerDevices

func (st *State) AllLinkLayerDevices() (devices []*LinkLayerDevice, err error)

AllLinkLayerDevices returns all link layer devices in the model.

func (*State) AllMachineRemovals

func (st *State) AllMachineRemovals() ([]string, error)

AllMachineRemovals returns (the ids of) all of the machines that need to be removed but need provider-level cleanup.

func (*State) AllMachines

func (st *State) AllMachines() ([]*Machine, error)

AllMachines returns all machines in the model ordered by id.

func (*State) AllMachinesFor

func (st *State) AllMachinesFor(modelUUID string) ([]*Machine, error)

AllMachinesFor returns all machines for the model represented by the given modeluuid

func (*State) AllMetricBatches

func (st *State) AllMetricBatches() ([]MetricBatch, error)

AllMetricBatches returns all metric batches currently stored in state. TODO (tasdomas): this method is currently only used in the uniter worker test -

it needs to be modified to restrict the scope of the values it
returns if it is to be used outside of tests.

func (*State) AllModels

func (st *State) AllModels() ([]*Model, error)

AllModels returns all the models in the system.

func (*State) AllRelations

func (st *State) AllRelations() (relations []*Relation, err error)

AllRelations returns all relations in the model ordered by id.

func (*State) AllSpaces

func (st *State) AllSpaces() ([]*Space, error)

AllSpaces returns all spaces for the model.

func (*State) AllStorageInstances

func (st *State) AllStorageInstances() (storageInstances []StorageInstance, err error)

AllStorageInstances lists all storage instances currently in state for this Juju model.

func (*State) AllSubnets

func (st *State) AllSubnets() (subnets []*Subnet, err error)

AllSubnets returns all known subnets in the model.

func (*State) AllUnitAssignments

func (st *State) AllUnitAssignments() ([]UnitAssignment, error)

UnitAssignments returns all staged unit assignments in the model.

func (*State) AllUsers

func (st *State) AllUsers(includeDeactivated bool) ([]*User, error)

AllUsers returns a slice of state.User. This includes all active users. If includeDeactivated is true it also returns inactive users. At this point it never returns deleted users.

func (*State) AllVolumes

func (st *State) AllVolumes() ([]Volume, error)

AllVolumes returns all Volumes scoped to the model.

func (*State) Annotation

func (st *State) Annotation(entity GlobalEntity, key string) (string, error)

Annotation returns the annotation value corresponding to the given key. If the requested annotation is not found, an empty string is returned.

func (*State) Annotations

func (st *State) Annotations(entity GlobalEntity) (map[string]string, error)

Annotations returns all the annotations corresponding to an entity.

func (*State) Application

func (st *State) Application(name string) (_ *Application, err error)

Service returns a service state by name.

func (*State) ApplicationLeaders

func (st *State) ApplicationLeaders() (map[string]string, error)

ApplicationLeaders returns a map of the application name to the unit name that is the current leader.

func (*State) AssignStagedUnits

func (st *State) AssignStagedUnits(ids []string) ([]UnitAssignmentResult, error)

AssignStagedUnits gets called by the UnitAssigner worker, and runs the given assignments.

func (*State) AssignUnit

func (st *State) AssignUnit(u *Unit, policy AssignmentPolicy) (err error)

AssignUnit places the unit on a machine. Depending on the policy, and the state of the model, this may lead to new instances being launched within the model.

func (*State) AssignUnitWithPlacement

func (st *State) AssignUnitWithPlacement(unit *Unit, placement *instance.Placement) error

AssignUnitWithPlacement chooses a machine using the given placement directive and then assigns the unit to it.

func (*State) AutocertCache

func (st *State) AutocertCache() autocert.Cache

AutocertCache returns an implementation of autocert.Cache backed by the state.

func (*State) BlockDevices

func (st *State) BlockDevices(machine names.MachineTag) ([]BlockDeviceInfo, error)

BlockDevices returns the BlockDeviceInfo for the specified machine.

func (*State) CACert

func (st *State) CACert() string

CACert returns the certificate used to validate the state connection.

func (*State) Charm

func (st *State) Charm(curl *charm.URL) (*Charm, error)

Charm returns the charm with the given URL. Charms pending upload to storage and placeholders are never returned.

func (*State) Cleanup

func (st *State) Cleanup() (err error)

Cleanup removes all documents that were previously marked for removal, if any such exist. It should be called periodically by at least one element of the system.

func (*State) CleanupOldMetrics

func (st *State) CleanupOldMetrics() error

CleanupOldMetrics looks for metrics that are 24 hours old (or older) and have been sent. Any metrics it finds are deleted.

func (*State) ClearUpgradeInfo

func (st *State) ClearUpgradeInfo() error

ClearUpgradeInfo clears information about an upgrade in progress. It returns an error if no upgrade is current.

func (*State) Close

func (st *State) Close() (err error)

Close the connection to the database.

func (*State) Cloud

func (st *State) Cloud(name string) (cloud.Cloud, error)

Cloud returns the controller's cloud definition.

func (*State) CloudCredential

func (st *State) CloudCredential(tag names.CloudCredentialTag) (cloud.Credential, error)

CloudCredential returns the cloud credential for the given tag.

func (*State) CloudCredentials

func (st *State) CloudCredentials(user names.UserTag, cloudName string) (map[string]cloud.Credential, error)

CloudCredentials returns the user's cloud credentials for a given cloud, keyed by credential name.

func (*State) Clouds

func (st *State) Clouds() (map[names.CloudTag]cloud.Cloud, error)

Clouds returns the definitions for all clouds in the controller.

func (*State) CompleteMachineRemovals

func (st *State) CompleteMachineRemovals(ids ...string) error

CompleteMachineRemovals finishes the removal of the specified machines. The machines must have been marked for removal previously. Valid-looking-but-unknown machine ids are ignored so that this is idempotent.

func (*State) ComposeNewModelConfig

func (st *State) ComposeNewModelConfig(modelAttr map[string]interface{}, regionSpec *environs.RegionSpec) (map[string]interface{}, error)

ComposeNewModelConfig returns a complete map of config attributes suitable for creating a new model, by combining user specified values with system defaults.

func (*State) ControllerConfig

func (st *State) ControllerConfig() (jujucontroller.Config, error)

ControllerConfig returns the config values for the controller.

func (*State) ControllerInfo

func (st *State) ControllerInfo() (*ControllerInfo, error)

ControllerInfo returns information about the currently configured controller machines.

func (*State) ControllerModel

func (st *State) ControllerModel() (*Model, error)

ControllerModel returns the model that was bootstrapped. This is the only model that can have controller machines. The owner of this model is also considered "special", in that they are the only user that is able to create other users (until we have more fine grained permissions), and they cannot be disabled.

func (*State) ControllerTag

func (st *State) ControllerTag() names.ControllerTag

func (*State) ControllerUUID

func (st *State) ControllerUUID() string

ControllerUUID returns the UUID for the controller of this state instance.

func (*State) CountOfSentMetrics

func (st *State) CountOfSentMetrics() (int, error)

CountOfSentMetrics returns the number of metrics that have been sent to the collection service and have not been removed by the cleanup worker.

func (*State) CountOfUnsentMetrics

func (st *State) CountOfUnsentMetrics() (int, error)

CountOfUnsentMetrics returns the number of metrics that haven't been sent to the collection service.

func (*State) CreateMigration

func (st *State) CreateMigration(spec MigrationSpec) (ModelMigration, error)

CreateMigration initialises state that tracks a model migration. It will return an error if there is already a model migration in progress.

func (*State) DestroyFilesystem

func (st *State) DestroyFilesystem(tag names.FilesystemTag) (err error)

DestroyFilesystem ensures that the filesystem and any attachments to it will be destroyed and removed from state at some point in the future.

func (*State) DestroyStorageAttachment

func (st *State) DestroyStorageAttachment(storage names.StorageTag, unit names.UnitTag) (err error)

DestroyStorageAttachment ensures that the storage attachment will be removed at some point.

func (*State) DestroyStorageInstance

func (st *State) DestroyStorageInstance(tag names.StorageTag) (err error)

DestroyStorageInstance ensures that the storage instance and all its attachments will be removed at some point; if the storage instance has no attachments, it will be removed immediately.

func (*State) DestroyUnitStorageAttachments

func (st *State) DestroyUnitStorageAttachments(unit names.UnitTag) (err error)

DestroyStorageAttachment ensures that the existing storage attachments of the specified unit are removed at some point.

func (*State) DestroyVolume

func (st *State) DestroyVolume(tag names.VolumeTag) (err error)

DestroyVolume ensures that the volume and any attachments to it will be destroyed and removed from state at some point in the future. DestroyVolume will fail with an IsContainsFilesystem error if the volume contains a filesystem; the filesystem must be fully removed first.

func (*State) DetachFilesystem

func (st *State) DetachFilesystem(machine names.MachineTag, filesystem names.FilesystemTag) (err error)

DetachFilesystem marks the filesystem attachment identified by the specified machine and filesystem tags as Dying, if it is Alive.

func (*State) DetachVolume

func (st *State) DetachVolume(machine names.MachineTag, volume names.VolumeTag) (err error)

DetachVolume marks the volume attachment identified by the specified machine and volume tags as Dying, if it is Alive. DetachVolume will fail with a IsContainsFilesystem error if the volume contains an attached filesystem; the filesystem attachment must be removed first.

func (*State) DumpAll

func (st *State) DumpAll() (map[string]interface{}, error)

DumpAll returns a map of collection names to a slice of documents in that collection. Every document that is related to the current model is returned in the map.

func (*State) EnableHA

func (st *State) EnableHA(
	numControllers int, cons constraints.Value, series string, placement []string,
) (ControllersChanges, error)

EnableHA adds controller machines as necessary to make the number of live controllers equal to numControllers. The given constraints and series will be attached to any new machines. If placement is not empty, any new machines which may be required are started according to the specified placement directives until the placement list is exhausted; thereafter any new machines are started according to the constraints and series.

func (*State) EndpointsRelation

func (st *State) EndpointsRelation(endpoints ...Endpoint) (*Relation, error)

EndpointsRelation returns the existing relation with the given endpoints.

func (*State) EnqueueAction

func (st *State) EnqueueAction(receiver names.Tag, actionName string, payload map[string]interface{}) (Action, error)

EnqueueAction

func (*State) EnsureModelRemoved

func (st *State) EnsureModelRemoved() error

EnsureModelRemoved returns an error if any multi-model documents for this model are found. It is intended only to be used in tests and exported so it can be used in the tests of other packages.

func (*State) EnsureUpgradeInfo

func (st *State) EnsureUpgradeInfo(machineId string, previousVersion, targetVersion version.Number) (*UpgradeInfo, error)

EnsureUpgradeInfo returns an UpgradeInfo describing a current upgrade between the supplied versions. If a matching upgrade is in progress, that upgrade is returned; if there's a mismatch, an error is returned. The supplied machine id must correspond to a current controller.

func (*State) Export

func (st *State) Export() (description.Model, error)

Export the current model for the State.

func (*State) Filesystem

func (st *State) Filesystem(tag names.FilesystemTag) (Filesystem, error)

Filesystem returns the Filesystem with the specified name.

func (*State) FilesystemAttachment

func (st *State) FilesystemAttachment(machine names.MachineTag, filesystem names.FilesystemTag) (FilesystemAttachment, error)

FilesystemAttachment returns the FilesystemAttachment corresponding to the specified filesystem and machine.

func (*State) FilesystemAttachments

func (st *State) FilesystemAttachments(filesystem names.FilesystemTag) ([]FilesystemAttachment, error)

FilesystemAttachments returns all of the FilesystemAttachments for the specified filesystem.

func (*State) FilesystemStatus

func (st *State) FilesystemStatus(tag names.FilesystemTag) (status.StatusInfo, error)

FilesystemStatus returns the status of the specified filesystem.

func (*State) FindActionTagsByPrefix

func (st *State) FindActionTagsByPrefix(prefix string) []names.ActionTag

FindActionTagsByPrefix finds Actions with ids that share the supplied prefix, and returns a list of corresponding ActionTags.

func (*State) FindActionsByName

func (st *State) FindActionsByName(name string) ([]Action, error)

FindActionsByName finds Actions with the given name.

func (*State) FindEntity

func (st *State) FindEntity(tag names.Tag) (Entity, error)

FindEntity returns the entity with the given tag.

The returned value can be of type *Machine, *Unit, *User, *Service, *Model, or *Action, depending on the tag.

func (*State) ForModel

func (st *State) ForModel(modelTag names.ModelTag) (*State, error)

ForModel returns a connection to mongo for the specified model. The connection uses the same credentials and policy as the existing connection.

func (*State) GUISetVersion

func (st *State) GUISetVersion(vers version.Number) error

GUISetVersion sets the Juju GUI version that the controller must serve.

func (*State) GUIStorage

func (st *State) GUIStorage() (binarystorage.StorageCloser, error)

GUIStorage returns a new binarystorage.StorageCloser that stores GUI archive metadata in the "juju" database "guimetadata" collection.

func (*State) GUIVersion

func (st *State) GUIVersion() (vers version.Number, err error)

GUIVersion returns the Juju GUI version currently served by the controller.

func (*State) GetBlockForType

func (st *State) GetBlockForType(t BlockType) (Block, bool, error)

GetBlockForType returns the Block of the specified type for the current model where

not found -> nil, false, nil
found -> block, true, nil
error -> nil, false, err

func (*State) GetModel

func (st *State) GetModel(tag names.ModelTag) (*Model, error)

GetModel looks for the model identified by the uuid passed in.

func (*State) GetSSHHostKeys

func (st *State) GetSSHHostKeys(tag names.MachineTag) (SSHHostKeys, error)

GetSSHHostKeys retrieves the SSH host keys stored for an entity. / NOTE: Currently only machines are supported. This can be generalised to take other tag types later, if and when we need it.

func (*State) HackLeadership

func (st *State) HackLeadership()

HackLeadership stops the state's internal leadership manager to prevent it from interfering with apiserver shutdown.

func (*State) ImageStorage

func (st *State) ImageStorage() imagestorage.Storage

ImageStorage returns a new imagestorage.Storage that stores image metadata.

func (*State) Import

func (st *State) Import(model description.Model) (_ *Model, _ *State, err error)

Import the database agnostic model representation into the database.

func (*State) InferEndpoints

func (st *State) InferEndpoints(names ...string) ([]Endpoint, error)

InferEndpoints returns the endpoints corresponding to the supplied names. There must be 1 or 2 supplied names, of the form <service>[:<relation>]. If the supplied names uniquely specify a possible relation, or if they uniquely specify a possible relation once all implicit relations have been filtered, the endpoints corresponding to that relation will be returned.

func (*State) IsController

func (st *State) IsController() bool

IsController returns true if this state instance has the bootstrap model UUID.

func (*State) IsControllerAdmin

func (st *State) IsControllerAdmin(user names.UserTag) (bool, error)

IsControllerAdmin returns true if the user specified has Super User Access.

func (*State) IsMigrationActive

func (st *State) IsMigrationActive() (bool, error)

IsMigrationActive returns true if a migration is in progress for the model associated with the State.

func (*State) IsUpgrading

func (st *State) IsUpgrading() (bool, error)

IsUpgrading returns true if an upgrade is currently in progress.

func (*State) KeyRelation

func (st *State) KeyRelation(key string) (*Relation, error)

KeyRelation returns the existing relation with the given key (which can be derived unambiguously from the relation's endpoints).

func (*State) LastModelConnection

func (st *State) LastModelConnection(user names.UserTag) (time.Time, error)

LastModelConnection returns when this User last connected through the API in UTC. The resulting time will be nil if the user has never logged in.

func (*State) LatestMigration

func (st *State) LatestMigration() (ModelMigration, error)

LatestMigration returns the most recent ModelMigration for a model (if any).

func (*State) LatestPlaceholderCharm

func (st *State) LatestPlaceholderCharm(curl *charm.URL) (*Charm, error)

LatestPlaceholderCharm returns the latest charm described by the given URL but which is not yet deployed.

func (*State) LeadershipChecker

func (st *State) LeadershipChecker() leadership.Checker

LeadershipChecker returns a leadership.Checker for units and services in the state's model.

func (*State) LeadershipClaimer

func (st *State) LeadershipClaimer() leadership.Claimer

LeadershipClaimer returns a leadership.Claimer for units and services in the state's model.

func (*State) Machine

func (st *State) Machine(id string) (*Machine, error)

Machine returns the machine with the given id.

func (*State) MachineFilesystemAttachments

func (st *State) MachineFilesystemAttachments(machine names.MachineTag) ([]FilesystemAttachment, error)

MachineFilesystemAttachments returns all of the FilesystemAttachments for the specified machine.

func (*State) MachineVolumeAttachments

func (st *State) MachineVolumeAttachments(machine names.MachineTag) ([]VolumeAttachment, error)

MachineVolumeAttachments returns all of the VolumeAttachments for the specified machine.

func (*State) MaybePruneTransactions

func (st *State) MaybePruneTransactions() error

MaybePruneTransactions removes data for completed transactions.

func (*State) MetricBatch

func (st *State) MetricBatch(id string) (*MetricBatch, error)

MetricBatch returns the metric batch with the given id.

func (*State) MetricBatchesForApplication

func (st *State) MetricBatchesForApplication(application string) ([]MetricBatch, error)

MetricBatchesForApplication returns metric batches for the given application.

func (*State) MetricBatchesForModel

func (st *State) MetricBatchesForModel() ([]MetricBatch, error)

MetricBatchesForModel returns metric batches for all the units in the model.

func (*State) MetricBatchesForUnit

func (st *State) MetricBatchesForUnit(unit string) ([]MetricBatch, error)

MetricBatchesForUnit returns metric batches for the given unit.

func (*State) MetricsManager

func (st *State) MetricsManager() (*MetricsManager, error)

MetricsManager returns an existing metricsmanager, or a new one if non exists.

func (*State) MetricsToSend

func (st *State) MetricsToSend(batchSize int) ([]*MetricBatch, error)

MetricsToSend returns batchSize metrics that need to be sent to the collector

func (*State) Migration

func (st *State) Migration(id string) (ModelMigration, error)

Migration retrieves a specific ModelMigration by its id. See also LatestMigration.

func (*State) Model

func (st *State) Model() (*Model, error)

Model returns the model entity.

func (*State) ModelConfig

func (st *State) ModelConfig() (*config.Config, error)

ModelConfig returns the complete config for the model represented by this state.

func (*State) ModelConfigDefaultValues

func (st *State) ModelConfigDefaultValues() (config.ModelDefaultAttributes, error)

ModelConfigDefaultValues returns the default config values to be used when creating a new model, and the origin of those values.

func (*State) ModelConfigValues

func (st *State) ModelConfigValues() (config.ConfigValues, error)

ModelConfigValues returns the config values for the model represented by this state.

func (*State) ModelConstraints

func (st *State) ModelConstraints() (constraints.Value, error)

ModelConstraints returns the current model constraints.

func (*State) ModelPayloads

func (st *State) ModelPayloads() (ModelPayloads, error)

ModelPayloads returns a ModelPayloads for the state's model.

func (*State) ModelTag

func (st *State) ModelTag() names.ModelTag

ModelTag() returns the model tag for the model controlled by this state instance.

func (*State) ModelUUID

func (st *State) ModelUUID() string

ModelUUID returns the model UUID for the model controlled by this state instance.

func (*State) ModelsForUser

func (st *State) ModelsForUser(user names.UserTag) ([]*UserModel, error)

ModelsForUser returns a list of models that the user is able to access.

func (*State) MongoConnectionInfo

func (st *State) MongoConnectionInfo() *mongo.MongoInfo

MongoConnectionInfo returns information for connecting to mongo

func (*State) MongoSession

func (st *State) MongoSession() *mgo.Session

MongoSession returns the underlying mongodb session used by the state. It is exposed so that external code can maintain the mongo replica set and should not otherwise be used.

func (*State) MongoVersion

func (st *State) MongoVersion() (string, error)

MongoVersion return the string repre

func (*State) NeedsCleanup

func (st *State) NeedsCleanup() (bool, error)

NeedsCleanup returns true if documents previously marked for removal exist.

func (*State) NewBakeryStorage

func (st *State) NewBakeryStorage() (bakerystorage.ExpirableStorage, error)

NewBakeryStorage returns a new bakery.Storage. By default, items added to the store are retained until deleted explicitly. The store's ExpireAt method can be called to derive a new store that will expire items at the specified time.

func (*State) NewModel

func (st *State) NewModel(args ModelArgs) (_ *Model, _ *State, err error)

NewModel creates a new model with its own UUID and prepares it for use. Model and State instances for the new model are returned.

The controller model's UUID is attached to the new model's document. Having the server UUIDs stored with each model document means that we have a way to represent external models, perhaps for future use around cross model relations.

func (*State) NowToTheSecond

func (st *State) NowToTheSecond() time.Time

NowToTheSecond returns the current time in UTC to the nearest second. We use this for a time source that is not more precise than we can handle. When serializing time in and out of mongo, we lose enough precision that it's misleading to store any more than precision to the second.

func (*State) Ping

func (st *State) Ping() error

Ping probes the state's database connection to ensure that it is still alive.

func (*State) PrepareLocalCharmUpload

func (st *State) PrepareLocalCharmUpload(curl *charm.URL) (chosenURL *charm.URL, err error)

PrepareLocalCharmUpload must be called before a local charm is uploaded to the provider storage in order to create a charm document in state. It returns the chosen unique charm URL reserved in state for the charm.

The url's schema must be "local" and it must include a revision.

func (*State) PrepareStoreCharmUpload

func (st *State) PrepareStoreCharmUpload(curl *charm.URL) (*Charm, error)

PrepareStoreCharmUpload must be called before a charm store charm is uploaded to the provider storage in order to create a charm document in state. If a charm with the same URL is already in state, it will be returned as a *state.Charm (it can be still pending or already uploaded). Otherwise, a new charm document is added in state with just the given charm URL and PendingUpload=true, which is then returned as a *state.Charm.

The url's schema must be "cs" and it must include a revision.

func (*State) ProcessDyingModel

func (st *State) ProcessDyingModel() (err error)

ProcessDyingModel checks if there are any machines or services left in state. If there are none, the model's life is changed from dying to dead.

func (*State) PutAuditEntryFn

func (st *State) PutAuditEntryFn() func(audit.AuditEntry) error

PutAuditEntryFn returns a function which will persist audit.AuditEntry instances to the database.

func (*State) ReadSettings

func (st *State) ReadSettings(collection, key string) (*Settings, error)

ReadSettings returns the settings for the given key.

func (*State) Relation

func (st *State) Relation(id int) (*Relation, error)

Relation returns the existing relation with the given id.

func (*State) RemoveAllBlocksForController

func (st *State) RemoveAllBlocksForController() error

RemoveAllBlocksForController removes all the blocks for the controller. It does not prevent new blocks from being added during / after removal.

func (*State) RemoveAllModelDocs

func (st *State) RemoveAllModelDocs() error

RemoveAllModelDocs removes all documents from multi-model collections. The model should be put into a dying state before call this method. Otherwise, there is a race condition in which collections could be added to during or after the running of this method.

func (*State) RemoveCloudCredential

func (st *State) RemoveCloudCredential(tag names.CloudCredentialTag) error

RemoveCloudCredential removes a cloud credential with the given tag.

func (*State) RemoveExportingModelDocs

func (st *State) RemoveExportingModelDocs() error

RemoveExportingModelDocs removes all documents from multi-model collections for the current model. This method asserts that the model's migration mode is "exporting".

func (*State) RemoveFilesystem

func (st *State) RemoveFilesystem(tag names.FilesystemTag) (err error)

RemoveFilesystem removes the filesystem from state. RemoveFilesystem will fail if there are any attachments remaining, or if the filesystem is not Dying. Removing a volume-backed filesystem will cause the volume to be destroyed.

func (*State) RemoveFilesystemAttachment

func (st *State) RemoveFilesystemAttachment(machine names.MachineTag, filesystem names.FilesystemTag) (err error)

RemoveFilesystemAttachment removes the filesystem attachment from state. Removing a volume-backed filesystem attachment will cause the volume to be detached.

func (*State) RemoveImportingModelDocs

func (st *State) RemoveImportingModelDocs() error

RemoveImportingModelDocs removes all documents from multi-model collections for the current model. This method asserts that the model's migration mode is "importing".

func (*State) RemoveStorageAttachment

func (st *State) RemoveStorageAttachment(storage names.StorageTag, unit names.UnitTag) (err error)

Remove removes the storage attachment from state, and may remove its storage instance as well, if the storage instance is Dying and no other references to it exist. It will fail if the storage attachment is not Dying.

func (*State) RemoveUser

func (st *State) RemoveUser(tag names.UserTag) error

RemoveUser marks the user as deleted. This obviates the ability of a user to function, but keeps the userDoc retaining provenance, i.e. auditing.

func (*State) RemoveUserAccess

func (st *State) RemoveUserAccess(subject names.UserTag, target names.Tag) error

RemoveUserAccess removes access for subject to the passed tag.

func (*State) RemoveVolume

func (st *State) RemoveVolume(tag names.VolumeTag) (err error)

RemoveVolume removes the volume from state. RemoveVolume will fail if the volume is not Dead, which implies that it still has attachments.

func (*State) RemoveVolumeAttachment

func (st *State) RemoveVolumeAttachment(machine names.MachineTag, volume names.VolumeTag) (err error)

RemoveVolumeAttachment removes the volume attachment from state. RemoveVolumeAttachment will fail if the attachment is not Dying.

func (*State) Resources

func (st *State) Resources() (Resources, error)

Resources returns the resources functionality for the current state.

func (*State) ResourcesPersistence

func (st *State) ResourcesPersistence() (ResourcesPersistence, error)

ResourcesPersistence returns the resources persistence functionality for the current state.

func (*State) RestoreInfo

func (st *State) RestoreInfo() *RestoreInfo

RestoreInfo exposes restore status.

func (*State) ResumeReplication

func (st *State) ResumeReplication(members []replicaset.Member) error

ResumeReplication will add all passed members to replicaset.

func (*State) ResumeTransactions

func (st *State) ResumeTransactions() error

ResumeTransactions resumes all pending transactions.

func (*State) SetAPIHostPorts

func (st *State) SetAPIHostPorts(netHostsPorts [][]network.HostPort) error

SetAPIHostPorts sets the addresses of the API server instances. Each server is represented by one element in the top level slice.

func (*State) SetAdminMongoPassword

func (st *State) SetAdminMongoPassword(password string) error

SetAdminMongoPassword sets the administrative password to access the state. If the password is non-empty, all subsequent attempts to access the state must be authorized; otherwise no authorization is required.

func (*State) SetAnnotations

func (st *State) SetAnnotations(entity GlobalEntity, annotations map[string]string) (err error)

SetAnnotations adds key/value pairs to annotations in MongoDB.

func (*State) SetClockForTesting

func (st *State) SetClockForTesting(clock clock.Clock) error

SetClockForTesting is an exported function to allow other packages to set the internal clock for the State instance. It is named such that it should be obvious if it is ever called from a non-test packgae.

func (*State) SetFilesystemAttachmentInfo

func (st *State) SetFilesystemAttachmentInfo(
	machineTag names.MachineTag,
	filesystemTag names.FilesystemTag,
	info FilesystemAttachmentInfo,
) (err error)

SetFilesystemAttachmentInfo sets the FilesystemAttachmentInfo for the specified filesystem attachment.

func (*State) SetFilesystemInfo

func (st *State) SetFilesystemInfo(tag names.FilesystemTag, info FilesystemInfo) (err error)

SetFilesystemInfo sets the FilesystemInfo for the specified filesystem.

func (*State) SetFilesystemStatus

func (st *State) SetFilesystemStatus(tag names.FilesystemTag, fsStatus status.Status, info string, data map[string]interface{}, updated *time.Time) error

SetFilesystemStatus sets the status of the specified filesystem.

func (*State) SetMetricBatchesSent

func (st *State) SetMetricBatchesSent(batchUUIDs []string) error

SetMetricBatchesSent sets sent on each MetricBatch corresponding to the uuids provided.

func (*State) SetModelAgentVersion

func (st *State) SetModelAgentVersion(newVersion version.Number) (err error)

SetModelAgentVersion changes the agent version for the model to the given version, only if the model is in a stable state (all agents are running the current version). If this is a hosted model, newVersion cannot be higher than the controller version.

func (*State) SetModelConstraints

func (st *State) SetModelConstraints(cons constraints.Value) error

SetModelConstraints replaces the current model constraints.

func (*State) SetMongoSpaceState

func (st *State) SetMongoSpaceState(mongoSpaceState MongoSpaceStates) error

SetMongoSpaceState attempts to set the Mongo space state or, if that fails, look up the current Mongo state. Either way, it always returns what is in the database by the end of the call.

func (*State) SetOrGetMongoSpaceName

func (st *State) SetOrGetMongoSpaceName(mongoSpaceName network.SpaceName) (network.SpaceName, error)

SetOrGetMongoSpaceName attempts to set the Mongo space or, if that fails, look up the current Mongo space. Either way, it always returns what is in the database by the end of the call.

func (*State) SetSSHHostKeys

func (st *State) SetSSHHostKeys(tag names.MachineTag, keys SSHHostKeys) error

SetSSHHostKeys updates the stored SSH host keys for an entity.

See the note for GetSSHHostKeys regarding supported entities.

func (*State) SetStateServingInfo

func (st *State) SetStateServingInfo(info StateServingInfo) error

SetStateServingInfo stores information needed for running a controller

func (*State) SetUpgradeMongoMode

func (st *State) SetUpgradeMongoMode(v mongo.Version) (UpgradeMongoParams, error)

SetUpgradeMongoMode writes a value in the state server to be picked up by api servers to know that there is an upgrade ready to happen.

func (*State) SetUserAccess

func (st *State) SetUserAccess(subject names.UserTag, target names.Tag, access permission.Access) (permission.UserAccess, error)

SetUserAccess sets <access> level on <target> to <subject>.

func (*State) SetVolumeAttachmentInfo

func (st *State) SetVolumeAttachmentInfo(machineTag names.MachineTag, volumeTag names.VolumeTag, info VolumeAttachmentInfo) (err error)

SetVolumeAttachmentInfo sets the VolumeAttachmentInfo for the specified volume attachment.

func (*State) SetVolumeInfo

func (st *State) SetVolumeInfo(tag names.VolumeTag, info VolumeInfo) (err error)

SetVolumeInfo sets the VolumeInfo for the specified volume.

func (*State) SetVolumeStatus

func (st *State) SetVolumeStatus(tag names.VolumeTag, volumeStatus status.Status, info string, data map[string]interface{}, updated *time.Time) error

SetVolumeStatus sets the status of the specified volume.

func (*State) SingularClaimer

func (st *State) SingularClaimer() lease.Claimer

SingularClaimer returns a lease.Claimer representing the exclusive right to manage the environment.

func (*State) Space

func (st *State) Space(name string) (*Space, error)

Space returns a space from state that matches the provided name. An error is returned if the space doesn't exist or if there was a problem accessing its information.

func (*State) StartSync

func (st *State) StartSync()

StartSync forces watchers to resynchronize their state with the database immediately. This will happen periodically automatically.

func (*State) StateServingInfo

func (st *State) StateServingInfo() (StateServingInfo, error)

StateServingInfo returns information for running a controller machine

func (*State) StorageAttachment

func (st *State) StorageAttachment(storage names.StorageTag, unit names.UnitTag) (StorageAttachment, error)

StorageAttachment returns the StorageAttachment wit hthe specified tags.

func (*State) StorageAttachments

func (st *State) StorageAttachments(storage names.StorageTag) ([]StorageAttachment, error)

StorageAttachments returns the StorageAttachments for the specified storage instance.

func (*State) StorageInstance

func (st *State) StorageInstance(tag names.StorageTag) (StorageInstance, error)

StorageInstance returns the StorageInstance with the specified tag.

func (*State) StorageInstanceFilesystem

func (st *State) StorageInstanceFilesystem(tag names.StorageTag) (Filesystem, error)

StorageInstanceFilesystem returns the Filesystem assigned to the specified storage instance.

func (*State) StorageInstanceVolume

func (st *State) StorageInstanceVolume(tag names.StorageTag) (Volume, error)

StorageInstanceVolume returns the Volume assigned to the specified storage instance.

func (*State) Subnet

func (st *State) Subnet(cidr string) (*Subnet, error)

Subnet returns the subnet specified by the cidr.

func (*State) SwitchBlockOff

func (st *State) SwitchBlockOff(t BlockType) error

SwitchBlockOff disables block of specified type for the current model.

func (*State) SwitchBlockOn

func (st *State) SwitchBlockOn(t BlockType, msg string) error

SwitchBlockOn enables block of specified type for the current model.

func (*State) ToolsStorage

func (st *State) ToolsStorage() (binarystorage.StorageCloser, error)

ToolsStorage returns a new binarystorage.StorageCloser that stores tools metadata in the "juju" database "toolsmetadata" collection.

func (*State) Unit

func (st *State) Unit(name string) (*Unit, error)

Unit returns a unit by name.

func (*State) UnitPayloads

func (st *State) UnitPayloads(unit *Unit) (UnitPayloads, error)

UnitPayloads returns a UnitPayloads for the supplied unit.

func (*State) UnitStorageAttachments

func (st *State) UnitStorageAttachments(unit names.UnitTag) ([]StorageAttachment, error)

UnitStorageAttachments returns the StorageAttachments for the specified unit.

func (*State) UnitsFor

func (st *State) UnitsFor(machineId string) ([]*Unit, error)

UnitsFor returns the units placed in the given machine id.

func (*State) UpdateCloudCredential

func (st *State) UpdateCloudCredential(tag names.CloudCredentialTag, credential cloud.Credential) error

UpdateCloudCredential adds or updates a cloud credential with the given tag.

func (*State) UpdateLastModelConnection

func (st *State) UpdateLastModelConnection(user names.UserTag) error

UpdateLastModelConnection updates the last connection time of the model user.

func (*State) UpdateModelConfig

func (st *State) UpdateModelConfig(updateAttrs map[string]interface{}, removeAttrs []string, additionalValidation ValidateConfigFunc) error

UpdateModelConfig adds, updates or removes attributes in the current configuration of the model with the provided updateAttrs and removeAttrs.

func (*State) UpdateModelConfigDefaultValues

func (st *State) UpdateModelConfigDefaultValues(attrs map[string]interface{}, removed []string, regionSpec *environs.RegionSpec) error

UpdateModelConfigDefaultValues updates the inherited settings used when creating a new model.

func (*State) UpdateUploadedCharm

func (st *State) UpdateUploadedCharm(info CharmInfo) (*Charm, error)

UpdateUploadedCharm marks the given charm URL as uploaded and updates the rest of its data, returning it as *state.Charm.

func (*State) User

func (st *State) User(tag names.UserTag) (*User, error)

User returns the state User for the given name.

func (*State) UserAccess

func (st *State) UserAccess(subject names.UserTag, target names.Tag) (permission.UserAccess, error)

UserAccess returns a new permission.UserAccess for the passed subject and target.

func (*State) Volume

func (st *State) Volume(tag names.VolumeTag) (Volume, error)

Volume returns the Volume with the specified name.

func (*State) VolumeAttachment

func (st *State) VolumeAttachment(machine names.MachineTag, volume names.VolumeTag) (VolumeAttachment, error)

VolumeAttachment returns the VolumeAttachment corresponding to the specified volume and machine.

func (*State) VolumeAttachments

func (st *State) VolumeAttachments(volume names.VolumeTag) ([]VolumeAttachment, error)

VolumeAttachments returns all of the VolumeAttachments for the specified volume.

func (*State) VolumeFilesystem

func (st *State) VolumeFilesystem(tag names.VolumeTag) (Filesystem, error)

VolumeFilesystem returns the Filesystem backed by the specified volume.

func (*State) VolumeStatus

func (st *State) VolumeStatus(tag names.VolumeTag) (status.StatusInfo, error)

VolumeStatus returns the status of the specified volume.

func (*State) Watch

func (st *State) Watch() *Multiwatcher

func (*State) WatchAPIHostPorts

func (st *State) WatchAPIHostPorts() NotifyWatcher

WatchAPIHostPorts returns a NotifyWatcher that notifies when the set of API addresses changes.

func (*State) WatchActionResults

func (st *State) WatchActionResults() StringsWatcher

WatchActionResults starts and returns a StringsWatcher that notifies on new ActionResults being added.

func (*State) WatchActionResultsFilteredBy

func (st *State) WatchActionResultsFilteredBy(receivers ...ActionReceiver) StringsWatcher

WatchActionResultsFilteredBy starts and returns a StringsWatcher that notifies on new ActionResults being added for the ActionRecevers being watched.

func (*State) WatchAllModels

func (st *State) WatchAllModels() *Multiwatcher

func (*State) WatchBlockDevices

func (st *State) WatchBlockDevices(machine names.MachineTag) NotifyWatcher

WatchBlockDevices returns a new NotifyWatcher watching for changes to block devices associated with the specified machine.

func (*State) WatchCleanups

func (st *State) WatchCleanups() NotifyWatcher

WatchCleanups starts and returns a CleanupWatcher.

func (*State) WatchControllerInfo

func (st *State) WatchControllerInfo() NotifyWatcher

WatchControllerInfo returns a NotifyWatcher for the controllers collection

func (*State) WatchControllerStatusChanges

func (st *State) WatchControllerStatusChanges() StringsWatcher

WatchControllerStatusChanges starts and returns a StringsWatcher that notifies when the status of a controller machine changes. TODO(cherylj) Add unit tests for this, as per bug 1543408.

func (*State) WatchCredential

func (st *State) WatchCredential(cred names.CloudCredentialTag) NotifyWatcher

WatchCredential returns a new NotifyWatcher watching for changes to the specified credential.

func (*State) WatchEnvironFilesystemAttachments

func (st *State) WatchEnvironFilesystemAttachments() StringsWatcher

WatchEnvironFilesystemAttachments returns a StringsWatcher that notifies of changes to the lifecycles of all filesystem attachments related to environ-scoped filesystems.

func (*State) WatchEnvironVolumeAttachments

func (st *State) WatchEnvironVolumeAttachments() StringsWatcher

WatchEnvironVolumeAttachments returns a StringsWatcher that notifies of changes to the lifecycles of all volume attachments related to environ- scoped volumes.

func (*State) WatchFilesystemAttachment

func (st *State) WatchFilesystemAttachment(m names.MachineTag, f names.FilesystemTag) NotifyWatcher

WatchFilesystemAttachment returns a watcher for observing changes to a filesystem attachment.

func (*State) WatchForMigration

func (st *State) WatchForMigration() NotifyWatcher

WatchForMigration returns a notify watcher which reports when a migration is in progress for the model associated with the State.

func (*State) WatchForModelConfigChanges

func (st *State) WatchForModelConfigChanges() NotifyWatcher

WatchForModelConfigChanges returns a NotifyWatcher waiting for the Model Config to change.

func (*State) WatchForUnitAssignment

func (st *State) WatchForUnitAssignment() StringsWatcher

WatchForUnitAssignment watches for new services that request units to be assigned to machines.

func (*State) WatchMachineFilesystemAttachments

func (st *State) WatchMachineFilesystemAttachments(m names.MachineTag) StringsWatcher

WatchMachineFilesystemAttachments returns a StringsWatcher that notifies of changes to the lifecycles of all filesystem attachments related to the specified machine, for filesystems scoped to the machine.

func (*State) WatchMachineFilesystems

func (st *State) WatchMachineFilesystems(m names.MachineTag) StringsWatcher

WatchMachineFilesystems returns a StringsWatcher that notifies of changes to the lifecycles of all filesystems scoped to the specified machine.

func (*State) WatchMachineRemovals

func (st *State) WatchMachineRemovals() NotifyWatcher

WatchMachineRemovals returns a NotifyWatcher which triggers whenever machine removal records are added or removed.

func (*State) WatchMachineVolumeAttachments

func (st *State) WatchMachineVolumeAttachments(m names.MachineTag) StringsWatcher

WatchMachineVolumeAttachments returns a StringsWatcher that notifies of changes to the lifecycles of all volume attachments related to the specified machine, for volumes scoped to the machine.

func (*State) WatchMachineVolumes

func (st *State) WatchMachineVolumes(m names.MachineTag) StringsWatcher

WatchMachineVolumes returns a StringsWatcher that notifies of changes to the lifecycles of all volumes scoped to the specified machine.

func (*State) WatchMigrationStatus

func (st *State) WatchMigrationStatus() NotifyWatcher

WatchMigrationStatus returns a NotifyWatcher which triggers whenever the status of latest migration for the State's model changes. One instance can be used across migrations. The watcher will report changes when one migration finishes and another one begins.

Note that this watcher does not produce an initial event if there's never been a migration attempt for the model.

func (*State) WatchMinUnits

func (st *State) WatchMinUnits() StringsWatcher

WatchMinUnits returns a StringsWatcher for the minUnits collection

func (*State) WatchModelFilesystems

func (st *State) WatchModelFilesystems() StringsWatcher

WatchModelFilesystems returns a StringsWatcher that notifies of changes to the lifecycles of all model-scoped filesystems.

func (*State) WatchModelMachines

func (st *State) WatchModelMachines() StringsWatcher

WatchModelMachines returns a StringsWatcher that notifies of changes to the lifecycles of the machines (but not containers) in the model.

func (*State) WatchModelVolumes

func (st *State) WatchModelVolumes() StringsWatcher

WatchModelVolumes returns a StringsWatcher that notifies of changes to the lifecycles of all model-scoped volumes.

func (*State) WatchModels

func (st *State) WatchModels() StringsWatcher

WatchModels returns a StringsWatcher that notifies of changes to the lifecycles of all models.

func (*State) WatchOpenedPorts

func (st *State) WatchOpenedPorts() StringsWatcher

WatchOpenedPorts starts and returns a StringsWatcher notifying of changes to the openedPorts collection. Reported changes have the following format: "<machine-id>:[<subnet-CIDR>]", i.e. "0:10.20.0.0/16" or "1:" (empty subnet ID is allowed for backwards-compatibility).

func (*State) WatchRestoreInfoChanges

func (st *State) WatchRestoreInfoChanges() NotifyWatcher

WatchRestoreInfoChanges returns a NotifyWatcher that will inform when the restore status changes.

func (*State) WatchServices

func (st *State) WatchServices() StringsWatcher

WatchServices returns a StringsWatcher that notifies of changes to the lifecycles of the services in the model.

func (*State) WatchStorageAttachment

func (st *State) WatchStorageAttachment(s names.StorageTag, u names.UnitTag) NotifyWatcher

WatchStorageAttachment returns a watcher for observing changes to a storage attachment.

func (*State) WatchStorageAttachments

func (st *State) WatchStorageAttachments(unit names.UnitTag) StringsWatcher

WatchStorageAttachments returns a StringsWatcher that notifies of changes to the lifecycles of all storage instances attached to the specified unit.

func (*State) WatchUpgradeInfo

func (st *State) WatchUpgradeInfo() NotifyWatcher

WatchUpgradeInfo returns a watcher for observing changes to upgrade synchronisation state.

func (*State) WatchVolumeAttachment

func (st *State) WatchVolumeAttachment(m names.MachineTag, v names.VolumeTag) NotifyWatcher

WatchVolumeAttachment returns a watcher for observing changes to a volume attachment.

type StatePool

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

StatePool is a simple cache of State instances for multiple models.

func NewStatePool

func NewStatePool(systemState *State) *StatePool

NewStatePool returns a new StatePool instance. It takes a State connected to the system (controller model).

func (*StatePool) Close

func (p *StatePool) Close() error

Close closes all State instances in the pool.

func (*StatePool) Get

func (p *StatePool) Get(modelUUID string) (*State, error)

Get returns a State for a given model from the pool, creating one if required.

func (*StatePool) SystemState

func (p *StatePool) SystemState() *State

SystemState returns the State passed in to NewStatePool.

type StateServingInfo

type StateServingInfo struct {
	APIPort      int
	StatePort    int
	Cert         string
	PrivateKey   string
	CAPrivateKey string
	// this will be passed as the KeyFile argument to MongoDB
	SharedSecret   string
	SystemIdentity string
}

StateServingInfo holds information needed by a controller. This type is a copy of the type of the same name from the api/params package. It is replicated here to avoid the state pacakge depending on api/params.

NOTE(fwereade): the api/params type exists *purely* for representing this data over the wire, and has a legitimate reason to exist. This type does not: it's non-implementation-specific and shoudl be defined under core/ somewhere, so it can be used both here and in the agent without dragging unnecessary/irrelevant packages into scope.

type StateSettings

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

StateSettings is used to expose various settings APIs outside of the state package.

func NewStateSettings

func NewStateSettings(st *State) *StateSettings

NewStateSettings creates a StateSettings from state.

func (*StateSettings) CreateSettings

func (s *StateSettings) CreateSettings(key string, settings map[string]interface{}) error

CreateSettings exposes createSettings on state for use outside the state package.

func (*StateSettings) ListSettings

func (s *StateSettings) ListSettings(keyPrefix string) (map[string]map[string]interface{}, error)

ListSettings exposes listSettings on state for use outside the state package.

func (*StateSettings) ReadSettings

func (s *StateSettings) ReadSettings(key string) (map[string]interface{}, error)

ReadSettings exposes readSettings on state for use outside the state package.

func (*StateSettings) RemoveSettings

func (s *StateSettings) RemoveSettings(key string) error

RemoveSettings exposes removeSettings on state for use outside the state package.

type StorageAttachment

type StorageAttachment interface {
	// StorageInstance returns the tag of the corresponding storage
	// instance.
	StorageInstance() names.StorageTag

	// Unit returns the tag of the corresponding unit.
	Unit() names.UnitTag

	// Life reports whether the storage attachment is Alive, Dying or Dead.
	Life() Life
}

StorageAttachment represents the state of a unit's attachment to a storage instance. A non-shared storage instance will have a single attachment for the storage instance's owning unit, whereas a shared storage instance will have an attachment for each unit of the service owning the storage instance.

type StorageConstraints

type StorageConstraints struct {
	// Pool is the name of the storage pool from which to provision the
	// storage instances.
	Pool string `bson:"pool"`

	// Size is the required size of the storage instances, in MiB.
	Size uint64 `bson:"size"`

	// Count is the required number of storage instances.
	Count uint64 `bson:"count"`
}

StorageConstraints contains the user-specified constraints for provisioning storage instances for a service unit.

type StorageInstance

type StorageInstance interface {
	Entity

	// StorageTag returns the tag for the storage instance.
	StorageTag() names.StorageTag

	// Kind returns the storage instance kind.
	Kind() StorageKind

	// Owner returns the tag of the application or unit that owns this storage
	// instance.
	Owner() names.Tag

	// StorageName returns the name of the storage, as defined in the charm
	// storage metadata. This does not uniquely identify storage instances,
	// but identifies the group that the instances belong to.
	StorageName() string

	// Life reports whether the storage instance is Alive, Dying or Dead.
	Life() Life
}

StorageInstance represents the state of a unit or application-wide storage instance in the model.

type StorageKind

type StorageKind int

StorageKind defines the type of a store: whether it is a block device or a filesystem.

const (
	StorageKindUnknown StorageKind = iota
	StorageKindBlock
	StorageKindFilesystem
)

func (StorageKind) String

func (k StorageKind) String() string

String returns a human readable string represting the type.

type StringsWatcher

type StringsWatcher interface {
	Watcher
	Changes() <-chan []string
}

StringsWatcher generates signals when something changes, returning the changes as a list of strings.

type Subnet

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

func (*Subnet) AvailabilityZone

func (s *Subnet) AvailabilityZone() string

AvailabilityZone returns the availability zone of the subnet. If the subnet is not associated with an availability zone it will be the empty string.

func (*Subnet) CIDR

func (s *Subnet) CIDR() string

CIDR returns the subnet CIDR (e.g. 192.168.50.0/24).

func (*Subnet) EnsureDead

func (s *Subnet) EnsureDead() (err error)

EnsureDead sets the Life of the subnet to Dead, if it's Alive. If the subnet is already Dead, no error is returned. When the subnet is no longer Alive or already removed, errNotAlive is returned.

func (*Subnet) GoString

func (s *Subnet) GoString() string

GoString implements fmt.GoStringer.

func (*Subnet) ID

func (s *Subnet) ID() string

ID returns the unique id for the subnet, for other entities to reference it.

func (*Subnet) Life

func (s *Subnet) Life() Life

Life returns whether the subnet is Alive, Dying or Dead.

func (*Subnet) ProviderId

func (s *Subnet) ProviderId() network.Id

ProviderId returns the provider-specific id of the subnet.

func (*Subnet) Refresh

func (s *Subnet) Refresh() error

Refresh refreshes the contents of the Subnet from the underlying state. It an error that satisfies errors.IsNotFound if the Subnet has been removed.

func (*Subnet) Remove

func (s *Subnet) Remove() (err error)

Remove removes a Dead subnet. If the subnet is not Dead or it is already removed, an error is returned. On success, all IP addresses added to the subnet are also removed.

func (*Subnet) SpaceName

func (s *Subnet) SpaceName() string

SpaceName returns the space the subnet is associated with. If the subnet is not associated with a space it will be the empty string.

func (*Subnet) String

func (s *Subnet) String() string

String implements fmt.Stringer.

func (*Subnet) VLANTag

func (s *Subnet) VLANTag() int

VLANTag returns the subnet VLAN tag. It's a number between 1 and 4094 for VLANs and 0 if the network is not a VLAN.

func (*Subnet) Validate

func (s *Subnet) Validate() error

Validate validates the subnet, checking the CIDR, and VLANTag, if present.

type SubnetInfo

type SubnetInfo struct {
	// ProviderId is a provider-specific network id. This may be empty.
	ProviderId network.Id

	// CIDR of the network, in 123.45.67.89/24 format.
	CIDR string

	// VLANTag needs to be between 1 and 4094 for VLANs and 0 for normal
	// networks. It's defined by IEEE 802.1Q standard.
	VLANTag int

	// AvailabilityZone describes which availability zone this subnet is in. It can
	// be empty if the provider does not support availability zones.
	AvailabilityZone string

	// SpaceName is the name of the space the subnet is associated with. It
	// can be empty if the subnet is not associated with a space yet.
	SpaceName string
}

SubnetInfo describes a single subnet.

type Unit

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

Unit represents the state of a service unit.

func (*Unit) ActionSpecs

func (u *Unit) ActionSpecs() (ActionSpecsByName, error)

ActionSpecs gets the ActionSpec map for the Unit's charm.

func (*Unit) Actions

func (u *Unit) Actions() ([]Action, error)

Actions returns a list of actions pending or completed for this unit.

func (*Unit) AddAction

func (u *Unit) AddAction(name string, payload map[string]interface{}) (Action, error)

AddAction adds a new Action of type name and using arguments payload to this Unit, and returns its ID. Note that the use of spec.InsertDefaults mutates payload.

func (*Unit) Agent

func (u *Unit) Agent() *UnitAgent

Agent Returns an agent by its unit's name.

func (*Unit) AgentHistory

func (u *Unit) AgentHistory() status.StatusHistoryGetter

AgentHistory returns an StatusHistoryGetter which can be used to query the status history of the unit's agent.

func (*Unit) AgentPresence

func (u *Unit) AgentPresence() (bool, error)

AgentPresence returns whether the respective remote agent is alive.

func (*Unit) AgentStatus

func (u *Unit) AgentStatus() (status.StatusInfo, error)

AgentStatus calls Status for this unit's agent, this call is equivalent to the former call to Status when Agent and Unit where not separate entities.

func (*Unit) AgentTools

func (u *Unit) AgentTools() (*tools.Tools, error)

AgentTools returns the tools that the agent is currently running. It an error that satisfies errors.IsNotFound if the tools have not yet been set.

func (*Unit) Application

func (u *Unit) Application() (*Application, error)

Application returns the application.

func (*Unit) ApplicationName

func (u *Unit) ApplicationName() string

ApplicationName returns the application name.

func (*Unit) AssignToCleanEmptyMachine

func (u *Unit) AssignToCleanEmptyMachine() (m *Machine, err error)

AssignToCleanEmptyMachine assigns u to a machine which is marked as clean and is also not hosting any containers. A machine is clean if it has never had any principal units assigned to it. If there are no clean machines besides any machine(s) running JobHostEnviron, an error is returned. This method does not take constraints into consideration when choosing a machine (lp:1161919).

func (*Unit) AssignToCleanMachine

func (u *Unit) AssignToCleanMachine() (m *Machine, err error)

AssignToCleanMachine assigns u to a machine which is marked as clean. A machine is clean if it has never had any principal units assigned to it. If there are no clean machines besides any machine(s) running JobHostEnviron, an error is returned. This method does not take constraints into consideration when choosing a machine (lp:1161919).

func (*Unit) AssignToMachine

func (u *Unit) AssignToMachine(m *Machine) (err error)

AssignToMachine assigns this unit to a given machine.

func (*Unit) AssignToNewMachine

func (u *Unit) AssignToNewMachine() (err error)

AssignToNewMachine assigns the unit to a new machine, with constraints determined according to the service and model constraints at the time of unit creation.

func (*Unit) AssignToNewMachineOrContainer

func (u *Unit) AssignToNewMachineOrContainer() (err error)

AssignToNewMachineOrContainer assigns the unit to a new machine, with constraints determined according to the service and model constraints at the time of unit creation. If a container is required, a clean, empty machine instance is required on which to create the container. An existing clean, empty instance is first searched for, and if not found, a new one is created.

func (*Unit) AssignedMachineId

func (u *Unit) AssignedMachineId() (id string, err error)

AssignedMachineId returns the id of the assigned machine.

func (*Unit) AvailabilityZone

func (u *Unit) AvailabilityZone() (string, error)

AvailabilityZone returns the name of the availability zone into which the unit's machine instance was provisioned.

func (*Unit) CancelAction

func (u *Unit) CancelAction(action Action) (Action, error)

CancelAction removes a pending Action from the queue for this ActionReceiver and marks it as cancelled.

func (*Unit) CharmURL

func (u *Unit) CharmURL() (*charm.URL, bool)

CharmURL returns the charm URL this unit is currently using.

func (*Unit) ClearResolved

func (u *Unit) ClearResolved() error

ClearResolved removes any resolved setting on the unit.

func (*Unit) ClosePort

func (u *Unit) ClosePort(protocol string, number int) error

ClosePort closes the given port and protocol for the unit.

TODO(dimitern): This should be removed once we use ClosePortsOnSubnet across the board, passing subnet IDs explicitly.

func (*Unit) ClosePortOnSubnet

func (u *Unit) ClosePortOnSubnet(subnetID, protocol string, number int) error

ClosePortOnSubnet closes the given port and protocol for the unit on the given subnet, which can be empty. When non-empty, subnetID must refer to an existing, alive subnet, otherwise an error is returned.

func (*Unit) ClosePorts

func (u *Unit) ClosePorts(protocol string, fromPort, toPort int) (err error)

ClosePorts closes the given port range and protocol for the unit.

TODO(dimitern): This should be removed once we use ClosePortsOnSubnet across the board, passing subnet IDs explicitly.

func (*Unit) ClosePortsOnSubnet

func (u *Unit) ClosePortsOnSubnet(subnetID, protocol string, fromPort, toPort int) (err error)

ClosePortsOnSubnet closes the given port range and protocol for the unit on the given subnet, which can be empty. When non-empty, subnetID must refer to an existing, alive subnet, otherwise an error is returned.

func (*Unit) CompletedActions

func (u *Unit) CompletedActions() ([]Action, error)

CompletedActions returns a list of actions that have finished for this unit.

func (*Unit) ConfigSettings

func (u *Unit) ConfigSettings() (charm.Settings, error)

ConfigSettings returns the complete set of service charm config settings available to the unit. Unset values will be replaced with the default value for the associated option, and may thus be nil when no default is specified.

func (*Unit) Constraints

func (u *Unit) Constraints() (*constraints.Value, error)

Constraints returns the unit's deployment constraints.

func (*Unit) DeployerTag

func (u *Unit) DeployerTag() (names.Tag, bool)

DeployerTag returns the tag of the agent responsible for deploying the unit. If no such entity can be determined, false is returned.

func (*Unit) Destroy

func (u *Unit) Destroy() (err error)

Destroy, when called on a Alive unit, advances its lifecycle as far as possible; it otherwise has no effect. In most situations, the unit's life is just set to Dying; but if a principal unit that is not assigned to a provisioned machine is Destroyed, it will be removed from state directly.

func (*Unit) EnsureDead

func (u *Unit) EnsureDead() (err error)

EnsureDead sets the unit lifecycle to Dead if it is Alive or Dying. It does nothing otherwise. If the unit has subordinates, it will return ErrUnitHasSubordinates; otherwise, if it has storage instances, it will return ErrUnitHasStorageInstances.

func (*Unit) GetMeterStatus

func (u *Unit) GetMeterStatus() (MeterStatus, error)

GetMeterStatus returns the meter status for the unit.

func (*Unit) IsPrincipal

func (u *Unit) IsPrincipal() bool

IsPrincipal returns whether the unit is deployed in its own container, and can therefore have subordinate services deployed alongside it.

func (*Unit) Life

func (u *Unit) Life() Life

Life returns whether the unit is Alive, Dying or Dead.

func (*Unit) Name

func (u *Unit) Name() string

Name returns the unit name.

func (*Unit) OpenPort

func (u *Unit) OpenPort(protocol string, number int) error

OpenPort opens the given port and protocol for the unit.

TODO(dimitern): This should be removed once we use OpenPort(s)OnSubnet across the board, passing subnet IDs explicitly.

func (*Unit) OpenPortOnSubnet

func (u *Unit) OpenPortOnSubnet(subnetID, protocol string, number int) error

OpenPortOnSubnet opens the given port and protocol for the unit on the given subnet, which can be empty. When non-empty, subnetID must refer to an existing, alive subnet, otherwise an error is returned.

func (*Unit) OpenPorts

func (u *Unit) OpenPorts(protocol string, fromPort, toPort int) error

OpenPorts opens the given port range and protocol for the unit, if it does not conflict with another already opened range on the unit's assigned machine.

TODO(dimitern): This should be removed once we use OpenPortsOnSubnet across the board, passing subnet IDs explicitly.

func (*Unit) OpenPortsOnSubnet

func (u *Unit) OpenPortsOnSubnet(subnetID, protocol string, fromPort, toPort int) (err error)

OpenPortsOnSubnet opens the given port range and protocol for the unit on the given subnet, which can be empty. When non-empty, subnetID must refer to an existing, alive subnet, otherwise an error is returned. Returns an error if opening the requested range conflicts with another already opened range on the same subnet and and the unit's assigned machine.

func (*Unit) OpenedPorts

func (u *Unit) OpenedPorts() ([]network.PortRange, error)

OpenedPorts returns a slice containing the open port ranges of the unit.

TODO(dimitern): This should be removed once we use OpenedPortsOnSubnet across the board, passing subnet IDs explicitly.

func (*Unit) OpenedPortsOnSubnet

func (u *Unit) OpenedPortsOnSubnet(subnetID string) ([]network.PortRange, error)

OpenedPortsOnSubnet returns a slice containing the open port ranges of the unit on the given subnet ID, which can be empty. When subnetID is not empty, it must refer to an existing, alive subnet, otherwise an error is returned. Also, when no ports are yet open for the unit on that subnet, no error and empty slice is returned.

func (*Unit) PasswordValid

func (u *Unit) PasswordValid(password string) bool

PasswordValid returns whether the given password is valid for the given unit.

func (*Unit) PendingActions

func (u *Unit) PendingActions() ([]Action, error)

PendingActions returns a list of actions pending for this unit.

func (*Unit) PrincipalName

func (u *Unit) PrincipalName() (string, bool)

PrincipalName returns the name of the unit's principal. If the unit is not a subordinate, false is returned.

func (*Unit) PrivateAddress

func (u *Unit) PrivateAddress() (network.Address, error)

PrivateAddress returns the private address of the unit.

func (*Unit) PublicAddress

func (u *Unit) PublicAddress() (network.Address, error)

PublicAddress returns the public address of the unit.

func (*Unit) Refresh

func (u *Unit) Refresh() error

Refresh refreshes the contents of the Unit from the underlying state. It an error that satisfies errors.IsNotFound if the unit has been removed.

func (*Unit) RelationsInScope

func (u *Unit) RelationsInScope() ([]*Relation, error)

RelationsInScope returns the relations for which the unit has entered scope and not left it.

func (*Unit) RelationsJoined

func (u *Unit) RelationsJoined() ([]*Relation, error)

RelationsJoined returns the relations for which the unit has entered scope and neither left it nor prepared to leave it

func (*Unit) Remove

func (u *Unit) Remove() (err error)

Remove removes the unit from state, and may remove its service as well, if the service is Dying and no other references to it exist. It will fail if the unit is not Dead.

func (*Unit) Resolve

func (u *Unit) Resolve(noretryHooks bool) error

Resolve marks the unit as having had any previous state transition problems resolved, and informs the unit that it may attempt to reestablish normal workflow. The retryHooks parameter informs whether to attempt to reexecute previous failed hooks or to continue as if they had succeeded before.

func (*Unit) Resolved

func (u *Unit) Resolved() ResolvedMode

Resolved returns the resolved mode for the unit.

func (*Unit) RunningActions

func (u *Unit) RunningActions() ([]Action, error)

RunningActions returns a list of actions running on this unit.

func (*Unit) Series

func (u *Unit) Series() string

Series returns the deployed charm's series.

func (*Unit) SetAgentPresence

func (u *Unit) SetAgentPresence() (*presence.Pinger, error)

SetAgentPresence signals that the agent for unit u is alive. It returns the started pinger.

func (*Unit) SetAgentStatus

func (u *Unit) SetAgentStatus(agentStatus status.StatusInfo) error

SetAgentStatus calls SetStatus for this unit's agent, this call is equivalent to the former call to SetStatus when Agent and Unit where not separate entities.

func (*Unit) SetAgentVersion

func (u *Unit) SetAgentVersion(v version.Binary) (err error)

SetAgentVersion sets the version of juju that the agent is currently running.

func (*Unit) SetCharmURL

func (u *Unit) SetCharmURL(curl *charm.URL) error

SetCharmURL marks the unit as currently using the supplied charm URL. An error will be returned if the unit is dead, or the charm URL not known.

func (*Unit) SetMeterStatus

func (u *Unit) SetMeterStatus(codeStr, info string) error

SetMeterStatus sets the meter status for the unit.

func (*Unit) SetPassword

func (u *Unit) SetPassword(password string) error

SetPassword sets the password for the machine's agent.

func (*Unit) SetResolved

func (u *Unit) SetResolved(mode ResolvedMode) (err error)

SetResolved marks the unit as having had any previous state transition problems resolved, and informs the unit that it may attempt to reestablish normal workflow. The resolved mode parameter informs whether to attempt to reexecute previous failed hooks or to continue as if they had succeeded before.

func (*Unit) SetStatus

func (u *Unit) SetStatus(unitStatus status.StatusInfo) error

SetStatus sets the status of the unit agent. The optional values allow to pass additional helpful status data. This method relies on globalKey instead of globalAgentKey since it is part of the effort to separate Unit from UnitAgent. Now the SetStatus for UnitAgent is in the UnitAgent struct.

func (*Unit) SetWorkloadVersion

func (u *Unit) SetWorkloadVersion(version string) error

SetWorkloadVersion sets the version of the workload that the unit is currently running.

func (*Unit) Status

func (u *Unit) Status() (status.StatusInfo, error)

Status returns the status of the unit. This method relies on globalKey instead of globalAgentKey since it is part of the effort to separate Unit from UnitAgent. Now the Status for UnitAgent is in the UnitAgent struct.

func (*Unit) StatusHistory

func (u *Unit) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

StatusHistory returns a slice of at most <size> StatusInfo items or items as old as <date> or items newer than now - <delta> time representing past statuses for this unit.

func (*Unit) StorageConstraints

func (u *Unit) StorageConstraints() (map[string]StorageConstraints, error)

StorageConstraints returns the unit's storage constraints.

func (*Unit) String

func (u *Unit) String() string

String returns the unit as string.

func (*Unit) SubordinateNames

func (u *Unit) SubordinateNames() []string

SubordinateNames returns the names of any subordinate units.

func (*Unit) Tag

func (u *Unit) Tag() names.Tag

Tag returns a name identifying the unit. The returned name will be different from other Tag values returned by any other entities from the same state.

func (*Unit) UnassignFromMachine

func (u *Unit) UnassignFromMachine() (err error)

UnassignFromMachine removes the assignment between this unit and the machine it's assigned to.

func (*Unit) UnitTag

func (u *Unit) UnitTag() names.UnitTag

UnitTag returns a names.UnitTag representing this Unit, unless the unit Name is invalid, in which case it will panic

func (*Unit) WaitAgentPresence

func (u *Unit) WaitAgentPresence(timeout time.Duration) (err error)

WaitAgentPresence blocks until the respective agent is alive.

func (*Unit) Watch

func (u *Unit) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a unit.

func (*Unit) WatchActionNotifications

func (u *Unit) WatchActionNotifications() StringsWatcher

WatchActionNotifications starts and returns a StringsWatcher that notifies when actions with Id prefixes matching this Unit are added

func (*Unit) WatchConfigSettings

func (u *Unit) WatchConfigSettings() (NotifyWatcher, error)

WatchConfigSettings returns a watcher for observing changes to the unit's service configuration settings. The unit must have a charm URL set before this method is called, and the returned watcher will be valid only while the unit's charm URL is not changed. TODO(fwereade): this could be much smarter; if it were, uniter.Filter could be somewhat simpler.

func (*Unit) WatchMeterStatus

func (u *Unit) WatchMeterStatus() NotifyWatcher

WatchMeterStatus returns a watcher observing changes that affect the meter status of a unit.

func (*Unit) WatchSubordinateUnits

func (u *Unit) WatchSubordinateUnits() StringsWatcher

WatchSubordinateUnits returns a StringsWatcher tracking the unit's subordinate units.

func (*Unit) WorkloadVersion

func (u *Unit) WorkloadVersion() (string, error)

WorkloadVersion returns the version of the running workload set by the charm (eg, the version of postgresql that is running, as opposed to the version of the postgresql charm).

func (*Unit) WorkloadVersionHistory

func (u *Unit) WorkloadVersionHistory() *HistoryGetter

WorkloadVersionHistory returns a HistoryGetter which enables the caller to request past workload version changes.

type UnitAgent

type UnitAgent struct {
	status.StatusHistoryGetter
	// contains filtered or unexported fields
}

UnitAgent represents the state of a service's unit agent.

func (*UnitAgent) SetStatus

func (u *UnitAgent) SetStatus(unitAgentStatus status.StatusInfo) (err error)

SetStatus sets the status of the unit agent. The optional values allow to pass additional helpful status data.

func (*UnitAgent) Status

func (u *UnitAgent) Status() (status.StatusInfo, error)

Status returns the status of the unit agent.

func (*UnitAgent) StatusHistory

func (u *UnitAgent) StatusHistory(filter status.StatusHistoryFilter) ([]status.StatusInfo, error)

StatusHistory returns a slice of at most filter.Size StatusInfo items or items as old as filter.Date or items newer than now - filter.Delta time representing past statuses for this agent.

func (*UnitAgent) String

func (u *UnitAgent) String() string

String returns the unit agent as string.

func (*UnitAgent) Tag

func (u *UnitAgent) Tag() names.Tag

Tag returns a names.Tag identifying this agent's unit.

type UnitAssignment

type UnitAssignment struct {
	// Unit is the ID of the unit to be assigned.
	Unit string

	// Scope is the placement scope to apply to the unit.
	Scope string

	// Directive is the placement directive to apply to the unit.
	Directive string
}

UnitAssignment represents a staged unit assignment.

type UnitAssignmentResult

type UnitAssignmentResult struct {
	Unit  string
	Error error
}

UnitAssignmentResult is the result of running a staged unit assignment.

type UnitPayloads

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

UnitPayloads lets you CRUD payloads for a single unit.

func (UnitPayloads) List

func (up UnitPayloads) List(names ...string) ([]payload.Result, error)

List has two different modes of operation, because that's never a bad idea. If you pass no args, it returns information about all payloads tracked by the unit; if you pass names, it returns a slice of results corresponding to names, in which any names not tracked have both the NotFound field *and* an Error set.

func (UnitPayloads) LookUp

func (UnitPayloads) LookUp(name, rawID string) (string, error)

LookUp returns its first argument and no error.

func (UnitPayloads) SetStatus

func (up UnitPayloads) SetStatus(name, status string) error

SetStatus updates the raw status for the identified payload to the provided value. If the payload is missing then payload.ErrNotFound is returned.

func (UnitPayloads) Track

func (up UnitPayloads) Track(pl payload.Payload) error

Track inserts the provided payload info in state. If the payload is already in the DB then it is replaced.

func (UnitPayloads) Untrack

func (up UnitPayloads) Untrack(name string) error

Untrack removes the identified payload from state. It does not trigger the actual destruction of the payload. If the payload is missing then this is a noop.

type UnitsWatcher

type UnitsWatcher interface {
	Entity
	WatchUnits() StringsWatcher
}

UnitsWatcher defines the methods needed to retrieve an entity (a machine or a service) and watch its units.

type UpgradeInfo

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

UpgradeInfo is used to synchronise controller upgrades.

func (*UpgradeInfo) Abort

func (info *UpgradeInfo) Abort() error

Abort marks the current upgrade as aborted. It should be called if the upgrade can't be completed for some reason.

func (*UpgradeInfo) AllProvisionedControllersReady

func (info *UpgradeInfo) AllProvisionedControllersReady() (bool, error)

AllProvisionedControllersReady returns true if and only if all controllers that have been started by the provisioner have called EnsureUpgradeInfo with matching versions.

When this returns true the master state controller can begin it's own upgrade.

func (*UpgradeInfo) ControllersDone

func (info *UpgradeInfo) ControllersDone() []string

ControllersDone returns the machine ids for controllers that have completed their upgrades.

func (*UpgradeInfo) ControllersReady

func (info *UpgradeInfo) ControllersReady() []string

ControllersReady returns the machine ids for controllers that have signalled that they are ready for upgrade.

func (*UpgradeInfo) PreviousVersion

func (info *UpgradeInfo) PreviousVersion() version.Number

PreviousVersion returns the version being upgraded from.

func (*UpgradeInfo) Refresh

func (info *UpgradeInfo) Refresh() error

Refresh updates the contents of the UpgradeInfo from underlying state.

func (*UpgradeInfo) SetControllerDone

func (info *UpgradeInfo) SetControllerDone(machineId string) error

SetControllerDone marks the supplied state machineId as having completed its upgrades. When SetControllerDone is called by the last provisioned controller, the current upgrade info document will be archived with a status of UpgradeComplete.

func (*UpgradeInfo) SetStatus

func (info *UpgradeInfo) SetStatus(status UpgradeStatus) error

SetStatus sets the status of the current upgrade. Checks are made to ensure that status changes are performed in the correct order.

func (*UpgradeInfo) Started

func (info *UpgradeInfo) Started() time.Time

Started returns the time at which the upgrade was started.

func (*UpgradeInfo) Status

func (info *UpgradeInfo) Status() UpgradeStatus

Status returns the status of the upgrade.

func (*UpgradeInfo) TargetVersion

func (info *UpgradeInfo) TargetVersion() version.Number

TargetVersion returns the version being upgraded to.

func (*UpgradeInfo) Watch

func (info *UpgradeInfo) Watch() NotifyWatcher

Watch returns a watcher for the state underlying the current UpgradeInfo instance. This is provided purely for convenience.

type UpgradeMongoParams

type UpgradeMongoParams struct {
	RsMembers []replicaset.Member

	Master  HAMember
	Members []HAMember
}

UpgradeMongoParams holds information that identifies the machines part of HA.

type UpgradeStatus

type UpgradeStatus string

UpgradeStatus describes the states an upgrade operation may be in.

const (
	// UpgradePending indicates that an upgrade is queued but not yet started.
	UpgradePending UpgradeStatus = "pending"

	// UpgradeRunning indicates that the master controller has started
	// running upgrade logic, and other controllers are waiting for it.
	UpgradeRunning UpgradeStatus = "running"

	// UpgradeFinishing indicates that the master controller has finished
	// running upgrade logic, and other controllers are catching up.
	UpgradeFinishing UpgradeStatus = "finishing"

	// UpgradeComplete indicates that all controllers have finished running
	// upgrade logic.
	UpgradeComplete UpgradeStatus = "complete"

	// UpgradeAborted indicates that the upgrade wasn't completed due
	// to some problem.
	UpgradeAborted UpgradeStatus = "aborted"
)

type User

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

User represents a local user in the database.

func (*User) CreatedBy

func (u *User) CreatedBy() string

CreatedBy returns the name of the User that created this User.

func (*User) DateCreated

func (u *User) DateCreated() time.Time

DateCreated returns when this User was created in UTC.

func (*User) Disable

func (u *User) Disable() error

Disable deactivates the user. Disabled identities cannot log in.

func (*User) DisplayName

func (u *User) DisplayName() string

DisplayName returns the display name of the User.

func (*User) Enable

func (u *User) Enable() error

Enable reactivates the user, setting disabled to false.

func (*User) IsDeleted

func (u *User) IsDeleted() bool

IsDeleted returns whether the user is currently deleted.

func (*User) IsDisabled

func (u *User) IsDisabled() bool

IsDisabled returns whether the user is currently enabled.

func (*User) LastLogin

func (u *User) LastLogin() (time.Time, error)

LastLogin returns when this User last connected through the API in UTC. The resulting time will be nil if the user has never logged in. In the normal case, the LastLogin is the last time that the user connected through the API server.

func (*User) Name

func (u *User) Name() string

Name returns the User name.

func (*User) PasswordValid

func (u *User) PasswordValid(password string) bool

PasswordValid returns whether the given password is valid for the User. The caller should call user.Refresh before calling this.

func (*User) Refresh

func (u *User) Refresh() error

Refresh refreshes information about the User from the state.

func (*User) SecretKey

func (u *User) SecretKey() []byte

SecretKey returns the user's secret key, if any.

func (*User) SetPassword

func (u *User) SetPassword(password string) error

SetPassword sets the password associated with the User.

func (*User) SetPasswordHash

func (u *User) SetPasswordHash(pwHash string, pwSalt string) error

SetPasswordHash stores the hash and the salt of the password. If the User has a secret key set then it will be cleared.

func (*User) String

func (u *User) String() string

String returns "<name>@local" where <name> is the Name of the user.

func (*User) Tag

func (u *User) Tag() names.Tag

Tag returns the Tag for the User.

func (*User) UpdateLastLogin

func (u *User) UpdateLastLogin() (err error)

UpdateLastLogin sets the LastLogin time of the user to be now (to the nearest second).

func (*User) UserTag

func (u *User) UserTag() names.UserTag

UserTag returns the Tag for the User.

type UserAccessSpec

type UserAccessSpec struct {
	User        names.UserTag
	CreatedBy   names.UserTag
	DisplayName string
	Access      permission.Access
}

UserAccessSpec defines the attributes that can be set when adding a new user access.

type UserModel

type UserModel struct {
	*Model
	User names.UserTag
}

UserModel contains information about an model that a user has access to.

func (*UserModel) LastConnection

func (e *UserModel) LastConnection() (time.Time, error)

LastConnection returns the last time the user has connected to the model.

type ValidateConfigFunc

type ValidateConfigFunc func(updateAttrs map[string]interface{}, removeAttrs []string, oldConfig *config.Config) error

type Volume

type Volume interface {
	GlobalEntity
	LifeBinder
	status.StatusGetter
	status.StatusSetter

	// VolumeTag returns the tag for the volume.
	VolumeTag() names.VolumeTag

	// StorageInstance returns the tag of the storage instance that this
	// volume is assigned to, if any. If the volume is not assigned to
	// a storage instance, an error satisfying errors.IsNotAssigned will
	// be returned.
	//
	// A volume can be assigned to at most one storage instance, and a
	// storage instance can have at most one associated volume.
	StorageInstance() (names.StorageTag, error)

	// Info returns the volume's VolumeInfo, or a NotProvisioned
	// error if the volume has not yet been provisioned.
	Info() (VolumeInfo, error)

	// Params returns the parameters for provisioning the volume,
	// if it has not already been provisioned. Params returns true if the
	// returned parameters are usable for provisioning, otherwise false.
	Params() (VolumeParams, bool)
}

Volume describes a volume (disk, logical volume, etc.) in the model.

type VolumeAttachment

type VolumeAttachment interface {
	Lifer

	// Volume returns the tag of the related Volume.
	Volume() names.VolumeTag

	// Machine returns the tag of the related Machine.
	Machine() names.MachineTag

	// Info returns the volume attachment's VolumeAttachmentInfo, or a
	// NotProvisioned error if the attachment has not yet been made.
	//
	// TODO(axw) use a different error, rather than NotProvisioned
	// (say, NotAttached or NotAssociated).
	Info() (VolumeAttachmentInfo, error)

	// Params returns the parameters for creating the volume attachment,
	// if it has not already been made. Params returns true if the returned
	// parameters are usable for creating an attachment, otherwise false.
	Params() (VolumeAttachmentParams, bool)
}

VolumeAttachment describes an attachment of a volume to a machine.

type VolumeAttachmentInfo

type VolumeAttachmentInfo struct {
	DeviceName string `bson:"devicename,omitempty"`
	DeviceLink string `bson:"devicelink,omitempty"`
	BusAddress string `bson:"busaddress,omitempty"`
	ReadOnly   bool   `bson:"read-only"`
}

VolumeAttachmentInfo describes information about a volume attachment.

type VolumeAttachmentParams

type VolumeAttachmentParams struct {
	ReadOnly bool `bson:"read-only"`
}

VolumeAttachmentParams records parameters for attaching a volume to a machine.

type VolumeInfo

type VolumeInfo struct {
	HardwareId string `bson:"hardwareid,omitempty"`
	Size       uint64 `bson:"size"`
	Pool       string `bson:"pool"`
	VolumeId   string `bson:"volumeid"`
	Persistent bool   `bson:"persistent"`
}

VolumeInfo describes information about a volume.

type VolumeParams

type VolumeParams struct {
	Pool string `bson:"pool"`
	Size uint64 `bson:"size"`
	// contains filtered or unexported fields
}

VolumeParams records parameters for provisioning a new volume.

type Watcher

type Watcher interface {
	// Kill asks the watcher to stop without waiting for it do so.
	Kill()
	// Wait waits for the watcher to die and returns any
	// error encountered when it was running.
	Wait() error
	// Stop kills the watcher, then waits for it to die.
	Stop() error
	// Err returns any error encountered while the watcher
	// has been running.
	Err() error
}

Watcher is implemented by all watchers; the actual changes channel is returned by a watcher-specific Changes method.

Directories

Path Synopsis
Package backups contains all the stand-alone backup-related functionality for juju state.
Package backups contains all the stand-alone backup-related functionality for juju state.
Package bakerystorage provides an implementation of the bakery Storage interface that uses MongoDB to store items.
Package bakerystorage provides an implementation of the bakery Storage interface that uses MongoDB to store items.
internal
The lease package exists to implement distributed lease management on top of mgo/txn, and to expose assert operations that allow us to gate other mgo/txn transactions on lease state.
The lease package exists to implement distributed lease management on top of mgo/txn, and to expose assert operations that allow us to gate other mgo/txn transactions on lease state.
The presence package implements an interface for observing liveness of arbitrary keys (agents, processes, etc) on top of MongoDB.
The presence package implements an interface for observing liveness of arbitrary keys (agents, processes, etc) on top of MongoDB.
Package stateenvirons provides types and functions that interface the state and environs packages.
Package stateenvirons provides types and functions that interface the state and environs packages.
The watcher package provides an interface for observing changes to arbitrary MongoDB documents that are maintained via the mgo/txn transaction package.
The watcher package provides an interface for observing changes to arbitrary MongoDB documents that are maintained via the mgo/txn transaction package.

Jump to

Keyboard shortcuts

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