X-Git-Url: https://osm.etsi.org/gitweb/?a=blobdiff_plain;f=examples%2Funitrun.py;h=a5b294bb9dd25e7eca61e2643896e498ab9bdf0b;hb=b89f2fff0ca59f55a5caed03d15e34884721c88b;hp=7e3c49069e069de9efd2935e20bd66ff2291fc31;hpb=769d19789b142ca3c1ffd0a172e9ac29cfb4b40e;p=osm%2FN2VC.git diff --git a/examples/unitrun.py b/examples/unitrun.py index 7e3c490..a5b294b 100644 --- a/examples/unitrun.py +++ b/examples/unitrun.py @@ -1,47 +1,53 @@ """ -Run this one against a model that has at least one unit deployed. +This example: + +1. Connects to current model and resets it. +2. Deploys one ubuntu unit. +3. Runs an action against the unit. +4. Waits for the action results to come back, then exits. """ import asyncio -import functools - -from juju.model import Model -from juju.unit import Unit -from juju.client.connection import Connection - - -loop = asyncio.get_event_loop() -conn = loop.run_until_complete(Connection.connect_current()) - -_seen_units = set() +import logging +from juju.model import Model, ModelObserver async def run_stuff_on_unit(unit): - if unit.Name in _seen_units: - return + print('Running command on unit', unit.name) - print('Running command on unit', unit.Name) # unit.run() returns a client.ActionResults instance - action_results = await unit.run('unit-get public-address') - _seen_units.add(unit.Name) - action_result = action_results.results[0] + action = await unit.run('unit-get public-address') + + print("Action results: {}".format(action.results)) - print('Results from unit', unit.Name) - print(action_result.__dict__) + # Inform asyncio that we're done. + await unit.model.disconnect() + unit.model.loop.stop() -def on_model_change(delta, old, new, model): - if isinstance(new, Unit): - task = loop.create_task(run_stuff_on_unit(new)) +class MyModelObserver(ModelObserver): + async def on_unit_add(self, delta, old, new, model): + loop.create_task(run_stuff_on_unit(new)) - if delta.entity == 'action': - print(delta.data) - print(new) +async def run(): + model = Model() + await model.connect_current() + await model.reset(force=True) + model.add_observer(MyModelObserver()) -async def watch_model(): - model = Model(conn) - model.add_observer(on_model_change) - await model.watch() + await model.deploy( + 'ubuntu-0', + service_name='ubuntu', + series='trusty', + channel='stable', + ) -loop.run_until_complete(watch_model()) + +logging.basicConfig(level=logging.DEBUG) +ws_logger = logging.getLogger('websockets.protocol') +ws_logger.setLevel(logging.INFO) +loop = asyncio.get_event_loop() +loop.set_debug(False) +loop.create_task(run()) +loop.run_forever()