def wait_for_deployment_to_settle(self, charm_name, allowed_workload_status=["active"], timeout=320): """ Wait for deployment to settle synchronously. """ loop.run( self._wait_for_deployment_to_settle(charm_name, allowed_workload_status, timeout))
def test_scaling(self): """ Testing manual scaling by configuring units_max and units_min to a set number. This does not test the autoscaling capabilities but it confirms that scaling is being done through the autoscaler. This means all of the CharmScaler components are up and running. """ self.addCleanup(self._configure, { "scaling_units_min": 1, "scaling_units_max": 4 }) loop.run(*[self._manual_scale(count) for count in [2, 4, 1]])
def main(): with open(path.join(VAR_LIB, "auto-lint-config.json")) as fp: auto_lint_config = json.load(fp) verify_auto_lint_config(auto_lint_config) juju_status = loop.run(get_juju_status(auto_lint_config)) with open(path.join(VAR_LIB, "juju-status.json"), "w") as fp: fp.write(juju_status.to_json()) lint_juju(auto_lint_config)
def test_run_in_model(self): self.patch_object(model, 'Model') self.Model.return_value = self.Model_mock async def _wrapper(): async with model.run_in_model('modelname') as mymodel: return mymodel self.assertEqual(loop.run(_wrapper()), self.Model_mock) self.Model_mock.connect_model.assert_called_once_with('modelname') self.Model_mock.disconnect.assert_called_once_with()
def test_run_in_model_not_awaitable(self): self.patch_object(model, 'Model') def _test_func(arg): return arg * 3 self.Model.return_value = self.Model_mock func = functools.partial(_test_func, 'hello') out = loop.run(model.run_in_model('mymodel', func, awaitable=False)) self.assertEqual(out, 'hellohellohello')
def scp_to_all_units(application_name, model_name, source, destination, user='******', proxy=False, scp_opts=''): """Transfer files from to all units of an application :param application_name: Name of application to scp file to :type unit_name: str :param model_name: Name of model unit is in :type model_name: str :param source: Local path of file(s) to transfer :type source: str :param destination: Remote destination of transferred files :type source: str :param user: Remote username :type source: str :param proxy: Proxy through the Juju API server :type proxy: bool :param scp_opts: Additional options to the scp command :type scp_opts: str """ async def _scp_to_all_units(application_name, source, destination, user, proxy, scp_opts, model): for unit in model.applications[application_name].units: await unit.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts) scp_func = functools.partial(_scp_to_all_units, application_name, source, destination, user=user, proxy=proxy, scp_opts=scp_opts) loop.run( run_in_model(model_name, scp_func, add_model_arg=True, awaitable=True))
def scp_to_unit(unit_name, model_name, source, destination, user='******', proxy=False, scp_opts=''): """Transfer files to unit_name in model_name. :param unit_name: Name of unit to scp to :type unit_name: str :param model_name: Name of model unit is in :type model_name: str :param source: Local path of file(s) to transfer :type source: str :param destination: Remote destination of transferred files :type source: str :param user: Remote username :type source: str :param proxy: Proxy through the Juju API server :type proxy: bool :param scp_opts: Additional options to the scp command :type scp_opts: str """ async def _scp_to_unit(unit_name, source, destination, user, proxy, scp_opts, model): unit = get_unit_from_name(unit_name, model) await unit.scp_to(source, destination, user=user, proxy=proxy, scp_opts=scp_opts) scp_func = functools.partial(_scp_to_unit, unit_name, source, destination, user=user, proxy=proxy, scp_opts=scp_opts) loop.run( run_in_model(model_name, scp_func, add_model_arg=True, awaitable=True))
def main(): action, timeout, args = parse_args(sys.argv[1:]) try: ret = loop.run( run_action(action, timeout, args) ) except Exception as e: log_traceback(e) ret = 1 sys.exit(ret)
def main(): logging.basicConfig(level=logging.INFO) # If you want to see everything sent over the wire, set this to DEBUG. ws_logger = logging.getLogger('websockets.protocol') ws_logger.setLevel(logging.INFO) parser = argparse.ArgumentParser() parser.add_argument("-d", "--database", choices=['mysql', 'postgresql'], help="Database backend", default='postgresql') parser.add_argument("--hamode", choices=['etcd', None], help="Database backend", default=None) args = parser.parse_args() # Run the deploy coroutine in an asyncio event loop, using a helper # that abstracts loop creation and teardown. loop.run(deploy(db=args.database, hamode=args.hamode))
def get_applications(): status = loop.run(get_juju_model_status()) apps = status.applications app_info = {} for app in apps: app_info[app] = {} if 'units' in apps[app] and apps[app]['units']: for unit in apps[app]['units']: app_info[app][unit] = {} app_info[app][unit]['ip'] = apps[app]['units'][unit][ 'public-address'] app_info[app][unit]['ports'] = apps[app]['units'][unit][ 'opened-ports'] return json.dumps(app_info), 200, {'ContentType': 'application/json'}
def test_run_in_model_add_model_arg(self): self.patch_object(model, 'Model') def _test_func(arg, model): return model self.Model.return_value = self.Model_mock func = functools.partial(_test_func, 'hello') out = loop.run( model.run_in_model('mymodel', func, add_model_arg=True, awaitable=False)) self.assertEqual(out, self.Model_mock)
def govern_model( endpoint, username, password, cacert, model_name, governor_charm, storage_path, ): """ Connect to juju components and call watchers. """ _, model = loop.run( connect_juju_components(endpoint, username, password, cacert, model_name)) sync_unit_watcher(model, governor_charm, storage_path)
def get_units(model_name, application_name): """Return all the units of a given application :param model_name: Name of model to query. :type model_name: str :param application_name: Name of application to retrieve units for :type application_name: str :returns: List of juju units :rtype: [juju.unit.Unit, juju.unit.Unit,...] """ async def _get_units(application_name, model): return model.applications[application_name].units f = functools.partial(_get_units, application_name) return loop.run(run_in_model(model_name, f, add_model_arg=True))
def get_machines(model_name, application_name): """Return all the machines of a given application :param model_name: Name of model to query. :type model_name: str :param application_name: Name of application to retrieve units for :type application_name: str :returns: List of juju machines :rtype: [juju.machine.Machine, juju.machine.Machine,...] """ async def _get_machines(application_name, model): machines = [] for unit in model.applications[application_name].units: machines.append(unit.machine) return machines f = functools.partial(_get_machines, application_name) return loop.run(run_in_model(model_name, f, add_model_arg=True))
def main(): # Run the deploy coroutine in an asyncio event loop, using a helper # that abstracts loop creation and teardown. print("Current applications: {}".format(", ".join(loop.run(deployed()))))
def add_relation(self, rel1, rel2): """ Adds a new relation to the model """ loop.run(self.model.add_relation(rel1, rel2))
2. Starts an AllWatcher 3. Prints all changes received from the AllWatcher 4. Runs forever (kill with Ctrl-C) """ import logging from juju import loop from juju.client import client from juju.model import Model async def watch(): model = Model() await model.connect() allwatcher = client.AllWatcherFacade.from_connection(model.connection()) while True: change = await allwatcher.Next() for delta in change.deltas: print(delta.deltas) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) ws_logger = logging.getLogger('websockets.protocol') ws_logger.setLevel(logging.INFO) # Run loop until the process is manually stopped (watch will loop # forever). loop.run(watch())
print('Waiting for active') await asyncio.sleep(10) await model.block_until( lambda: all(unit.workload_status == 'active' for unit in application.units)) print("Verifying that we can ssh into the created model") ret = await utils.execute_process( 'juju', 'ssh', '-m', model_name, 'ubuntu/0', 'ls /', log=LOG) assert ret print('Removing ubuntu') await application.remove() print("Destroying model") await controller.destroy_model(model.info.uuid) except Exception: LOG.exception( "Test failed! Model {} may not be cleaned up".format(model_name)) finally: print('Disconnecting from controller') if model: await model.disconnect() await controller.disconnect() if __name__ == '__main__': loop.run(main())
""" This example: 1. Connects to the current model. 2. Prints out leadership status for all deployed units in the model. 3. Cleanly disconnects. """ import asyncio from juju.model import Model from juju import loop async def report_leadership(): model = Model() await model.connect() print("Leadership: ") for app in model.applications.values(): for unit in app.units: print("{}: {}".format(unit.name, await unit.is_leader_from_status())) await model.disconnect() if __name__ == '__main__': loop.run(report_leadership())
This example: 1. Connects to the current model 2. Starts an AllWatcher 3. Prints all changes received from the AllWatcher 4. Runs forever (kill with Ctrl-C) """ import asyncio import logging from juju.client.connection import Connection from juju.client import client from juju import loop async def watch(): conn = await Connection.connect() allwatcher = client.AllWatcherFacade.from_connection(conn) while True: change = await allwatcher.Next() for delta in change.deltas: print(delta.deltas) if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) # Run loop until the process is manually stopped (watch will loop # forever). loop.run(watch())
def set_config(self, app_name, **kwargs): """ Call application.set_config. """ application = self.model.applications[app_name] loop.run(application.set_config(**kwargs))
This example: 1. Connects to the current model 2. Watches the model and prints all changes 3. Runs forever (kill with Ctrl-C) """ from juju.model import Model from juju import loop async def on_model_change(delta, old, new, model): print(delta.entity, delta.type, delta.data) print(old) print(new) print(model) async def watch_model(): model = Model() # connect to current model with current user, per Juju CLI await model.connect() model.add_observer(on_model_change) if __name__ == '__main__': # Run loop until the process is manually stopped (watch_model will loop # forever). loop.run(watch_model())
def deploy(self, **kwargs): """ Call model.deploy. """ loop.run(self.model.deploy(**kwargs))
def listStatus(): return loop.run(WorkerScaler.listStatus(controller))
""" This example: 1. Connects to the current model. 2. Prints out leadership status for all deployed units in the model. 3. Cleanly disconnects. """ import asyncio from juju.model import Model from juju import loop async def report_leadership(): model = Model() await model.connect() print("Leadership: ") for app in model.applications.values(): for unit in app.units: print("{}: {}".format( unit.name, await unit.is_leader_from_status())) await model.disconnect() if __name__ == '__main__': loop.run(report_leadership())
def get_config(self, app_name): """ Return the configuration for the given application. """ application = self.model.applications[app_name] return loop.run(application.get_config())
credential_name=credential_name) # verify credential print("Verify model's credential: {}".format( model.info.cloud_credential_tag)) # verify we can deploy print('Deploying ubuntu') app = await model.deploy('ubuntu-10') print('Waiting for active') await model.block_until(lambda: app.units and all( unit.workload_status == 'active' for unit in app.units)) print('Removing ubuntu') await app.remove() finally: print('Cleaning up') if model: print('Removing model') model_uuid = model.info.uuid await model.disconnect() await controller.destroy_model(model_uuid) print('Disconnecting') await controller.disconnect() if __name__ == '__main__': assert len(sys.argv) > 2, 'Please provide a cloud and credential name' loop.run(main(sys.argv[1], sys.argv[2]))
import asyncio from juju.client.connection import Connection from juju.client.client import ClientFacade from juju import loop async def status(): conn = await Connection.connect() client = ClientFacade.from_connection(conn) patterns = None status = await client.FullStatus(patterns) await conn.close() print('Applications:', list(status.applications.keys())) print('Machines:', list(status.machines.keys())) print('Relations:', status.relations) return status if __name__ == '__main__': loop.run(status())
def sync_unit_watcher(model, governor_charm, storage_path): """ Instanciate UnitWatcher and start watcher """ uw = UnitWatcher(model, governor_charm, storage_path) loop.run(uw.start_watcher())
def get_leader_unit(self, app_name): """ Returns the leader unit of the given application. """ return loop.run(self._get_leader_unit(app_name))
""" This example: 1. Connects to current controller. 2. Gets all the clouds from a controller 3. Disconnects from the controller """ import logging from juju import loop from juju.controller import Controller async def main(): controller = Controller() await controller.connect() await controller.clouds() await controller.disconnect() if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) ws_logger = logging.getLogger('websockets.protocol') ws_logger.setLevel(logging.INFO) loop.run(main())
def execute_action(self, application_name, action_name, **kwargs): """ Execute Action synchronously. """ loop.run(self._execute_action(application_name, action_name, **kwargs))
# verify credential print("Verify model's credential: {}".format( model.info.cloud_credential_tag)) # verify we can deploy print('Deploying ubuntu') app = await model.deploy('ubuntu-10') print('Waiting for active') await model.block_until( lambda: app.units and all(unit.workload_status == 'active' for unit in app.units)) print('Removing ubuntu') await app.remove() finally: print('Cleaning up') if model: print('Removing model') model_uuid = model.info.uuid await model.disconnect() await controller.destroy_model(model_uuid) print('Disconnecting') await controller.disconnect() if __name__ == '__main__': assert len(sys.argv) > 2, 'Please provide a cloud and credential name' loop.run(main(sys.argv[1], sys.argv[2]))
def add_machine(self, **kwargs): """ Adds a new machine to the model. Returns the machine id. """ return loop.run(self._add_machine(**kwargs))