Hook up Unit.run() to api
[osm/N2VC.git] / examples / unitrun.py
1 """
2 Run this one against a model that has at least one unit deployed.
3
4 """
5 import asyncio
6 import functools
7
8 from juju.model import Model
9 from juju.unit import Unit
10 from juju.client.connection import Connection
11
12
13 loop = asyncio.get_event_loop()
14 conn = loop.run_until_complete(Connection.connect_current())
15
16 _seen_units = set()
17
18
19 async def run_stuff_on_unit(unit):
20 if unit.Name in _seen_units:
21 return
22
23 print('Running command on unit', unit.Name)
24 # unit.run() returns a client.ActionResults instance
25 action_results = await unit.run('unit-get public-address')
26 _seen_units.add(unit.Name)
27 action_result = action_results.results[0]
28
29 print('Results from unit', unit.Name)
30 print(action_result.__dict__)
31
32
33 def on_model_change(delta, old, new, model):
34 if isinstance(new, Unit):
35 task = loop.create_task(run_stuff_on_unit(new))
36
37 if delta.entity == 'action':
38 print(delta.data)
39 print(new)
40
41
42 async def watch_model():
43 model = Model(conn)
44 model.add_observer(on_model_change)
45 await model.watch()
46
47 loop.run_until_complete(watch_model())