c0ce4c6f43176541972b1b838d2cc0bfeafbff4a
[osm/N2VC.git] / modules / libjuju / 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 from juju import loop
15
16
17 class MyRemoveObserver(ModelObserver):
18 async def on_change(self, delta, old, new, model):
19 if delta.type == 'remove':
20 assert(new.latest() == new)
21 assert(new.next() is None)
22 assert(new.dead)
23 assert(new.current)
24 assert(new.connected)
25 assert(new.previous().dead)
26 assert(not new.previous().current)
27 assert(not new.previous().connected)
28
29
30 class MyModelObserver(ModelObserver):
31 _shutting_down = False
32
33 async def on_change(self, delta, old, new, model):
34 if model.units and model.all_units_idle() and not self._shutting_down:
35 self._shutting_down = True
36 logging.debug('All units idle, disconnecting')
37 await model.reset(force=True)
38 await model.disconnect()
39
40
41 async def main():
42 model = Model()
43 await model.connect()
44
45 try:
46 model.add_observer(MyRemoveObserver())
47 await model.reset(force=True)
48 model.add_observer(MyModelObserver())
49
50 ubuntu_app = await model.deploy(
51 'ubuntu',
52 application_name='ubuntu',
53 series='trusty',
54 channel='stable',
55 )
56 ubuntu_app.on_change(asyncio.coroutine(
57 lambda delta, old_app, new_app, model:
58 print('App changed: {}'.format(new_app.entity_id))
59 ))
60 ubuntu_app.on_remove(asyncio.coroutine(
61 lambda delta, old_app, new_app, model:
62 print('App removed: {}'.format(old_app.entity_id))
63 ))
64 ubuntu_app.on_unit_add(asyncio.coroutine(
65 lambda delta, old_unit, new_unit, model:
66 print('Unit added: {}'.format(new_unit.entity_id))
67 ))
68 ubuntu_app.on_unit_remove(asyncio.coroutine(
69 lambda delta, old_unit, new_unit, model:
70 print('Unit removed: {}'.format(old_unit.entity_id))
71 ))
72 unit_a, unit_b = await ubuntu_app.add_units(count=2)
73 unit_a.on_change(asyncio.coroutine(
74 lambda delta, old_unit, new_unit, model:
75 print('Unit changed: {}'.format(new_unit.entity_id))
76 ))
77 await model.deploy(
78 'nrpe',
79 application_name='nrpe',
80 series='trusty',
81 channel='stable',
82 # subordinates must be deployed without units
83 num_units=0,
84 )
85 my_relation = await model.add_relation(
86 'ubuntu',
87 'nrpe',
88 )
89 my_relation.on_remove(asyncio.coroutine(
90 lambda delta, old_rel, new_rel, model:
91 print('Relation removed: {}'.format(old_rel.endpoints))
92 ))
93 finally:
94 await model.disconnect()
95
96
97 if __name__ == '__main__':
98 logging.basicConfig(level=logging.INFO)
99 ws_logger = logging.getLogger('websockets.protocol')
100 ws_logger.setLevel(logging.INFO)
101 loop.run(main())