Move add_relation logic from BundleHandler up into Model
[osm/N2VC.git] / juju / application.py
index a72533d..1e87ced 100644 (file)
@@ -1,7 +1,39 @@
+import logging
+
 from . import model
+from .client import client
+
+log = logging.getLogger(__name__)
 
 
 class Application(model.ModelEntity):
+    @property
+    def _unit_match_pattern(self):
+        return r'^{}.*$'.format(self.entity_id)
+
+    def on_unit_add(self, callable_):
+        """Add a "unit added" observer to this entity, which will be called
+        whenever a unit is added to this application.
+
+        """
+        self.model.add_observer(
+            callable_, 'unit', 'add', self._unit_match_pattern)
+
+    def on_unit_remove(self, callable_):
+        """Add a "unit removed" observer to this entity, which will be called
+        whenever a unit is removed from this application.
+
+        """
+        self.model.add_observer(
+            callable_, 'unit', 'remove', self._unit_match_pattern)
+
+    @property
+    def units(self):
+        return [
+            unit for unit in self.model.units.values()
+            if unit.application == self.name
+        ]
+
     def add_relation(self, local_relation, remote_relation):
         """Add a relation to another service.
 
@@ -62,11 +94,17 @@ class Application(model.ModelEntity):
         pass
     remove_relation = destroy_relation
 
-    def destroy(self):
+    async def destroy(self):
         """Remove this service from the model.
 
         """
-        pass
+        app_facade = client.ApplicationFacade()
+        app_facade.connect(self.connection)
+
+        log.debug(
+            'Destroying %s', self.name)
+
+        return await app_facade.Destroy(self.name)
     remove = destroy
 
     def expose(self):