7887d249239633cee2dca25323cb94e74f77a162
[osm/N2VC.git] / examples / deploy.py
1 """
2 This example:
3
4 1. Connects to the current model
5 2. Resets it
6 3. Deploy a charm and waits until it's idle
7 4. Destroys the unit and application
8
9 """
10 import asyncio
11 import logging
12
13 from juju.model import Model, ModelObserver
14
15
16 class MyModelObserver(ModelObserver):
17 async def on_unit_add(self, delta, old, new, model):
18 logging.info(
19 'New unit added: %s', new.name)
20
21 async def on_change(self, delta, old, new, model):
22 for unit in model.units.values():
23 unit_status = unit.data['agent-status']['current']
24 logging.info(
25 'Unit %s status: %s', unit.name, unit_status)
26 if unit_status == 'idle':
27 logging.info(
28 'Destroying unit %s', unit.name)
29 loop.create_task(unit.destroy())
30
31 async def on_unit_remove(self, delta, old, new, model):
32 app_name = old.application
33 app = model.applications[app_name]
34 if not app.units:
35 logging.info(
36 'Destroying application %s', app.name)
37 loop.create_task(app.destroy())
38 await model.block_until(
39 lambda: len(model.applications) == 0
40 )
41 await model.disconnect()
42 model.loop.stop()
43
44
45 async def run():
46 model = Model()
47 await model.connect_current()
48
49 await model.reset(force=True)
50 model.add_observer(MyModelObserver())
51
52 await model.deploy(
53 'ubuntu-0',
54 application_name='ubuntu',
55 series='trusty',
56 channel='stable',
57 )
58
59
60 logging.basicConfig(level=logging.DEBUG)
61 ws_logger = logging.getLogger('websockets.protocol')
62 ws_logger.setLevel(logging.INFO)
63 loop = asyncio.get_event_loop()
64 loop.set_debug(False)
65 loop.create_task(run())
66 loop.run_forever()