6 from concurrent
.futures
import CancelledError
7 from functools
import partial
9 from theblues
import charmstore
11 from .client
import client
12 from .client
import watcher
13 from .client
import connection
14 from .delta
import get_entity_delta
15 from .delta
import get_entity_class
16 from .exceptions
import DeadEntityException
17 from .errors
import JujuAPIError
19 log
= logging
.getLogger(__name__
)
22 class _Observer(object):
23 """Wrapper around an observer callable.
25 This wrapper allows filter criteria to be associated with the
26 callable so that it's only called for changes that meet the criteria.
29 def __init__(self
, callable_
, entity_type
, action
, entity_id
, predicate
):
30 self
.callable_
= callable_
31 self
.entity_type
= entity_type
33 self
.entity_id
= entity_id
34 self
.predicate
= predicate
36 self
.entity_id
= str(self
.entity_id
)
37 if not self
.entity_id
.startswith('^'):
38 self
.entity_id
= '^' + self
.entity_id
39 if not self
.entity_id
.endswith('$'):
42 async def __call__(self
, delta
, old
, new
, model
):
43 await self
.callable_(delta
, old
, new
, model
)
45 def cares_about(self
, delta
):
46 """Return True if this observer "cares about" (i.e. wants to be
47 called) for a this delta.
50 if (self
.entity_id
and delta
.get_id() and
51 not re
.match(self
.entity_id
, str(delta
.get_id()))):
54 if self
.entity_type
and self
.entity_type
!= delta
.entity
:
57 if self
.action
and self
.action
!= delta
.type:
60 if self
.predicate
and not self
.predicate(delta
):
66 class ModelObserver(object):
67 async def __call__(self
, delta
, old
, new
, model
):
68 handler_name
= 'on_{}_{}'.format(delta
.entity
, delta
.type)
69 method
= getattr(self
, handler_name
, self
.on_change
)
70 await method(delta
, old
, new
, model
)
72 async def on_change(self
, delta
, old
, new
, model
):
76 class ModelState(object):
77 """Holds the state of the model, including the delta history of all
78 entities in the model.
81 def __init__(self
, model
):
85 def _live_entity_map(self
, entity_type
):
86 """Return an id:Entity map of all the living entities of
91 entity_id
: self
.get_entity(entity_type
, entity_id
)
92 for entity_id
, history
in self
.state
.get(entity_type
, {}).items()
93 if history
[-1] is not None
97 def applications(self
):
98 """Return a map of application-name:Application for all applications
99 currently in the model.
102 return self
._live
_entity
_map
('application')
106 """Return a map of machine-id:Machine for all machines currently in
110 return self
._live
_entity
_map
('machine')
114 """Return a map of unit-id:Unit for all units currently in
118 return self
._live
_entity
_map
('unit')
120 def entity_history(self
, entity_type
, entity_id
):
121 """Return the history deque for an entity.
124 return self
.state
[entity_type
][entity_id
]
126 def entity_data(self
, entity_type
, entity_id
, history_index
):
127 """Return the data dict for an entity at a specific index of its
131 return self
.entity_history(entity_type
, entity_id
)[history_index
]
133 def apply_delta(self
, delta
):
134 """Apply delta to our state and return a copy of the
135 affected object as it was before and after the update, e.g.:
137 old_obj, new_obj = self.apply_delta(delta)
139 old_obj may be None if the delta is for the creation of a new object,
140 e.g. a new application or unit is deployed.
142 new_obj will never be None, but may be dead (new_obj.dead == True)
143 if the object was deleted as a result of the delta being applied.
148 .setdefault(delta
.entity
, {})
149 .setdefault(delta
.get_id(), collections
.deque())
152 history
.append(delta
.data
)
153 if delta
.type == 'remove':
156 entity
= self
.get_entity(delta
.entity
, delta
.get_id())
157 return entity
.previous(), entity
160 self
, entity_type
, entity_id
, history_index
=-1, connected
=True):
161 """Return an object instance representing the entity created or
167 'Getting %s:%s at index %s',
168 entity_type, entity_id, history_index)
171 if history_index
< 0 and history_index
!= -1:
172 history_index
+= len(self
.entity_history(entity_type
, entity_id
))
173 if history_index
< 0:
177 self
.entity_data(entity_type
, entity_id
, history_index
)
181 entity_class
= get_entity_class(entity_type
)
183 entity_id
, self
.model
, history_index
=history_index
,
187 class ModelEntity(object):
188 """An object in the Model tree"""
190 def __init__(self
, entity_id
, model
, history_index
=-1, connected
=True):
191 """Initialize a new entity
193 :param entity_id str: The unique id of the object in the model
194 :param model: The model instance in whose object tree this
196 :history_index int: The index of this object's state in the model's
197 history deque for this entity
198 :connected bool: Flag indicating whether this object gets live updates
202 self
.entity_id
= entity_id
204 self
._history
_index
= history_index
205 self
.connected
= connected
206 self
.connection
= model
.connection
208 def __getattr__(self
, name
):
209 """Fetch object attributes from the underlying data dict held in the
213 if self
.data
is None:
214 raise DeadEntityException(
215 "Entity {}:{} is dead - its attributes can no longer be "
216 "accessed. Use the .previous() method on this object to get "
217 "a copy of the object at its previous state.".format(
218 self
.entity_type
, self
.entity_id
))
219 return self
.data
[name
]
222 return bool(self
.data
)
224 def on_change(self
, callable_
):
225 """Add a change observer to this entity.
228 self
.model
.add_observer(
229 callable_
, self
.entity_type
, 'change', self
.entity_id
)
231 def on_remove(self
, callable_
):
232 """Add a remove observer to this entity.
235 self
.model
.add_observer(
236 callable_
, self
.entity_type
, 'remove', self
.entity_id
)
239 def entity_type(self
):
240 """A string identifying the entity type of this object, e.g.
241 'application' or 'unit', etc.
244 return self
.__class
__.__name
__.lower()
248 """Return True if this object represents the current state of the
249 entity in the underlying model.
251 This will be True except when the object represents an entity at a
252 non-latest state in history, e.g. if the object was obtained by calling
253 .previous() on another object.
256 return self
._history
_index
== -1
260 """Returns True if this entity no longer exists in the underlying
266 self
.model
.state
.entity_data(
267 self
.entity_type
, self
.entity_id
, -1) is None
272 """Returns True if this entity still exists in the underlying
280 """The data dictionary for this entity.
283 return self
.model
.state
.entity_data(
284 self
.entity_type
, self
.entity_id
, self
._history
_index
)
287 """Return a copy of this object as was at its previous state in
290 Returns None if this object is new (and therefore has no history).
292 The returned object is always "disconnected", i.e. does not receive
296 return self
.model
.state
.get_entity(
297 self
.entity_type
, self
.entity_id
, self
._history
_index
- 1,
301 """Return a copy of this object at its next state in
304 Returns None if this object is already the latest.
306 The returned object is "disconnected", i.e. does not receive
307 live updates, unless it is current (latest).
310 if self
._history
_index
== -1:
313 new_index
= self
._history
_index
+ 1
315 new_index
== len(self
.model
.state
.entity_history(
316 self
.entity_type
, self
.entity_id
)) - 1
318 return self
.model
.state
.get_entity(
319 self
.entity_type
, self
.entity_id
, self
._history
_index
- 1,
323 """Return a copy of this object at its current state in the model.
325 Returns self if this object is already the latest.
327 The returned object is always "connected", i.e. receives
328 live updates from the model.
331 if self
._history
_index
== -1:
334 return self
.model
.state
.get_entity(self
.entity_type
, self
.entity_id
)
338 def __init__(self
, loop
=None):
339 """Instantiate a new connected Model.
341 :param loop: an asyncio event loop
344 self
.loop
= loop
or asyncio
.get_event_loop()
345 self
.connection
= None
346 self
.observers
= weakref
.WeakValueDictionary()
347 self
.state
= ModelState(self
)
348 self
._watcher
_task
= None
349 self
._watch
_shutdown
= asyncio
.Event(loop
=loop
)
350 self
._watch
_received
= asyncio
.Event(loop
=loop
)
351 self
._charmstore
= CharmStore(self
.loop
)
353 async def connect_current(self
):
354 """Connect to the current Juju model.
357 self
.connection
= await connection
.Connection
.connect_current()
359 await self
._watch
_received
.wait()
361 async def disconnect(self
):
362 """Shut down the watcher task and close websockets.
365 self
._stop
_watching
()
366 if self
.connection
and self
.connection
.is_open
:
367 await self
._watch
_shutdown
.wait()
368 log
.debug('Closing model connection')
369 await self
.connection
.close()
370 self
.connection
= None
372 def all_units_idle(self
):
373 """Return True if all units are idle.
376 for unit
in self
.units
.values():
377 unit_status
= unit
.data
['agent-status']['current']
378 if unit_status
!= 'idle':
382 async def reset(self
, force
=False):
383 """Reset the model to a clean state.
385 :param bool force: Force-terminate machines.
387 This returns only after the model has reached a clean state. "Clean"
388 means no applications or machines exist in the model.
391 log
.debug('Resetting model')
392 for app
in self
.applications
.values():
394 for machine
in self
.machines
.values():
395 await machine
.destroy(force
=force
)
396 await self
.block_until(
397 lambda: len(self
.machines
) == 0
400 async def block_until(self
, *conditions
, timeout
=None):
401 """Return only after all conditions are true.
405 while not all(c() for c
in conditions
):
406 await asyncio
.sleep(0)
407 await asyncio
.wait_for(_block(), timeout
)
410 def applications(self
):
411 """Return a map of application-name:Application for all applications
412 currently in the model.
415 return self
.state
.applications
419 """Return a map of machine-id:Machine for all machines currently in
423 return self
.state
.machines
427 """Return a map of unit-id:Unit for all units currently in
431 return self
.state
.units
434 self
, callable_
, entity_type
=None, action
=None, entity_id
=None,
436 """Register an "on-model-change" callback
438 Once the model is connected, ``callable_``
439 will be called each time the model changes. callable_ should
440 be Awaitable and accept the following positional arguments:
442 delta - An instance of :class:`juju.delta.EntityDelta`
443 containing the raw delta data recv'd from the Juju
446 old_obj - If the delta modifies an existing object in the model,
447 old_obj will be a copy of that object, as it was before the
448 delta was applied. Will be None if the delta creates a new
451 new_obj - A copy of the new or updated object, after the delta
452 is applied. Will be None if the delta removes an entity
455 model - The :class:`Model` itself.
457 Events for which ``callable_`` is called can be specified by passing
458 entity_type, action, and/or id_ filter criteria, e.g.:
461 myfunc, entity_type='application', action='add', id_='ubuntu')
463 For more complex filtering conditions, pass a predicate function. It
464 will be called with a delta as its only argument. If the predicate
465 function returns True, the callable_ will be called.
468 observer
= _Observer(
469 callable_
, entity_type
, action
, entity_id
, predicate
)
470 self
.observers
[observer
] = callable_
473 """Start an asynchronous watch against this model.
475 See :meth:`add_observer` to register an onchange callback.
478 async def _start_watch():
479 self
._watch
_shutdown
.clear()
481 allwatcher
= watcher
.AllWatcher()
482 self
._watch
_conn
= await self
.connection
.clone()
483 allwatcher
.connect(self
._watch
_conn
)
485 results
= await allwatcher
.Next()
486 for delta
in results
.deltas
:
487 delta
= get_entity_delta(delta
)
488 old_obj
, new_obj
= self
.state
.apply_delta(delta
)
489 # XXX: Might not want to shield at this level
490 # We are shielding because when the watcher is
491 # canceled (on disconnect()), we don't want all of
492 # its children (every observer callback) to be
493 # canceled with it. So we shield them. But this means
494 # they can *never* be canceled.
495 await asyncio
.shield(
496 self
._notify
_observers
(delta
, old_obj
, new_obj
))
497 self
._watch
_received
.set()
498 except CancelledError
:
499 log
.debug('Closing watcher connection')
500 await self
._watch
_conn
.close()
501 self
._watch
_shutdown
.set()
502 self
._watch
_conn
= None
504 log
.debug('Starting watcher task')
505 self
._watcher
_task
= self
.loop
.create_task(_start_watch())
507 def _stop_watching(self
):
508 """Stop the asynchronous watch against this model.
511 log
.debug('Stopping watcher task')
512 if self
._watcher
_task
:
513 self
._watcher
_task
.cancel()
515 async def _notify_observers(self
, delta
, old_obj
, new_obj
):
516 """Call observing callbacks, notifying them of a change in model state
518 :param delta: The raw change from the watcher
519 (:class:`juju.client.overrides.Delta`)
520 :param old_obj: The object in the model that this delta updates.
522 :param new_obj: The object in the model that is created or updated
523 by applying this delta.
526 if new_obj
and not old_obj
:
530 'Model changed: %s %s %s',
531 delta
.entity
, delta
.type, delta
.get_id())
533 for o
in self
.observers
:
534 if o
.cares_about(delta
):
535 asyncio
.ensure_future(o(delta
, old_obj
, new_obj
, self
))
537 async def _wait_for_new(self
, entity_type
, entity_id
, predicate
=None):
538 """Wait for a new object to appear in the Model and return it.
540 Waits for an object of type ``entity_type`` with id ``entity_id``.
542 This coroutine blocks until the new object appears in the model.
545 entity_added
= asyncio
.Queue(loop
=self
.loop
)
547 async def callback(delta
, old
, new
, model
):
548 await entity_added
.put(delta
.get_id())
550 self
.add_observer(callback
, entity_type
, 'add', entity_id
, predicate
)
551 entity_id
= await entity_added
.get()
552 return self
.state
._live
_entity
_map
(entity_type
)[entity_id
]
555 self
, spec
=None, constraints
=None, disks
=None, series
=None,
557 """Start a new, empty machine and optionally a container, or add a
558 container to a machine.
560 :param str spec: Machine specification
563 (None) - starts a new machine
564 'lxc' - starts a new machine with on lxc container
565 'lxc:4' - starts a new lxc container on machine 4
566 'ssh:user@10.10.0.3' - manually provisions a machine with ssh
567 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS
568 'maas2.name' - acquire machine maas2.name on MAAS
569 :param constraints: Machine constraints
570 :type constraints: :class:`juju.Constraints`
571 :param list disks: List of disk :class:`constraints <juju.Constraints>`
572 :param str series: Series
573 :param int count: Number of machines to deploy
575 Supported container types are: lxc, lxd, kvm
577 When deploying a container to an existing machine, constraints cannot
582 add_machines
= add_machine
584 async def add_relation(self
, relation1
, relation2
):
585 """Add a relation between two applications.
587 :param str relation1: '<application>[:<relation_name>]'
588 :param str relation2: '<application>[:<relation_name>]'
591 app_facade
= client
.ApplicationFacade()
592 app_facade
.connect(self
.connection
)
595 'Adding relation %s <-> %s', relation1
, relation2
)
598 result
= await app_facade
.AddRelation([relation1
, relation2
])
599 except JujuAPIError
as e
:
600 if 'relation already exists' not in e
.message
:
603 'Relation %s <-> %s already exists', relation1
, relation2
)
604 # TODO: if relation already exists we should return the
605 # Relation ModelEntity here
608 def predicate(delta
):
610 for endpoint
in delta
.data
['endpoints']:
611 endpoints
[endpoint
['application-name']] = endpoint
['relation']
612 return endpoints
== result
.endpoints
614 return await self
._wait
_for
_new
('relation', None, predicate
)
616 def add_space(self
, name
, *cidrs
):
617 """Add a new network space.
619 Adds a new space with the given name and associates the given
620 (optional) list of existing subnet CIDRs with it.
622 :param str name: Name of the space
623 :param \*cidrs: Optional list of existing subnet CIDRs
628 def add_ssh_key(self
, key
):
629 """Add a public SSH key to this model.
631 :param str key: The public ssh key
635 add_ssh_keys
= add_ssh_key
637 def add_subnet(self
, cidr_or_id
, space
, *zones
):
638 """Add an existing subnet to this model.
640 :param str cidr_or_id: CIDR or provider ID of the existing subnet
641 :param str space: Network space with which to associate
642 :param str \*zones: Zone(s) in which the subnet resides
647 def get_backups(self
):
648 """Retrieve metadata for backups in this model.
653 def block(self
, *commands
):
654 """Add a new block to this model.
656 :param str \*commands: The commands to block. Valid values are
657 'all-changes', 'destroy-model', 'remove-object'
662 def get_blocks(self
):
663 """List blocks for this model.
668 def get_cached_images(self
, arch
=None, kind
=None, series
=None):
669 """Return a list of cached OS images.
671 :param str arch: Filter by image architecture
672 :param str kind: Filter by image kind, e.g. 'lxd'
673 :param str series: Filter by image series, e.g. 'xenial'
678 def create_backup(self
, note
=None, no_download
=False):
679 """Create a backup of this model.
681 :param str note: A note to store with the backup
682 :param bool no_download: Do not download the backup archive
683 :return str: Path to downloaded archive
688 def create_storage_pool(self
, name
, provider_type
, **pool_config
):
689 """Create or define a storage pool.
691 :param str name: Name to give the storage pool
692 :param str provider_type: Pool provider type
693 :param \*\*pool_config: key/value pool configuration pairs
699 self
, no_tail
=False, exclude_module
=None, include_module
=None,
700 include
=None, level
=None, limit
=0, lines
=10, replay
=False,
702 """Get log messages for this model.
704 :param bool no_tail: Stop after returning existing log messages
705 :param list exclude_module: Do not show log messages for these logging
707 :param list include_module: Only show log messages for these logging
709 :param list include: Only show log messages for these entities
710 :param str level: Log level to show, valid options are 'TRACE',
711 'DEBUG', 'INFO', 'WARNING', 'ERROR,
712 :param int limit: Return this many of the most recent (possibly
713 filtered) lines are shown
714 :param int lines: Yield this many of the most recent lines, and keep
716 :param bool replay: Yield the entire log, and keep yielding
717 :param list exclude: Do not show log messages for these entities
723 self
, entity_url
, service_name
=None, bind
=None, budget
=None,
724 channel
=None, config
=None, constraints
=None, force
=False,
725 num_units
=1, plan
=None, resources
=None, series
=None, storage
=None,
727 """Deploy a new service or bundle.
729 :param str entity_url: Charm or bundle url
730 :param str service_name: Name to give the service
731 :param dict bind: <charm endpoint>:<network space> pairs
732 :param dict budget: <budget name>:<limit> pairs
733 :param str channel: Charm store channel from which to retrieve
734 the charm or bundle, e.g. 'development'
735 :param dict config: Charm configuration dictionary
736 :param constraints: Service constraints
737 :type constraints: :class:`juju.Constraints`
738 :param bool force: Allow charm to be deployed to a machine running
739 an unsupported series
740 :param int num_units: Number of units to deploy
741 :param str plan: Plan under which to deploy charm
742 :param dict resources: <resource name>:<file path> pairs
743 :param str series: Series on which to deploy
744 :param dict storage: Storage constraints TODO how do these look?
745 :param str to: Placement directive, e.g.::
748 'lxc:7' - new lxc container on machine 7
749 '24/lxc/3' - lxc container 3 or machine 24
751 If None, a new machine is provisioned.
756 - service_name is required; fill this in automatically if not
758 - series is required; how do we pick a default?
762 constraints
= client
.Value(**constraints
)
766 client
.Placement(**p
) for p
in to
773 k
: client
.Constraints(**v
)
774 for k
, v
in storage
.items()
777 entity_id
= await self
.charmstore
.entityId(entity_url
)
779 app_facade
= client
.ApplicationFacade()
780 client_facade
= client
.ClientFacade()
781 app_facade
.connect(self
.connection
)
782 client_facade
.connect(self
.connection
)
784 if 'bundle/' in entity_id
:
785 handler
= BundleHandler(self
)
786 await handler
.fetch_plan(entity_id
)
787 await handler
.execute_plan()
790 'Deploying %s', entity_id
)
792 await client_facade
.AddCharm(channel
, entity_id
)
793 app
= client
.ApplicationDeploy(
794 application
=service_name
,
798 constraints
=constraints
,
799 endpoint_bindings
=bind
,
807 await app_facade
.Deploy([app
])
808 return await self
._wait
_for
_new
('application', service_name
)
811 """Terminate all machines and resources for this model.
816 def get_backup(self
, archive_id
):
817 """Download a backup archive file.
819 :param str archive_id: The id of the archive to download
820 :return str: Path to the archive file
826 self
, num_controllers
=0, constraints
=None, series
=None, to
=None):
827 """Ensure sufficient controllers exist to provide redundancy.
829 :param int num_controllers: Number of controllers to make available
830 :param constraints: Constraints to apply to the controller machines
831 :type constraints: :class:`juju.Constraints`
832 :param str series: Series of the controller machines
833 :param list to: Placement directives for controller machines, e.g.::
836 'lxc:7' - new lxc container on machine 7
837 '24/lxc/3' - lxc container 3 or machine 24
839 If None, a new machine is provisioned.
844 def get_config(self
):
845 """Return the configuration settings for this model.
850 def get_constraints(self
):
851 """Return the machine constraints for this model.
856 def grant(self
, username
, acl
='read'):
857 """Grant a user access to this model.
859 :param str username: Username
860 :param str acl: Access control ('read' or 'write')
865 def import_ssh_key(self
, identity
):
866 """Add a public SSH key from a trusted indentity source to this model.
868 :param str identity: User identity in the form <lp|gh>:<username>
872 import_ssh_keys
= import_ssh_key
874 def get_machines(self
, machine
, utc
=False):
875 """Return list of machines in this model.
877 :param str machine: Machine id, e.g. '0'
878 :param bool utc: Display time as UTC in RFC3339 format
883 def get_shares(self
):
884 """Return list of all users with access to this model.
889 def get_spaces(self
):
890 """Return list of all known spaces, including associated subnets.
895 def get_ssh_key(self
):
896 """Return known SSH keys for this model.
900 get_ssh_keys
= get_ssh_key
902 def get_storage(self
, filesystem
=False, volume
=False):
903 """Return details of storage instances.
905 :param bool filesystem: Include filesystem storage
906 :param bool volume: Include volume storage
911 def get_storage_pools(self
, names
=None, providers
=None):
912 """Return list of storage pools.
914 :param list names: Only include pools with these names
915 :param list providers: Only include pools for these providers
920 def get_subnets(self
, space
=None, zone
=None):
921 """Return list of known subnets.
923 :param str space: Only include subnets in this space
924 :param str zone: Only include subnets in this zone
929 def remove_blocks(self
):
930 """Remove all blocks from this model.
935 def remove_backup(self
, backup_id
):
938 :param str backup_id: The id of the backup to remove
943 def remove_cached_images(self
, arch
=None, kind
=None, series
=None):
944 """Remove cached OS images.
946 :param str arch: Architecture of the images to remove
947 :param str kind: Image kind to remove, e.g. 'lxd'
948 :param str series: Image series to remove, e.g. 'xenial'
953 def remove_machine(self
, *machine_ids
):
954 """Remove a machine from this model.
956 :param str \*machine_ids: Ids of the machines to remove
960 remove_machines
= remove_machine
962 def remove_ssh_key(self
, *keys
):
963 """Remove a public SSH key(s) from this model.
965 :param str \*keys: Keys to remove
969 remove_ssh_keys
= remove_ssh_key
972 self
, bootstrap
=False, constraints
=None, archive
=None,
973 backup_id
=None, upload_tools
=False):
974 """Restore a backup archive to a new controller.
976 :param bool bootstrap: Bootstrap a new state machine
977 :param constraints: Model constraints
978 :type constraints: :class:`juju.Constraints`
979 :param str archive: Path to backup archive to restore
980 :param str backup_id: Id of backup to restore
981 :param bool upload_tools: Upload tools if bootstrapping a new machine
986 def retry_provisioning(self
):
987 """Retry provisioning for failed machines.
992 def revoke(self
, username
, acl
='read'):
993 """Revoke a user's access to this model.
995 :param str username: Username to revoke
996 :param str acl: Access control ('read' or 'write')
1001 def run(self
, command
, timeout
=None):
1002 """Run command on all machines in this model.
1004 :param str command: The command to run
1005 :param int timeout: Time to wait before command is considered failed
1010 def set_config(self
, **config
):
1011 """Set configuration keys on this model.
1013 :param \*\*config: Config key/values
1018 def set_constraints(self
, constraints
):
1019 """Set machine constraints on this model.
1021 :param :class:`juju.Constraints` constraints: Machine constraints
1026 def get_action_output(self
, action_uuid
, wait
=-1):
1027 """Get the results of an action by ID.
1029 :param str action_uuid: Id of the action
1030 :param int wait: Time in seconds to wait for action to complete
1035 def get_action_status(self
, uuid_or_prefix
=None, name
=None):
1036 """Get the status of all actions, filtered by ID, ID prefix, or action name.
1038 :param str uuid_or_prefix: Filter by action uuid or prefix
1039 :param str name: Filter by action name
1044 def get_budget(self
, budget_name
):
1045 """Get budget usage info.
1047 :param str budget_name: Name of budget
1052 def get_status(self
, filter_
=None, utc
=False):
1053 """Return the status of the model.
1055 :param str filter_: Service or unit name or wildcard ('*')
1056 :param bool utc: Display time as UTC in RFC3339 format
1063 self
, all_
=False, destination
=None, dry_run
=False, public
=False,
1064 source
=None, stream
=None, version
=None):
1065 """Copy Juju tools into this model.
1067 :param bool all_: Copy all versions, not just the latest
1068 :param str destination: Path to local destination directory
1069 :param bool dry_run: Don't do the actual copy
1070 :param bool public: Tools are for a public cloud, so generate mirrors
1072 :param str source: Path to local source directory
1073 :param str stream: Simplestreams stream for which to sync metadata
1074 :param str version: Copy a specific major.minor version
1079 def unblock(self
, *commands
):
1080 """Unblock an operation that would alter this model.
1082 :param str \*commands: The commands to unblock. Valid values are
1083 'all-changes', 'destroy-model', 'remove-object'
1088 def unset_config(self
, *keys
):
1089 """Unset configuration on this model.
1091 :param str \*keys: The keys to unset
1096 def upgrade_gui(self
):
1097 """Upgrade the Juju GUI for this model.
1103 self
, dry_run
=False, reset_previous_upgrade
=False,
1104 upload_tools
=False, version
=None):
1105 """Upgrade Juju on all machines in a model.
1107 :param bool dry_run: Don't do the actual upgrade
1108 :param bool reset_previous_upgrade: Clear the previous (incomplete)
1110 :param bool upload_tools: Upload local version of tools
1111 :param str version: Upgrade to a specific version
1116 def upload_backup(self
, archive_path
):
1117 """Store a backup archive remotely in Juju.
1119 :param str archive_path: Path to local archive
1125 def charmstore(self
):
1126 return self
._charmstore
1129 class BundleHandler(object):
1131 Handle bundles by using the API to translate bundle YAML into a plan of
1132 steps and then dispatching each of those using the API.
1134 def __init__(self
, model
):
1136 self
.charmstore
= model
.charmstore
1138 self
.references
= {}
1139 self
._units
_by
_app
= {}
1140 for unit_name
, unit
in model
.units
.items():
1141 app_units
= self
._units
_by
_app
.setdefault(unit
.application
, [])
1142 app_units
.append(unit_name
)
1143 self
.client_facade
= client
.ClientFacade()
1144 self
.client_facade
.connect(model
.connection
)
1145 self
.app_facade
= client
.ApplicationFacade()
1146 self
.app_facade
.connect(model
.connection
)
1147 self
.ann_facade
= client
.AnnotationsFacade()
1148 self
.ann_facade
.connect(model
.connection
)
1150 async def fetch_plan(self
, entity_id
):
1151 yaml
= await self
.charmstore
.files(entity_id
,
1152 filename
='bundle.yaml',
1154 self
.plan
= await self
.client_facade
.GetBundleChanges(yaml
)
1156 async def execute_plan(self
):
1157 for step
in self
.plan
.changes
:
1158 method
= getattr(self
, step
.method
)
1159 result
= await method(*step
.args
)
1160 self
.references
[step
.id_
] = result
1162 def resolve(self
, reference
):
1163 if reference
and reference
.startswith('$'):
1164 reference
= self
.references
[reference
[1:]]
1167 async def addCharm(self
, charm
, series
):
1169 :param charm string:
1170 Charm holds the URL of the charm to be added.
1172 :param series string:
1173 Series holds the series of the charm to be added
1174 if the charm default is not sufficient.
1176 entity_id
= await self
.charmstore
.entityId(charm
)
1177 log
.debug('Adding %s', entity_id
)
1178 await self
.client_facade
.AddCharm(None, entity_id
)
1181 async def addMachines(self
, series
, constraints
, container_type
,
1184 :param series string:
1185 Series holds the optional machine OS series.
1187 :param constraints string:
1188 Constraints holds the optional machine constraints.
1190 :param Container_type string:
1191 ContainerType optionally holds the type of the container (for
1192 instance ""lxc" or kvm"). It is not specified for top level
1195 :param parent_id string:
1196 ParentId optionally holds a placeholder pointing to another machine
1197 change or to a unit change. This value is only specified in the
1198 case this machine is a container, in which case also ContainerType
1201 params
= client
.AddMachineParams(
1203 constraints
=constraints
,
1204 container_type
=container_type
,
1205 parent_id
=self
.resolve(parent_id
),
1207 results
= await self
.client_facade
.AddMachines(params
)
1208 log
.debug('Added new machine %s', results
[0].machine
)
1209 return results
[0].machine
1211 async def addRelation(self
, endpoint1
, endpoint2
):
1213 :param endpoint1 string:
1214 :param endpoint2 string:
1215 Endpoint1 and Endpoint2 hold relation endpoints in the
1216 "application:interface" form, where the application is always a
1217 placeholder pointing to an application change, and the interface is
1218 optional. Examples are "$deploy-42:web" or just "$deploy-42".
1220 endpoints
= [endpoint1
, endpoint2
]
1221 # resolve indirect references
1222 for i
in range(len(endpoints
)):
1223 parts
= endpoints
[i
].split(':')
1224 parts
[0] = self
.resolve(parts
[0])
1225 endpoints
[i
] = ':'.join(parts
)
1227 return await self
.model
.add_relation(*endpoints
)
1229 async def deploy(self
, charm
, series
, application
, options
, constraints
,
1230 storage
, endpoint_bindings
, resources
):
1232 :param charm string:
1233 Charm holds the URL of the charm to be used to deploy this
1236 :param series string:
1237 Series holds the series of the application to be deployed
1238 if the charm default is not sufficient.
1240 :param application string:
1241 Application holds the application name.
1243 :param options map[string]interface{}:
1244 Options holds application options.
1246 :param constraints string:
1247 Constraints holds the optional application constraints.
1249 :param storage map[string]string:
1250 Storage holds the optional storage constraints.
1252 :param endpoint_bindings map[string]string:
1253 EndpointBindings holds the optional endpoint bindings
1255 :param resources map[string]int:
1256 Resources identifies the revision to use for each resource
1257 of the application's charm.
1259 # resolve indirect references
1260 charm
= self
.resolve(charm
)
1261 # stringify all config values for API
1262 options
= {k
: str(v
) for k
, v
in options
.items()}
1263 # build param object
1264 app
= client
.ApplicationDeploy(
1267 application
=application
,
1269 constraints
=constraints
,
1271 endpoint_bindings
=endpoint_bindings
,
1272 resources
=resources
,
1275 log
.debug('Deploying %s', charm
)
1276 await self
.app_facade
.Deploy([app
])
1279 async def addUnit(self
, application
, to
):
1281 :param application string:
1282 Application holds the application placeholder name for which a unit
1286 To holds the optional location where to add the unit, as a
1287 placeholder pointing to another unit change or to a machine change.
1289 application
= self
.resolve(application
)
1290 placement
= self
.resolve(to
)
1291 if self
._units
_by
_app
.get(application
):
1292 # enough units for this application already exist;
1293 # claim one, and carry on
1294 # NB: this should probably honor placement, but the juju client
1295 # doesn't, so we're not bothering, either
1296 unit_name
= self
._units
_by
_app
[application
].pop()
1297 log
.debug('Reusing unit %s for %s', unit_name
, application
)
1298 return self
.model
.units
[unit_name
]
1300 return await self
.model
.applications
[application
].add_unit(
1305 async def expose(self
, application
):
1307 :param application string:
1308 Application holds the placeholder name of the application that must
1311 application
= self
.resolve(application
)
1312 return await self
.model
.applications
[application
].expose()
1314 async def setAnnotations(self
, id_
, entity_type
, annotations
):
1317 Id is the placeholder for the application or machine change
1318 corresponding to the entity to be annotated.
1320 :param entity_type EntityType:
1321 EntityType holds the type of the entity, "application" or
1324 :param annotations map[string]string:
1325 Annotations holds the annotations as key/value pairs.
1327 entity_id
= self
.resolve(id_
)
1328 entity
= self
.model
.state
.get_entity(entity_type
, entity_id
)
1329 return await entity
.set_annotations(annotations
)
1332 class CharmStore(object):
1334 Async wrapper around theblues.charmstore.CharmStore
1336 def __init__(self
, loop
):
1338 self
._cs
= charmstore
.CharmStore()
1340 def __getattr__(self
, name
):
1342 Wrap method calls in coroutines that use run_in_executor to make them
1345 attr
= getattr(self
._cs
, name
)
1346 if not callable(attr
):
1347 wrapper
= partial(getattr, self
._cs
, name
)
1348 setattr(self
, name
, wrapper
)
1350 async def coro(*args
, **kwargs
):
1351 method
= partial(attr
, *args
, **kwargs
)
1352 return await self
.loop
.run_in_executor(None, method
)
1353 setattr(self
, name
, coro
)