7 from concurrent
.futures
import CancelledError
8 from functools
import partial
9 from pathlib
import Path
12 from theblues
import charmstore
14 from .client
import client
15 from .client
import watcher
16 from .client
import connection
17 from .constraints
import parse
as parse_constraints
, normalize_key
18 from .delta
import get_entity_delta
19 from .delta
import get_entity_class
20 from .exceptions
import DeadEntityException
21 from .errors
import JujuError
, JujuAPIError
23 log
= logging
.getLogger(__name__
)
26 class _Observer(object):
27 """Wrapper around an observer callable.
29 This wrapper allows filter criteria to be associated with the
30 callable so that it's only called for changes that meet the criteria.
33 def __init__(self
, callable_
, entity_type
, action
, entity_id
, predicate
):
34 self
.callable_
= callable_
35 self
.entity_type
= entity_type
37 self
.entity_id
= entity_id
38 self
.predicate
= predicate
40 self
.entity_id
= str(self
.entity_id
)
41 if not self
.entity_id
.startswith('^'):
42 self
.entity_id
= '^' + self
.entity_id
43 if not self
.entity_id
.endswith('$'):
46 async def __call__(self
, delta
, old
, new
, model
):
47 await self
.callable_(delta
, old
, new
, model
)
49 def cares_about(self
, delta
):
50 """Return True if this observer "cares about" (i.e. wants to be
51 called) for a this delta.
54 if (self
.entity_id
and delta
.get_id() and
55 not re
.match(self
.entity_id
, str(delta
.get_id()))):
58 if self
.entity_type
and self
.entity_type
!= delta
.entity
:
61 if self
.action
and self
.action
!= delta
.type:
64 if self
.predicate
and not self
.predicate(delta
):
70 class ModelObserver(object):
71 async def __call__(self
, delta
, old
, new
, model
):
72 handler_name
= 'on_{}_{}'.format(delta
.entity
, delta
.type)
73 method
= getattr(self
, handler_name
, self
.on_change
)
74 await method(delta
, old
, new
, model
)
76 async def on_change(self
, delta
, old
, new
, model
):
77 """Generic model-change handler.
79 :param delta: :class:`juju.client.overrides.Delta`
80 :param old: :class:`juju.model.ModelEntity`
81 :param new: :class:`juju.model.ModelEntity`
82 :param model: :class:`juju.model.Model`
88 class ModelState(object):
89 """Holds the state of the model, including the delta history of all
90 entities in the model.
93 def __init__(self
, model
):
97 def _live_entity_map(self
, entity_type
):
98 """Return an id:Entity map of all the living entities of
103 entity_id
: self
.get_entity(entity_type
, entity_id
)
104 for entity_id
, history
in self
.state
.get(entity_type
, {}).items()
105 if history
[-1] is not None
109 def applications(self
):
110 """Return a map of application-name:Application for all applications
111 currently in the model.
114 return self
._live
_entity
_map
('application')
118 """Return a map of machine-id:Machine for all machines currently in
122 return self
._live
_entity
_map
('machine')
126 """Return a map of unit-id:Unit for all units currently in
130 return self
._live
_entity
_map
('unit')
132 def entity_history(self
, entity_type
, entity_id
):
133 """Return the history deque for an entity.
136 return self
.state
[entity_type
][entity_id
]
138 def entity_data(self
, entity_type
, entity_id
, history_index
):
139 """Return the data dict for an entity at a specific index of its
143 return self
.entity_history(entity_type
, entity_id
)[history_index
]
145 def apply_delta(self
, delta
):
146 """Apply delta to our state and return a copy of the
147 affected object as it was before and after the update, e.g.:
149 old_obj, new_obj = self.apply_delta(delta)
151 old_obj may be None if the delta is for the creation of a new object,
152 e.g. a new application or unit is deployed.
154 new_obj will never be None, but may be dead (new_obj.dead == True)
155 if the object was deleted as a result of the delta being applied.
160 .setdefault(delta
.entity
, {})
161 .setdefault(delta
.get_id(), collections
.deque())
164 history
.append(delta
.data
)
165 if delta
.type == 'remove':
168 entity
= self
.get_entity(delta
.entity
, delta
.get_id())
169 return entity
.previous(), entity
172 self
, entity_type
, entity_id
, history_index
=-1, connected
=True):
173 """Return an object instance for the given entity_type and id.
175 By default the object state matches the most recent state from
176 Juju. To get an instance of the object in an older state, pass
177 history_index, an index into the history deque for the entity.
181 if history_index
< 0 and history_index
!= -1:
182 history_index
+= len(self
.entity_history(entity_type
, entity_id
))
183 if history_index
< 0:
187 self
.entity_data(entity_type
, entity_id
, history_index
)
191 entity_class
= get_entity_class(entity_type
)
193 entity_id
, self
.model
, history_index
=history_index
,
197 class ModelEntity(object):
198 """An object in the Model tree"""
200 def __init__(self
, entity_id
, model
, history_index
=-1, connected
=True):
201 """Initialize a new entity
203 :param entity_id str: The unique id of the object in the model
204 :param model: The model instance in whose object tree this
206 :history_index int: The index of this object's state in the model's
207 history deque for this entity
208 :connected bool: Flag indicating whether this object gets live updates
212 self
.entity_id
= entity_id
214 self
._history
_index
= history_index
215 self
.connected
= connected
216 self
.connection
= model
.connection
219 return '<{} entity_id="{}">'.format(type(self
).__name
__,
222 def __getattr__(self
, name
):
223 """Fetch object attributes from the underlying data dict held in the
227 return self
.safe_data
[name
]
230 return bool(self
.data
)
232 def on_change(self
, callable_
):
233 """Add a change observer to this entity.
236 self
.model
.add_observer(
237 callable_
, self
.entity_type
, 'change', self
.entity_id
)
239 def on_remove(self
, callable_
):
240 """Add a remove observer to this entity.
243 self
.model
.add_observer(
244 callable_
, self
.entity_type
, 'remove', self
.entity_id
)
247 def entity_type(self
):
248 """A string identifying the entity type of this object, e.g.
249 'application' or 'unit', etc.
252 return self
.__class
__.__name
__.lower()
256 """Return True if this object represents the current state of the
257 entity in the underlying model.
259 This will be True except when the object represents an entity at a
260 non-latest state in history, e.g. if the object was obtained by calling
261 .previous() on another object.
264 return self
._history
_index
== -1
268 """Returns True if this entity no longer exists in the underlying
274 self
.model
.state
.entity_data(
275 self
.entity_type
, self
.entity_id
, -1) is None
280 """Returns True if this entity still exists in the underlying
288 """The data dictionary for this entity.
291 return self
.model
.state
.entity_data(
292 self
.entity_type
, self
.entity_id
, self
._history
_index
)
296 """The data dictionary for this entity.
298 If this `ModelEntity` points to the dead state, it will
299 raise `DeadEntityException`.
302 if self
.data
is None:
303 raise DeadEntityException(
304 "Entity {}:{} is dead - its attributes can no longer be "
305 "accessed. Use the .previous() method on this object to get "
306 "a copy of the object at its previous state.".format(
307 self
.entity_type
, self
.entity_id
))
311 """Return a copy of this object as was at its previous state in
314 Returns None if this object is new (and therefore has no history).
316 The returned object is always "disconnected", i.e. does not receive
320 return self
.model
.state
.get_entity(
321 self
.entity_type
, self
.entity_id
, self
._history
_index
- 1,
325 """Return a copy of this object at its next state in
328 Returns None if this object is already the latest.
330 The returned object is "disconnected", i.e. does not receive
331 live updates, unless it is current (latest).
334 if self
._history
_index
== -1:
337 new_index
= self
._history
_index
+ 1
339 new_index
== len(self
.model
.state
.entity_history(
340 self
.entity_type
, self
.entity_id
)) - 1
342 return self
.model
.state
.get_entity(
343 self
.entity_type
, self
.entity_id
, self
._history
_index
- 1,
347 """Return a copy of this object at its current state in the model.
349 Returns self if this object is already the latest.
351 The returned object is always "connected", i.e. receives
352 live updates from the model.
355 if self
._history
_index
== -1:
358 return self
.model
.state
.get_entity(self
.entity_type
, self
.entity_id
)
362 def __init__(self
, loop
=None):
363 """Instantiate a new connected Model.
365 :param loop: an asyncio event loop
368 self
.loop
= loop
or asyncio
.get_event_loop()
369 self
.connection
= None
370 self
.observers
= weakref
.WeakValueDictionary()
371 self
.state
= ModelState(self
)
373 self
._watcher
_task
= None
374 self
._watch
_shutdown
= asyncio
.Event(loop
=loop
)
375 self
._watch
_received
= asyncio
.Event(loop
=loop
)
376 self
._charmstore
= CharmStore(self
.loop
)
378 async def connect(self
, *args
, **kw
):
379 """Connect to an arbitrary Juju model.
381 args and kw are passed through to Connection.connect()
384 self
.connection
= await connection
.Connection
.connect(*args
, **kw
)
385 await self
._after
_connect
()
387 async def connect_current(self
):
388 """Connect to the current Juju model.
391 self
.connection
= await connection
.Connection
.connect_current()
392 await self
._after
_connect
()
394 async def connect_model(self
, model_name
):
395 """Connect to a specific Juju model by name.
397 :param model_name: Format [controller:][user/]model
400 self
.connection
= await connection
.Connection
.connect_model(model_name
)
401 await self
._after
_connect
()
403 async def _after_connect(self
):
404 """Run initialization steps after connecting to websocket.
408 await self
._watch
_received
.wait()
409 await self
.get_info()
411 async def disconnect(self
):
412 """Shut down the watcher task and close websockets.
415 self
._stop
_watching
()
416 if self
.connection
and self
.connection
.is_open
:
417 await self
._watch
_shutdown
.wait()
418 log
.debug('Closing model connection')
419 await self
.connection
.close()
420 self
.connection
= None
422 def all_units_idle(self
):
423 """Return True if all units are idle.
426 for unit
in self
.units
.values():
427 unit_status
= unit
.data
['agent-status']['current']
428 if unit_status
!= 'idle':
432 async def reset(self
, force
=False):
433 """Reset the model to a clean state.
435 :param bool force: Force-terminate machines.
437 This returns only after the model has reached a clean state. "Clean"
438 means no applications or machines exist in the model.
441 log
.debug('Resetting model')
442 for app
in self
.applications
.values():
444 for machine
in self
.machines
.values():
445 await machine
.destroy(force
=force
)
446 await self
.block_until(
447 lambda: len(self
.machines
) == 0
450 async def block_until(self
, *conditions
, timeout
=None, wait_period
=0.5):
451 """Return only after all conditions are true.
455 while not all(c() for c
in conditions
):
456 await asyncio
.sleep(wait_period
)
457 await asyncio
.wait_for(_block(), timeout
)
460 def applications(self
):
461 """Return a map of application-name:Application for all applications
462 currently in the model.
465 return self
.state
.applications
469 """Return a map of machine-id:Machine for all machines currently in
473 return self
.state
.machines
477 """Return a map of unit-id:Unit for all units currently in
481 return self
.state
.units
483 async def get_info(self
):
484 """Return a client.ModelInfo object for this Model.
486 Retrieves latest info for this Model from the api server. The
487 return value is cached on the Model.info attribute so that the
488 valued may be accessed again without another api call, if
491 This method is called automatically when the Model is connected,
492 resulting in Model.info being initialized without requiring an
493 explicit call to this method.
496 facade
= client
.ClientFacade()
497 facade
.connect(self
.connection
)
499 self
.info
= await facade
.ModelInfo()
500 log
.debug('Got ModelInfo: %s', vars(self
.info
))
505 self
, callable_
, entity_type
=None, action
=None, entity_id
=None,
507 """Register an "on-model-change" callback
509 Once the model is connected, ``callable_``
510 will be called each time the model changes. ``callable_`` should
511 be Awaitable and accept the following positional arguments:
513 delta - An instance of :class:`juju.delta.EntityDelta`
514 containing the raw delta data recv'd from the Juju
517 old_obj - If the delta modifies an existing object in the model,
518 old_obj will be a copy of that object, as it was before the
519 delta was applied. Will be None if the delta creates a new
522 new_obj - A copy of the new or updated object, after the delta
523 is applied. Will be None if the delta removes an entity
526 model - The :class:`Model` itself.
528 Events for which ``callable_`` is called can be specified by passing
529 entity_type, action, and/or entitiy_id filter criteria, e.g.::
533 entity_type='application', action='add', entity_id='ubuntu')
535 For more complex filtering conditions, pass a predicate function. It
536 will be called with a delta as its only argument. If the predicate
537 function returns True, the ``callable_`` will be called.
540 observer
= _Observer(
541 callable_
, entity_type
, action
, entity_id
, predicate
)
542 self
.observers
[observer
] = callable_
545 """Start an asynchronous watch against this model.
547 See :meth:`add_observer` to register an onchange callback.
550 async def _start_watch():
551 self
._watch
_shutdown
.clear()
553 allwatcher
= watcher
.AllWatcher()
554 self
._watch
_conn
= await self
.connection
.clone()
555 allwatcher
.connect(self
._watch
_conn
)
557 results
= await allwatcher
.Next()
558 for delta
in results
.deltas
:
559 delta
= get_entity_delta(delta
)
560 old_obj
, new_obj
= self
.state
.apply_delta(delta
)
561 # XXX: Might not want to shield at this level
562 # We are shielding because when the watcher is
563 # canceled (on disconnect()), we don't want all of
564 # its children (every observer callback) to be
565 # canceled with it. So we shield them. But this means
566 # they can *never* be canceled.
567 await asyncio
.shield(
568 self
._notify
_observers
(delta
, old_obj
, new_obj
))
569 self
._watch
_received
.set()
570 except CancelledError
:
571 log
.debug('Closing watcher connection')
572 await self
._watch
_conn
.close()
573 self
._watch
_shutdown
.set()
574 self
._watch
_conn
= None
576 log
.debug('Starting watcher task')
577 self
._watcher
_task
= self
.loop
.create_task(_start_watch())
579 def _stop_watching(self
):
580 """Stop the asynchronous watch against this model.
583 log
.debug('Stopping watcher task')
584 if self
._watcher
_task
:
585 self
._watcher
_task
.cancel()
587 async def _notify_observers(self
, delta
, old_obj
, new_obj
):
588 """Call observing callbacks, notifying them of a change in model state
590 :param delta: The raw change from the watcher
591 (:class:`juju.client.overrides.Delta`)
592 :param old_obj: The object in the model that this delta updates.
594 :param new_obj: The object in the model that is created or updated
595 by applying this delta.
598 if new_obj
and not old_obj
:
602 'Model changed: %s %s %s',
603 delta
.entity
, delta
.type, delta
.get_id())
605 for o
in self
.observers
:
606 if o
.cares_about(delta
):
607 asyncio
.ensure_future(o(delta
, old_obj
, new_obj
, self
))
609 async def _wait(self
, entity_type
, entity_id
, action
, predicate
=None):
611 Block the calling routine until a given action has happened to the
614 :param entity_type: The entity's type.
615 :param entity_id: The entity's id.
616 :param action: the type of action (e.g., 'add' or 'change')
617 :param predicate: optional callable that must take as an
618 argument a delta, and must return a boolean, indicating
619 whether the delta contains the specific action we're looking
620 for. For example, you might check to see whether a 'change'
621 has a 'completed' status. See the _Observer class for details.
624 q
= asyncio
.Queue(loop
=self
.loop
)
626 async def callback(delta
, old
, new
, model
):
627 await q
.put(delta
.get_id())
629 self
.add_observer(callback
, entity_type
, action
, entity_id
, predicate
)
630 entity_id
= await q
.get()
631 return self
.state
._live
_entity
_map
(entity_type
)[entity_id
]
633 async def _wait_for_new(self
, entity_type
, entity_id
=None, predicate
=None):
634 """Wait for a new object to appear in the Model and return it.
636 Waits for an object of type ``entity_type`` with id ``entity_id``.
637 If ``entity_id`` is ``None``, it will wait for the first new entity
640 This coroutine blocks until the new object appears in the model.
643 # if the entity is already in the model, just return it
644 if entity_id
in self
.state
._live
_entity
_map
(entity_type
):
645 return self
.state
._live
_entity
_map
(entity_type
)[entity_id
]
646 # if we know the entity_id, we can trigger on any action that puts
647 # the enitty into the model; otherwise, we have to watch for the
648 # next "add" action on that entity_type
649 action
= 'add' if entity_id
is None else None
650 return await self
._wait
(entity_type
, entity_id
, action
, predicate
)
652 async def wait_for_action(self
, action_id
):
653 """Given an action, wait for it to complete."""
655 if action_id
.startswith("action-"):
656 # if we've been passed action.tag, transform it into the
657 # id that the api deltas will use.
658 action_id
= action_id
[7:]
660 def predicate(delta
):
661 return delta
.data
['status'] in ('completed', 'failed')
663 return await self
._wait
('action', action_id
, 'change', predicate
)
666 self
, spec
=None, constraints
=None, disks
=None, series
=None,
668 """Start a new, empty machine and optionally a container, or add a
669 container to a machine.
671 :param str spec: Machine specification
674 (None) - starts a new machine
675 'lxc' - starts a new machine with on lxc container
676 'lxc:4' - starts a new lxc container on machine 4
677 'ssh:user@10.10.0.3' - manually provisions a machine with ssh
678 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS
679 'maas2.name' - acquire machine maas2.name on MAAS
680 :param constraints: Machine constraints
681 :type constraints: :class:`juju.Constraints`
682 :param list disks: List of disk :class:`constraints <juju.Constraints>`
683 :param str series: Series
684 :param int count: Number of machines to deploy
686 Supported container types are: lxc, lxd, kvm
688 When deploying a container to an existing machine, constraints cannot
693 add_machines
= add_machine
695 async def add_relation(self
, relation1
, relation2
):
696 """Add a relation between two applications.
698 :param str relation1: '<application>[:<relation_name>]'
699 :param str relation2: '<application>[:<relation_name>]'
702 app_facade
= client
.ApplicationFacade()
703 app_facade
.connect(self
.connection
)
706 'Adding relation %s <-> %s', relation1
, relation2
)
709 result
= await app_facade
.AddRelation([relation1
, relation2
])
710 except JujuAPIError
as e
:
711 if 'relation already exists' not in e
.message
:
714 'Relation %s <-> %s already exists', relation1
, relation2
)
715 # TODO: if relation already exists we should return the
716 # Relation ModelEntity here
719 def predicate(delta
):
721 for endpoint
in delta
.data
['endpoints']:
722 endpoints
[endpoint
['application-name']] = endpoint
['relation']
723 return endpoints
== result
.endpoints
725 return await self
._wait
_for
_new
('relation', None, predicate
)
727 def add_space(self
, name
, *cidrs
):
728 """Add a new network space.
730 Adds a new space with the given name and associates the given
731 (optional) list of existing subnet CIDRs with it.
733 :param str name: Name of the space
734 :param \*cidrs: Optional list of existing subnet CIDRs
739 def add_ssh_key(self
, key
):
740 """Add a public SSH key to this model.
742 :param str key: The public ssh key
746 add_ssh_keys
= add_ssh_key
748 def add_subnet(self
, cidr_or_id
, space
, *zones
):
749 """Add an existing subnet to this model.
751 :param str cidr_or_id: CIDR or provider ID of the existing subnet
752 :param str space: Network space with which to associate
753 :param str \*zones: Zone(s) in which the subnet resides
758 def get_backups(self
):
759 """Retrieve metadata for backups in this model.
764 def block(self
, *commands
):
765 """Add a new block to this model.
767 :param str \*commands: The commands to block. Valid values are
768 'all-changes', 'destroy-model', 'remove-object'
773 def get_blocks(self
):
774 """List blocks for this model.
779 def get_cached_images(self
, arch
=None, kind
=None, series
=None):
780 """Return a list of cached OS images.
782 :param str arch: Filter by image architecture
783 :param str kind: Filter by image kind, e.g. 'lxd'
784 :param str series: Filter by image series, e.g. 'xenial'
789 def create_backup(self
, note
=None, no_download
=False):
790 """Create a backup of this model.
792 :param str note: A note to store with the backup
793 :param bool no_download: Do not download the backup archive
794 :return str: Path to downloaded archive
799 def create_storage_pool(self
, name
, provider_type
, **pool_config
):
800 """Create or define a storage pool.
802 :param str name: Name to give the storage pool
803 :param str provider_type: Pool provider type
804 :param \*\*pool_config: key/value pool configuration pairs
810 self
, no_tail
=False, exclude_module
=None, include_module
=None,
811 include
=None, level
=None, limit
=0, lines
=10, replay
=False,
813 """Get log messages for this model.
815 :param bool no_tail: Stop after returning existing log messages
816 :param list exclude_module: Do not show log messages for these logging
818 :param list include_module: Only show log messages for these logging
820 :param list include: Only show log messages for these entities
821 :param str level: Log level to show, valid options are 'TRACE',
822 'DEBUG', 'INFO', 'WARNING', 'ERROR,
823 :param int limit: Return this many of the most recent (possibly
824 filtered) lines are shown
825 :param int lines: Yield this many of the most recent lines, and keep
827 :param bool replay: Yield the entire log, and keep yielding
828 :param list exclude: Do not show log messages for these entities
834 self
, entity_url
, application_name
=None, bind
=None, budget
=None,
835 channel
=None, config
=None, constraints
=None, force
=False,
836 num_units
=1, plan
=None, resources
=None, series
=None, storage
=None,
838 """Deploy a new service or bundle.
840 :param str entity_url: Charm or bundle url
841 :param str application_name: Name to give the service
842 :param dict bind: <charm endpoint>:<network space> pairs
843 :param dict budget: <budget name>:<limit> pairs
844 :param str channel: Charm store channel from which to retrieve
845 the charm or bundle, e.g. 'development'
846 :param dict config: Charm configuration dictionary
847 :param constraints: Service constraints
848 :type constraints: :class:`juju.Constraints`
849 :param bool force: Allow charm to be deployed to a machine running
850 an unsupported series
851 :param int num_units: Number of units to deploy
852 :param str plan: Plan under which to deploy charm
853 :param dict resources: <resource name>:<file path> pairs
854 :param str series: Series on which to deploy
855 :param dict storage: Storage constraints TODO how do these look?
856 :param str to: Placement directive, e.g.::
859 'lxc:7' - new lxc container on machine 7
860 '24/lxc/3' - lxc container 3 or machine 24
862 If None, a new machine is provisioned.
867 - application_name is required; fill this in automatically if not
869 - series is required; how do we pick a default?
874 client
.Placement(**p
) for p
in to
881 k
: client
.Constraints(**v
)
882 for k
, v
in storage
.items()
885 is_local
= not entity_url
.startswith('cs:') and \
886 os
.path
.isdir(entity_url
)
887 entity_id
= await self
.charmstore
.entityId(entity_url
) \
888 if not is_local
else entity_url
890 app_facade
= client
.ApplicationFacade()
891 client_facade
= client
.ClientFacade()
892 app_facade
.connect(self
.connection
)
893 client_facade
.connect(self
.connection
)
895 is_bundle
= ((is_local
and
896 (Path(entity_id
) / 'bundle.yaml').exists()) or
897 (not is_local
and 'bundle/' in entity_id
))
900 handler
= BundleHandler(self
)
901 await handler
.fetch_plan(entity_id
)
902 await handler
.execute_plan()
903 extant_apps
= {app
for app
in self
.applications
}
904 pending_apps
= set(handler
.applications
) - extant_apps
906 # new apps will usually be in the model by now, but if some
907 # haven't made it yet we'll need to wait on them to be added
908 await asyncio
.gather(*[
909 asyncio
.ensure_future(
910 self
._wait
_for
_new
('application', app_name
))
911 for app_name
in pending_apps
913 return [app
for name
, app
in self
.applications
.items()
914 if name
in handler
.applications
]
917 'Deploying %s', entity_id
)
919 await client_facade
.AddCharm(channel
, entity_id
)
920 app
= client
.ApplicationDeploy(
921 application
=application_name
,
925 constraints
=parse_constraints(constraints
),
926 endpoint_bindings
=bind
,
934 result
= await app_facade
.Deploy([app
])
935 errors
= [r
.error
.message
for r
in result
.results
if r
.error
]
937 raise JujuError('\n'.join(errors
))
938 return await self
._wait
_for
_new
('application', application_name
)
941 """Terminate all machines and resources for this model.
946 async def destroy_unit(self
, *unit_names
):
947 """Destroy units by name.
950 app_facade
= client
.ApplicationFacade()
951 app_facade
.connect(self
.connection
)
954 'Destroying unit%s %s',
955 's' if len(unit_names
) == 1 else '',
956 ' '.join(unit_names
))
958 return await app_facade
.DestroyUnits(list(unit_names
))
959 destroy_units
= destroy_unit
961 def get_backup(self
, archive_id
):
962 """Download a backup archive file.
964 :param str archive_id: The id of the archive to download
965 :return str: Path to the archive file
971 self
, num_controllers
=0, constraints
=None, series
=None, to
=None):
972 """Ensure sufficient controllers exist to provide redundancy.
974 :param int num_controllers: Number of controllers to make available
975 :param constraints: Constraints to apply to the controller machines
976 :type constraints: :class:`juju.Constraints`
977 :param str series: Series of the controller machines
978 :param list to: Placement directives for controller machines, e.g.::
981 'lxc:7' - new lxc container on machine 7
982 '24/lxc/3' - lxc container 3 or machine 24
984 If None, a new machine is provisioned.
989 def get_config(self
):
990 """Return the configuration settings for this model.
995 def get_constraints(self
):
996 """Return the machine constraints for this model.
1001 def grant(self
, username
, acl
='read'):
1002 """Grant a user access to this model.
1004 :param str username: Username
1005 :param str acl: Access control ('read' or 'write')
1010 def import_ssh_key(self
, identity
):
1011 """Add a public SSH key from a trusted indentity source to this model.
1013 :param str identity: User identity in the form <lp|gh>:<username>
1017 import_ssh_keys
= import_ssh_key
1019 def get_machines(self
, machine
, utc
=False):
1020 """Return list of machines in this model.
1022 :param str machine: Machine id, e.g. '0'
1023 :param bool utc: Display time as UTC in RFC3339 format
1028 def get_shares(self
):
1029 """Return list of all users with access to this model.
1034 def get_spaces(self
):
1035 """Return list of all known spaces, including associated subnets.
1040 def get_ssh_key(self
):
1041 """Return known SSH keys for this model.
1045 get_ssh_keys
= get_ssh_key
1047 def get_storage(self
, filesystem
=False, volume
=False):
1048 """Return details of storage instances.
1050 :param bool filesystem: Include filesystem storage
1051 :param bool volume: Include volume storage
1056 def get_storage_pools(self
, names
=None, providers
=None):
1057 """Return list of storage pools.
1059 :param list names: Only include pools with these names
1060 :param list providers: Only include pools for these providers
1065 def get_subnets(self
, space
=None, zone
=None):
1066 """Return list of known subnets.
1068 :param str space: Only include subnets in this space
1069 :param str zone: Only include subnets in this zone
1074 def remove_blocks(self
):
1075 """Remove all blocks from this model.
1080 def remove_backup(self
, backup_id
):
1083 :param str backup_id: The id of the backup to remove
1088 def remove_cached_images(self
, arch
=None, kind
=None, series
=None):
1089 """Remove cached OS images.
1091 :param str arch: Architecture of the images to remove
1092 :param str kind: Image kind to remove, e.g. 'lxd'
1093 :param str series: Image series to remove, e.g. 'xenial'
1098 def remove_machine(self
, *machine_ids
):
1099 """Remove a machine from this model.
1101 :param str \*machine_ids: Ids of the machines to remove
1105 remove_machines
= remove_machine
1107 def remove_ssh_key(self
, *keys
):
1108 """Remove a public SSH key(s) from this model.
1110 :param str \*keys: Keys to remove
1114 remove_ssh_keys
= remove_ssh_key
1117 self
, bootstrap
=False, constraints
=None, archive
=None,
1118 backup_id
=None, upload_tools
=False):
1119 """Restore a backup archive to a new controller.
1121 :param bool bootstrap: Bootstrap a new state machine
1122 :param constraints: Model constraints
1123 :type constraints: :class:`juju.Constraints`
1124 :param str archive: Path to backup archive to restore
1125 :param str backup_id: Id of backup to restore
1126 :param bool upload_tools: Upload tools if bootstrapping a new machine
1131 def retry_provisioning(self
):
1132 """Retry provisioning for failed machines.
1137 def revoke(self
, username
, acl
='read'):
1138 """Revoke a user's access to this model.
1140 :param str username: Username to revoke
1141 :param str acl: Access control ('read' or 'write')
1146 def run(self
, command
, timeout
=None):
1147 """Run command on all machines in this model.
1149 :param str command: The command to run
1150 :param int timeout: Time to wait before command is considered failed
1155 def set_config(self
, **config
):
1156 """Set configuration keys on this model.
1158 :param \*\*config: Config key/values
1163 def set_constraints(self
, constraints
):
1164 """Set machine constraints on this model.
1166 :param :class:`juju.Constraints` constraints: Machine constraints
1171 def get_action_output(self
, action_uuid
, wait
=-1):
1172 """Get the results of an action by ID.
1174 :param str action_uuid: Id of the action
1175 :param int wait: Time in seconds to wait for action to complete
1180 def get_action_status(self
, uuid_or_prefix
=None, name
=None):
1181 """Get the status of all actions, filtered by ID, ID prefix, or action name.
1183 :param str uuid_or_prefix: Filter by action uuid or prefix
1184 :param str name: Filter by action name
1189 def get_budget(self
, budget_name
):
1190 """Get budget usage info.
1192 :param str budget_name: Name of budget
1197 def get_status(self
, filter_
=None, utc
=False):
1198 """Return the status of the model.
1200 :param str filter_: Service or unit name or wildcard ('*')
1201 :param bool utc: Display time as UTC in RFC3339 format
1208 self
, all_
=False, destination
=None, dry_run
=False, public
=False,
1209 source
=None, stream
=None, version
=None):
1210 """Copy Juju tools into this model.
1212 :param bool all_: Copy all versions, not just the latest
1213 :param str destination: Path to local destination directory
1214 :param bool dry_run: Don't do the actual copy
1215 :param bool public: Tools are for a public cloud, so generate mirrors
1217 :param str source: Path to local source directory
1218 :param str stream: Simplestreams stream for which to sync metadata
1219 :param str version: Copy a specific major.minor version
1224 def unblock(self
, *commands
):
1225 """Unblock an operation that would alter this model.
1227 :param str \*commands: The commands to unblock. Valid values are
1228 'all-changes', 'destroy-model', 'remove-object'
1233 def unset_config(self
, *keys
):
1234 """Unset configuration on this model.
1236 :param str \*keys: The keys to unset
1241 def upgrade_gui(self
):
1242 """Upgrade the Juju GUI for this model.
1248 self
, dry_run
=False, reset_previous_upgrade
=False,
1249 upload_tools
=False, version
=None):
1250 """Upgrade Juju on all machines in a model.
1252 :param bool dry_run: Don't do the actual upgrade
1253 :param bool reset_previous_upgrade: Clear the previous (incomplete)
1255 :param bool upload_tools: Upload local version of tools
1256 :param str version: Upgrade to a specific version
1261 def upload_backup(self
, archive_path
):
1262 """Store a backup archive remotely in Juju.
1264 :param str archive_path: Path to local archive
1270 def charmstore(self
):
1271 return self
._charmstore
1273 async def get_metrics(self
, *tags
):
1274 """Retrieve metrics.
1276 :param str \*tags: Tags of entities from which to retrieve metrics.
1277 No tags retrieves the metrics of all units in the model.
1278 :return: Dictionary of unit_name:metrics
1281 log
.debug("Retrieving metrics for %s",
1282 ', '.join(tags
) if tags
else "all units")
1284 metrics_facade
= client
.MetricsDebugFacade()
1285 metrics_facade
.connect(self
.connection
)
1287 entities
= [client
.Entity(tag
) for tag
in tags
]
1288 metrics_result
= await metrics_facade
.GetMetrics(entities
)
1290 metrics
= collections
.defaultdict(list)
1292 for entity_metrics
in metrics_result
.results
:
1293 error
= entity_metrics
.error
1295 if "is not a valid tag" in error
:
1296 raise ValueError(error
.message
)
1298 raise Exception(error
.message
)
1300 for metric
in entity_metrics
.metrics
:
1301 metrics
[metric
.unit
].append(vars(metric
))
1306 class BundleHandler(object):
1308 Handle bundles by using the API to translate bundle YAML into a plan of
1309 steps and then dispatching each of those using the API.
1311 def __init__(self
, model
):
1313 self
.charmstore
= model
.charmstore
1315 self
.references
= {}
1316 self
._units
_by
_app
= {}
1317 for unit_name
, unit
in model
.units
.items():
1318 app_units
= self
._units
_by
_app
.setdefault(unit
.application
, [])
1319 app_units
.append(unit_name
)
1320 self
.client_facade
= client
.ClientFacade()
1321 self
.client_facade
.connect(model
.connection
)
1322 self
.app_facade
= client
.ApplicationFacade()
1323 self
.app_facade
.connect(model
.connection
)
1324 self
.ann_facade
= client
.AnnotationsFacade()
1325 self
.ann_facade
.connect(model
.connection
)
1327 async def fetch_plan(self
, entity_id
):
1328 is_local
= not entity_id
.startswith('cs:') and os
.path
.isdir(entity_id
)
1330 bundle_yaml
= (Path(entity_id
) / "bundle.yaml").read_text()
1332 bundle_yaml
= await self
.charmstore
.files(entity_id
,
1333 filename
='bundle.yaml',
1335 self
.bundle
= yaml
.safe_load(bundle_yaml
)
1336 self
.plan
= await self
.client_facade
.GetBundleChanges(bundle_yaml
)
1338 if self
.plan
.errors
:
1339 raise JujuError('\n'.join(self
.plan
.errors
))
1341 async def execute_plan(self
):
1342 for step
in self
.plan
.changes
:
1343 method
= getattr(self
, step
.method
)
1344 result
= await method(*step
.args
)
1345 self
.references
[step
.id_
] = result
1348 def applications(self
):
1349 return list(self
.bundle
['services'].keys())
1351 def resolve(self
, reference
):
1352 if reference
and reference
.startswith('$'):
1353 reference
= self
.references
[reference
[1:]]
1356 async def addCharm(self
, charm
, series
):
1358 :param charm string:
1359 Charm holds the URL of the charm to be added.
1361 :param series string:
1362 Series holds the series of the charm to be added
1363 if the charm default is not sufficient.
1365 entity_id
= await self
.charmstore
.entityId(charm
)
1366 log
.debug('Adding %s', entity_id
)
1367 await self
.client_facade
.AddCharm(None, entity_id
)
1370 async def addMachines(self
, params
=None):
1373 Dictionary specifying the machine to add. All keys are optional.
1376 series: string specifying the machine OS series.
1378 constraints: string holding machine constraints, if any. We'll
1379 parse this into the json friendly dict that the juju api
1382 container_type: string holding the type of the container (for
1383 instance ""lxd" or kvm"). It is not specified for top level
1386 parent_id: string holding a placeholder pointing to another
1387 machine change or to a unit change. This value is only
1388 specified in the case this machine is a container, in
1389 which case also ContainerType is set.
1392 params
= params
or {}
1395 params
= {normalize_key(k
): params
[k
] for k
in params
.keys()}
1397 # Fix up values, as necessary.
1398 if 'parent_id' in params
:
1399 params
['parent_id'] = self
.resolve(params
['parent_id'])
1401 params
['constraints'] = parse_constraints(
1402 params
.get('constraints'))
1403 params
['jobs'] = params
.get('jobs', ['JobHostUnits'])
1405 if params
.get('container_type') == 'lxc':
1406 log
.warning('Juju 2.0 does not support lxc containers. '
1407 'Converting containers to lxd.')
1408 params
['container_type'] = 'lxd'
1410 # Submit the request.
1411 params
= client
.AddMachineParams(**params
)
1412 results
= await self
.client_facade
.AddMachines([params
])
1413 error
= results
.machines
[0].error
1415 raise ValueError("Error adding machine: %s", error
.message
)
1416 machine
= results
.machines
[0].machine
1417 log
.debug('Added new machine %s', machine
)
1420 async def addRelation(self
, endpoint1
, endpoint2
):
1422 :param endpoint1 string:
1423 :param endpoint2 string:
1424 Endpoint1 and Endpoint2 hold relation endpoints in the
1425 "application:interface" form, where the application is always a
1426 placeholder pointing to an application change, and the interface is
1427 optional. Examples are "$deploy-42:web" or just "$deploy-42".
1429 endpoints
= [endpoint1
, endpoint2
]
1430 # resolve indirect references
1431 for i
in range(len(endpoints
)):
1432 parts
= endpoints
[i
].split(':')
1433 parts
[0] = self
.resolve(parts
[0])
1434 endpoints
[i
] = ':'.join(parts
)
1436 log
.info('Relating %s <-> %s', *endpoints
)
1437 return await self
.model
.add_relation(*endpoints
)
1439 async def deploy(self
, charm
, series
, application
, options
, constraints
,
1440 storage
, endpoint_bindings
, resources
):
1442 :param charm string:
1443 Charm holds the URL of the charm to be used to deploy this
1446 :param series string:
1447 Series holds the series of the application to be deployed
1448 if the charm default is not sufficient.
1450 :param application string:
1451 Application holds the application name.
1453 :param options map[string]interface{}:
1454 Options holds application options.
1456 :param constraints string:
1457 Constraints holds the optional application constraints.
1459 :param storage map[string]string:
1460 Storage holds the optional storage constraints.
1462 :param endpoint_bindings map[string]string:
1463 EndpointBindings holds the optional endpoint bindings
1465 :param resources map[string]int:
1466 Resources identifies the revision to use for each resource
1467 of the application's charm.
1469 # resolve indirect references
1470 charm
= self
.resolve(charm
)
1471 # stringify all config values for API
1472 options
= {k
: str(v
) for k
, v
in options
.items()}
1473 # build param object
1474 app
= client
.ApplicationDeploy(
1477 application
=application
,
1479 constraints
=parse_constraints(constraints
),
1481 endpoint_bindings
=endpoint_bindings
,
1482 resources
=resources
,
1485 log
.info('Deploying %s', charm
)
1486 await self
.app_facade
.Deploy([app
])
1487 # ensure the app is in the model for future operations
1488 await self
.model
._wait
_for
_new
('application', application
)
1491 async def addUnit(self
, application
, to
):
1493 :param application string:
1494 Application holds the application placeholder name for which a unit
1498 To holds the optional location where to add the unit, as a
1499 placeholder pointing to another unit change or to a machine change.
1501 application
= self
.resolve(application
)
1502 placement
= self
.resolve(to
)
1503 if self
._units
_by
_app
.get(application
):
1504 # enough units for this application already exist;
1505 # claim one, and carry on
1506 # NB: this should probably honor placement, but the juju client
1507 # doesn't, so we're not bothering, either
1508 unit_name
= self
._units
_by
_app
[application
].pop()
1509 log
.debug('Reusing unit %s for %s', unit_name
, application
)
1510 return self
.model
.units
[unit_name
]
1512 log
.debug('Adding new unit for %s%s', application
,
1513 ' to %s' % placement
if placement
else '')
1514 return await self
.model
.applications
[application
].add_unit(
1519 async def expose(self
, application
):
1521 :param application string:
1522 Application holds the placeholder name of the application that must
1525 application
= self
.resolve(application
)
1526 log
.info('Exposing %s', application
)
1527 return await self
.model
.applications
[application
].expose()
1529 async def setAnnotations(self
, id_
, entity_type
, annotations
):
1532 Id is the placeholder for the application or machine change
1533 corresponding to the entity to be annotated.
1535 :param entity_type EntityType:
1536 EntityType holds the type of the entity, "application" or
1539 :param annotations map[string]string:
1540 Annotations holds the annotations as key/value pairs.
1542 entity_id
= self
.resolve(id_
)
1544 entity
= self
.model
.state
.get_entity(entity_type
, entity_id
)
1546 entity
= await self
.model
._wait
_for
_new
(entity_type
, entity_id
)
1547 return await entity
.set_annotations(annotations
)
1550 class CharmStore(object):
1552 Async wrapper around theblues.charmstore.CharmStore
1554 def __init__(self
, loop
):
1556 self
._cs
= charmstore
.CharmStore()
1558 def __getattr__(self
, name
):
1560 Wrap method calls in coroutines that use run_in_executor to make them
1563 attr
= getattr(self
._cs
, name
)
1564 if not callable(attr
):
1565 wrapper
= partial(getattr, self
._cs
, name
)
1566 setattr(self
, name
, wrapper
)
1568 async def coro(*args
, **kwargs
):
1569 method
= partial(attr
, *args
, **kwargs
)
1570 return await self
.loop
.run_in_executor(None, method
)
1571 setattr(self
, name
, coro
)