juju: github.com/juju/juju/state Index | Files | Directories

package state

import "github.com/juju/juju/state"

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

Index

Package Files

action.go addmachine.go address.go allcollections.go allwatcher.go annotations.go application.go applicationoffers.go applicationofferuser.go autocertcache.go backend.go bakerystorage.go binarystorage.go block.go blockdevices.go caasmodel.go callcontext.go charm.go charmref.go cleanup.go cloud.go cloudcontainer.go cloudcredentials.go cloudservice.go clouduser.go collection.go constraints.go container.go containernetworking.go controller.go controlleruser.go database.go devices.go distribution.go docker_resource.go dump.go enableha.go endpoint.go endpoint_bindings.go errors.go externalcontroller.go filesystem.go firewallrules.go forcedoperation.go gui.go images.go initialize.go interface.go leadership.go life.go life_ns.go linklayerdevices.go linklayerdevices_ipaddresses.go linklayerdevices_refs.go logs.go machine.go machine_linklayerdevices.go machine_upgradeseries.go machineremovals.go meterstatus.go metrics.go metricsmanager.go migration_export.go migration_import.go minimumunits.go model.go modelconfig.go modelcredential.go modelgeneration.go modelmigration.go modeloperation.go modelsummaries.go modeluser.go mongo.go multienv.go multiwatcher.go offerconnections.go open.go payloads.go payloads_ns.go persistence.go podspec.go policy.go pool.go ports.go prune.go reboot.go refcounts_ns.go relation.go relationnetworks.go relationunit.go remoteapplication.go remoteentities.go resources.go resources_adapters.go resources_mongo.go resources_persistence.go resources_persistence_staged.go resources_state_resource.go restore.go sequence.go settings.go singular.go spaces.go spacesdiscovery.go sshhostkeys.go state.go status.go storage.go subnets.go txns.go undertaker.go unit.go unit_assignment.go unitagent.go upgrade.go upgrades.go user.go useraccess.go userpermission.go volume.go watcher.go workers.go

Constants

const (
    // SSHRule is a rule for SSH connections.
    SSHRule = WellKnownServiceType("ssh")

    // JujuControllerRule is a rule for connections to the Juju controller.
    JujuControllerRule = WellKnownServiceType("juju-controller")

    // JujuApplicationOfferRule is a rule for connections to a Juju offer.
    JujuApplicationOfferRule = WellKnownServiceType("juju-application-offer")
)
const (
    ModelTypeIAAS = ModelType("iaas")
    ModelTypeCAAS = ModelType("caas")
)
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")
)
const (
    SLAUnsupported = slaLevel("unsupported")
    SLAEssential   = slaLevel("essential")
    SLAStandard    = slaLevel("standard")
    SLAAdvanced    = slaLevel("advanced")
)
const (
    CleanupAge = time.Hour * 24
)
const InitialLeaderClaimTime = time.Minute

Variables

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.

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.

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.

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.

var ErrDead = fmt.Errorf("not found or dead")
var ErrModelNotDying = errors.New("model is not dying")
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.

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

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

var ErrNoDefaultStoragePool = fmt.Errorf("no storage pool specified and no default available")

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

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

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

var ErrSubordinateConstraints = stderrors.New("constraints do not apply to subordinate applications")
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.

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 applications.

var MinVersionSupportNewActionID = version.MustParse("2.6.999")

MinVersionSupportNewActionID should be un-exposed after 2.7 released. TODO(action): un-expose MinVersionSupportNewActionID and IsNewActionIDSupported and remove those helper functions using these two vars in tests from 2.7.0.

var NewBroker caas.NewContainerBrokerFunc = caas.New

NewBroker returns a CAAS broker. Override for testing.

var (

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

func AddActionPruneSettings Uses

func AddActionPruneSettings(pool *StatePool) error

AddActionPruneSettings adds the model settings to control log pruning if they are missing.

func AddCloudModelCounts Uses

func AddCloudModelCounts(pool *StatePool) error

AddCloudModelCounts updates cloud docs to ensure the model count field is set.

func AddControllerLogCollectionsSizeSettings Uses

func AddControllerLogCollectionsSizeSettings(pool *StatePool) error

AddControllerLogCollectionsSizeSettings adds the controller settings to control log pruning and txn log size if they are missing.

func AddControllerNodeDocs Uses

func AddControllerNodeDocs(pool *StatePool) error

AddControllerNodeDocs creates controller nodes for each machine that wants to be a member of the mongo replicaset.

func AddLocalCharmSequences Uses

func AddLocalCharmSequences(pool *StatePool) error

AddLocalCharmSequences creates any missing sequences in the database for tracking already used local charm revisions.

func AddMigrationAttempt Uses

func AddMigrationAttempt(pool *StatePool) error

AddMigrationAttempt adds an "attempt" field to migration documents which are missing one.

func AddModelEnvironVersion Uses

func AddModelEnvironVersion(pool *StatePool) error

AddModelEnvironVersion ensures that all model docs have an environ-version field. For those that do not have one, they are seeded with version zero. This will force all environ upgrade steps to be run; there are only two providers (azure and vsphere) that had upgrade steps at the time, and the upgrade steps are required to be idempotent anyway.

func AddModelLogsSize Uses

func AddModelLogsSize(pool *StatePool) error

AddModelLogsSize to controller config.

func AddModelType Uses

func AddModelType(pool *StatePool) error

AddModelType adds a "type" field to model documents which don't have one. The "iaas" type is used.

func AddNonDetachableStorageMachineId Uses

func AddNonDetachableStorageMachineId(pool *StatePool) error

AddNonDetachableStorageMachineId sets the "machineid" field on volume and filesystem docs that are inherently bound to that machine.

func AddRelationStatus Uses

func AddRelationStatus(pool *StatePool) error

AddRelationStatus sets the initial status for existing relations without a status.

func AddSpaceIdToSpaceDocs Uses

func AddSpaceIdToSpaceDocs(pool *StatePool) (err error)

AddSpaceIdToSpaceDocs ensures that every space document includes a a sequentially generated ID. It also adds a doc for the default space (ID=0).

func AddStatusHistoryPruneSettings Uses

func AddStatusHistoryPruneSettings(pool *StatePool) error

AddStatusHistoryPruneSettings adds the model settings to control log pruning if they are missing.

func AddStorageInstanceConstraints Uses

func AddStorageInstanceConstraints(pool *StatePool) error

AddStorageInstanceConstraints sets the "constraints" field on storage instance docs.

func AddSubnetIdToSubnetDocs Uses

func AddSubnetIdToSubnetDocs(pool *StatePool) (err error)

AddSubnetIdToSubnetDocs ensures that every subnet document includes a a sequentially generated ID.

func AddUpdateStatusHookSettings Uses

func AddUpdateStatusHookSettings(pool *StatePool) error

AddUpdateStatusHookSettings adds the model settings to control how often to run the update-status hook if they are missing.

func ApplicationInstances Uses

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

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

func ApplicationMachines Uses

func ApplicationMachines(st *State, application string) ([]string, error)

ApplicationMachines returns the machine IDs of machines which have the specified application listed as a principal.

func Apply Uses

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 CallContext Uses

func CallContext(st *State) context.ProviderCallContext

func ChangeSubnetAZtoSlice Uses

func ChangeSubnetAZtoSlice(pool *StatePool) (err error)

ChangeSubnetAZtoSlice changes AvailabilityZone in every subnet document to AvailabilityZones, a slice of strings.

func ChangeSubnetSpaceNameToSpaceID Uses

func ChangeSubnetSpaceNameToSpaceID(pool *StatePool) (err error)

ChangeSubnetSpaceNameToSpaceID replaces the SpaceName with the SpaceID in a subnet.

func ContainerTypeFromId Uses

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 Uses

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

func ConvertAddressSpaceIDs Uses

func ConvertAddressSpaceIDs(pool *StatePool) error

ConvertAddressSpaceIDs interrogates stored addresses. Where such addresses include a space name or provider ID, The space is retrieved and these fields are removed in favour of space's ID.

func CorrectRelationUnitCounts Uses

func CorrectRelationUnitCounts(pool *StatePool) error

CorrectRelationUnitCounts ensures that there aren't any rows in relationscopes for applications that shouldn't be there. Fix for https://bugs.launchpad.net/juju/+bug/1699050

func CreateMissingApplicationConfig Uses

func CreateMissingApplicationConfig(pool *StatePool) error

CreateMissingApplicationConfig ensures that all models have an application config in the db.

func DefaultEndpointBindingsForCharm Uses

func DefaultEndpointBindingsForCharm(st EndpointBinding, charmMeta *charm.Meta) (map[string]string, error)

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 DeleteCloudImageMetadata Uses

func DeleteCloudImageMetadata(pool *StatePool) error

DeleteCloudImageMetadata deletes any non-custom cloud image metadata records from the cloudimagemetadata collection.

func EnsureApplicationDeviceConstraints Uses

func EnsureApplicationDeviceConstraints(pool *StatePool) error

EnsureApplicationDeviceConstraints ensures that there is a device constraints document for every application.

func EnsureDefaultModificationStatus Uses

func EnsureDefaultModificationStatus(pool *StatePool) error

EnsureDefaultModificationStatus ensures that there is a modification status document for every machine in the statuses.

func EnsureDefaultSpaceSetting Uses

func EnsureDefaultSpaceSetting(pool *StatePool) error

EnsureDefaultSpaceSetting sets the model config value for "default-space" to "" if it is unset or is set to the now-deprecated value "_default".

func EnsureRelationApplicationSettings Uses

func EnsureRelationApplicationSettings(pool *StatePool) error

EnsureRelationApplicationSettings creates an application settings doc for each endpoint in each relation if one doesn't already exist.

func ErrStoppedf Uses

func ErrStoppedf(format string, args ...interface{}) error

ErrStoppedf returns an error which satisfies IsErrStopped().

func FilesystemMountPoint Uses

func FilesystemMountPoint(
    meta charm.Storage,
    tag names.StorageTag,
    series string,
) (string, error)

FilesystemMountPoint returns a mount point to use for the given charm storage. For stores with potentially multiple instances, the instance name is appended to the location.

func HostedModelCountOp Uses

func HostedModelCountOp(amount int) txn.Op

func InitDatabase Uses

func InitDatabase(session *mgo.Session, modelUUID string, settings *controller.Config) error

InitDatabase creates all the collections and indices in a Juju database.

func InitDbLogs Uses

func InitDbLogs(session *mgo.Session) error

InitDbLogs sets up the capped collections for the logging, along with the indexes for the logs collection. It should be called as state is opened. It is idempotent.

func InitDbLogsForModel Uses

func InitDbLogsForModel(session *mgo.Session, modelUUID string, size int) error

InitDbLogsForModel sets up the indexes for the logs collection for the specified model. It should be called as state is opened. It is idempotent. This function also ensures that the logs collection is capped at the right size.

func IsCharmAlreadyUploadedError Uses

func IsCharmAlreadyUploadedError(err interface{}) bool

IsCharmAlreadyUploadedError returns if the given error is ErrCharmAlreadyUploaded.

func IsContainsFilesystem Uses

func IsContainsFilesystem(err error) bool

func IsErrStopped Uses

func IsErrStopped(err error) bool

IsErrStopped reports whether the error was created with ErrStoppedf() or NewErrStopped().

func IsHasAssignedUnitsError Uses

func IsHasAssignedUnitsError(err error) bool

func IsHasAttachmentsError Uses

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 Uses

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 Uses

func IsHasHostedModelsError(err error) bool

IsHasHostedModelsError reports whether or not the given error was caused by an attempt to destroy the controller model while it contained non-empty hosted models, without specifying that they should also be destroyed.

func IsHasPersistentStorageError Uses

func IsHasPersistentStorageError(err error) bool

IsHasPersistentStorageError reports whether or not the given error was caused by an attempt to destroy a model while it contained persistent storage, without specifying how the storage should be removed (destroyed or released).

func IsIncompatibleSeriesError Uses

func IsIncompatibleSeriesError(err interface{}) bool

IsIncompatibleSeriesError returns if the given error or its cause is ErrIncompatibleSeries.

func IsMigrationActive Uses

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 IsModelNotEmptyError Uses

func IsModelNotEmptyError(err error) bool

IsModelNotEmptyError reports whether or not the given error was caused due to an operation requiring a model to be empty, where the model is non-empty.

func IsNeverConnectedError Uses

func IsNeverConnectedError(err error) bool

IsNeverConnectedError returns true if err is of type NeverConnectedError.

func IsNeverLoggedInError Uses

func IsNeverLoggedInError(err error) bool

IsNeverLoggedInError returns true if err is of type NeverLoggedInError.

func IsNewActionIDSupported Uses

func IsNewActionIDSupported(ver version.Number) bool

IsNewActionIDSupported checks if new action ID is supported for the specified version.

func IsNotAlive Uses

func IsNotAlive(err error) bool

IsNotAlive returns true if err is cause by a not alive error.

func IsParentDeviceHasChildrenError Uses

func IsParentDeviceHasChildrenError(err interface{}) bool

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

func IsProviderIDNotUniqueError Uses

func IsProviderIDNotUniqueError(err interface{}) bool

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

func IsStorageAttachedError Uses

func IsStorageAttachedError(err error) bool

IsStorageAttachedError reports whether or not the given error was caused by an operation on storage that should not be, but is, attached.

func IsUpgradeInProgressError Uses

func IsUpgradeInProgressError(err error) bool

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

func IsValidAddressConfigMethod Uses

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 IsVersionInconsistentError Uses

func IsVersionInconsistentError(e interface{}) bool

IsVersionInconsistentError returns if the given error is versionInconsistentError.

func LegacyLeases Uses

func LegacyLeases(pool *StatePool, localTime time.Time) (map[corelease.Key]corelease.Info, error)

LegacyLeases returns information about all of the leases in the state-based lease store.

func MigrateAddModelPermissions Uses

func MigrateAddModelPermissions(pool *StatePool) error

MigrateAddModelPermissions converts add-model permissions on the controller to add-model permissions on the controller cloud.

func MigrateLeasesToGlobalTime Uses

func MigrateLeasesToGlobalTime(pool *StatePool) error

MigrateLeasesToGlobalTime removes old (<2.3-beta2) lease/clock-skew documents, replacing the lease documents with new ones for the existing lease holders.

func MigrateStorageMachineIdFields Uses

func MigrateStorageMachineIdFields(pool *StatePool) error

MigrateStorageMachineIdFields updates the various storage collections to copy any machineid field value across to hostid.

func MoveMongoSpaceToHASpaceConfig Uses

func MoveMongoSpaceToHASpaceConfig(pool *StatePool) error

CopyMongoSpaceToHASpaceConfig copies the Mongo space name from ControllerInfo to the HA space name in ControllerConfig. This only happens if the Mongo space state is valid, it is not empty, and if there is no value already set for the HA space name. The old keys are then deleted from ControllerInfo.

func MoveOldAuditLog Uses

func MoveOldAuditLog(pool *StatePool) error

MoveOldAuditLog renames the no-longer-needed audit.log collection to old-audit.log if it has any rows - if it's empty it deletes it.

func NestingLevel Uses

func NestingLevel(machineId string) int

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

func NewApplicationOffers Uses

func NewApplicationOffers(st *State) crossmodel.ApplicationOffers

NewApplicationOffers creates a application directory backed by a state instance.

func NewControllerUserAccess Uses

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

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

func NewDeviceBackend Uses

func NewDeviceBackend(st *State) (*deviceBackend, error)

NewDeviceBackend creates a backend for managing device.

func NewErrStopped Uses

func NewErrStopped() error

NewErrStopped returns an error which wraps err and satisfies IsErrStopped().

func NewExternalControllers Uses

func NewExternalControllers(st *State) *externalControllers

NewExternalControllers creates an external controllers instance backed by a state.

func NewFirewallRules Uses

func NewFirewallRules(st *State) *firewallRulesState

NewFirewallRules creates a FirewallRule instance backed by a state.

func NewModelUserAccess Uses

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

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

func NewProviderIDNotUniqueError Uses

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

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

func NewRelationEgressNetworks Uses

func NewRelationEgressNetworks(st *State) *relationNetworksState

NewRelationEgressNetworks creates a RelationNetworks instance for egress CIDRS backed by a state.

func NewRelationIngressNetworks Uses

func NewRelationIngressNetworks(st *State) *relationNetworksState

NewRelationIngressNetworks creates a RelationNetworks instance for ingress CIDRS backed by a state.

func NewRelationNetworks Uses

func NewRelationNetworks(st *State) *rootRelationNetworksState

NewRelationNetworks creates a root RelationNetworks without a direction, so accessing RelationNetworks is possible agnostically.

func NewStorageBackend Uses

func NewStorageBackend(st *State) (*storageBackend, error)

NewStorageBackend creates a backend for managing storage.

func ParentId Uses

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 Uses

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

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

func ParseVolumeAttachmentId Uses

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

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

func PruneActions Uses

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

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

func PruneStatusHistory Uses

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

func RemoveContainerImageStreamFromNonModelSettings Uses

func RemoveContainerImageStreamFromNonModelSettings(pool *StatePool) error

RemoveContainerImageStreamFromNonModelSettings In 2.3.6 we accidentally had an upgrade step that added "container-image-stream": "released" to all settings documents, not just the ones relating to Model data. This removes it from all the ones that aren't model docs if it is exactly what we would have added in 2.3.6

func RemoveControllerConfigMaxLogAgeAndSize Uses

func RemoveControllerConfigMaxLogAgeAndSize(pool *StatePool) error

RemoveControllerConfigMaxLogAgeAndSize deletes the controller configuration settings for max-logs-age and max-logs-size if they exist.

func RemoveInstanceCharmProfileDataCollection Uses

func RemoveInstanceCharmProfileDataCollection(pool *StatePool) error

RemoveInstanceCharmProfileDataCollection removes the instanceCharmProfileData collection on upgrade.

func RemoveModelBlock Uses

func RemoveModelBlock(st *State, t BlockType) error

func RemoveModelBlockOps Uses

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

func RemoveNilValueApplicationSettings Uses

func RemoveNilValueApplicationSettings(pool *StatePool) error

RemoveNilValueApplicationSettings removes any application setting key-value pairs from "settings" where value is nil.

func RemoveVotingMachineIds Uses

func RemoveVotingMachineIds(pool *StatePool) error

RemoveVotingMachineIds ensures that the 'votingmachineids' field on controller info has been removed

func RenameAddModelPermission Uses

func RenameAddModelPermission(pool *StatePool) error

RenameAddModelPermission renames any permissions called addmodel to add-model.

func ReplacePortsDocSubnetIDCIDR Uses

func ReplacePortsDocSubnetIDCIDR(pool *StatePool) (err error)

ReplacePortsDocSubnetIDCIDR ensures that every ports document use an ID rather than a CIDR for subnetID.

func ReplaceSpaceNameWithIDEndpointBindings Uses

func ReplaceSpaceNameWithIDEndpointBindings(pool *StatePool) error

ReplaceSpaceNameWithIDEndpointBindings replaces space names with space ids for endpoint bindings.

func ReplicaSetMembers Uses

func ReplicaSetMembers(pool *StatePool) ([]replicaset.Member, error)

ReplicaSetMembers gets the members of the current Mongo replica set. These are needed to bootstrap the raft cluster in an upgrade and using MongoSession directly from an upgrade steps would make testing difficult.

func SetEnableDiskUUIDOnVsphere Uses

func SetEnableDiskUUIDOnVsphere(pool *StatePool) error

SetEnableDiskUUIDOnVsphere updates the settings for all vsphere models to have enable-disk-uuid=false. The new default is true, but this maintains the previous behaviour for upgraded models.

func SplitLogCollections Uses

func SplitLogCollections(pool *StatePool) error

SplitLogCollections moves log entries from the old single log collection to the log collection per model.

func StripLocalUserDomain Uses

func StripLocalUserDomain(pool *StatePool) error

StripLocalUserDomain removes any @local suffix from any relevant document field values.

func TopParentId Uses

func TopParentId(machineId string) string

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

func UpdateInheritedControllerConfig Uses

func UpdateInheritedControllerConfig(pool *StatePool) error

UpdateInheritedControllerConfig migrates the existing global settings doc keyed on "controller" to be keyed on the cloud name.

func UpdateK8sModelNameIndex Uses

func UpdateK8sModelNameIndex(pool *StatePool) error

UpdateK8sModelNameIndex migrates k8s model indices to be based on the model owner rather than the cloud name.

func UpdateKubernetesStorageConfig Uses

func UpdateKubernetesStorageConfig(pool *StatePool) error

UpdateKubernetesStorageConfig sets default storage classes for operator and workload storage.

func UpdateLegacyLXDCloudCredentials Uses

func UpdateLegacyLXDCloudCredentials(
    st *State,
    endpoint string,
    credential cloud.Credential,
) error

UpdateLegacyLXDCloudCredentials updates the cloud credentials for the LXD-based controller, and updates the cloud endpoint with the given value.

func UpgradeContainerImageStreamDefault Uses

func UpgradeContainerImageStreamDefault(pool *StatePool) error

UpgradeDefaultContainerImageStreamConfig ensures that the config value for container-image-stream is set to its default value, "released".

func UpgradeNoProxyDefaults Uses

func UpgradeNoProxyDefaults(pool *StatePool) error

UpgradeNoProxyDefaults changes the default values of no_proxy to hold localhost values as defaults.

type Action Uses

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)

    // Log adds message to the action's progress message array.
    Log(message string) error

    // Messages returns the action's progress messages.
    Messages() []ActionMessage
}

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

type ActionMessage Uses

type ActionMessage struct {
    MessageValue   string    `bson:"message"`
    TimestampValue time.Time `bson:"timestamp"`
}

ActionMessage represents a progress message logged by an action.

func (ActionMessage) Message Uses

func (m ActionMessage) Message() string

Message returns the message string.

func (ActionMessage) Timestamp Uses

func (m ActionMessage) Timestamp() time.Time

Timestamp returns the message timestamp.

type ActionReceiver Uses

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 Uses

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 Uses

type ActionSpecsByName map[string]charm.ActionSpec

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

type ActionStatus Uses

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 Uses

type ActionsWatcher interface {
    Entity
    WatchActionNotifications() StringsWatcher
}

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

type AddApplicationArgs Uses

type AddApplicationArgs struct {
    Name              string
    Series            string
    Charm             *Charm
    Channel           csparams.Channel
    Storage           map[string]StorageConstraints
    Devices           map[string]DeviceConstraints
    AttachStorage     []names.StorageTag
    EndpointBindings  map[string]string
    ApplicationConfig *application.Config
    CharmConfig       charm.Settings
    NumUnits          int
    Placement         []*instance.Placement
    Constraints       constraints.Value
    Resources         map[string]string
}

type AddOfferConnectionParams Uses

type AddOfferConnectionParams struct {
    // SourceModelUUID is the UUID of the consuming model.
    SourceModelUUID string

    // OfferUUID is the UUID of the offer.
    OfferUUID string

    // Username is the name of the user who created this connection.
    Username string

    // RelationId is the id of the relation to which this offer pertains.
    RelationId int

    // RelationKey is the key of the relation to which this offer pertains.
    RelationKey string
}

AddOfferConnectionParams contains the parameters for adding an offer connection to the model.

type AddRemoteApplicationParams Uses

type AddRemoteApplicationParams struct {
    // Name is the name to give the remote application. This does not have to
    // match the application name in the URL, or the name in the remote model.
    Name string

    // OfferUUID is the UUID of the offer.
    OfferUUID string

    // URL is either empty, or the URL that the remote application was offered
    // with on the hosting model.
    URL string

    // SourceModel is the tag of the model to which the remote application belongs.
    SourceModel names.ModelTag

    // Token is an opaque string that identifies the remote application in the
    // source model.
    Token string

    // Endpoints describes the endpoints that the remote application implements.
    Endpoints []charm.Relation

    // Spaces describes the network spaces that the remote
    // application's endpoints inhabit in the remote model.
    Spaces []*environs.ProviderSpaceInfo

    // Bindings maps each endpoint name to the remote space it is bound to.
    Bindings map[string]string

    // IsConsumerProxy is true when a remote application is created as a result
    // of a registration operation from a remote model.
    IsConsumerProxy bool

    // Macaroon is used for authentication on the offering side.
    Macaroon *macaroon.Macaroon
}

AddRemoteApplicationParams contains the parameters for adding a remote application to the model.

func (AddRemoteApplicationParams) Validate Uses

func (p AddRemoteApplicationParams) Validate() error

Validate returns an error if there's a problem with the parameters being used to create a remote application.

type AddUnitOperation Uses

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

AddUnitOperation is a model operation that will add a unit.

func (*AddUnitOperation) Build Uses

func (op *AddUnitOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*AddUnitOperation) Done Uses

func (op *AddUnitOperation) Done(err error) error

Done is part of the ModelOperation interface.

type AddUnitParams Uses

type AddUnitParams struct {
    // AttachStorage identifies storage instances to attach to the unit.
    AttachStorage []names.StorageTag

    // ProviderId identifies the unit for a given provider.
    ProviderId *string

    // Address is the container address.
    Address *string

    // Ports are the open ports on the container.
    Ports *[]string
}

AddUnitParams contains parameters for the Application.AddUnit method.

type Address Uses

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 Uses

func (addr *Address) ConfigMethod() AddressConfigMethod

ConfigMethod returns the AddressConfigMethod used for this IP address.

func (*Address) DNSSearchDomains Uses

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

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

func (*Address) DNSServers Uses

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

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

func (*Address) Device Uses

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

Device returns the LinkLayerDevice this IP address is assigned to.

func (*Address) DeviceName Uses

func (addr *Address) DeviceName() string

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

func (*Address) DocID Uses

func (addr *Address) DocID() string

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

func (*Address) GatewayAddress Uses

func (addr *Address) GatewayAddress() string

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

func (*Address) IsDefaultGateway Uses

func (addr *Address) IsDefaultGateway() bool

IsDefaultGateway returns true if this address is used for the default gw on the machine.

func (*Address) LoopbackConfigMethod Uses

func (addr *Address) LoopbackConfigMethod() bool

LoopbackConfigMethod returns whether AddressConfigMethod used for this IP address was loopback.

func (*Address) Machine Uses

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

Machine returns the Machine this IP address belongs to.

func (*Address) MachineID Uses

func (addr *Address) MachineID() string

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

func (*Address) NetworkAddress Uses

func (addr *Address) NetworkAddress() network.SpaceAddress

NetworkAddress returns the address transformed to a network.Address.

func (*Address) ProviderID Uses

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

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

func (*Address) ProviderSubnetID Uses

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

ProviderSubnetID returns the provider-specific subnet ID, if set.

func (*Address) Remove Uses

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 Uses

func (addr *Address) String() string

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

func (*Address) Subnet Uses

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 Uses

func (addr *Address) SubnetCIDR() string

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

func (*Address) Value Uses

func (addr *Address) Value() string

Value returns the value of this IP address.

type AddressConfigMethod Uses

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 Uses

type AgentEntity interface {
    Entity
    Lifer
    Authenticator
    AgentTooler
    status.StatusSetter
    EnsureDeader
    Remover
    NotifyWatcherFactory
}

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

type AgentLiving Uses

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

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

type AgentTooler Uses

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

AgentTooler is implemented by entities that have associated agent tools.

type Application Uses

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

Application represents the state of an application.

func (*Application) AddOperation Uses

func (a *Application) AddOperation(props UnitUpdateProperties) *AddUnitOperation

AddOperation returns a model operation that will add a unit.

func (*Application) AddUnit Uses

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

AddUnit adds a new principal unit to the application.

func (*Application) AgentPresence Uses

func (a *Application) AgentPresence() (bool, error)

AgentPresence returns whether the respective remote agent is alive.

func (*Application) AgentTools Uses

func (a *Application) AgentTools() (*tools.Tools, error)

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

func (*Application) AllUnits Uses

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

AllUnits returns all units of the application.

func (*Application) ApplicationAndUnitsStatus Uses

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

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

func (*Application) ApplicationConfig Uses

func (a *Application) ApplicationConfig() (application.ConfigAttributes, error)

ApplicationConfig returns the configuration for the application itself.

func (*Application) ApplicationTag Uses

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

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

func (*Application) ChangeScale Uses

func (a *Application) ChangeScale(scaleChange int) (int, error)

ChangeScale alters the existing scale by the provided change amount, returning the new amount. This is used on CAAS models.

func (*Application) Channel Uses

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

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

func (*Application) Charm Uses

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

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

func (*Application) CharmConfig Uses

func (a *Application) CharmConfig(branchName string) (charm.Settings, error)

CharmConfig returns the raw user configuration for the application's charm.

func (*Application) CharmModifiedVersion Uses

func (a *Application) CharmModifiedVersion() int

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

func (*Application) CharmURL Uses

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

CharmURL returns the application'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 Uses

func (a *Application) ClearExposed() error

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

func (*Application) Constraints Uses

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

Constraints returns the current application constraints.

func (*Application) DeployedMachines Uses

func (a *Application) DeployedMachines() ([]*Machine, error)

Deployed machines returns the collection of machines that this application has units deployed to.

func (*Application) Destroy Uses

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) DestroyOperation Uses

func (a *Application) DestroyOperation() *DestroyApplicationOperation

DestroyOperation returns a model operation that will destroy the application.

func (*Application) DeviceConstraints Uses

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

DeviceConstraints returns the device constraints for the application.

func (*Application) Endpoint Uses

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

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

func (*Application) EndpointBindings Uses

func (a *Application) EndpointBindings() (*Bindings, error)

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

func (*Application) Endpoints Uses

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

Endpoints returns the application's currently available relation endpoints.

func (*Application) EnsureMinUnits Uses

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

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

func (*Application) GetPlacement Uses

func (a *Application) GetPlacement() string

GetPlacement returns the application's placement directive. This is used on CAAS models.

func (*Application) GetScale Uses

func (a *Application) GetScale() int

GetScale returns the application's desired scale value. This is used on CAAS models.

func (*Application) IsExposed Uses

func (a *Application) IsExposed() bool

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

func (*Application) IsPrincipal Uses

func (a *Application) IsPrincipal() bool

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

func (*Application) IsRemote Uses

func (a *Application) IsRemote() bool

IsRemote returns false for a local application.

func (*Application) LeaderSettings Uses

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

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

func (*Application) Life Uses

func (a *Application) Life() Life

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

func (*Application) MergeBindings Uses

func (a *Application) MergeBindings(operatorBindings *Bindings, force bool) error

MergeBindings merges the provided bindings map with the existing application bindings.

func (*Application) MetricCredentials Uses

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

MetricCredentials returns any metric credentials associated with this application.

func (*Application) MinUnits Uses

func (a *Application) MinUnits() int

MinUnits returns the minimum units count for the application.

func (*Application) Name Uses

func (a *Application) Name() string

Name returns the application name.

func (*Application) PasswordValid Uses

func (a *Application) PasswordValid(password string) bool

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

func (*Application) Refresh Uses

func (a *Application) Refresh() error

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

func (*Application) RelationCount Uses

func (a *Application) RelationCount() int

RelationCount returns the of number of active relations for this application.

func (*Application) Relations Uses

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

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

func (*Application) Series Uses

func (a *Application) Series() string

Series returns the specified series for this charm.

func (*Application) ServiceInfo Uses

func (a *Application) ServiceInfo() (CloudServicer, error)

ServiceInfo returns information about this application's cloud service. This is only used for CAAS models.

func (*Application) SetAgentPresence Uses

func (a *Application) SetAgentPresence() (*presence.Pinger, error)

SetAgentPresence signals that the agent for application a is alive. It returns the started pinger.

func (*Application) SetAgentVersion Uses

func (a *Application) SetAgentVersion(v version.Binary) (err error)

SetAgentVersion sets the Tools value in applicationDoc.

func (*Application) SetCharm Uses

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

SetCharm changes the charm for the application.

func (*Application) SetConstraints Uses

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

SetConstraints replaces the current application constraints.

func (*Application) SetExposed Uses

func (a *Application) SetExposed() error

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

func (*Application) SetMetricCredentials Uses

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

SetMetricCredentials updates the metric credentials associated with this application.

func (*Application) SetMinUnits Uses

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

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

func (*Application) SetOperatorStatus Uses

func (a *Application) SetOperatorStatus(sInfo status.StatusInfo) error

SetOperatorStatus sets the operator status for an application. This is used on CAAS models.

func (*Application) SetPassword Uses

func (a *Application) SetPassword(password string) error

SetPassword sets the password for the application's agent. TODO(caas) - consider a separate CAAS application entity

func (*Application) SetScale Uses

func (a *Application) SetScale(scale int, generation int64, force bool) error

SetScale sets the application's desired scale value. This is used on CAAS models.

func (*Application) SetStatus Uses

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

SetStatus sets the status for the application.

func (*Application) Status Uses

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

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

func (*Application) StatusHistory Uses

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 application.

func (*Application) StorageConstraints Uses

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

StorageConstraints returns the storage constraints for the application.

func (*Application) String Uses

func (a *Application) String() string

String returns the application name.

func (*Application) Tag Uses

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

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

func (*Application) UnitCount Uses

func (a *Application) UnitCount() int

UnitCount returns the of number of units for this application.

func (*Application) UnitNames Uses

func (a *Application) UnitNames() ([]string, error)

UnitNames returns the of this application's units.

func (*Application) UpdateApplicationConfig Uses

func (a *Application) UpdateApplicationConfig(
    changes application.ConfigAttributes,
    reset []string,
    schema environschema.Fields,
    defaults schema.Defaults,
) error

UpdateApplicationConfig changes an application's config settings. Unknown and invalid values will return an error.

func (*Application) UpdateApplicationSeries Uses

func (a *Application) UpdateApplicationSeries(series string, force bool) (err error)

UpdateApplicationSeries updates the series for the Application.

func (*Application) UpdateCharmConfig Uses

func (a *Application) UpdateCharmConfig(branchName string, changes charm.Settings) error

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

func (*Application) UpdateCloudService Uses

func (a *Application) UpdateCloudService(providerId string, addresses []network.SpaceAddress) error

UpdateCloudService updates the cloud service details for the application.

func (*Application) UpdateLeaderSettings Uses

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

UpdateLeaderSettings updates the application'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) UpdateUnits Uses

func (a *Application) UpdateUnits(unitsOp *UpdateUnitsOperation) error

UpdateUnits applies the given application unit update operations.

func (*Application) VerifySupportedSeries Uses

func (a *Application) VerifySupportedSeries(series string, force bool) error

VerifySupportedSeries verifies if the given series is supported by the application.

func (*Application) WaitAgentPresence Uses

func (a *Application) WaitAgentPresence(timeout time.Duration) (err error)

WaitAgentPresence blocks until the respective agent is alive. This should really only be used in the test suite.

func (*Application) Watch Uses

func (a *Application) Watch() NotifyWatcher

Watch returns a watcher for observing changes to an application.

func (*Application) WatchCharmConfig Uses

func (a *Application) WatchCharmConfig() (NotifyWatcher, error)

WatchCharmConfig returns a watcher for observing changes to the application's charm configuration settings. The returned watcher will be valid only while the application's charm URL is not changed.

func (*Application) WatchLeaderSettings Uses

func (a *Application) WatchLeaderSettings() NotifyWatcher

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

func (*Application) WatchRelations Uses

func (a *Application) WatchRelations() StringsWatcher

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

func (*Application) WatchScale Uses

func (a *Application) WatchScale() NotifyWatcher

WatchScale returns a new NotifyWatcher watching for changes to the specified application's scale value.

func (*Application) WatchServiceAddressesHash Uses

func (a *Application) WatchServiceAddressesHash() StringsWatcher

WatchServiceAddressesHash returns a StringsWatcher that emits a hash of the unit's container address whenever it changes.

func (*Application) WatchUnits Uses

func (a *Application) WatchUnits() StringsWatcher

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

type ApplicationEndpointBindings Uses

type ApplicationEndpointBindings struct {
    AppName  string
    Bindings *Bindings
}

ApplicationEndpointBindings - endpointBinding->space details for each application

type ApplicationEntity Uses

type ApplicationEntity interface {
    status.StatusGetter

    // Life returns the life status of the application.
    Life() Life

    // IsRemote returns true if the application is remote (hosted in a different model).
    IsRemote() bool

    // Endpoints returns the application's currently available relation endpoints.
    Endpoints() ([]Endpoint, error)

    // Endpoint returns the relation endpoint with the supplied name, if it exists.
    Endpoint(relationName string) (Endpoint, error)

    // Relations returns a Relation for every relation the application is in.
    Relations() (relations []*Relation, err error)
}

ApplicationEntity represents a local or remote application.

type AssignmentPolicy Uses

type AssignmentPolicy string

AssignmentPolicy controls what machine a unit will be assigned to.

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

    // AssignClean indicates that every application 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 application 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 application unit should be assigned to a new
    // dedicated machine.  A new machine will be launched for each new unit.
    AssignNew AssignmentPolicy = "new"
)

type Authenticator Uses

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

Authenticator represents entites capable of handling password authentication.

type Backing Uses

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 Uses

func NewAllModelWatcherStateBacking(st *State, pool *StatePool) Backing

type BatchParam Uses

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 Bindings Uses

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

Bindings are EndpointBindings.

func NewBindings Uses

func NewBindings(st EndpointBinding, givenMap map[string]string) (*Bindings, error)

NewBindings returns a bindings guaranteed to be in space id format.

func (Bindings) GetBSON Uses

func (b Bindings) GetBSON() (interface{}, error)

GetBSON ensures any special characters ($ or .) are escaped in keys before marshalling the map into BSON and storing in mongo.

func (*Bindings) Map Uses

func (b *Bindings) Map() map[string]string

Map returns the current bindingMap with space ids.

func (*Bindings) MapWithSpaceNames Uses

func (b *Bindings) MapWithSpaceNames() (map[string]string, error)

MapWithSpaceNames returns the current bindingMap with space names rather than ids.

func (*Bindings) Merge Uses

func (b *Bindings) Merge(mergeWith map[string]string, meta *charm.Meta) (bool, error)

Merge the default bindings based on the given charm metadata with the current bindings, overriding with mergeWith values (for the same keys). Current values and mergeWith are both optional and will ignored when empty. The current object contains the combined finalized bindings. Returns true/false if there are any actual differences.

func (*Bindings) SetBSON Uses

func (b *Bindings) SetBSON(raw bson.Raw) error

SetBSON ensures any special characters ($ or .) are unescaped in keys after unmarshalling the raw BSON coming from the stored document.

type Block Uses

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 Uses

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 Uses

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"`
    WWN            string   `bson:"wwn,omitempty"`
    BusAddress     string   `bson:"busaddress,omitempty"`
    Size           uint64   `bson:"size"`
    FilesystemType string   `bson:"fstype,omitempty"`
    InUse          bool     `bson:"inuse"`
    MountPoint     string   `bson:"mountpoint,omitempty"`
    SerialId       string   `bson:"serialid,omitempty"`
}

BlockDeviceInfo describes information about a block device.

type BlockType Uses

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, applications, units or relations.
    RemoveBlock

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

func AllTypes Uses

func AllTypes() []BlockType

AllTypes returns all supported block types.

func ParseBlockType Uses

func ParseBlockType(str string) BlockType

ParseBlockType returns BlockType from humanly readable type representation.

func (BlockType) MigrationValue Uses

func (t BlockType) MigrationValue() string

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

func (BlockType) String Uses

func (t BlockType) String() string

String returns humanly readable type representation.

func (BlockType) ToParams Uses

func (t BlockType) ToParams() model.BlockType

ToParams returns the type as model.BlockType.

type CAASModel Uses

type CAASModel struct {
    // TODO(caas) - this is all still messy until things shake out.
    *Model
    // contains filtered or unexported fields
}

CAASModel contains functionality that is specific to an Containers-As-A-Service (CAAS) model. It embeds a Model so that all generic Model functionality is also available.

func (*CAASModel) Containers Uses

func (m *CAASModel) Containers(providerIds ...string) ([]CloudContainer, error)

Containers returns the containers for the specified provider ids.

func (*CAASModel) PodSpec Uses

func (m *CAASModel) PodSpec(appTag names.ApplicationTag) (string, error)

PodSpec returns the pod spec for the given application tag.

func (*CAASModel) SetPodSpec Uses

func (m *CAASModel) SetPodSpec(appTag names.ApplicationTag, spec string) error

SetPodSpec sets the pod spec for the given application tag. An error will be returned if the specified application is not alive.

func (*CAASModel) WatchPodSpec Uses

func (m *CAASModel) WatchPodSpec(appTag names.ApplicationTag) (NotifyWatcher, error)

WatchPodSpec returns a watcher observing changes that affect the pod spec for an application or unit.

type Change Uses

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 Uses

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

Charm represents the state of a charm in the model.

func (*Charm) Actions Uses

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

Actions returns the actions definition of the charm.

func (*Charm) BundleSha256 Uses

func (c *Charm) BundleSha256() string

BundleSha256 returns the SHA256 digest of the charm bundle bytes.

func (*Charm) Config Uses

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

Config returns the configuration of the charm.

func (*Charm) Destroy Uses

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 Uses

func (c *Charm) IsPlaceholder() bool

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

func (*Charm) IsUploaded Uses

func (c *Charm) IsUploaded() bool

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

func (*Charm) LXDProfile Uses

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

LXDProfile returns the lxd profile definition of the charm.

func (*Charm) Life Uses

func (c *Charm) Life() Life

Life returns the charm's life state.

func (*Charm) Macaroon Uses

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 Uses

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

Meta returns the metadata of the charm.

func (*Charm) Metrics Uses

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

Metrics returns the metrics declared for the charm.

func (*Charm) Refresh Uses

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 Uses

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 Uses

func (c *Charm) Revision() int

Revision returns the monotonically increasing charm revision number.

func (*Charm) StoragePath Uses

func (c *Charm) StoragePath() string

StoragePath returns the storage path of the charm bundle.

func (*Charm) String Uses

func (c *Charm) String() string

func (*Charm) Tag Uses

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

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

func (*Charm) URL Uses

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

URL returns the URL that identifies the charm.

func (*Charm) UpdateMacaroon Uses

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

UpdateMacaroon updates the stored macaroon for this charm.

func (*Charm) Version Uses

func (c *Charm) Version() string

Version returns the charm version.

type CharmInfo Uses

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

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

type CloudAccessor Uses

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

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

type CloudContainer Uses

type CloudContainer interface {
    // Unit returns the name of the unit for this container.
    Unit() string

    // ProviderId returns the id assigned to the container/pod
    // by the cloud.
    ProviderId() string

    // Address returns the container address.
    Address() *network.SpaceAddress

    // Ports returns the open container ports.
    Ports() []string
}

CloudContainer represents the state of a CAAS container, eg pod.

type CloudInfo Uses

type CloudInfo struct {
    cloud.Cloud

    // Access is the access level the supplied user has on this cloud.
    Access permission.Access
}

CloudInfo describes interesting information for a given cloud.

type CloudService Uses

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

CloudService is an implementation of CloudService.

func (*CloudService) Addresses Uses

func (c *CloudService) Addresses() network.SpaceAddresses

Addresses implements CloudServicer.

func (*CloudService) CloudService Uses

func (c *CloudService) CloudService() (*CloudService, error)

CloudService return the content of cloud service from the underlying state. It returns an error that satisfies errors.IsNotFound if the cloud service has been removed.

func (*CloudService) DesiredScaleProtected Uses

func (c *CloudService) DesiredScaleProtected() bool

DesiredScaleProtected implements CloudServicer.

func (*CloudService) Generation Uses

func (c *CloudService) Generation() int64

Generation implements CloudServicer.

func (*CloudService) Id Uses

func (c *CloudService) Id() string

Id implements CloudServicer.

func (*CloudService) ProviderId Uses

func (c *CloudService) ProviderId() string

ProviderId implements CloudServicer.

func (*CloudService) Refresh Uses

func (c *CloudService) Refresh() error

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

func (*CloudService) Watch Uses

func (c *CloudService) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a controller service.

type CloudServicer Uses

type CloudServicer interface {
    // ProviderId returns the id assigned to the service
    // by the cloud.
    ProviderId() string

    // Addresses returns the service addresses.
    Addresses() network.SpaceAddresses

    // Generation returns the service config generation.
    Generation() int64

    // DesiredScaleProtected indicates if current desired scale in application has been applied to the cluster.
    DesiredScaleProtected() bool
}

CloudServicer represents the state of a CAAS service.

type CollectionInfo Uses

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

collectionInfo describes important features of a collection.

type CollectionSchema Uses

type CollectionSchema map[string]CollectionInfo

collectionSchema defines the set of collections used in juju.

func (CollectionSchema) Create Uses

func (schema CollectionSchema) Create(
    db *mgo.Database,
    settings *controller.Config,
) error

Create causes all recorded collections to be created and indexed as specified

type Controller Uses

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

Controller encapsulates state for the Juju controller as a whole, as opposed to model specific functionality.

This type is primarily used in the state.Initialize function, and in the yet to be hooked up controller worker.

func Initialize Uses

func Initialize(args InitializeParams) (_ *Controller, err error)

Initialize sets up the database with all the collections and indices it needs. It also creates the initial model for the controller. This needs to be performed only once for the initial controller model. It returns unauthorizedError if access is unauthorized.

func NewController Uses

func NewController(pool *StatePool) *Controller

NewController returns a controller object that doesn't own the state pool it has been given. This is for convenience at this time to get access to controller methods.

func OpenController Uses

func OpenController(args OpenParams) (*Controller, error)

OpenController connects to the server with the given parameters, waits for it to be initialized, and returns a new Controller instance.

OpenController returns unauthorizedError if access is unauthorized.

func (*Controller) Close Uses

func (ctlr *Controller) Close() error

Close the connection to the database.

func (*Controller) GetState Uses

func (ctlr *Controller) GetState(modelTag names.ModelTag) (*PooledState, error)

GetState returns a new State instance for the specified model. The connection uses the same credentials and policy as the Controller.

func (*Controller) Import Uses

func (ctrl *Controller) Import(model description.Model) (_ *Model, _ *State, err error)

Import the database agnostic model representation into the database.

func (*Controller) NewModel Uses

func (ctlr *Controller) 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 (*Controller) Ping Uses

func (ctlr *Controller) Ping() error

Ping probes the Controllers's database connection to ensure that it is still alive.

func (*Controller) StatePool Uses

func (ctlr *Controller) StatePool() *StatePool

StatePool provides access to the state pool of the controller.

func (*Controller) SystemState Uses

func (ctlr *Controller) SystemState() *State

SystemState returns the State object for the controller model.

type ControllerAccessor Uses

type ControllerAccessor interface {
    ControllerConfig() (controller.Config, error)
    ControllerInfo(modelUUID string) (addrs []string, CACert string, _ error)
}

ControllerAccessor defines the methods needed to access controller information.

type ControllerInfo Uses

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

    // ControllerIds holds the ids of all the controller nodes.
    // It's main purpose is to allow assertions tha the set of
    // controllers hasn't changed when adding/removing controller nodes.
    ControllerIds []string
}

ControllerInfo holds information about currently configured controller machines.

type ControllerNode Uses

type ControllerNode interface {
    Id() string
    Tag() names.Tag
    Refresh() error
    WantsVote() bool
    HasVote() bool
    SetHasVote(hasVote bool) error
    Watch() NotifyWatcher
    SetMongoPassword(password string) error
}

ControllerNode represents an instance of a HA controller.

type ControllerSessioner Uses

type ControllerSessioner interface {
    MongoSessioner

    // IsController indicates if current state is controller.
    IsController() bool
    // contains filtered or unexported methods
}

ControllerSessioner supports creating new mongo sessions for the controller.

type ControllersChanges Uses

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

Change in controllers after the ensure availability txn has committed.

type Credential Uses

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

Credential contains information about the credential as stored on the controller.

func (Credential) CloudCredentialTag Uses

func (c Credential) CloudCredentialTag() (names.CloudCredentialTag, error)

CloudCredentialTag returns cloud credential tag.

func (Credential) IsValid Uses

func (c Credential) IsValid() bool

IsValid indicates whether the credential is valid.

type CredentialOwnerModelAccess Uses

type CredentialOwnerModelAccess struct {
    ModelUUID   string
    ModelName   string
    OwnerAccess permission.Access
    Error       error
}

CredentialOwnerModelAccess stores cloud credential model information for the credential owner or an error retrieving it.

type Database Uses

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)

    // GetCollecitonFor returns the named Collection, scoped for the
    // model specified. As for GetCollection, a closer is also returned.
    GetCollectionFor(modelUUID, name string) (mongo.Collection, SessionCloser)

    // GetRawCollection returns the named mgo Collection. As no
    // automatic model filtering is performed by the returned
    // collection it should be rarely used. GetCollection() should be
    // used in almost all cases.
    GetRawCollection(name string) (*mgo.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)

    // RunTransaction is a convenience method for running a single
    // transaction.
    RunTransaction(ops []txn.Op) error

    // RunTransaction is a convenience method for running a single
    // transaction for the model specified.
    RunTransactionFor(modelUUID string, ops []txn.Op) error

    // RunRawTransaction is a convenience method that will run a
    // single transaction using a "raw" transaction runner that won't
    // perform model filtering.
    RunRawTransaction(ops []txn.Op) error

    // Run is a convenience method running a transaction using a
    // transaction building function.
    Run(transactions jujutxn.TransactionSource) error

    // 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 Uses

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

func NewDbLogger Uses

func NewDbLogger(st ModelSessioner) *DbLogger

func (*DbLogger) Close Uses

func (logger *DbLogger) Close()

Close cleans up resources used by the DbLogger instance.

func (*DbLogger) Log Uses

func (logger *DbLogger) Log(records []LogRecord) error

Log writes log messages to the database. Log records are written to the database in bulk; callers should buffer log records to and call Log with a batch to minimise database writes.

The ModelUUID and ID fields of records are ignored; DbLogger is scoped to a single model, and ID is controlled by the DbLogger code.

type DebugLogger Uses

type DebugLogger interface {
    Debugf(string, ...interface{})
}

DebugLogger is a logger that implements Debugf.

type DeletedUserError Uses

type DeletedUserError struct {
    UserName string
}

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

func (DeletedUserError) Error Uses

func (e DeletedUserError) Error() string

Error implements the error interface.

type DestroyApplicationOperation Uses

type DestroyApplicationOperation struct {

    // DestroyStorage controls whether or not storage attached
    // to units of the application are destroyed. If this is false,
    // then detachable storage will be detached and left in the model.
    DestroyStorage bool

    // RemoveOffers controls whether or not application offers
    // are removed. If this is false, then the operation will
    // fail if there are any offers remaining.
    RemoveOffers bool

    // ForcedOperation stores needed information to force this operation.
    ForcedOperation
    // contains filtered or unexported fields
}

DestroyApplicationOperation is a model operation for destroying an application.

func (*DestroyApplicationOperation) Build Uses

func (op *DestroyApplicationOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*DestroyApplicationOperation) Done Uses

func (op *DestroyApplicationOperation) Done(err error) error

Done is part of the ModelOperation interface.

type DestroyModelParams Uses

type DestroyModelParams struct {
    // DestroyHostedModels controls whether or not hosted models
    // are destroyed also. This only applies to the controller
    // model.
    //
    // If this is false when destroying the controller model,
    // there must be no hosted models, or an error satisfying
    // IsHasHostedModelsError will be returned.
    //
    // TODO(axw) this should be moved to the Controller type.
    DestroyHostedModels bool

    // DestroyStorage controls whether or not storage in the
    // model (and hosted models, if DestroyHostedModels is true)
    // should be destroyed.
    //
    // This is ternary: nil, false, or true. If nil and
    // there is persistent storage in the model (or hosted
    // models), an error satisfying IsHasPersistentStorageError
    // will be returned.
    DestroyStorage *bool

    // Force specifies whether model destruction will be forced, i.e.
    // keep going despite operational errors.
    Force *bool

    // MaxWait specifies the amount of time that each step in model destroy process
    // will wait before forcing the next step to kick-off. This parameter
    // only makes sense in combination with 'force' set to 'true'.
    MaxWait time.Duration
}

DestroyModelParams contains parameters for destroy a model.

type DestroyRelationOperation Uses

type DestroyRelationOperation struct {
    // ForcedOperation stores needed information to force this operation.
    ForcedOperation
    // contains filtered or unexported fields
}

DestroyRelationOperation is a model operation destroy relation.

func (*DestroyRelationOperation) Build Uses

func (op *DestroyRelationOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*DestroyRelationOperation) Done Uses

func (op *DestroyRelationOperation) Done(err error) error

Done is part of the ModelOperation interface.

type DestroyRemoteApplicationOperation Uses

type DestroyRemoteApplicationOperation struct {
    // ForcedOperation stores needed information to force this operation.
    ForcedOperation
    // contains filtered or unexported fields
}

DestroyRemoteApplicationOperation is a model operation to destroy a remote application.

func (*DestroyRemoteApplicationOperation) Build Uses

func (op *DestroyRemoteApplicationOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*DestroyRemoteApplicationOperation) Done Uses

func (op *DestroyRemoteApplicationOperation) Done(err error) error

Done is part of the ModelOperation interface.

type DestroyUnitOperation Uses

type DestroyUnitOperation struct {
    // ForcedOperation stores needed information to force this operation.
    ForcedOperation

    // DestroyStorage controls whether or not storage attached
    // to the unit is destroyed. If this is false, then detachable
    // storage will be detached and left in the model.
    DestroyStorage bool
    // contains filtered or unexported fields
}

DestroyUnitOperation is a model operation for destroying a unit.

func (*DestroyUnitOperation) Build Uses

func (op *DestroyUnitOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*DestroyUnitOperation) Done Uses

func (op *DestroyUnitOperation) Done(err error) error

Done is part of the ModelOperation interface.

type DeviceConstraints Uses

type DeviceConstraints struct {

    // Type is the device type or device-class.
    // currently supported types are
    // - gpu
    // - nvidia.com/gpu
    // - amd.com/gpu
    Type DeviceType `bson:"type"`

    // Count is the number of devices that the user has asked for - count min and max are the
    // number of devices the charm requires.
    Count int64 `bson:"count"`

    // Attributes is a collection of key value pairs device related (node affinity labels/tags etc.).
    Attributes map[string]string `bson:"attributes"`
}

DeviceConstraints describes a set of device constraints.

type DeviceType Uses

type DeviceType string

type DocModelNamespace Uses

type DocModelNamespace interface {
    DocID(string) string
}

DocModelNamespace takes a document model ID and ensures it has a model id associated with the model.

type DockerMetadataStorage Uses

type DockerMetadataStorage interface {
    Save(resourceID string, drInfo resources.DockerImageDetails) error
    Remove(resourceID string) error
    Get(resourceID string) (io.ReadCloser, int64, error)
}

DockerMetadataStorage provides the interface for storing Docker resource-type data

func NewDockerMetadataStorage Uses

func NewDockerMetadataStorage(st *State) DockerMetadataStorage

NewDockerMetadataStorage returns a dockerMetadataStorage for persisting Docker resources.

type Endpoint Uses

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 ApplicationOfferEndpoint Uses

func ApplicationOfferEndpoint(offer crossmodel.ApplicationOffer, relationName string) (Endpoint, error)

ApplicationOfferEndpoint returns from the specified offer, the relation endpoint with the supplied name, if it exists.

func (Endpoint) CanRelateTo Uses

func (ep Endpoint) CanRelateTo(other Endpoint) bool

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

func (Endpoint) String Uses

func (ep Endpoint) String() string

String returns the unique identifier of the relation endpoint.

type EndpointBinding Uses

type EndpointBinding interface {
    network.SpaceLookup
    DefaultEndpointBindingSpace() (string, error)
    Space(id string) (*Space, error)
}

EndpointBinding are the methods necessary for exported methods of Bindings to work.

go:generate mockgen -package mocks -destination mocks/endpointbinding_mock.go github.com/juju/juju/state EndpointBinding

type EnsureDeader Uses

type EnsureDeader interface {
    EnsureDead() error
}

EnsureDeader with an EnsureDead method.

type Entity Uses

type Entity interface {
    Tag() names.Tag
}

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

type EntityFinder Uses

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

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

type EntityWithApplication Uses

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

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

type ErrCharmAlreadyUploaded Uses

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 Uses

func (e *ErrCharmAlreadyUploaded) Error() string

type ErrIncompatibleSeries Uses

type ErrIncompatibleSeries struct {
    SeriesList []string
    Series     string
    CharmName  string
}

ErrIncompatibleSeries is a standard error to indicate that the series requested is not compatible with the charm of the application.

func (*ErrIncompatibleSeries) Error Uses

func (e *ErrIncompatibleSeries) Error() string

type ErrParentDeviceHasChildren Uses

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 Uses

func (e *ErrParentDeviceHasChildren) Error() string

type ErrProviderIDNotUnique Uses

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 Uses

func (e *ErrProviderIDNotUnique) Error() string

type ExportConfig Uses

type ExportConfig struct {
    SkipActions              bool
    SkipAnnotations          bool
    SkipCloudImageMetadata   bool
    SkipCredentials          bool
    SkipIPAddresses          bool
    SkipSettings             bool
    SkipSSHHostKeys          bool
    SkipStatusHistory        bool
    SkipLinkLayerDevices     bool
    SkipUnitAgentBinaries    bool
    SkipMachineAgentBinaries bool
    SkipRelationData         bool
    SkipInstanceData         bool
    SkipApplicationOffers    bool
}

ExportConfig allows certain aspects of the model to be skipped during the export. The intent of this is to be able to get a partial export to support other API calls, like status.

type ExportStateMigration Uses

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

ExportStateMigration defines a migration for exporting various entities into a destiniation description model from the source state. It accumulates a series of migrations to Run at a later time. Running the state migration visits all the migrations and exits upon seeing the first error from the migration.

func (*ExportStateMigration) Add Uses

func (m *ExportStateMigration) Add(f func() error)

Add adds a migration to execute at a later time Return error from the addition will cause the Run to terminate early.

func (*ExportStateMigration) Run Uses

func (m *ExportStateMigration) Run() error

Run executes all the migrations required to be run.

type ExternalController Uses

type ExternalController interface {
    // Id returns the external controller UUID, also used as
    // the mongo id.
    Id() string

    // ControllerInfo returns the details required to connect to the
    // external controller.
    ControllerInfo() crossmodel.ControllerInfo
}

ExternalController represents the state of a controller hosting other models.

type ExternalControllers Uses

type ExternalControllers interface {
    Save(_ crossmodel.ControllerInfo, modelUUIDs ...string) (ExternalController, error)
    Controller(controllerUUID string) (ExternalController, error)
    ControllerForModel(modelUUID string) (ExternalController, error)
    Remove(controllerUUID string) error
    Watch() StringsWatcher
    WatchController(controllerUUID string) NotifyWatcher
}

ExternalControllers instances provide access to external controllers in state.

type Filesystem Uses

type Filesystem interface {
    GlobalEntity
    Lifer
    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)

    // Detachable reports whether or not the filesystem is detachable.
    Detachable() bool

    // Releasing reports whether or not the filesystem is to be released
    // from the model when it is Dying/Dead.
    Releasing() 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 Uses

type FilesystemAttachment interface {
    Lifer

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

    // Host returns the tag of the entity to which this attachment belongs.
    Host() names.Tag

    // 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 Uses

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 Uses

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 Uses

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

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

FilesystemInfo describes information about a filesystem.

type FilesystemParams Uses

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 FirewallRule Uses

type FirewallRule struct {
    // WellKnownService is the known service for the firewall rules entity.
    WellKnownService WellKnownServiceType

    // WhitelistCIDRS is the whitelist CIDRs for the rule.
    WhitelistCIDRs []string
}

FirewallRule instances describe the ingress networks whitelist/blacklist for a given well known service. Primarily, whitelisting allowed ingress subnets is the main use case. However, blacklisting subnets is useful to allow restrictions placed on incoming traffic for cross model relations, where the source of traffic is requested from the consuming side. WellKnownService is either a well known internet service (currently just SSH) or a Juju defined value. Supported values are: - ssh - juju-controller - juju-application-offer

type FirewallRuler Uses

type FirewallRuler interface {
    Save(service WellKnownServiceType, whiteListCidrs []string) (FirewallRule, error)
    Rule(service WellKnownServiceType) (FirewallRule, error)
    AllRules() ([]FirewallRule, error)
}

FirewallRuler instances provide access to firewall rules in state.

type ForcedOperation Uses

type ForcedOperation struct {
    // Force controls whether or not the removal of a unit
    // will be forced, i.e. ignore operational errors.
    Force bool

    // Errors contains errors encountered while applying this operation.
    // Generally, these are non-fatal errors that have been encountered
    // during, say, force. They may not have prevented the operation from being
    // aborted but the user might still want to know about them.
    Errors []error

    // MaxWait specifies the amount of time that each step in relation destroy process
    // will wait before forcing the next step to kick-off. This parameter
    // only makes sense in combination with 'force' set to 'true'.
    MaxWait time.Duration
}

ForcedOperation that allows accumulation of operational errors and can be forced.

func (*ForcedOperation) AddError Uses

func (op *ForcedOperation) AddError(one ...error)

AddError adds an error to the collection of errors for this operation.

func (*ForcedOperation) FatalError Uses

func (op *ForcedOperation) FatalError(err error) bool

FatalError returns true if the err is not nil and Force is false. If the error is not nil, it's added to the slice of errors for the operation.

func (*ForcedOperation) LastError Uses

func (op *ForcedOperation) LastError() error

LastError returns last added error for this operation.

type Generation Uses

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

Generation represents the state of a model generation.

func (*Generation) Abort Uses

func (g *Generation) Abort(userName string) error

Abort marks the generation as completed however no value is assigned from the generation sequence.

func (*Generation) AssignAllUnits Uses

func (g *Generation) AssignAllUnits(appName string) error

AssignAllUnits ensures that all units of the input application are designated as tracking the branch, by adding the unit names to the generation.

func (*Generation) AssignApplication Uses

func (g *Generation) AssignApplication(appName string) error

AssignApplication indicates that the application with the input name has had changes in this generation.

func (*Generation) AssignUnit Uses

func (g *Generation) AssignUnit(unitName string) error

AssignUnit indicates that the unit with the input name is tracking this branch, by adding the name to the generation.

func (*Generation) AssignUnits Uses

func (g *Generation) AssignUnits(appName string, numUnits int) error

func (*Generation) AssignedUnits Uses

func (g *Generation) AssignedUnits() map[string][]string

AssignedUnits returns the unit names, keyed by application name that have been assigned to this generation.

func (*Generation) BranchName Uses

func (g *Generation) BranchName() string

func (*Generation) CheckNotComplete Uses

func (g *Generation) CheckNotComplete() error

CheckNotComplete returns an error if this generation was committed or aborted.

func (*Generation) Commit Uses

func (g *Generation) Commit(userName string) (int, error)

Commit marks the generation as completed and assigns it the next value from the generation sequence. The new generation ID is returned.

func (*Generation) Completed Uses

func (g *Generation) Completed() int64

Completed returns the Unix timestamp at generation completion.

func (*Generation) CompletedBy Uses

func (g *Generation) CompletedBy() string

CompletedBy returns the user who committed the generation.

func (*Generation) Config Uses

func (g *Generation) Config() map[string]settings.ItemChanges

Config returns all changed charm configuration for the generation. The persisted objects are converted to core changes.

func (*Generation) Created Uses

func (g *Generation) Created() int64

Created returns the Unix timestamp at generation creation.

func (*Generation) CreatedBy Uses

func (g *Generation) CreatedBy() string

CreatedBy returns the user who created the generation.

func (*Generation) GenerationId Uses

func (g *Generation) GenerationId() int

GenerationId indicates the relative order that this branch was committed and had its changes applied to the whole model.

func (*Generation) HasChangesFor Uses

func (g *Generation) HasChangesFor(appName string) bool

HasChangesFor returns true when the generation has config changes for the provided application.

func (*Generation) IsCompleted Uses

func (g *Generation) IsCompleted() bool

IsCompleted returns true if the generation has been completed; i.e it has a completion time-stamp.

func (*Generation) IsTracking Uses

func (g *Generation) IsTracking(unitName string) bool

IsTracking returns true if the generation is tracking the provided unit.

func (*Generation) ModelUUID Uses

func (g *Generation) ModelUUID() string

ModelUUID returns the ID of the model to which this generation applies.

func (*Generation) Refresh Uses

func (g *Generation) Refresh() error

Refresh refreshes the contents of the generation from the underlying state.

func (*Generation) UpdateCharmConfig Uses

func (g *Generation) UpdateCharmConfig(appName string, master *Settings, validChanges charm.Settings) error

UpdateCharmConfig applies the input changes to the input application's charm configuration under this branch. the incoming charm settings are assumed to have been validated.

type GlobalEntity Uses

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

GlobalEntity specifies entity.

type HasAssignedUnitsError Uses

type HasAssignedUnitsError struct {
    MachineId string
    UnitNames []string
}

func (*HasAssignedUnitsError) Error Uses

func (e *HasAssignedUnitsError) Error() string

type HasAttachmentsError Uses

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 Uses

func (e *HasAttachmentsError) Error() string

type HasContainersError Uses

type HasContainersError struct {
    MachineId    string
    ContainerIds []string
}

func (*HasContainersError) Error Uses

func (e *HasContainersError) Error() string

type HistoryGetter Uses

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

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

func (*HistoryGetter) StatusHistory Uses

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

StatusHistory implements status.StatusHistoryGetter.

type HostFilesystemParams Uses

type HostFilesystemParams struct {
    Filesystem FilesystemParams
    Attachment FilesystemAttachmentParams
}

HostFilesystemParams holds the parameters for creating a filesystem and attaching it to a new host.

type HostVolumeParams Uses

type HostVolumeParams struct {
    Volume     VolumeParams
    Attachment VolumeAttachmentParams
}

HostVolumeParams holds the parameters for creating a volume and attaching it to a new host.

type ImportRelationNetworks Uses

type ImportRelationNetworks struct{}

ImportRelationNetworks describes a way to import relation networks from a description.

func (ImportRelationNetworks) Execute Uses

func (ImportRelationNetworks) Execute(src RelationNetworksDescription, runner TransactionRunner) error

Execute the import on the relation networks description, carefully modelling the dependencies we have.

type ImportRemoteApplications Uses

type ImportRemoteApplications struct{}

ImportRemoteApplications describes a way to import remote applications from a description.

func (ImportRemoteApplications) Execute Uses

func (i ImportRemoteApplications) Execute(src RemoteApplicationsDescription,
    runner TransactionRunner,
) error

Execute the import on the remote entities description, carefully modelling the dependencies we have.

type ImportRemoteEntities Uses

type ImportRemoteEntities struct{}

ImportRemoteEntities describes a way to import remote entities from a description.

func (ImportRemoteEntities) Execute Uses

func (ImportRemoteEntities) Execute(src RemoteEntitiesDescription, runner TransactionRunner) error

Execute the import on the remote entities description, carefully modelling the dependencies we have.

type ImportStateMigration Uses

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

ImportStateMigration defines a migration for importing various entities from a source description model to the destination state. It accumulates a series of migrations to Run at a later time. Running the state migration visits all the migrations and exits upon seeing the first error from the migration.

func (*ImportStateMigration) Add Uses

func (m *ImportStateMigration) Add(f func() error)

Add adds a migration to execute at a later time Return error from the addition will cause the Run to terminate early.

func (*ImportStateMigration) Run Uses

func (m *ImportStateMigration) Run() error

Run executes all the migrations required to be run.

type InitDatabaseFunc Uses

type InitDatabaseFunc func(*mgo.Session, string, *controller.Config) error

InitDatabaseFunc defines a function used to create the collections and indices in a Juju database.

type InitializeParams Uses

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

    // 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

    // MongoSession is the mgo.Session to use for storing and
    // accessing state data. The caller remains responsible
    // for closing this session; Initialize will copy it.
    MongoSession *mgo.Session

    // AdminPassword holds the password for the initial user.
    AdminPassword string
}

InitializeParams contains the parameters for initializing the state database.

func (InitializeParams) Validate Uses

func (p InitializeParams) Validate() error

Validate checks that the state initialization parameters are valid.

type InstanceIdGetter Uses

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

InstanceIdGetter defines a single method - InstanceId.

type LastSentLogTracker Uses

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 NewLastSentLogTracker Uses

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 Uses

func (logger *LastSentLogTracker) Close() error

Close implements io.Closer

func (*LastSentLogTracker) Get Uses

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

Get retrieves the id and timestamp.

func (*LastSentLogTracker) Set Uses

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

Set records the timestamp.

type LeaveScopeOperation Uses

type LeaveScopeOperation struct {
    // ForcedOperation stores needed information to force this operation.
    ForcedOperation
    // contains filtered or unexported fields
}

LeaveScopeOperation is a model operation for relation to leave scope.

func (*LeaveScopeOperation) Build Uses

func (op *LeaveScopeOperation) Build(attempt int) ([]txn.Op, error)

Build is part of the ModelOperation interface.

func (*LeaveScopeOperation) Description Uses

func (op *LeaveScopeOperation) Description() string

func (*LeaveScopeOperation) Done Uses

func (op *LeaveScopeOperation) Done(err error) error

Done is part of the ModelOperation interface.

type Life Uses

type Life int8

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

const (
    Alive Life = iota
    Dying
    Dead
)

func (Life) String Uses

func (l Life) String() string

String is deprecated, use Value.

func (Life) Value Uses

func (l Life) Value() life.Value

Value returns the core.life.Value type.

type Lifer Uses

type Lifer interface {
    Life() Life
}

Lifer represents an entity with a life.

type LinkLayerDevice Uses

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

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

func (*LinkLayerDevice) Addresses Uses

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

Addresses returns all IP addresses assigned to the device.

func (*LinkLayerDevice) DocID Uses

func (dev *LinkLayerDevice) DocID() string

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

func (*LinkLayerDevice) EthernetDeviceForBridge Uses

func (dev *LinkLayerDevice) EthernetDeviceForBridge(name string) (LinkLayerDeviceArgs, error)

EthernetDeviceForBridge returns LinkLayerDeviceArgs representing an ethernet device with the input name and this device as its parent. If the device is not a bridge, an error is returned.

func (*LinkLayerDevice) IsAutoStart Uses

func (dev *LinkLayerDevice) IsAutoStart() bool

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

func (*LinkLayerDevice) IsLoopbackDevice Uses

func (dev *LinkLayerDevice) IsLoopbackDevice() bool

IsLoopbackDevice returns whether this is a loopback device.

func (*LinkLayerDevice) IsUp Uses

func (dev *LinkLayerDevice) IsUp() bool

IsUp returns whether the device is currently up.

func (*LinkLayerDevice) MACAddress Uses

func (dev *LinkLayerDevice) MACAddress() string

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

func (*LinkLayerDevice) MTU Uses

func (dev *LinkLayerDevice) MTU() uint

MTU returns the maximum transmission unit the device can handle.

func (*LinkLayerDevice) Machine Uses

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

Machine returns the Machine this device belongs to.

func (*LinkLayerDevice) MachineID Uses

func (dev *LinkLayerDevice) MachineID() string

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

func (*LinkLayerDevice) Name Uses

func (dev *LinkLayerDevice) Name() string

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

func (*LinkLayerDevice) ParentDevice Uses

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 Uses

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 Uses

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

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

func (*LinkLayerDevice) Remove Uses

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 Uses

func (dev *LinkLayerDevice) RemoveAddresses() error

RemoveAddresses removes all IP addresses assigned to the device.

func (*LinkLayerDevice) String Uses

func (dev *LinkLayerDevice) String() string

String returns a human-readable representation of the device.

func (*LinkLayerDevice) Type Uses

func (dev *LinkLayerDevice) Type() network.LinkLayerDeviceType

Type returns this device's underlying type.

type LinkLayerDeviceAddress Uses

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 corenetwork.Id

    // ProviderNetworkID is the provider-specific network ID of the address.
    // It can be left empty if not supported or known.
    ProviderNetworkID corenetwork.Id

    // ProviderSubnetID is the provider-specific subnet ID to which the
    // device is attached.
    ProviderSubnetID corenetwork.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

    // IsDefaultGateway is set to true if this address on this device is the
    // default gw on a machine.
    IsDefaultGateway bool
}

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

type LinkLayerDeviceArgs Uses

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 corenetwork.Id

    // Type is the type of the underlying link-layer device.
    Type corenetwork.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 Living Uses

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

Living describes state entities with a lifecycle.

type LogRecord Uses

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

    // origin fields
    ModelUUID string
    Entity    string
    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 Uses

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 Uses

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

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

type LogTailerParams Uses

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
}

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

type LogTailerState Uses

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 Uses

type MacaroonCache struct {
    *State
}

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

func (MacaroonCache) Get Uses

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

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

func (MacaroonCache) Set Uses

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

Set stores the macaroon on the charm.

type Machine Uses

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

Machine represents the state of a machine.

func (*Machine) Actions Uses

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

Actions is part of the ActionReceiver interface.

func (*Machine) AddAction Uses

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

AddAction is part of the ActionReceiver interface.

func (*Machine) Addresses Uses

func (m *Machine) Addresses() (addresses corenetwork.SpaceAddresses)

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) AddressesBySpaceID Uses

func (m *Machine) AddressesBySpaceID() (map[string][]corenetwork.SpaceAddress, error)

AddressesBySpaceID groups the machine addresses by space id and returns the result as a map where the space id is used a the key.

func (*Machine) AgentPresence Uses

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

AgentPresence returns whether the respective remote agent is alive.

func (*Machine) AgentTools Uses

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 Uses

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

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

func (*Machine) AllLinkLayerDevices Uses

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

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

func (*Machine) AllNetworkAddresses Uses

func (m *Machine) AllNetworkAddresses() (corenetwork.SpaceAddresses, error)

AllNetworkAddresses returns the result of AllAddresses(), but transformed to []network.Address.

func (*Machine) AllPorts Uses

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

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

func (*Machine) AllProviderInterfaceInfos Uses

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) AllSpaces Uses

func (m *Machine) AllSpaces() (set.Strings, error)

AllSpaces returns the set of spaceIDs that this machine is actively connected to.

func (*Machine) ApplicationNames Uses

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

ApplicationNames returns the names of applications represented by units running on the machine.

func (*Machine) AvailabilityZone Uses

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

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

func (*Machine) CancelAction Uses

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

CancelAction is part of the ActionReceiver interface.

func (*Machine) CharmProfiles Uses

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

CharmProfiles returns the names of any LXD profiles used by the machine, which were defined in the charm deployed to that machine.

func (*Machine) CheckProvisioned Uses

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

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

func (*Machine) Clean Uses

func (m *Machine) Clean() bool

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

func (*Machine) CompleteUpgradeSeries Uses

func (m *Machine) CompleteUpgradeSeries() error

CompleteUpgradeSeries notifies units and machines that an upgrade series is ready for its "completion" phase.

func (*Machine) CompletedActions Uses

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

CompletedActions is part of the ActionReceiver interface.

func (*Machine) Constraints Uses

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 Uses

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

ContainerType returns the type of container hosting this machine.

func (*Machine) Containers Uses

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) CreateUpgradeSeriesLock Uses

func (m *Machine) CreateUpgradeSeriesLock(unitNames []string, toSeries string) error

CreateUpgradeSeriesLock create a prepare lock for series upgrade. If this item exists in the database for a given machine it indicates that a machine's operating system is being upgraded from one series to another; for example, from xenial to bionic.

func (*Machine) Destroy Uses

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 Uses

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 Uses

func (m *Machine) ForceDestroy(maxWait time.Duration) error

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

func (*Machine) GetNetworkInfoForSpaces Uses

func (m *Machine) GetNetworkInfoForSpaces(spaces set.Strings) map[string]MachineNetworkInfoResult

GetNetworkInfoForSpaces returns MachineNetworkInfoResult with a list of devices for each space in spaces TODO(wpk): 2017-05-04 This does not work for L2-only devices as it iterates over addresses, needs to be fixed. When changing the method we have to keep the ordering. Returns a map based on space ID.

func (*Machine) GetRebootFlag Uses

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

GetRebootFlag returns the reboot flag for this machine.

func (*Machine) GetUpgradeSeriesMessages Uses

func (m *Machine) GetUpgradeSeriesMessages() ([]string, bool, error)

GetUpgradeSeriesMessages returns all 'unseen' upgrade series notifications sorted by timestamp.

func (*Machine) HardwareCharacteristics Uses

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

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

func (*Machine) Id Uses

func (m *Machine) Id() string

Id returns the machine id.

func (*Machine) InstanceId Uses

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) InstanceNames Uses

func (m *Machine) InstanceNames() (instance.Id, string, error)

InstanceNames returns both the provider's instance id and a user-friendly display name. The display name is intended used for human input and is ignored internally.

func (*Machine) InstanceStatus Uses

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 Uses

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 Uses

func (m *Machine) IsContainer() bool

IsContainer returns true if the machine is a container.

func (*Machine) IsLockedForSeriesUpgrade Uses

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

IsLockedForSeriesUpgrade determines if a machine is locked for upgrade series.

func (*Machine) IsManager Uses

func (m *Machine) IsManager() bool

IsManager returns true if the machine has JobManageModel.

func (*Machine) IsManual Uses

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

IsManual returns true if the machine was manually provisioned.

func (*Machine) IsParentLockedForSeriesUpgrade Uses

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

IsParentLockedForSeriesUpgrade determines if a machine is a container who's parent is locked for series upgrade.

func (*Machine) Jobs Uses

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

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

func (*Machine) KeepInstance Uses

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

KeepInstance reports whether a machine, when removed from Juju, will cause the corresponding cloud instance to be stopped.

func (*Machine) Life Uses

func (m *Machine) Life() Life

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

func (*Machine) LinkLayerDevice Uses

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 Uses

func (m *Machine) MachineAddresses() (addresses corenetwork.SpaceAddresses)

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

func (*Machine) MachineTag Uses

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

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

func (*Machine) MarkForRemoval Uses

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

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

func (*Machine) ModelName Uses

func (m *Machine) ModelName() string

func (*Machine) ModificationStatus Uses

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

ModificationStatus returns the provider specific modification status for this machine or NotProvisionedError if instance is not yet provisioned.

func (*Machine) OpenedPorts Uses

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

OpenedPorts returns this machine ports document for the given subnetID.

func (*Machine) ParentId Uses

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

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

func (*Machine) PasswordValid Uses

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

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

func (*Machine) PendingActions Uses

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

PendingActions is part of the ActionReceiver interface.

func (*Machine) Placement Uses

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 Uses

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

Principals returns the principals for the machine.

func (*Machine) PrivateAddress Uses

func (m *Machine) PrivateAddress() (corenetwork.SpaceAddress, 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 Uses

func (m *Machine) ProviderAddresses() (addresses corenetwork.SpaceAddresses)

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

func (*Machine) PublicAddress Uses

func (m *Machine) PublicAddress() (corenetwork.SpaceAddress, 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 Uses

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 Uses

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

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

func (*Machine) RemoveAllAddresses Uses

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 Uses

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) RemoveUpgradeSeriesLock Uses

func (m *Machine) RemoveUpgradeSeriesLock() error

func (*Machine) RunningActions Uses

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

RunningActions is part of the ActionReceiver interface.

func (*Machine) Series Uses

func (m *Machine) Series() string

Series returns the operating system series running on the machine.

func (*Machine) SetAgentPresence Uses

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 Uses

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

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

func (*Machine) SetCharmProfiles Uses

func (m *Machine) SetCharmProfiles(profiles []string) error

SetCharmProfiles sets the names of the charm profiles used on a machine in its instanceData.

func (*Machine) SetConstraints Uses

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) SetDevicesAddresses Uses

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 Uses

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) SetInstanceInfo Uses

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

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

func (*Machine) SetInstanceStatus Uses

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

SetInstanceStatus sets the provider specific instance status for a machine.

func (*Machine) SetKeepInstance Uses

func (m *Machine) SetKeepInstance(keepInstance bool) error

SetKeepInstance sets whether the cloud machine instance will be retained when the machine is removed from Juju. This is only relevant if an instance exists.

func (*Machine) SetLinkLayerDevices Uses

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 Uses

func (m *Machine) SetMachineAddresses(addresses ...corenetwork.SpaceAddress) error

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

func (*Machine) SetMachineBlockDevices Uses

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

SetMachineBlockDevices sets the block devices visible on the machine.

func (*Machine) SetModificationStatus Uses

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

SetModificationStatus sets the provider specific modification status for a machine. Allowing the propagation of status messages to the operator.

func (*Machine) SetMongoPassword Uses

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 Uses

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 Uses

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

SetPassword sets the password for the machine's agent.

func (*Machine) SetProviderAddresses Uses

func (m *Machine) SetProviderAddresses(addresses ...corenetwork.SpaceAddress) error

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

func (*Machine) SetProvisioned Uses

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

SetProvisioned stores the machine's provider-specific details in the database. These details are used to infer that the machine has been provisioned.

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.

Once set, the instance id cannot be changed. A non-empty instance id will be detected as a provisioned machine.

func (*Machine) SetRebootFlag Uses

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 Uses

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

SetStatus sets the status of the machine.

func (*Machine) SetStopMongoUntilVersion Uses

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 Uses

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

SetSupportedContainers sets the list of containers supported by this machine.

func (*Machine) SetUpgradeSeriesMessagesAsSeen Uses

func (m *Machine) SetUpgradeSeriesMessagesAsSeen(messages []UpgradeSeriesMessage) error

SetUpgradeSeriesMessagesAsSeen marks a given upgrade series messages as having been seen by a client of the API.

func (*Machine) SetUpgradeSeriesStatus Uses

func (m *Machine) SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, message string) error

SetUpgradeSeriesStatus sets the status of the machine in the upgrade-series lock.

func (*Machine) SetUpgradeSeriesUnitStatus Uses

func (m *Machine) SetUpgradeSeriesUnitStatus(unitName string, status model.UpgradeSeriesStatus, message string) error

SetUpgradeSeriesUnitStatus sets the status of a series upgrade for a unit.

func (*Machine) ShouldRebootOrShutdown Uses

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) StartUpgradeSeriesUnitCompletion Uses

func (m *Machine) StartUpgradeSeriesUnitCompletion(message string) error

StartUpgradeSeriesUnitCompletion notifies units that an upgrade-series workflow is ready for its "completion" phase.

func (*Machine) Status Uses

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

Status returns the status of the machine.

func (*Machine) StatusHistory Uses

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 Uses

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 Uses

func (m *Machine) String() string

String returns a unique description of this machine.

func (*Machine) SupportedContainers Uses

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 Uses

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

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

func (*Machine) Tag Uses

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 Uses

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

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

func (*Machine) UpdateMachineSeries Uses

func (m *Machine) UpdateMachineSeries(series string, force bool) error

UpdateMachineSeries updates the series for the Machine.

func (*Machine) UpdateOperation Uses

func (m *Machine) UpdateOperation() *UpdateMachineOperation

UpdateOperation returns a model operation that will update the machine.

func (*Machine) UpgradeSeriesStatus Uses

func (m *Machine) UpgradeSeriesStatus() (model.UpgradeSeriesStatus, error)

func (*Machine) UpgradeSeriesTarget Uses

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

UpgradeSeriesTarget returns the series that the machine is being upgraded to.

func (*Machine) UpgradeSeriesUnitStatus Uses

func (m *Machine) UpgradeSeriesUnitStatus(unitName string) (model.UpgradeSeriesStatus, error)

UnitStatus returns the series upgrade status for the input unit.

func (*Machine) UpgradeSeriesUnitStatuses Uses

func (m *Machine) UpgradeSeriesUnitStatuses() (map[string]UpgradeSeriesUnitStatus, error)

UnitStatus returns the unit statuses from the upgrade-series lock for this machine.

func (*Machine) VerifyUnitsSeries Uses

func (m *Machine) VerifyUnitsSeries(unitNames []string, series string, force bool) ([]*Unit, error)

VerifyUnitsSeries iterates over the units with the input names, and checks that the application for each supports the input series. Recursion is used to verify all subordinates, with the results accrued into a slice before returning.

func (*Machine) VolumeAttachments Uses

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

VolumeAttachments returns the machine's volume attachments.

func (*Machine) WaitAgentPresence Uses

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

WaitAgentPresence blocks until the respective agent is alive. This should really only be used in the test suite.

func (*Machine) Watch Uses

func (m *Machine) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a machine.

func (*Machine) WatchActionNotifications Uses

func (m *Machine) WatchActionNotifications() StringsWatcher

WatchActionNotifications is part of the ActionReceiver interface.

func (*Machine) WatchAddresses Uses

func (m *Machine) WatchAddresses() NotifyWatcher

WatchAddresses returns a new NotifyWatcher watching m's addresses.

func (*Machine) WatchAllContainers Uses

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 Uses

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 Uses

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 Uses

func (m *Machine) WatchHardwareCharacteristics() NotifyWatcher

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

func (*Machine) WatchInstanceData Uses

func (m *Machine) WatchInstanceData() NotifyWatcher

WatchInstanceData returns a watcher for observing changes to a model.

func (*Machine) WatchLXDProfileUpgradeNotifications Uses

func (m *Machine) WatchLXDProfileUpgradeNotifications(applicationName string) (StringsWatcher, error)

WatchLXDProfileUpgradeNotifications returns a watcher that observes the status of a lxd profile upgrade by monitoring changes on the unit machine's lxd profile upgrade completed field that is specific to an application name. Used by UniterAPI v9.

func (*Machine) WatchPrincipalUnits Uses

func (m *Machine) WatchPrincipalUnits() StringsWatcher

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

func (*Machine) WatchUnits Uses

func (m *Machine) WatchUnits() StringsWatcher

WatchUnits returns a new StringsWatcher watching m's units.

func (*Machine) WatchUpgradeSeriesNotifications Uses

func (m *Machine) WatchUpgradeSeriesNotifications() (NotifyWatcher, error)

WatchUpgradeSeriesNotifications returns a watcher that observes the status of a series upgrade by monitoring changes to its parent machine's upgrade series lock.

type MachineJob Uses

type MachineJob int

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

const (
    JobHostUnits MachineJob
    JobManageModel
)

func (MachineJob) MigrationValue Uses

func (job MachineJob) MigrationValue() string

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

func (MachineJob) String Uses

func (job MachineJob) String() string

func (MachineJob) ToParams Uses

func (job MachineJob) ToParams() model.MachineJob

ToParams returns the job as model.MachineJob.

type MachineModelInfo Uses

type MachineModelInfo struct {
    Id         string
    Hardware   *instance.HardwareCharacteristics
    InstanceId string
    Status     string
}

MachineModelInfo contains the summary information about a machine for a given model.

type MachineNetworkInfoResult Uses

type MachineNetworkInfoResult struct {
    NetworkInfos []network.NetworkInfo
    Error        error
}

MachineNetworkInfoResult contains an error or a list of NetworkInfo structures for a specific space.

type MachineTemplate Uses

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

    // 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.SpaceAddresses

    // 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 []HostVolumeParams

    // 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 []HostFilesystemParams

    // 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 MeterStatus Uses

type MeterStatus struct {
    Code MeterStatusCode
    Info string
}

MeterStatus represents the metering status of a unit.

func (*MeterStatus) Severity Uses

func (m *MeterStatus) Severity() int

Severity returns relative severity of the meter status.

type MeterStatusCode Uses

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 Uses

func MeterStatusFromString(str string) MeterStatusCode

MeterStatusFromString returns a valid MeterStatusCode given a string representation.

func (MeterStatusCode) Severity Uses

func (m MeterStatusCode) Severity() int

Severity returns the relative severity.

func (MeterStatusCode) String Uses

func (m MeterStatusCode) String() string

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

type Metric Uses

type Metric struct {
    Key    string            `bson:"key"`
    Value  string            `bson:"value"`
    Time   time.Time         `bson:"time"`
    Labels map[string]string `bson:"labels,omitempty"`
}

Metric represents a single Metric.

type MetricBatch Uses

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 Uses

func (m *MetricBatch) CharmURL() string

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

func (*MetricBatch) Created Uses

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

Created returns the time this metric batch was created.

func (*MetricBatch) Credentials Uses

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

Credentials returns any credentials associated with the metric batch.

func (*MetricBatch) MarshalJSON Uses

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

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

func (*MetricBatch) Metrics Uses

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

Metrics returns the metrics in this batch.

func (*MetricBatch) ModelUUID Uses

func (m *MetricBatch) ModelUUID() string

ModelUUID returns the model UUID this metric applies to.

func (*MetricBatch) SLACredentials Uses

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

SLACredentials returns any sla credentials associated with the metric batch.

func (*MetricBatch) Sent Uses

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 Uses

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

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

func (*MetricBatch) UUID Uses

func (m *MetricBatch) UUID() string

UUID returns to uuid of the metric.

func (*MetricBatch) UniqueMetrics Uses

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

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

func (*MetricBatch) Unit Uses

func (m *MetricBatch) Unit() string

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

type MetricsManager Uses

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

MetricsManager stores data about the state of the metrics manager

func (*MetricsManager) ConsecutiveErrors Uses

func (m *MetricsManager) ConsecutiveErrors() int

ConsecutiveErrors returns the number of consecutive failures.

func (*MetricsManager) GracePeriod Uses

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

GracePeriod returns the current grace period.

func (*MetricsManager) IncrementConsecutiveErrors Uses

func (m *MetricsManager) IncrementConsecutiveErrors() error

IncrementConsecutiveErrors adds 1 to the consecutive errors count.

func (*MetricsManager) LastSuccessfulSend Uses

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

LastSuccessfulSend returns the time of the last successful send.

func (*MetricsManager) MeterStatus Uses

func (m *MetricsManager) MeterStatus() MeterStatus

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

func (*MetricsManager) ModelStatus Uses

func (m *MetricsManager) ModelStatus() MeterStatus

func (*MetricsManager) SetGracePeriod Uses

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

func (*MetricsManager) SetLastSuccessfulSend Uses

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

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

type MigrationMode Uses

type MigrationMode string

MigrationMode specifies where the Model is with respect to migration.

type MigrationSpec Uses

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

MigrationSpec holds the information required to create a ModelMigration instance.

func (*MigrationSpec) Validate Uses

func (spec *MigrationSpec) Validate() error

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

type MinionReports Uses

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 Uses

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

Model represents the state of a model.

func (*Model) Action Uses

func (m *Model) Action(id string) (Action, error)

Action returns an Action by Id, which is a UUID.

func (*Model) ActionByTag Uses

func (m *Model) ActionByTag(tag names.ActionTag) (Action, error)

ActionByTag returns an Action given an ActionTag.

func (*Model) AddBranch Uses

func (m *Model) AddBranch(branchName, userName string) error

AddBranch creates a new branch in the current model.

func (*Model) AddUser Uses

func (m *Model) AddUser(spec UserAccessSpec) (permission.UserAccess, error)

AddUser adds a new user for the model to the database.

func (*Model) AgentVersion Uses

func (m *Model) AgentVersion() (version.Number, error)

AgentVersion returns the agent version for the model config. If no agent version is found, it returns NotFound error.

func (*Model) AllActions Uses

func (m *Model) AllActions() ([]Action, error)

AllActions returns all Actions.

func (*Model) AllEndpointBindings Uses

func (m *Model) AllEndpointBindings() ([]ApplicationEndpointBindings, error)

AllEndpointBindings returns all endpoint->space bindings for every application

func (*Model) AllUnits Uses

func (m *Model) AllUnits() ([]*Unit, error)

AllUnits returns all units for a model, for all applications.

func (*Model) Annotation Uses

func (m *Model) 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 (*Model) Annotations Uses

func (m *Model) Annotations(entity GlobalEntity) (map[string]string, error)

Annotations returns all the annotations corresponding to an entity.

func (*Model) AutoConfigureContainerNetworking Uses

func (m *Model) AutoConfigureContainerNetworking(environ environs.BootstrapEnviron) error

AutoConfigureContainerNetworking tries to set up best container networking available for the specific model if user hasn't set anything.

func (*Model) Branch Uses

func (m *Model) Branch(name string) (*Generation, error)

Branch retrieves the generation with the the input branch name from the collection of not-yet-completed generations.

func (*Model) Branches Uses

func (m *Model) Branches() ([]*Generation, error)

Branches returns all "in-flight" branches for the model.

func (*Model) CAASModel Uses

func (m *Model) CAASModel() (*CAASModel, error)

CAASModel returns an Containers-As-A-Service (CAAS) model.

func (*Model) Cloud Uses

func (m *Model) Cloud() string

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

func (*Model) CloudCredential Uses

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 Uses

func (m *Model) CloudRegion() string

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

func (*Model) Config Uses

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

Config returns the config for the model.

func (*Model) ControllerTag Uses

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

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

func (*Model) ControllerUUID Uses

func (m *Model) ControllerUUID() string

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

func (*Model) Destroy Uses

func (m *Model) Destroy(args DestroyModelParams) (err error)

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

func (*Model) EnqueueAction Uses

func (m *Model) EnqueueAction(receiver names.Tag, actionName string, payload map[string]interface{}) (Action, error)

EnqueueAction caches the action doc to the database.

func (*Model) EnvironVersion Uses

func (m *Model) EnvironVersion() int

EnvironVersion is the version of the model's environ -- the related cloud provider resources. The environ version is used by the controller to identify environ/provider upgrade steps to run for a model's environ after the controller is upgraded, or the model is migrated to another controller.

func (*Model) FindActionTagsById Uses

func (m *Model) FindActionTagsById(idValue string) []names.ActionTag

FindActionTagsById finds Actions with ids that either share the supplied prefix (for deprecated UUIDs), or match the supplied id (for newer id integers). It returns a list of corresponding ActionTags.

func (*Model) FindActionsByName Uses

func (m *Model) FindActionsByName(name string) ([]Action, error)

FindActionsByName finds Actions with the given name.

func (*Model) ForceDestroyed Uses

func (m *Model) ForceDestroyed() bool

ForceDestroyed returns whether the destruction of a dying/dead model was forced. It's always false for a model that's alive.

func (*Model) Generation Uses

func (m *Model) Generation(id int) (*Generation, error)

Generation retrieves the generation with the the input generation_id from the collection of completed generations.

func (*Model) Generations Uses

func (m *Model) Generations() ([]*Generation, error)

Generations returns all committed branches.

func (*Model) IsControllerModel Uses

func (m *Model) IsControllerModel() bool

IsControllerModel returns a boolean indicating whether this model is responsible for running a controller.

func (*Model) LastModelConnection Uses

func (m *Model) 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 (*Model) LatestToolsVersion Uses

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 Uses

func (m *Model) Life() Life

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

func (*Model) LoadModelStatus Uses

func (m *Model) LoadModelStatus() (*ModelStatus, error)

LoadModelStatus retrieves all the status documents for the model at once. Used to primarily speed up status.

func (*Model) MeterStatus Uses

func (m *Model) MeterStatus() MeterStatus

MeterStatus returns the current meter status for this model.

func (*Model) MigrationMode Uses

func (m *Model) MigrationMode() MigrationMode

MigrationMode returns whether the model is active or being migrated.

func (*Model) ModelConfig Uses

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

ModelConfig returns the complete config for the model

func (*Model) ModelConfigValues Uses

func (model *Model) ModelConfigValues() (config.ConfigValues, error)

ModelConfigValues returns the config values for the model represented by this state.

func (*Model) ModelTag Uses

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

ModelTag is the concrete model tag for this model.

func (*Model) Name Uses

func (m *Model) Name() string

Name returns the human friendly name of the model.

func (*Model) Owner Uses

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 Uses

func (m *Model) Refresh() error

func (*Model) SLACredential Uses

func (m *Model) SLACredential() []byte

SLACredential returns the SLA credential.

func (*Model) SLALevel Uses

func (m *Model) SLALevel() string

SLALevel returns the SLA level as a string.

func (*Model) SLAOwner Uses

func (m *Model) SLAOwner() string

SLAOwner returns the SLA owner as a string. Note that this may differ from the model owner.

func (*Model) SetAnnotations Uses

func (m *Model) SetAnnotations(entity GlobalEntity, annotations map[string]string) (err error)

SetAnnotations adds key/value pairs to annotations in MongoDB.

func (*Model) SetCloudCredential Uses

func (m *Model) SetCloudCredential(tag names.CloudCredentialTag) (bool, error)

SetCloudCredential sets new cloud credential for this model. Returned bool indicates if model credential was set.

func (*Model) SetEnvironVersion Uses

func (m *Model) SetEnvironVersion(v int) error

SetEnvironVersion sets the model's current environ version. The value must be monotonically increasing.

func (*Model) SetMeterStatus Uses

func (m *Model) SetMeterStatus(status, info string) error

SetMeterStatus sets the current meter status for this model.

func (*Model) SetMigrationMode Uses

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

SetMigrationMode updates the migration mode of the model.

func (*Model) SetSLA Uses

func (m *Model) SetSLA(level, owner string, credentials []byte) error

SetSLA sets the SLA on the model.

func (*Model) SetStatus Uses

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

SetStatus sets the status of the model.

func (*Model) State Uses

func (model *Model) State() *State

(TODO) externalreality: Temporary method to access state from model while factoring Model concerns out from state.

func (*Model) Status Uses

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

Status returns the status of the model.

func (*Model) StatusHistory Uses

func (m *Model) 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 application.

func (*Model) Tag Uses

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) Type Uses

func (m *Model) Type() ModelType

Type returns the type of the model.

func (*Model) UUID Uses

func (m *Model) UUID() string

UUID returns the universally unique identifier of the model.

func (*Model) UpdateLastModelConnection Uses

func (m *Model) UpdateLastModelConnection(user names.UserTag) error

UpdateLastModelConnection updates the last connection time of the model user.

func (*Model) UpdateLatestToolsVersion Uses

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

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

func (*Model) UpdateModelConfig Uses

func (m *Model) 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 (*Model) Users Uses

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

Users returns a slice of all users for this model.

func (*Model) ValidateCloudCredential Uses

func (m *Model) ValidateCloudCredential(tag names.CloudCredentialTag, credential cloud.Credential) error

ValidateCloudCredential validates new cloud credential for this model.

func (*Model) Watch Uses

func (m *Model) Watch() NotifyWatcher

Watch returns a watcher for observing changes to a model.

func (*Model) WatchActionResults Uses

func (m *Model) WatchActionResults() StringsWatcher

WatchActionResults starts and returns a StringsWatcher that notifies on new ActionResults being added.

func (*Model) WatchActionResultsFilteredBy Uses

func (m *Model) WatchActionResultsFilteredBy(receivers ...ActionReceiver) StringsWatcher

WatchActionResultsFilteredBy starts and returns a StringsWatcher that notifies on new ActionResults being added for the ActionRecevers being watched.

func (*Model) WatchCloudSpecChanges Uses

func (model *Model) WatchCloudSpecChanges() NotifyWatcher

WatchCloudSpecChanges returns a NotifyWatcher waiting for the cloud to change for the model.

func (*Model) WatchForModelConfigChanges Uses

func (model *Model) WatchForModelConfigChanges() NotifyWatcher

WatchForModelConfigChanges returns a NotifyWatcher waiting for the Model Config to change.

func (*Model) WatchModelCredential Uses

func (m *Model) WatchModelCredential() NotifyWatcher

WatchModelCredential returns a new NotifyWatcher that watches a model reference to a cloud credential.

type ModelAccessInfo Uses

type ModelAccessInfo struct {
    Name           string    `bson:"name"`
    UUID           string    `bson:"_id"`
    Owner          string    `bson:"owner"`
    Type           ModelType `bson:"type"`
    LastConnection time.Time
}

type ModelAccessor Uses

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 Uses

type ModelArgs struct {
    // Type specifies the general type of the model (IAAS or CAAS).
    Type ModelType

    // 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

    // EnvironVersion is the initial version of the Environ for the model.
    EnvironVersion int
}

ModelArgs is a params struct for creating a new model.

func (ModelArgs) Validate Uses

func (m ModelArgs) Validate() error

Validate validates the ModelArgs.

type ModelBatchParam Uses

type ModelBatchParam struct {
    UUID    string
    Created time.Time
    Metrics []Metric
}

ModelBatchParam contains the properties of a metric batch for a model The model uuid will be attenuated in the call to AddModelMetrics.

type ModelMachinesWatcher Uses

type ModelMachinesWatcher interface {
    WatchModelMachines() StringsWatcher
}

ModelMachinesWatcher defines a single method - WatchModelMachines.

type ModelMigration Uses

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

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

    // 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

    // ModelUserAccess returns the type of access that the given tag had to
    // the model prior to it being migrated.
    ModelUserAccess(names.Tag) permission.Access
}

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

type ModelOperation Uses

type ModelOperation interface {
    // Build builds the low-level database transaction operations required
    // to apply the change. If the transaction operations fail (e.g. due
    // to concurrent changes), then Build may be called again. The attempt
    // number, starting at zero, is passed in.
    //
    // Build is treated as a jujutxn.TransactionSource, so the errors
    // in the jujutxn package may be returned by Build to influence
    // transaction execution.
    Build(attempt int) ([]txn.Op, error)

    // Done is called after the operation is run, whether it succeeds or
    // not. The result of running the operation is passed in, and the Done
    // method may annotate the error; or run additional, non-transactional
    // logic depending on the outcome.
    Done(error) error
}

ModelOperation is a high-level model operation, encapsulating the logic required to apply a change to a model.

type ModelPayloads Uses

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

ModelPayloads lets you read all unit payloads in a model.

func (ModelPayloads) ListAll Uses

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

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

type ModelSessioner Uses

type ModelSessioner interface {
    MongoSessioner

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

ModelSessioner supports creating new mongo sessions for a model.

type ModelStatus Uses

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

ModelStatus holds all the current status values for a given model and offers accessors for the various parts of a model.

func (*ModelStatus) Application Uses

func (m *ModelStatus) Application(appName string, unitNames []string) (status.StatusInfo, error)

Application returns the status of the model. The unitNames are needed due to the current weird implementation of application status. Considers the operator pods status (for caas models)

func (*ModelStatus) FullUnitWorkloadVersion Uses

func (m *ModelStatus) FullUnitWorkloadVersion(unitName string) (status.StatusInfo, error)

FullUnitWorkloadVersion returns the full status info for the workload version of a unit. This is used for selecting the workload version for an application.

func (*ModelStatus) MachineAgent Uses

func (m *ModelStatus) MachineAgent(machineID string) (status.StatusInfo, error)

MachineAgent returns the status of the machine agent.

func (*ModelStatus) MachineInstance Uses

func (m *ModelStatus) MachineInstance(machineID string) (status.StatusInfo, error)

MachineInstance returns the status of the machine instance.

func (*ModelStatus) MachineModification Uses

func (m *ModelStatus) MachineModification(machineID string) (status.StatusInfo, error)

MachineModification returns the status of the machine modification

func (*ModelStatus) Model Uses

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

Model returns the status of the model.

func (*ModelStatus) UnitAgent Uses

func (m *ModelStatus) UnitAgent(unitName string) (status.StatusInfo, error)

UnitAgent returns the status of the Unit's agent.

func (*ModelStatus) UnitWorkload Uses

func (m *ModelStatus) UnitWorkload(unitName string, expectWorkload bool) (status.StatusInfo, error)

UnitWorkload returns the status of the unit's workload.

func (*ModelStatus) UnitWorkloadVersion Uses

func (m *ModelStatus) UnitWorkloadVersion(unitName string) (string, error)

UnitWorkloadVersion returns workload version for the unit

type ModelSummary Uses

type ModelSummary struct {
    Name           string
    UUID           string
    Type           ModelType
    Owner          string
    ControllerUUID string
    IsController   bool
    Life           Life

    CloudTag           string
    CloudRegion        string
    CloudCredentialTag string

    // SLA contains the information about the SLA for the model, if set.
    SLALevel string
    SLAOwner string

    // Needs Config()
    ProviderType  string
    DefaultSeries string
    AgentVersion  *version.Number

    // Needs Statuses collection
    Status status.StatusInfo

    // Access is the access level the supplied user has on this model
    Access permission.Access
    // UserLastConnection is the last time this user has accessed this model
    UserLastConnection *time.Time

    MachineCount int64
    CoreCount    int64
    UnitCount    int64

    // Needs Migration collection
    // Do we need all the Migration fields?
    // Migration needs to be a pointer as we may not always have one.
    Migration ModelMigration
}

ModelSummary describe interesting information for a given model. This is meant to match the values that a user wants to see as part of either show-model or list-models.

type ModelType Uses

type ModelType string

ModelType signals the type of a model - IAAS or CAAS

func ParseModelType Uses

func ParseModelType(raw string) (ModelType, error)

ParseModelType turns a valid model type string into a ModelType constant.

type MongoSessioner Uses

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

MongoSessioner supports creating new mongo sessions.

type Multiwatcher Uses

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

Multiwatcher watches any changes to the state.

func NewMultiwatcher Uses

func NewMultiwatcher(all *storeManager) *Multiwatcher

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

func (*Multiwatcher) Next Uses

func (w *Multiwatcher) Next() ([]params.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 Uses

func (w *Multiwatcher) Stop() error

Stop stops the watcher.

type NeverConnectedError Uses

type NeverConnectedError string

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

func (NeverConnectedError) Error Uses

func (e NeverConnectedError) Error() string

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

type NeverLoggedInError Uses

type NeverLoggedInError string

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

func (NeverLoggedInError) Error Uses

func (e NeverLoggedInError) Error() string

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

type NewPolicyFunc Uses

type NewPolicyFunc func(*State) Policy

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

type NotifyWatcher Uses

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 Uses

type NotifyWatcherFactory interface {
    Watch() NotifyWatcher
}

NotifyWatcherFactory represents an entity that can be watched.

type OfferConnection Uses

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

OfferConnection represents the state of an relation to an offer hosted in this model.

func (*OfferConnection) OfferUUID Uses

func (oc *OfferConnection) OfferUUID() string

OfferUUID returns the offer UUID.

func (*OfferConnection) RelationId Uses

func (oc *OfferConnection) RelationId() int

RelationId is the id of the relation to which this connection pertains.

func (*OfferConnection) RelationKey Uses

func (oc *OfferConnection) RelationKey() string

RelationKey is the key of the relation to which this connection pertains.

func (*OfferConnection) SourceModelUUID Uses

func (oc *OfferConnection) SourceModelUUID() string

SourceModelUUID is the uuid of the consuming model.

func (*OfferConnection) String Uses

func (oc *OfferConnection) String() string

String returns the details of the connection.

func (*OfferConnection) UserName Uses

func (oc *OfferConnection) UserName() string

UserName returns the name of the user who created this connection.

type OpenParams Uses

type OpenParams struct {
    // Clock is the clock used for time-related operations.
    Clock clock.Clock

    // ControllerTag is the tag of the controller.
    ControllerTag names.ControllerTag

    // ControllerModelTag is the tag of the controller model.
    ControllerModelTag names.ModelTag

    // MongoSession is the mgo.Session to use for storing and
    // accessing state data. The caller remains responsible
    // for closing this session; Open will copy it.
    MongoSession *mgo.Session

    // NewPolicy, if non-nil, returns a policy which will be used to
    // validate and modify behaviour of certain operations in state.
    NewPolicy NewPolicyFunc

    // RunTransactionObserver, if non-nil, is a function that will
    // be called after mgo/txn transactions are run, successfully
    // or not.
    RunTransactionObserver RunTransactionObserverFunc

    // InitDatabaseFunc, if non-nil, is a function that will be called
    // just after the state database is opened.
    InitDatabaseFunc InitDatabaseFunc
}

OpenParams contains the parameters for opening the state database.

func (OpenParams) Validate Uses

func (p OpenParams) Validate() error

Validate validates the OpenParams.

type Origin Uses

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 Uses

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 model.
    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
}

Persistence exposes persistence-layer functionality of State.

type Policy Uses

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

    // ProviderConfigSchemaSource returns a config.ConfigSchemaSource
    // for the cloud, or an error.
    ProviderConfigSchemaSource(cloudName string) (config.ConfigSchemaSource, error)

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

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

    // InstanceDistributor returns an context.Distributor or an error.
    InstanceDistributor() (context.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 PoolHelper Uses

type PoolHelper interface {
    Release() bool
    Annotate(string)
}

PoolHelper describes methods for working with a pool-supplied state.

type PoolItem Uses

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

PoolItem tracks the usage of a State instance unique to a model. It associates context information about state usage for each reference holder by associating it with a unique key. It tracks whether the state has been marked for removal from the pool.

type PooledState Uses

type PooledState struct {
    *State
    // contains filtered or unexported fields
}

PooledState is a wrapper for a State reference, indicating that it is managed by a pool.

func (*PooledState) Annotate Uses

func (ps *PooledState) Annotate(context string)

Annotate writes the supplied context information back to the pool item. The information is stored against the unique ID for the referer, indicated by the itemKey member.

func (*PooledState) Release Uses

func (ps *PooledState) Release() bool

Release indicates that the pooled state is no longer required and can be removed from the pool if there are no other references to it. The return indicates whether the released state was actually removed from the pool - items marked for removal are only removed when released by all other reference holders.

type PortRange Uses

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

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

func NewPortRange Uses

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

NewPortRange create a new port range and validate it.

func (PortRange) CheckConflicts Uses

func (prA PortRange) CheckConflicts(prB PortRange) error

CheckConflicts determines if the two port ranges conflict.

func (PortRange) Length Uses

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 Uses

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 Uses

func (p PortRange) String() string

Strings returns the port range as a string.

func (PortRange) Validate Uses

func (p PortRange) Validate() error

Validate checks if the port range is valid.

type Ports Uses

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

Ports represents the state of ports on a machine.

func (*Ports) AllPortRanges Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (p *Ports) Refresh() error

Refresh refreshes the port document from state.

func (*Ports) Remove Uses

func (p *Ports) Remove() error

Remove removes the ports document from state.

func (*Ports) String Uses

func (p *Ports) String() string

String returns p as a user-readable string.

func (*Ports) SubnetID Uses

func (p *Ports) SubnetID() string

SubnetID returns the subnet ID associated with this ports document.

type RebootAction Uses

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 Uses

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

type RebootFlagSetter Uses

type RebootFlagSetter interface {
    SetRebootFlag(flag bool) error
}

type Relation Uses

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

Relation represents a relation between one or two application endpoints.

func (*Relation) AllRemoteUnits Uses

func (r *Relation) AllRemoteUnits(appName string) ([]*RelationUnit, error)

AllRemoteUnits returns all the RelationUnits for the remote application units for a given application.

func (*Relation) ApplicationSettings Uses

func (r *Relation) ApplicationSettings(app *Application) (map[string]interface{}, error)

ApplicationSettings returns the application-level settings for the specified application in this relation.

func (*Relation) Destroy Uses

func (r *Relation) Destroy() 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) DestroyOperation Uses

func (r *Relation) DestroyOperation(force bool) *DestroyRelationOperation

DestroyOperation returns a model operation that will allow relation to leave scope.

func (*Relation) DestroyWithForce Uses

func (r *Relation) DestroyWithForce(force bool, maxWait time.Duration) ([]error, error)

DestroyWithForce may force the destruction of the relation. In addition, this function also returns all non-fatal operational errors encountered.

func (*Relation) Endpoint Uses

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

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

func (*Relation) Endpoints Uses

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

Endpoints returns the endpoints for the relation.

func (*Relation) Id Uses

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 applications.

func (*Relation) Life Uses

func (r *Relation) Life() Life

Life returns the relation's current life state.

func (*Relation) Refresh Uses

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 Uses

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

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

func (*Relation) RemoteApplication Uses

func (r *Relation) RemoteApplication() (*RemoteApplication, bool, error)

RemoteApplication returns the remote application if this relation is a cross-model relation, and a bool indicating if it cross-model or not.

func (*Relation) RemoteUnit Uses

func (r *Relation) RemoteUnit(unitName string) (*RelationUnit, error)

RemoteUnit returns a RelationUnit for the supplied unit of a remote application.

func (*Relation) SetStatus Uses

func (r *Relation) SetStatus(statusInfo status.StatusInfo) error

SetStatus sets the status of the relation.

func (*Relation) SetSuspended Uses

func (r *Relation) SetSuspended(suspended bool, suspendedReason string) error

SetSuspended sets whether the relation is suspended.

func (*Relation) Status Uses

func (r *Relation) Status() (status.StatusInfo, error)

Status returns the relation's current status data.

func (*Relation) String Uses

func (r *Relation) String() string

func (*Relation) Suspended Uses

func (r *Relation) Suspended() bool

Suspended returns true if the relation is suspended.

func (*Relation) SuspendedReason Uses

func (r *Relation) SuspendedReason() string

SuspendedReason returns the reason why the relation is suspended.

func (*Relation) Tag Uses

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

Tag returns a name identifying the relation.

func (*Relation) Unit Uses

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

Unit returns a RelationUnit for the supplied unit.

func (*Relation) UpdateApplicationSettings Uses

func (r *Relation) UpdateApplicationSettings(app *Application, token leadership.Token, updates map[string]interface{}) error

UpdateApplicationSettings updates the given application's settings in this relation. It requires a current leadership token.

func (*Relation) WatchApplicationSettings Uses

func (r *Relation) WatchApplicationSettings(app *Application) (NotifyWatcher, error)

WatchApplicationSettings returns a notify watcher that will signal whenever the specified application's relation settings are changed.

func (*Relation) WatchLifeSuspendedStatus Uses

func (r *Relation) WatchLifeSuspendedStatus() StringsWatcher

WatchLifeSuspendedStatus returns a watcher that notifies of changes to the life or suspended status of the relation.

func (*Relation) WatchRelationEgressNetworks Uses

func (r *Relation) WatchRelationEgressNetworks() StringsWatcher

WatchRelationEgressNetworks starts and returns a StringsWatcher notifying of egress changes to the relationNetworks collection for the relation.

func (*Relation) WatchRelationIngressNetworks Uses

func (r *Relation) WatchRelationIngressNetworks() StringsWatcher

WatchRelationIngressNetworks starts and returns a StringsWatcher notifying of ingress changes to the relationNetworks collection for the relation.

func (*Relation) WatchUnits Uses

func (r *Relation) WatchUnits(appName string) (RelationUnitsWatcher, error)

WatchUnits returns a watcher that notifies of changes to the units of the specified application endpoint in the relation. This method will return an error if the endpoint is not globally scoped.

type RelationNetworkDirection Uses

type RelationNetworkDirection string

RelationNetworkDirection represents a type that describes the direction of the network, either ingress or egress.

const (
    // IngressDirection for a ingress relation network direction
    IngressDirection RelationNetworkDirection = "ingress"
    // EgressDirection for a egress relation network direction
    EgressDirection RelationNetworkDirection = "egress"
)

func (RelationNetworkDirection) String Uses

func (r RelationNetworkDirection) String() string

type RelationNetworker Uses

type RelationNetworker interface {
    Save(relationKey string, adminOverride bool, cidrs []string) (RelationNetworks, error)
    Networks(relationKey string) (RelationNetworks, error)
}

RelationNetworker instances provide access to relation networks in state.

type RelationNetworks Uses

type RelationNetworks interface {
    Id() string
    RelationKey() string
    CIDRS() []string
}

RelationNetworks instances describe the ingress or egress networks required for a cross model relation.

type RelationNetworksDescription Uses

type RelationNetworksDescription interface {
    DocModelNamespace
    RelationNetworks() []description.RelationNetwork
}

RelationNetworksDescription defines an inplace usage for reading relation networks.

type RelationScopeChange Uses

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

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

type RelationScopeWatcher Uses

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

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

func (*RelationScopeWatcher) Changes Uses

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 Uses

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 Uses

func (w *RelationScopeWatcher) Kill()

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

func (*RelationScopeWatcher) Stop Uses

func (w *RelationScopeWatcher) Stop() error

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

func (*RelationScopeWatcher) Wait Uses

func (w *RelationScopeWatcher) Wait() error

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

type RelationUnit Uses

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) CounterpartApplications Uses

func (ru *RelationUnit) CounterpartApplications() []string

CounterpartApplications returns the slice of application names that are the counterpart of this unit. (So for Peer relations, app is returned, for a Provider the apps on Requirer side is returned

func (*RelationUnit) Endpoint Uses

func (ru *RelationUnit) Endpoint() Endpoint

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

func (*RelationUnit) EnterScope Uses

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 Uses

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

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

func (*RelationUnit) Joined Uses

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 Uses

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) LeaveScopeOperation Uses

func (ru *RelationUnit) LeaveScopeOperation(force bool) *LeaveScopeOperation

LeaveScopeOperation returns a model operation that will allow relation to leave scope.

func (*RelationUnit) LeaveScopeWithForce Uses

func (ru *RelationUnit) LeaveScopeWithForce(force bool, maxWait time.Duration) ([]error, error)

LeaveScopeWithForce in addition to doing what LeaveScope() does, when force is passed in as 'true', forces relation unit to leave scope, ignoring errors.

func (*RelationUnit) PrepareLeaveScope Uses

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) ReadSettings Uses

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 application 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 Uses

func (ru *RelationUnit) Relation() *Relation

Relation returns the relation associated with the unit.

func (*RelationUnit) Settings Uses

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

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

func (*RelationUnit) Valid Uses

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

Valid returns whether this RelationUnit is one that can actually exist in the relation. For container-scoped relations, RUs can be created for subordinate units whose principal unit isn't a member of the relation. There are too many places that rely on being able to construct a nonsensical RU to query InScope or Joined, so we allow them to be constructed but they will always return false for Valid. TODO(babbageclunk): unpick the reliance on creating invalid RUs.

func (*RelationUnit) Watch Uses

func (ru *RelationUnit) Watch() RelationUnitsWatcher

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

func (*RelationUnit) WatchScope Uses

func (ru *RelationUnit) WatchScope() *RelationScopeWatcher

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

type RelationUnitsWatcher Uses

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 RemoteApplication Uses

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

RemoteApplication represents the state of an application hosted in an external (remote) model.

func (*RemoteApplication) AddEndpoints Uses

func (s *RemoteApplication) AddEndpoints(eps []charm.Relation) error

AddEndpoints adds the specified endpoints to the remote application. If an endpoint with the same name already exists, an error is returned. If the endpoints change during the update, the operation is retried.

func (*RemoteApplication) Bindings Uses

func (s *RemoteApplication) Bindings() map[string]string

Bindings returns the endpoint->space bindings for the application.

func (*RemoteApplication) Destroy Uses

func (s *RemoteApplication) Destroy() error

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

func (*RemoteApplication) DestroyOperation Uses

func (s *RemoteApplication) DestroyOperation(force bool) *DestroyRemoteApplicationOperation

DestroyOperation returns a model operation to destroy remote application.

func (*RemoteApplication) DestroyWithForce Uses

func (s *RemoteApplication) DestroyWithForce(force bool, maxWait time.Duration) (opErrs []error, err error)

DestroyWithForce in addition to doing what Destroy() does, when force is passed in as 'true', forces th destruction of remote application, ignoring errors.

func (*RemoteApplication) Endpoint Uses

func (s *RemoteApplication) Endpoint(relationName string) (Endpoint, error)

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

func (*RemoteApplication) Endpoints Uses

func (s *RemoteApplication) Endpoints() ([]Endpoint, error)

Endpoints returns the application's currently available relation endpoints.

func (*RemoteApplication) IsConsumerProxy Uses

func (s *RemoteApplication) IsConsumerProxy() bool

IsConsumerProxy returns the application is created from a registration operation by a consuming model.

func (*RemoteApplication) IsRemote Uses

func (s *RemoteApplication) IsRemote() bool

IsRemote returns true for a remote application.

func (*RemoteApplication) Life Uses

func (s *RemoteApplication) Life() Life

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

func (*RemoteApplication) Macaroon Uses

func (s *RemoteApplication) Macaroon() (*macaroon.Macaroon, error)

func (*RemoteApplication) Name Uses

func (s *RemoteApplication) Name() string

Name returns the application name.

func (*RemoteApplication) OfferUUID Uses

func (s *RemoteApplication) OfferUUID() string

OfferUUID returns the offer UUID.

func (*RemoteApplication) Refresh Uses

func (s *RemoteApplication) Refresh() error

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

func (*RemoteApplication) Relations Uses

func (s *RemoteApplication) Relations() (relations []*Relation, err error)

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

func (*RemoteApplication) SetStatus Uses

func (s *RemoteApplication) SetStatus(info status.StatusInfo) error

SetStatus sets the status for the application.

func (*RemoteApplication) SourceModel Uses

func (s *RemoteApplication) SourceModel() names.ModelTag

SourceModel returns the tag of the model to which the application belongs.

func (*RemoteApplication) SpaceForEndpoint Uses

func (s *RemoteApplication) SpaceForEndpoint(endpointName string) (RemoteSpace, bool)

SpaceForEndpoint returns the remote space an endpoint is bound to, if one is found.

func (*RemoteApplication) Spaces Uses

func (s *RemoteApplication) Spaces() []RemoteSpace

Spaces returns the remote spaces this application is connected to.

func (*RemoteApplication) Status Uses

func (s *RemoteApplication) Status() (status.StatusInfo, error)

Status returns the status of the remote application.

func (*RemoteApplication) String Uses

func (s *RemoteApplication) String() string

String returns the application name.

func (*RemoteApplication) Tag Uses

func (s *RemoteApplication) Tag() names.Tag

Tag returns a name identifying the application.

func (*RemoteApplication) TerminateOperation Uses

func (s *RemoteApplication) TerminateOperation(message string) ModelOperation

TerminateOperation returns a ModelOperation that will terminate this remote application when applied, ensuring that all units have left scope as well.

func (*RemoteApplication) Token Uses

func (s *RemoteApplication) Token() (string, error)

Token returns the token for the remote application, provided by the remote model to identify the application in future communications.

func (*RemoteApplication) URL Uses

func (s *RemoteApplication) URL() (string, bool)

URL returns the remote application URL, and a boolean indicating whether or not a URL is known for the remote application. A URL will only be available for the consumer of an offered application.

func (*RemoteApplication) WatchRelations Uses

func (s *RemoteApplication) WatchRelations() StringsWatcher

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

type RemoteApplicationsDescription Uses

type RemoteApplicationsDescription interface {
    DocModelNamespace
    StateDocumentFactory
    RemoteApplications() []description.RemoteApplication
}

RemoteApplicationsDescription defines an inplace usage for reading remote applications.

type RemoteConnectionStatus Uses

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

RemoteConnectionStatus holds summary information about connections to an application offer.

func (*RemoteConnectionStatus) ActiveConnectionCount Uses

func (r *RemoteConnectionStatus) ActiveConnectionCount() int

ActiveConnectionCount returns the number of active remote applications related to an offer.

func (*RemoteConnectionStatus) TotalConnectionCount Uses

func (r *RemoteConnectionStatus) TotalConnectionCount() int

TotalConnectionCount returns the number of remote applications related to an offer.

type RemoteEntities Uses

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

RemoteEntities wraps State to provide access to the remote entities collection.

func (*RemoteEntities) ExportLocalEntity Uses

func (r *RemoteEntities) ExportLocalEntity(entity names.Tag) (string, error)

ExportLocalEntity adds an entity to the remote entities collection, returning an opaque token that uniquely identifies the entity within the model.

If an entity is exported twice, we return an error satisfying errors.IsAlreadyExists(); we also still return the token so that a second api call is not required by the caller to get the token.

func (*RemoteEntities) GetMacaroon Uses

func (r *RemoteEntities) GetMacaroon(entity names.Tag) (*macaroon.Macaroon, error)

GetMacaroon returns the macaroon associated with the entity with the given tag and model.

func (*RemoteEntities) GetRemoteEntity Uses

func (r *RemoteEntities) GetRemoteEntity(token string) (names.Tag, error)

GetRemoteEntity returns the tag of the entity associated with the given token.

func (*RemoteEntities) GetToken Uses

func (r *RemoteEntities) GetToken(entity names.Tag) (string, error)

GetToken returns the token associated with the entity with the given tag and model.

func (*RemoteEntities) ImportRemoteEntity Uses

func (r *RemoteEntities) ImportRemoteEntity(entity names.Tag, token string) error

ImportRemoteEntity adds an entity to the remote entities collection with the specified opaque token. If the entity already exists, its token will be overwritten. This method assumes that the provided token is unique within the source model, and does not perform any uniqueness checks on it.

func (*RemoteEntities) RemoveRemoteEntity Uses

func (r *RemoteEntities) RemoveRemoteEntity(entity names.Tag) error

RemoveRemoteEntity removes the entity from the remote entities collection, and releases the token if the entity belongs to the local model.

func (*RemoteEntities) SaveMacaroon Uses

func (r *RemoteEntities) SaveMacaroon(entity names.Tag, mac *macaroon.Macaroon) error

SaveMacaroon saves the given macaroon for the specified entity.

type RemoteEntitiesDescription Uses

type RemoteEntitiesDescription interface {
    DocModelNamespace
    RemoteEntities() []description.RemoteEntity
}

RemoteEntitiesDescription defines an inplace usage for reading remote entities.