12 # FIXME: this should load the juju inside or modules without having to
13 # explicitly install it. Check why it's not working.
14 # Load our subtree of the juju library
15 path
= os
.path
.abspath(os
.path
.join(os
.path
.dirname(__file__
), '..'))
16 path
= os
.path
.join(path
, "modules/libjuju/")
17 if path
not in sys
.path
:
18 sys
.path
.insert(1, path
)
20 from juju
.controller
import Controller
21 from juju
.model
import ModelObserver
22 from juju
.errors
import JujuAPIError
24 # We might need this to connect to the websocket securely, but test and verify.
26 ssl
._create
_default
_https
_context
= ssl
._create
_unverified
_context
27 except AttributeError:
28 # Legacy Python doesn't verify by default (see pep-0476)
29 # https://www.python.org/dev/peps/pep-0476/
34 class JujuCharmNotFound(Exception):
35 """The Charm can't be found or is not readable."""
38 class JujuApplicationExists(Exception):
39 """The Application already exists."""
42 class N2VCPrimitiveExecutionFailed(Exception):
43 """Something failed while attempting to execute a primitive."""
46 # Quiet the debug logging
47 logging
.getLogger('websockets.protocol').setLevel(logging
.INFO
)
48 logging
.getLogger('juju.client.connection').setLevel(logging
.WARN
)
49 logging
.getLogger('juju.model').setLevel(logging
.WARN
)
50 logging
.getLogger('juju.machine').setLevel(logging
.WARN
)
53 class VCAMonitor(ModelObserver
):
54 """Monitor state changes within the Juju Model."""
59 def __init__(self
, ns_name
):
60 self
.log
= logging
.getLogger(__name__
)
62 self
.ns_name
= ns_name
64 def AddApplication(self
, application_name
, callback
, *callback_args
):
65 if application_name
not in self
.applications
:
66 self
.applications
[application_name
] = {
68 'callback_args': callback_args
71 def RemoveApplication(self
, application_name
):
72 if application_name
in self
.applications
:
73 del self
.applications
[application_name
]
75 async def on_change(self
, delta
, old
, new
, model
):
76 """React to changes in the Juju model."""
78 if delta
.entity
== "unit":
79 # Ignore change events from other applications
80 if delta
.data
['application'] not in self
.applications
.keys():
85 application_name
= delta
.data
['application']
87 callback
= self
.applications
[application_name
]['callback']
89 self
.applications
[application_name
]['callback_args']
92 # Fire off a callback with the application state
96 delta
.data
['application'],
98 new
.workload_status_message
,
102 # This is a charm being removed
106 delta
.data
['application'],
110 except Exception as e
:
111 self
.log
.debug("[1] notify_callback exception: {}".format(e
))
113 elif delta
.entity
== "action":
114 # TODO: Decide how we want to notify the user of actions
116 # uuid = delta.data['id'] # The Action's unique id
117 # msg = delta.data['message'] # The output of the action
119 # if delta.data['status'] == "pending":
120 # # The action is queued
122 # elif delta.data['status'] == "completed""
123 # # The action was successful
125 # elif delta.data['status'] == "failed":
126 # # The action failed.
134 # Create unique models per network service
135 # Document all public functions
150 :param vcaconfig dict A dictionary containing the VCA configuration
152 :param artifacts str The directory where charms required by a vnfd are
156 n2vc = N2VC(vcaconfig={
157 'secret': 'MzI3MDJhOTYxYmM0YzRjNTJiYmY1Yzdm',
159 'ip-address': '10.44.127.137',
161 'artifacts': '/path/to/charms'
165 # Initialize instance-level variables
168 self
.controller
= None
169 self
.connecting
= False
170 self
.authenticated
= False
179 self
.default_model
= None
193 self
.log
= logging
.getLogger(__name__
)
195 # Quiet websocket traffic
196 logging
.getLogger('websockets.protocol').setLevel(logging
.INFO
)
197 logging
.getLogger('juju.client.connection').setLevel(logging
.WARN
)
198 logging
.getLogger('model').setLevel(logging
.WARN
)
199 # logging.getLogger('websockets.protocol').setLevel(logging.DEBUG)
201 self
.log
.debug('JujuApi: instantiated')
207 if user
.startswith('user-'):
210 self
.user
= 'user-{}'.format(user
)
212 self
.endpoint
= '%s:%d' % (server
, int(port
))
214 self
.artifacts
= artifacts
216 self
.loop
= loop
or asyncio
.get_event_loop()
219 """Close any open connections."""
222 def notify_callback(self
, model_name
, application_name
, status
, message
,
223 callback
=None, *callback_args
):
232 except Exception as e
:
233 self
.log
.error("[0] notify_callback exception {}".format(e
))
238 async def CreateNetworkService(self
, nsd
):
239 """Create a new model to encapsulate this network service.
241 Create a new model in the Juju controller to encapsulate the
242 charms associated with a network service.
244 You can pass either the nsd record or the id of the network
245 service, but this method will fail without one of them.
247 if not self
.authenticated
:
250 # Ideally, we will create a unique model per network service.
251 # This change will require all components, i.e., LCM and SO, to use
252 # N2VC for 100% compatibility. If we adopt unique models for the LCM,
253 # services deployed via LCM would't be manageable via SO and vice versa
255 return self
.default_model
257 async def Relate(self
, ns_name
, vnfd
):
258 """Create a relation between the charm-enabled VDUs in a VNF.
260 The Relation mapping has two parts: the id of the vdu owning the endpoint, and the name of the endpoint.
265 - provides: dataVM:db
268 This tells N2VC that the charm referred to by the dataVM vdu offers a relation named 'db', and the mgmtVM vdu has an 'app' endpoint that should be connected to a database.
270 :param str ns_name: The name of the network service.
271 :param dict vnfd: The parsed yaml VNF descriptor.
274 # Currently, the call to Relate() is made automatically after the
275 # deployment of each charm; if the relation depends on a charm that
276 # hasn't been deployed yet, the call will fail silently. This will
277 # prevent an API breakage, with the intent of making this an explicitly
278 # required call in a more object-oriented refactor of the N2VC API.
281 vnf_config
= vnfd
.get("vnf-configuration")
283 juju
= vnf_config
['juju']
285 configs
.append(vnf_config
)
287 for vdu
in vnfd
['vdu']:
288 vdu_config
= vdu
.get('vdu-configuration')
290 juju
= vdu_config
['juju']
292 configs
.append(vdu_config
)
294 def _get_application_name(name
):
295 """Get the application name that's mapped to a vnf/vdu."""
297 vnf_name
= vnfd
['name']
299 for vdu
in vnfd
.get('vdu'):
300 # Compare the named portion of the relation to the vdu's id
301 if vdu
['id'] == name
:
302 application_name
= self
.FormatApplicationName(
305 str(vnf_member_index
),
307 return application_name
309 vnf_member_index
+= 1
313 # Loop through relations
316 if 'relation' in juju
:
317 for rel
in juju
['relation']:
320 # get the application name for the provides
321 (name
, endpoint
) = rel
['provides'].split(':')
322 application_name
= _get_application_name(name
)
324 provides
= "{}:{}".format(
329 # get the application name for thr requires
330 (name
, endpoint
) = rel
['requires'].split(':')
331 application_name
= _get_application_name(name
)
333 requires
= "{}:{}".format(
337 self
.log
.debug("Relation: {} <-> {}".format(
341 await self
.add_relation(
346 except Exception as e
:
347 self
.log
.debug("Exception: {}".format(e
))
351 async def DeployCharms(self
, model_name
, application_name
, vnfd
,
352 charm_path
, params
={}, machine_spec
={},
353 callback
=None, *callback_args
):
354 """Deploy one or more charms associated with a VNF.
356 Deploy the charm(s) referenced in a VNF Descriptor.
358 :param str model_name: The name of the network service.
359 :param str application_name: The name of the application
360 :param dict vnfd: The name of the application
361 :param str charm_path: The path to the Juju charm
362 :param dict params: A dictionary of runtime parameters
365 'rw_mgmt_ip': '1.2.3.4',
366 # Pass the initial-config-primitives section of the vnf or vdu
367 'initial-config-primitives': {...}
369 :param dict machine_spec: A dictionary describing the machine to
373 'hostname': '1.2.3.4',
374 'username': 'ubuntu',
376 :param obj callback: A callback function to receive status changes.
377 :param tuple callback_args: A list of arguments to be passed to the
381 ########################################################
382 # Verify the path to the charm exists and is readable. #
383 ########################################################
384 if not os
.path
.exists(charm_path
):
385 self
.log
.debug("Charm path doesn't exist: {}".format(charm_path
))
386 self
.notify_callback(
393 raise JujuCharmNotFound("No artifacts configured.")
395 ################################
396 # Login to the Juju controller #
397 ################################
398 if not self
.authenticated
:
399 self
.log
.debug("Authenticating with Juju")
402 ##########################################
403 # Get the model for this network service #
404 ##########################################
405 # TODO: In a point release, we will use a model per deployed network
406 # service. In the meantime, we will always use the 'default' model.
407 model_name
= 'default'
408 model
= await self
.get_model(model_name
)
410 ########################################
411 # Verify the application doesn't exist #
412 ########################################
413 app
= await self
.get_application(model
, application_name
)
415 raise JujuApplicationExists("Can't deploy application \"{}\" to model \"{}\" because it already exists.".format(application_name
, model_name
))
417 ################################################################
418 # Register this application with the model-level event monitor #
419 ################################################################
421 self
.monitors
[model_name
].AddApplication(
427 ########################################################
428 # Check for specific machine placement (native charms) #
429 ########################################################
431 if machine_spec
.keys():
432 if all(k
in machine_spec
for k
in ['hostname', 'username']):
433 # Get the path to the previously generated ssh private key.
434 # Machines we're manually provisioned must have N2VC's public
435 # key injected, so if we don't have a keypair, raise an error.
436 private_key_path
= ""
438 # Enlist the existing machine in Juju
439 machine
= await self
.model
.add_machine(
440 spec
='ssh:{}@{}:{}'.format(
446 # Set the machine id that the deploy below will use.
450 #######################################
451 # Get the initial charm configuration #
452 #######################################
455 if 'rw_mgmt_ip' in params
:
456 rw_mgmt_ip
= params
['rw_mgmt_ip']
458 if 'initial-config-primitive' not in params
:
459 params
['initial-config-primitive'] = {}
461 initial_config
= self
._get
_config
_from
_dict
(
462 params
['initial-config-primitive'],
463 {'<rw_mgmt_ip>': rw_mgmt_ip
}
466 self
.log
.debug("JujuApi: Deploying charm ({}) from {}".format(
472 ########################################################
473 # Deploy the charm and apply the initial configuration #
474 ########################################################
475 app
= await model
.deploy(
476 # We expect charm_path to be either the path to the charm on disk
477 # or in the format of cs:series/name
479 # This is the formatted, unique name for this charm
480 application_name
=application_name
,
481 # Proxy charms should use the current LTS. This will need to be
482 # changed for native charms.
484 # Apply the initial 'config' primitive during deployment
485 config
=initial_config
,
486 # Where to deploy the charm to.
490 # Map the vdu id<->app name,
492 await self
.Relate(model_name
, vnfd
)
494 # #######################################
495 # # Execute initial config primitive(s) #
496 # #######################################
497 await self
.ExecuteInitialPrimitives(
505 # # Build a sequential list of the primitives to execute
506 # for primitive in params['initial-config-primitive']:
508 # if primitive['name'] == 'config':
509 # # This is applied when the Application is deployed
512 # seq = primitive['seq']
515 # if 'parameter' in primitive:
516 # params = primitive['parameter']
518 # primitives[seq] = {
519 # 'name': primitive['name'],
520 # 'parameters': self._map_primitive_parameters(
522 # {'<rw_mgmt_ip>': rw_mgmt_ip}
526 # for primitive in sorted(primitives):
527 # await self.ExecutePrimitive(
530 # primitives[primitive]['name'],
533 # **primitives[primitive]['parameters'],
535 # except N2VCPrimitiveExecutionFailed as e:
537 # "[N2VC] Exception executing primitive: {}".format(e)
541 async def GetPrimitiveStatus(self
, model_name
, uuid
):
542 """Get the status of an executed Primitive.
544 The status of an executed Primitive will be one of three values:
551 if not self
.authenticated
:
554 # FIXME: This is hard-coded until model-per-ns is added
555 model_name
= 'default'
557 model
= await self
.get_model(model_name
)
559 results
= await model
.get_action_status(uuid
)
562 status
= results
[uuid
]
564 except Exception as e
:
566 "Caught exception while getting primitive status: {}".format(e
)
568 raise N2VCPrimitiveExecutionFailed(e
)
572 async def GetPrimitiveOutput(self
, model_name
, uuid
):
573 """Get the output of an executed Primitive.
575 Note: this only returns output for a successfully executed primitive.
579 if not self
.authenticated
:
582 # FIXME: This is hard-coded until model-per-ns is added
583 model_name
= 'default'
585 model
= await self
.get_model(model_name
)
586 results
= await model
.get_action_output(uuid
, 60)
587 except Exception as e
:
589 "Caught exception while getting primitive status: {}".format(e
)
591 raise N2VCPrimitiveExecutionFailed(e
)
595 # async def ProvisionMachine(self, model_name, hostname, username):
596 # """Provision machine for usage with Juju.
598 # Provisions a previously instantiated machine for use with Juju.
601 # if not self.authenticated:
604 # # FIXME: This is hard-coded until model-per-ns is added
605 # model_name = 'default'
607 # model = await self.get_model(model_name)
608 # model.add_machine(spec={})
610 # machine = await model.add_machine(spec='ssh:{}@{}:{}'.format(
617 # except Exception as e:
619 # "Caught exception while getting primitive status: {}".format(e)
621 # raise N2VCPrimitiveExecutionFailed(e)
623 def GetPrivateKeyPath(self
):
624 homedir
= os
.environ
['HOME']
625 sshdir
= "{}/.ssh".format(homedir
)
626 private_key_path
= "{}/id_n2vc_rsa".format(sshdir
)
627 return private_key_path
629 async def GetPublicKey(self
):
630 """Get the N2VC SSH public key.abs
632 Returns the SSH public key, to be injected into virtual machines to
633 be managed by the VCA.
635 The first time this is run, a ssh keypair will be created. The public
636 key is injected into a VM so that we can provision the machine with
637 Juju, after which Juju will communicate with the VM directly via the
642 # Find the path to where we expect our key to live.
643 homedir
= os
.environ
['HOME']
644 sshdir
= "{}/.ssh".format(homedir
)
645 if not os
.path
.exists(sshdir
):
648 private_key_path
= "{}/id_n2vc_rsa".format(sshdir
)
649 public_key_path
= "{}.pub".format(private_key_path
)
651 # If we don't have a key generated, generate it.
652 if not os
.path
.exists(private_key_path
):
653 cmd
= "ssh-keygen -t {} -b {} -N '' -f {}".format(
658 subprocess
.check_output(shlex
.split(cmd
))
660 # Read the public key
661 with
open(public_key_path
, "r") as f
:
662 public_key
= f
.readline()
666 async def ExecuteInitialPrimitives(self
, model_name
, application_name
,
667 params
, callback
=None, *callback_args
):
668 """Execute multiple primitives.
670 Execute multiple primitives as declared in initial-config-primitive.
671 This is useful in cases where the primitives initially failed -- for
672 example, if the charm is a proxy but the proxy hasn't been configured
678 # Build a sequential list of the primitives to execute
679 for primitive
in params
['initial-config-primitive']:
681 if primitive
['name'] == 'config':
684 seq
= primitive
['seq']
687 if 'parameter' in primitive
:
688 params
= primitive
['parameter']
691 'name': primitive
['name'],
692 'parameters': self
._map
_primitive
_parameters
(
694 {'<rw_mgmt_ip>': None}
698 for primitive
in sorted(primitives
):
700 await self
.ExecutePrimitive(
703 primitives
[primitive
]['name'],
706 **primitives
[primitive
]['parameters'],
709 except N2VCPrimitiveExecutionFailed
as e
:
711 "[N2VC] Exception executing primitive: {}".format(e
)
716 async def ExecutePrimitive(self
, model_name
, application_name
, primitive
,
717 callback
, *callback_args
, **params
):
718 """Execute a primitive of a charm for Day 1 or Day 2 configuration.
720 Execute a primitive defined in the VNF descriptor.
722 :param str model_name: The name of the network service.
723 :param str application_name: The name of the application
724 :param str primitive: The name of the primitive to execute.
725 :param obj callback: A callback function to receive status changes.
726 :param tuple callback_args: A list of arguments to be passed to the
728 :param dict params: A dictionary of key=value pairs representing the
729 primitive's parameters
732 'rw_mgmt_ip': '1.2.3.4',
733 # Pass the initial-config-primitives section of the vnf or vdu
734 'initial-config-primitives': {...}
737 self
.log
.debug("Executing {}".format(primitive
))
740 if not self
.authenticated
:
743 # FIXME: This is hard-coded until model-per-ns is added
744 model_name
= 'default'
746 model
= await self
.get_model(model_name
)
748 if primitive
== 'config':
749 # config is special, and expecting params to be a dictionary
750 await self
.set_config(
756 app
= await self
.get_application(model
, application_name
)
758 # Run against the first (and probably only) unit in the app
761 action
= await unit
.run_action(primitive
, **params
)
763 except Exception as e
:
765 "Caught exception while executing primitive: {}".format(e
)
767 raise N2VCPrimitiveExecutionFailed(e
)
770 async def RemoveCharms(self
, model_name
, application_name
, callback
=None,
772 """Remove a charm from the VCA.
774 Remove a charm referenced in a VNF Descriptor.
776 :param str model_name: The name of the network service.
777 :param str application_name: The name of the application
778 :param obj callback: A callback function to receive status changes.
779 :param tuple callback_args: A list of arguments to be passed to the
783 if not self
.authenticated
:
786 model
= await self
.get_model(model_name
)
787 app
= await self
.get_application(model
, application_name
)
789 # Remove this application from event monitoring
790 self
.monitors
[model_name
].RemoveApplication(application_name
)
792 # self.notify_callback(model_name, application_name, "removing", callback, *callback_args)
794 "Removing the application {}".format(application_name
)
798 # Notify the callback that this charm has been removed.
799 self
.notify_callback(
807 except Exception as e
:
808 print("Caught exception: {}".format(e
))
812 async def DestroyNetworkService(self
, nsd
):
813 raise NotImplementedError()
815 async def GetMetrics(self
, model_name
, application_name
):
816 """Get the metrics collected by the VCA.
818 :param model_name The name of the model
819 :param application_name The name of the application
822 model
= await self
.get_model(model_name
)
823 app
= await self
.get_application(model
, application_name
)
825 metrics
= await app
.get_metrics()
829 async def HasApplication(self
, model_name
, application_name
):
830 model
= await self
.get_model(model_name
)
831 app
= await self
.get_application(model
, application_name
)
837 async def add_relation(self
, model_name
, relation1
, relation2
):
839 Add a relation between two application endpoints.
841 :param str model_name Name of the network service.
842 :param str relation1 '<application>[:<relation_name>]'
843 :param str relation12 '<application>[:<relation_name>]'
846 if not self
.authenticated
:
849 m
= await self
.get_model(model_name
)
851 await m
.add_relation(relation1
, relation2
)
852 except JujuAPIError
as e
:
853 # If one of the applications in the relationship doesn't exist,
854 # or the relation has already been added, let the operation fail
856 if 'not found' in e
.message
:
858 if 'already exists' in e
.message
:
863 # async def apply_config(self, config, application):
864 # """Apply a configuration to the application."""
865 # print("JujuApi: Applying configuration to {}.".format(
868 # return await self.set_config(application=application, config=config)
870 def _get_config_from_dict(self
, config_primitive
, values
):
871 """Transform the yang config primitive to dict.
880 for primitive
in config_primitive
:
881 if primitive
['name'] == 'config':
882 # config = self._map_primitive_parameters()
883 for parameter
in primitive
['parameter']:
884 param
= str(parameter
['name'])
885 if parameter
['value'] == "<rw_mgmt_ip>":
886 config
[param
] = str(values
[parameter
['value']])
888 config
[param
] = str(parameter
['value'])
892 def _map_primitive_parameters(self
, parameters
, values
):
894 for parameter
in parameters
:
895 param
= str(parameter
['name'])
898 # Typecast parameter value, if present
899 if 'data-type' in parameter
:
900 paramtype
= str(parameter
['data-type']).lower()
902 if paramtype
== "integer":
903 value
= int(parameter
['value'])
904 elif paramtype
== "boolean":
905 value
= bool(parameter
['value'])
907 value
= str(parameter
['value'])
909 if parameter
['value'] == "<rw_mgmt_ip>":
910 params
[param
] = str(values
[parameter
['value']])
912 params
[param
] = value
915 def _get_config_from_yang(self
, config_primitive
, values
):
916 """Transform the yang config primitive to dict."""
918 for primitive
in config_primitive
.values():
919 if primitive
['name'] == 'config':
920 for parameter
in primitive
['parameter'].values():
921 param
= str(parameter
['name'])
922 if parameter
['value'] == "<rw_mgmt_ip>":
923 config
[param
] = str(values
[parameter
['value']])
925 config
[param
] = str(parameter
['value'])
930 def FormatApplicationName(self
, *args
):
932 Generate a Juju-compatible Application name
934 :param args tuple: Positional arguments to be used to construct the
938 - Only accepts characters a-z and non-consequitive dashes (-)
939 - Application name should not exceed 50 characters
943 FormatApplicationName("ping_pong_ns", "ping_vnf", "a")
947 for c
in "-".join(list(args
)):
950 elif not c
.isalpha():
953 return re
.sub('\-+', '-', appname
.lower())
955 # def format_application_name(self, nsd_name, vnfr_name, member_vnf_index=0):
956 # """Format the name of the application
959 # - Only accepts characters a-z and non-consequitive dashes (-)
960 # - Application name should not exceed 50 characters
962 # name = "{}-{}-{}".format(nsd_name, vnfr_name, member_vnf_index)
966 # c = chr(97 + int(c))
967 # elif not c.isalpha():
970 # return re.sub('\-+', '-', new_name.lower())
972 def format_model_name(self
, name
):
973 """Format the name of model.
975 Model names may only contain lowercase letters, digits and hyphens
978 return name
.replace('_', '-').lower()
980 async def get_application(self
, model
, application
):
981 """Get the deployed application."""
982 if not self
.authenticated
:
986 if application
and model
:
987 if model
.applications
:
988 if application
in model
.applications
:
989 app
= model
.applications
[application
]
993 async def get_model(self
, model_name
='default'):
994 """Get a model from the Juju Controller.
996 Note: Model objects returned must call disconnected() before it goes
998 if not self
.authenticated
:
1001 if model_name
not in self
.models
:
1002 self
.models
[model_name
] = await self
.controller
.get_model(
1005 self
.refcount
['model'] += 1
1007 # Create an observer for this model
1008 self
.monitors
[model_name
] = VCAMonitor(model_name
)
1009 self
.models
[model_name
].add_observer(self
.monitors
[model_name
])
1011 return self
.models
[model_name
]
1013 async def login(self
):
1014 """Login to the Juju controller."""
1016 if self
.authenticated
:
1019 self
.connecting
= True
1021 self
.log
.debug("JujuApi: Logging into controller")
1024 self
.controller
= Controller(loop
=self
.loop
)
1028 "Connecting to controller... ws://{}:{} as {}/{}".format(
1035 await self
.controller
.connect(
1036 endpoint
=self
.endpoint
,
1038 password
=self
.secret
,
1041 self
.refcount
['controller'] += 1
1043 # current_controller no longer exists
1044 # self.log.debug("Connecting to current controller...")
1045 # await self.controller.connect_current()
1046 # await self.controller.connect(
1047 # endpoint=self.endpoint,
1048 # username=self.user,
1051 self
.log
.fatal("VCA credentials not configured.")
1053 self
.authenticated
= True
1054 self
.log
.debug("JujuApi: Logged into controller")
1056 async def logout(self
):
1057 """Logout of the Juju controller."""
1058 if not self
.authenticated
:
1062 if self
.default_model
:
1063 self
.log
.debug("Disconnecting model {}".format(
1066 await self
.default_model
.disconnect()
1067 self
.refcount
['model'] -= 1
1068 self
.default_model
= None
1070 for model
in self
.models
:
1071 await self
.models
[model
].disconnect()
1072 self
.refcount
['model'] -= 1
1073 self
.models
[model
] = None
1076 self
.log
.debug("Disconnecting controller {}".format(
1079 await self
.controller
.disconnect()
1080 self
.refcount
['controller'] -= 1
1081 self
.controller
= None
1083 self
.authenticated
= False
1085 self
.log
.debug(self
.refcount
)
1087 except Exception as e
:
1089 "Fatal error logging out of Juju Controller: {}".format(e
)
1093 # async def remove_application(self, name):
1094 # """Remove the application."""
1095 # if not self.authenticated:
1096 # await self.login()
1098 # app = await self.get_application(name)
1100 # self.log.debug("JujuApi: Destroying application {}".format(
1104 # await app.destroy()
1106 async def remove_relation(self
, a
, b
):
1108 Remove a relation between two application endpoints
1110 :param a An application endpoint
1111 :param b An application endpoint
1113 if not self
.authenticated
:
1116 m
= await self
.get_model()
1118 m
.remove_relation(a
, b
)
1120 await m
.disconnect()
1122 async def resolve_error(self
, application
=None):
1123 """Resolve units in error state."""
1124 if not self
.authenticated
:
1127 app
= await self
.get_application(self
.default_model
, application
)
1130 "JujuApi: Resolving errors for application {}".format(
1135 for unit
in app
.units
:
1136 app
.resolved(retry
=True)
1138 async def run_action(self
, application
, action_name
, **params
):
1139 """Execute an action and return an Action object."""
1140 if not self
.authenticated
:
1149 app
= await self
.get_application(self
.default_model
, application
)
1151 # We currently only have one unit per application
1152 # so use the first unit available.
1156 "JujuApi: Running Action {} against Application {}".format(
1162 action
= await unit
.run_action(action_name
, **params
)
1164 # Wait for the action to complete
1167 result
['status'] = action
.status
1168 result
['action']['tag'] = action
.data
['id']
1169 result
['action']['results'] = action
.results
1173 async def set_config(self
, model_name
, application
, config
):
1174 """Apply a configuration to the application."""
1175 if not self
.authenticated
:
1178 app
= await self
.get_application(model_name
, application
)
1180 self
.log
.debug("JujuApi: Setting config for Application {}".format(
1183 await app
.set_config(config
)
1185 # Verify the config is set
1186 newconf
= await app
.get_config()
1188 if config
[key
] != newconf
[key
]['value']:
1189 self
.log
.debug("JujuApi: Config not set! Key {} Value {} doesn't match {}".format(key
, config
[key
], newconf
[key
]))
1191 # async def set_parameter(self, parameter, value, application=None):
1192 # """Set a config parameter for a service."""
1193 # if not self.authenticated:
1194 # await self.login()
1196 # self.log.debug("JujuApi: Setting {}={} for Application {}".format(
1201 # return await self.apply_config(
1202 # {parameter: value},
1203 # application=application,
1206 async def wait_for_application(self
, model_name
, application_name
,
1208 """Wait for an application to become active."""
1209 if not self
.authenticated
:
1212 # TODO: In a point release, we will use a model per deployed network
1213 # service. In the meantime, we will always use the 'default' model.
1214 model_name
= 'default'
1215 model
= await self
.get_model(model_name
)
1217 app
= await self
.get_application(model
, application_name
)
1218 self
.log
.debug("Application: {}".format(app
))
1219 # app = await self.get_application(model_name, application_name)
1222 "JujuApi: Waiting {} seconds for Application {}".format(
1228 await model
.block_until(
1230 unit
.agent_status
== 'idle' and unit
.workload_status
in
1231 ['active', 'unknown'] for unit
in app
.units