Fixes for latest juju-2 beta
[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 import logging
8
9 from juju.model import Model
10 from juju.unit import Unit
11 from juju.client.connection import Connection
12
13
14 loop = asyncio.get_event_loop()
15 conn = loop.run_until_complete(Connection.connect_current())
16
17 _seen_units = set()
18
19
20 async def run_stuff_on_unit(unit):
21 if unit.name in _seen_units:
22 return
23
24 print('Running command on unit', unit.name)
25 # unit.run() returns a client.ActionResults instance
26 action_results = await unit.run('unit-get public-address')
27 _seen_units.add(unit.name)
28 action_result = action_results.results[0]
29
30 print('Results from unit', unit.name)
31 print(action_result.__dict__)
32
33
34 def on_model_change(delta, old, new, model):
35 if isinstance(new, Unit):
36 task = loop.create_task(run_stuff_on_unit(new))
37
38 if delta.entity == 'action':
39 print(delta.data)
40 print(new)
41
42
43 async def watch_model():
44 model = Model(conn)
45 model.add_observer(on_model_change)
46 await model.watch()
47
48 logging.basicConfig(level=logging.INFO)
49 loop.run_until_complete(watch_model())