01cee3732f451d44f20654556b3f505da298f728
[osm/N2VC.git] / examples / relate.py
1 """
2 This example:
3
4 1. Connects to the current model
5 2. Resets it
6 3. Deploys two charms and relates them
7 4. Waits for units to be idle, then exits
8
9 """
10 import asyncio
11 import logging
12
13 from juju.model import Model, ModelObserver
14
15
16 class MyRemoveObserver(ModelObserver):
17 async def on_change(self, delta, old, new, model):
18 if delta.type == 'remove':
19 assert(new.latest() == new)
20 assert(new.next() is None)
21 assert(new.dead)
22 assert(new.current)
23 assert(new.connected)
24 assert(new.previous().dead)
25 assert(not new.previous().current)
26 assert(not new.previous().connected)
27
28
29 class MyModelObserver(ModelObserver):
30 _shutting_down = False
31
32 async def on_change(self, delta, old, new, model):
33 if model.units and model.all_units_idle() and not self._shutting_down:
34 self._shutting_down = True
35 logging.debug('All units idle, disconnecting')
36 await model.reset(force=True)
37 await model.disconnect()
38 model.loop.stop()
39
40
41 async def run():
42 model = Model()
43 await model.connect_current()
44
45 model.add_observer(MyRemoveObserver())
46 await model.reset(force=True)
47 model.add_observer(MyModelObserver())
48
49 ubuntu_app = await model.deploy(
50 'ubuntu',
51 application_name='ubuntu',
52 series='trusty',
53 channel='stable',
54 )
55 ubuntu_app.on_change(asyncio.coroutine(
56 lambda delta, old_app, new_app, model:
57 print('App changed: {}'.format(new_app.entity_id))
58 ))
59 ubuntu_app.on_remove(asyncio.coroutine(
60 lambda delta, old_app, new_app, model:
61 print('App removed: {}'.format(old_app.entity_id))
62 ))
63 ubuntu_app.on_unit_add(asyncio.coroutine(
64 lambda delta, old_unit, new_unit, model:
65 print('Unit added: {}'.format(new_unit.entity_id))
66 ))
67 ubuntu_app.on_unit_remove(asyncio.coroutine(
68 lambda delta, old_unit, new_unit, model:
69 print('Unit removed: {}'.format(old_unit.entity_id))
70 ))
71 unit_a, unit_b = await ubuntu_app.add_units(count=2)
72 unit_a.on_change(asyncio.coroutine(
73 lambda delta, old_unit, new_unit, model:
74 print('Unit changed: {}'.format(new_unit.entity_id))
75 ))
76 await model.deploy(
77 'nrpe',
78 application_name='nrpe',
79 series='trusty',
80 channel='stable',
81 num_units=1,
82 )
83 my_relation = await model.add_relation(
84 'ubuntu',
85 'nrpe',
86 )
87 my_relation.on_remove(asyncio.coroutine(
88 lambda delta, old_rel, new_rel, model:
89 print('Relation removed: {}'.format(old_rel.endpoints))
90 ))
91
92 logging.basicConfig(level=logging.DEBUG)
93 ws_logger = logging.getLogger('websockets.protocol')
94 ws_logger.setLevel(logging.INFO)
95 loop = asyncio.get_event_loop()
96 loop.set_debug(True)
97 loop.create_task(run())
98 loop.run_forever()