+ def __init__(self, loop=None):
+ """Instantiate a new connected Model.
+
+ :param loop: an asyncio event loop
+
+ """
+ self.loop = loop or asyncio.get_event_loop()
+ self.connection = None
+ self.observers = set()
+ self.state = dict()
+ self._watcher_task = None
+ self._watch_shutdown = asyncio.Event(loop=loop)
+ self._watch_received = asyncio.Event(loop=loop)
+
+ async def connect_current(self):
+ """Connect to the current Juju model.
+
+ """
+ self.connection = await connection.Connection.connect_current()
+ self._watch()
+ await self._watch_received.wait()
+
+ async def disconnect(self):
+ """Shut down the watcher task and close websockets.
+
+ """
+ self._stop_watching()
+ if self.connection and self.connection.is_open:
+ await self._watch_shutdown.wait()
+ log.debug('Closing model connection')
+ await self.connection.close()
+ self.connection = None
+
+ def all_units_idle(self):
+ """Return True if all units are idle.
+
+ """
+ for unit in self.units.values():
+ unit_status = unit.data['agent-status']['current']
+ if unit_status != 'idle':
+ return False
+ return True
+
+ async def reset(self, force=False):
+ """Reset the model to a clean state.
+
+ :param bool force: Force-terminate machines.
+
+ This returns only after the model has reached a clean state. "Clean"
+ means no applications or machines exist in the model.
+
+ """
+ for app in self.applications.values():
+ await app.destroy()
+ for machine in self.machines.values():
+ await machine.destroy(force=force)
+ await self.block_until(
+ lambda: len(self.machines) == 0
+ )
+
+ async def block_until(self, *conditions, timeout=None):
+ """Return only after all conditions are true.
+
+ """
+ async def _block():
+ while not all(c() for c in conditions):
+ await asyncio.sleep(.1)
+ await asyncio.wait_for(_block(), timeout)
+
+ @property
+ def applications(self):
+ """Return a map of application-name:Application for all applications
+ currently in the model.
+
+ """
+ return self.state.get('application', {})
+
+ @property
+ def machines(self):
+ """Return a map of machine-id:Machine for all machines currently in
+ the model.
+
+ """
+ return self.state.get('machine', {})
+
+ @property
+ def units(self):
+ """Return a map of unit-id:Unit for all units currently in
+ the model.
+
+ """
+ return self.state.get('unit', {})
+
+ def add_observer(self, callable_):
+ """Register an "on-model-change" callback
+
+ Once a watch is started (Model.watch() is called), ``callable_``
+ will be called each time the model changes. callable_ should
+ be Awaitable and accept the following positional arguments:
+
+ delta - An instance of :class:`juju.delta.EntityDelta`
+ containing the raw delta data recv'd from the Juju
+ websocket.
+
+ old_obj - If the delta modifies an existing object in the model,
+ old_obj will be a copy of that object, as it was before the
+ delta was applied. Will be None if the delta creates a new
+ entity in the model.
+
+ new_obj - A copy of the new or updated object, after the delta
+ is applied. Will be None if the delta removes an entity
+ from the model.
+
+ model - The :class:`Model` itself.
+
+ """
+ self.observers.add(callable_)
+
+ def _watch(self):
+ """Start an asynchronous watch against this model.
+
+ See :meth:`add_observer` to register an onchange callback.
+
+ """
+ async def _start_watch():
+ self._watch_shutdown.clear()
+ try:
+ allwatcher = watcher.AllWatcher()
+ self._watch_conn = await self.connection.clone()
+ allwatcher.connect(self._watch_conn)
+ while True:
+ results = await allwatcher.Next()
+ for delta in results.deltas:
+ delta = get_entity_delta(delta)
+ old_obj, new_obj = self._apply_delta(delta)
+ # XXX: Might not want to shield at this level
+ # We are shielding because when the watcher is
+ # canceled (on disconnect()), we don't want all of
+ # its children (every observer callback) to be
+ # canceled with it. So we shield them. But this means
+ # they can *never* be canceled.
+ await asyncio.shield(
+ self._notify_observers(delta, old_obj, new_obj))
+ self._watch_received.set()
+ except CancelledError:
+ log.debug('Closing watcher connection')
+ await self._watch_conn.close()
+ self._watch_shutdown.set()
+ self._watch_conn = None
+
+ log.debug('Starting watcher task')
+ self._watcher_task = self.loop.create_task(_start_watch())
+
+ def _stop_watching(self):
+ """Stop the asynchronous watch against this model.
+
+ """
+ log.debug('Stopping watcher task')
+ if self._watcher_task:
+ self._watcher_task.cancel()
+
+ def _apply_delta(self, delta):
+ """Apply delta to our model state and return the a copy of the
+ affected object as it was before and after the update, e.g.:
+
+ old_obj, new_obj = self._apply_delta(delta)
+
+ old_obj may be None if the delta is for the creation of a new object,
+ e.g. a new application or unit is deployed.
+
+ new_obj may be None if no object was created or updated, or if an
+ object was deleted as a result of the delta being applied.
+
+ """
+ old_obj, new_obj = None, None
+
+ if (delta.entity in self.state and
+ delta.get_id() in self.state[delta.entity]):
+ old_obj = self.state[delta.entity][delta.get_id()]
+ if delta.type == 'remove':
+ del self.state[delta.entity][delta.get_id()]
+ return old_obj, new_obj
+
+ new_obj = self.state.setdefault(delta.entity, {})[delta.get_id()] = (
+ self._create_model_entity(delta))
+
+ return old_obj, new_obj
+
+ def _create_model_entity(self, delta):
+ """Return an object instance representing the entity created or
+ updated by ``delta``
+
+ """
+ entity_class = delta.get_entity_class()
+ return entity_class(delta.data, self)
+
+ async def _notify_observers(self, delta, old_obj, new_obj):
+ """Call observing callbacks, notifying them of a change in model state
+
+ :param delta: The raw change from the watcher
+ (:class:`juju.client.overrides.Delta`)
+ :param old_obj: The object in the model that this delta updates.
+ May be None.
+ :param new_obj: The object in the model that is created or updated
+ by applying this delta.
+
+ """
+ for o in self.observers:
+ asyncio.ensure_future(o(delta, old_obj, new_obj, self))
+