Wire up more Application apis
[osm/N2VC.git] / examples / unitrun.py
1 """
2 This example:
3
4 1. Connects to current model and resets it.
5 2. Deploys one ubuntu unit.
6 3. Runs an action against the unit.
7 4. Waits for the action results to come back, then exits.
8
9 """
10 import asyncio
11 import logging
12
13 from juju.model import Model, ModelObserver
14
15
16 async def run_stuff_on_unit(unit):
17 print('Running command on unit', unit.name)
18
19 # unit.run() returns a client.ActionResults instance
20 action_results = await unit.run('unit-get public-address')
21 action_result = action_results.results[0]
22
23 print('Results from unit', unit.name)
24 print(action_result.__dict__)
25
26
27 class MyModelObserver(ModelObserver):
28 async def on_unit_add(self, delta, old, new, model):
29 loop.create_task(run_stuff_on_unit(new))
30
31 async def on_action_change(self, delta, old, new, model):
32 print(delta.data)
33
34 action = new
35 if action.status == 'completed':
36 await action.model.disconnect()
37 action.model.loop.stop()
38
39
40 async def run():
41 model = Model()
42 await model.connect_current()
43 await model.reset(force=True)
44 model.add_observer(MyModelObserver())
45
46 await model.deploy(
47 'ubuntu-0',
48 service_name='ubuntu',
49 series='trusty',
50 channel='stable',
51 )
52
53
54 logging.basicConfig(level=logging.DEBUG)
55 ws_logger = logging.getLogger('websockets.protocol')
56 ws_logger.setLevel(logging.INFO)
57 loop = asyncio.get_event_loop()
58 loop.set_debug(False)
59 loop.create_task(run())
60 loop.run_forever()