2ef903b8702ad9fb18b4cbc4866cddb25ba14fe5
1 from .client
import watcher
2 from .delta
import get_entity_delta
5 class ModelEntity(object):
6 """An object in the Model tree"""
8 def __init__(self
, data
, model
):
9 """Initialize a new entity
11 :param data: dict of data from a watcher delta
12 :param model: The model instance in whose object tree this
21 def __init__(self
, connection
):
22 """Instantiate a new connected Model.
24 :param connection: `juju.client.connection.Connection` instance
27 self
.connection
= connection
28 self
.observers
= set()
31 def add_observer(self
, callable_
):
32 """Register an "on-model-change" callback
34 Once a watch is started (Model.watch() is called), ``callable_``
35 will be called each time the model changes. callable_ should
36 accept the following positional arguments:
38 delta - An instance of :class:`juju.delta.EntityDelta`
39 containing the raw delta data recv'd from the Juju
42 old_obj - If the delta modifies an existing object in the model,
43 old_obj will be a copy of that object, as it was before the
44 delta was applied. Will be None if the delta creates a new
47 new_obj - A copy of the new or updated object, after the delta
48 is applied. Will be None if the delta removes an entity
51 model - The :class:`Model` itself.
54 self
.observers
.add(callable_
)
56 async def watch(self
):
57 """Start an asynchronous watch against this model.
59 See :meth:`add_observer` to register an onchange callback.
62 allwatcher
= watcher
.AllWatcher()
63 allwatcher
.connect(self
.connection
)
65 results
= await allwatcher
.Next()
66 for delta
in results
.deltas
:
67 delta
= get_entity_delta(delta
)
68 old_obj
, new_obj
= self
._apply
_delta
(delta
)
69 self
._notify
_observers
(delta
, old_obj
, new_obj
)
71 def _apply_delta(self
, delta
):
72 """Apply delta to our model state and return the a copy of the
73 affected object as it was before and after the update, e.g.:
75 old_obj, new_obj = self._apply_delta(delta)
77 old_obj may be None if the delta is for the creation of a new object,
78 e.g. a new application or unit is deployed.
80 new_obj may be if no object was created or updated, or if an object
81 was deleted as a result of the delta being applied.
84 old_obj
, new_obj
= None, None
86 if (delta
.entity
in self
.state
and
87 delta
.get_id() in self
.state
[delta
.entity
]):
88 old_obj
= self
.state
[delta
.entity
][delta
.get_id()]
89 if delta
.type == 'remove':
90 del self
.state
[delta
.entity
][delta
.get_id()]
91 return old_obj
, new_obj
93 new_obj
= self
.state
.setdefault(delta
.entity
, {})[delta
.get_id()] = (
94 self
._create
_model
_entity
(delta
))
96 return old_obj
, new_obj
98 def _create_model_entity(self
, delta
):
99 """Return an object instance representing the entity created or
103 entity_class
= delta
.get_entity_class()
104 return entity_class(delta
.data
, self
)
106 def _notify_observers(self
, delta
, old_obj
, new_obj
):
107 """Call observing callbacks, notifying them of a change in model state
109 :param delta: The raw change from the watcher
110 (:class:`juju.client.overrides.Delta`)
111 :param old_obj: The object in the model that this delta updates.
113 :param new_obj: The object in the model that is created or updated
114 by applying this delta.
117 for o
in self
.observers
:
118 o(delta
, old_obj
, new_obj
, self
)
121 self
, spec
=None, constraints
=None, disks
=None, series
=None,
123 """Start a new, empty machine and optionally a container, or add a
124 container to a machine.
126 :param str spec: Machine specification
129 (None) - starts a new machine
130 'lxc' - starts a new machine with on lxc container
131 'lxc:4' - starts a new lxc container on machine 4
132 'ssh:user@10.10.0.3' - manually provisions a machine with ssh
133 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS
134 'maas2.name' - acquire machine maas2.name on MAAS
135 :param constraints: Machine constraints
136 :type constraints: :class:`juju.Constraints`
137 :param list disks: List of disk :class:`constraints <juju.Constraints>`
138 :param str series: Series
139 :param int count: Number of machines to deploy
141 Supported container types are: lxc, lxd, kvm
143 When deploying a container to an existing machine, constraints cannot
148 add_machines
= add_machine
150 def add_relation(self
, relation1
, relation2
):
151 """Add a relation between two services.
153 :param str relation1: '<service>[:<relation_name>]'
154 :param str relation2: '<service>[:<relation_name>]'
159 def add_space(self
, name
, *cidrs
):
160 """Add a new network space.
162 Adds a new space with the given name and associates the given
163 (optional) list of existing subnet CIDRs with it.
165 :param str name: Name of the space
166 :param \*cidrs: Optional list of existing subnet CIDRs
171 def add_ssh_key(self
, key
):
172 """Add a public SSH key to this model.
174 :param str key: The public ssh key
178 add_ssh_keys
= add_ssh_key
180 def add_subnet(self
, cidr_or_id
, space
, *zones
):
181 """Add an existing subnet to this model.
183 :param str cidr_or_id: CIDR or provider ID of the existing subnet
184 :param str space: Network space with which to associate
185 :param str \*zones: Zone(s) in which the subnet resides
190 def get_backups(self
):
191 """Retrieve metadata for backups in this model.
196 def block(self
, *commands
):
197 """Add a new block to this model.
199 :param str \*commands: The commands to block. Valid values are
200 'all-changes', 'destroy-model', 'remove-object'
205 def get_blocks(self
):
206 """List blocks for this model.
211 def get_cached_images(self
, arch
=None, kind
=None, series
=None):
212 """Return a list of cached OS images.
214 :param str arch: Filter by image architecture
215 :param str kind: Filter by image kind, e.g. 'lxd'
216 :param str series: Filter by image series, e.g. 'xenial'
221 def create_backup(self
, note
=None, no_download
=False):
222 """Create a backup of this model.
224 :param str note: A note to store with the backup
225 :param bool no_download: Do not download the backup archive
226 :return str: Path to downloaded archive
231 def create_storage_pool(self
, name
, provider_type
, **pool_config
):
232 """Create or define a storage pool.
234 :param str name: Name to give the storage pool
235 :param str provider_type: Pool provider type
236 :param \*\*pool_config: key/value pool configuration pairs
242 self
, no_tail
=False, exclude_module
=None, include_module
=None,
243 include
=None, level
=None, limit
=0, lines
=10, replay
=False,
245 """Get log messages for this model.
247 :param bool no_tail: Stop after returning existing log messages
248 :param list exclude_module: Do not show log messages for these logging
250 :param list include_module: Only show log messages for these logging
252 :param list include: Only show log messages for these entities
253 :param str level: Log level to show, valid options are 'TRACE',
254 'DEBUG', 'INFO', 'WARNING', 'ERROR,
255 :param int limit: Return this many of the most recent (possibly
256 filtered) lines are shown
257 :param int lines: Yield this many of the most recent lines, and keep
259 :param bool replay: Yield the entire log, and keep yielding
260 :param list exclude: Do not show log messages for these entities
266 self
, entity_url
, service_name
=None, bind
=None, budget
=None,
267 channel
=None, config
=None, constraints
=None, force
=False,
268 num_units
=1, plan
=None, resource
=None, series
=None, storage
=None,
270 """Deploy a new service or bundle.
272 :param str entity_url: Charm or bundle url
273 :param str service_name: Name to give the service
274 :param dict bind: <charm endpoint>:<network space> pairs
275 :param dict budget: <budget name>:<limit> pairs
276 :param str channel: Charm store channel from which to retrieve
277 the charm or bundle, e.g. 'development'
278 :param dict config: Charm configuration dictionary
279 :param constraints: Service constraints
280 :type constraints: :class:`juju.Constraints`
281 :param bool force: Allow charm to be deployed to a machine running
282 an unsupported series
283 :param int num_units: Number of units to deploy
284 :param str plan: Plan under which to deploy charm
285 :param dict resource: <resource name>:<file path> pairs
286 :param str series: Series on which to deploy
287 :param dict storage: Storage constraints TODO how do these look?
288 :param str to: Placement directive, e.g.::
291 'lxc:7' - new lxc container on machine 7
292 '24/lxc/3' - lxc container 3 or machine 24
294 If None, a new machine is provisioned.
300 """Terminate all machines and resources for this model.
305 def get_backup(self
, archive_id
):
306 """Download a backup archive file.
308 :param str archive_id: The id of the archive to download
309 :return str: Path to the archive file
315 self
, num_controllers
=0, constraints
=None, series
=None, to
=None):
316 """Ensure sufficient controllers exist to provide redundancy.
318 :param int num_controllers: Number of controllers to make available
319 :param constraints: Constraints to apply to the controller machines
320 :type constraints: :class:`juju.Constraints`
321 :param str series: Series of the controller machines
322 :param list to: Placement directives for controller machines, e.g.::
325 'lxc:7' - new lxc container on machine 7
326 '24/lxc/3' - lxc container 3 or machine 24
328 If None, a new machine is provisioned.
333 def get_config(self
):
334 """Return the configuration settings for this model.
339 def get_constraints(self
):
340 """Return the machine constraints for this model.
345 def grant(self
, username
, acl
='read'):
346 """Grant a user access to this model.
348 :param str username: Username
349 :param str acl: Access control ('read' or 'write')
354 def import_ssh_key(self
, identity
):
355 """Add a public SSH key from a trusted indentity source to this model.
357 :param str identity: User identity in the form <lp|gh>:<username>
361 import_ssh_keys
= import_ssh_key
363 def get_machines(self
, machine
, utc
=False):
364 """Return list of machines in this model.
366 :param str machine: Machine id, e.g. '0'
367 :param bool utc: Display time as UTC in RFC3339 format
372 def get_shares(self
):
373 """Return list of all users with access to this model.
378 def get_spaces(self
):
379 """Return list of all known spaces, including associated subnets.
384 def get_ssh_key(self
):
385 """Return known SSH keys for this model.
389 get_ssh_keys
= get_ssh_key
391 def get_storage(self
, filesystem
=False, volume
=False):
392 """Return details of storage instances.
394 :param bool filesystem: Include filesystem storage
395 :param bool volume: Include volume storage
400 def get_storage_pools(self
, names
=None, providers
=None):
401 """Return list of storage pools.
403 :param list names: Only include pools with these names
404 :param list providers: Only include pools for these providers
409 def get_subnets(self
, space
=None, zone
=None):
410 """Return list of known subnets.
412 :param str space: Only include subnets in this space
413 :param str zone: Only include subnets in this zone
418 def remove_blocks(self
):
419 """Remove all blocks from this model.
424 def remove_backup(self
, backup_id
):
427 :param str backup_id: The id of the backup to remove
432 def remove_cached_images(self
, arch
=None, kind
=None, series
=None):
433 """Remove cached OS images.
435 :param str arch: Architecture of the images to remove
436 :param str kind: Image kind to remove, e.g. 'lxd'
437 :param str series: Image series to remove, e.g. 'xenial'
442 def remove_machine(self
, *machine_ids
):
443 """Remove a machine from this model.
445 :param str \*machine_ids: Ids of the machines to remove
449 remove_machines
= remove_machine
451 def remove_ssh_key(self
, *keys
):
452 """Remove a public SSH key(s) from this model.
454 :param str \*keys: Keys to remove
458 remove_ssh_keys
= remove_ssh_key
461 self
, bootstrap
=False, constraints
=None, archive
=None,
462 backup_id
=None, upload_tools
=False):
463 """Restore a backup archive to a new controller.
465 :param bool bootstrap: Bootstrap a new state machine
466 :param constraints: Model constraints
467 :type constraints: :class:`juju.Constraints`
468 :param str archive: Path to backup archive to restore
469 :param str backup_id: Id of backup to restore
470 :param bool upload_tools: Upload tools if bootstrapping a new machine
475 def retry_provisioning(self
):
476 """Retry provisioning for failed machines.
481 def revoke(self
, username
, acl
='read'):
482 """Revoke a user's access to this model.
484 :param str username: Username to revoke
485 :param str acl: Access control ('read' or 'write')
490 def run(self
, command
, timeout
=None):
491 """Run command on all machines in this model.
493 :param str command: The command to run
494 :param int timeout: Time to wait before command is considered failed
499 def set_config(self
, **config
):
500 """Set configuration keys on this model.
502 :param \*\*config: Config key/values
507 def set_constraints(self
, constraints
):
508 """Set machine constraints on this model.
510 :param :class:`juju.Constraints` constraints: Machine constraints
515 def get_action_output(self
, action_uuid
, wait
=-1):
516 """Get the results of an action by ID.
518 :param str action_uuid: Id of the action
519 :param int wait: Time in seconds to wait for action to complete
524 def get_action_status(self
, uuid_or_prefix
=None, name
=None):
525 """Get the status of all actions, filtered by ID, ID prefix, or action name.
527 :param str uuid_or_prefix: Filter by action uuid or prefix
528 :param str name: Filter by action name
533 def get_budget(self
, budget_name
):
534 """Get budget usage info.
536 :param str budget_name: Name of budget
541 def get_status(self
, filter_
=None, utc
=False):
542 """Return the status of the model.
544 :param str filter_: Service or unit name or wildcard ('*')
545 :param bool utc: Display time as UTC in RFC3339 format
552 self
, all_
=False, destination
=None, dry_run
=False, public
=False,
553 source
=None, stream
=None, version
=None):
554 """Copy Juju tools into this model.
556 :param bool all_: Copy all versions, not just the latest
557 :param str destination: Path to local destination directory
558 :param bool dry_run: Don't do the actual copy
559 :param bool public: Tools are for a public cloud, so generate mirrors
561 :param str source: Path to local source directory
562 :param str stream: Simplestreams stream for which to sync metadata
563 :param str version: Copy a specific major.minor version
568 def unblock(self
, *commands
):
569 """Unblock an operation that would alter this model.
571 :param str \*commands: The commands to unblock. Valid values are
572 'all-changes', 'destroy-model', 'remove-object'
577 def unset_config(self
, *keys
):
578 """Unset configuration on this model.
580 :param str \*keys: The keys to unset
585 def upgrade_gui(self
):
586 """Upgrade the Juju GUI for this model.
592 self
, dry_run
=False, reset_previous_upgrade
=False,
593 upload_tools
=False, version
=None):
594 """Upgrade Juju on all machines in a model.
596 :param bool dry_run: Don't do the actual upgrade
597 :param bool reset_previous_upgrade: Clear the previous (incomplete)
599 :param bool upload_tools: Upload local version of tools
600 :param str version: Upgrade to a specific version
605 def upload_backup(self
, archive_path
):
606 """Store a backup archive remotely in Juju.
608 :param str archive_path: Path to local archive