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
, JujuError
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 class NetworkServiceDoesNotExist(Exception):
47 """The Network Service being acted against does not exist."""
50 # Quiet the debug logging
51 logging
.getLogger('websockets.protocol').setLevel(logging
.INFO
)
52 logging
.getLogger('juju.client.connection').setLevel(logging
.WARN
)
53 logging
.getLogger('juju.model').setLevel(logging
.WARN
)
54 logging
.getLogger('juju.machine').setLevel(logging
.WARN
)
57 class VCAMonitor(ModelObserver
):
58 """Monitor state changes within the Juju Model."""
61 def __init__(self
, ns_name
):
62 self
.log
= logging
.getLogger(__name__
)
64 self
.ns_name
= ns_name
65 self
.applications
= {}
67 def AddApplication(self
, application_name
, callback
, *callback_args
):
68 if application_name
not in self
.applications
:
69 self
.applications
[application_name
] = {
71 'callback_args': callback_args
74 def RemoveApplication(self
, application_name
):
75 if application_name
in self
.applications
:
76 del self
.applications
[application_name
]
78 async def on_change(self
, delta
, old
, new
, model
):
79 """React to changes in the Juju model."""
81 if delta
.entity
== "unit":
82 # Ignore change events from other applications
83 if delta
.data
['application'] not in self
.applications
.keys():
88 application_name
= delta
.data
['application']
90 callback
= self
.applications
[application_name
]['callback']
92 self
.applications
[application_name
]['callback_args']
95 # Fire off a callback with the application state
99 delta
.data
['application'],
101 new
.workload_status_message
,
105 # This is a charm being removed
109 delta
.data
['application'],
113 except Exception as e
:
114 self
.log
.debug("[1] notify_callback exception: {}".format(e
))
116 elif delta
.entity
== "action":
117 # TODO: Decide how we want to notify the user of actions
119 # uuid = delta.data['id'] # The Action's unique id
120 # msg = delta.data['message'] # The output of the action
122 # if delta.data['status'] == "pending":
123 # # The action is queued
125 # elif delta.data['status'] == "completed""
126 # # The action was successful
128 # elif delta.data['status'] == "failed":
129 # # The action failed.
137 # Create unique models per network service
138 # Document all public functions
150 juju_public_key
=None,
154 :param log obj: The logging object to log to
155 :param server str: The IP Address or Hostname of the Juju controller
156 :param port int: The port of the Juju Controller
157 :param user str: The Juju username to authenticate with
158 :param secret str: The Juju password to authenticate with
159 :param artifacts str: The directory where charms required by a vnfd are
161 :param loop obj: The loop to use.
162 :param juju_public_key str: The contents of the Juju public SSH key
163 :param ca_cert str: The CA certificate to use to authenticate
167 client = n2vc.vnf.N2VC(
173 artifacts='/app/storage/myvnf/charms',
175 juju_public_key='<contents of the juju public key>',
176 ca_cert='<contents of CA certificate>',
180 # Initialize instance-level variables
183 self
.controller
= None
184 self
.connecting
= False
185 self
.authenticated
= False
204 self
.juju_public_key
= juju_public_key
206 self
._create
_juju
_public
_key
(juju_public_key
)
208 self
.ca_cert
= ca_cert
213 self
.log
= logging
.getLogger(__name__
)
215 # Quiet websocket traffic
216 logging
.getLogger('websockets.protocol').setLevel(logging
.INFO
)
217 logging
.getLogger('juju.client.connection').setLevel(logging
.WARN
)
218 logging
.getLogger('model').setLevel(logging
.WARN
)
219 # logging.getLogger('websockets.protocol').setLevel(logging.DEBUG)
221 self
.log
.debug('JujuApi: instantiated')
227 if user
.startswith('user-'):
230 self
.user
= 'user-{}'.format(user
)
232 self
.endpoint
= '%s:%d' % (server
, int(port
))
234 self
.artifacts
= artifacts
236 self
.loop
= loop
or asyncio
.get_event_loop()
239 """Close any open connections."""
242 def _create_juju_public_key(self
, public_key
):
243 """Recreate the Juju public key on disk.
245 Certain libjuju commands expect to be run from the same machine as Juju
246 is bootstrapped to. This method will write the public key to disk in
247 that location: ~/.local/share/juju/ssh/juju_id_rsa.pub
249 # Make sure that we have a public key before writing to disk
250 if public_key
is None or len(public_key
) == 0:
251 if 'OSM_VCA_PUBKEY' in os
.environ
:
252 public_key
= os
.getenv('OSM_VCA_PUBKEY', '')
253 if len(public_key
== 0):
258 path
= "{}/.local/share/juju/ssh".format(
259 os
.path
.expanduser('~'),
261 if not os
.path
.exists(path
):
264 with
open('{}/juju_id_rsa.pub'.format(path
), 'w') as f
:
267 def notify_callback(self
, model_name
, application_name
, status
, message
,
268 callback
=None, *callback_args
):
277 except Exception as e
:
278 self
.log
.error("[0] notify_callback exception {}".format(e
))
283 async def Relate(self
, model_name
, vnfd
):
284 """Create a relation between the charm-enabled VDUs in a VNF.
286 The Relation mapping has two parts: the id of the vdu owning the endpoint, and the name of the endpoint.
291 - provides: dataVM:db
294 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.
296 :param str ns_name: The name of the network service.
297 :param dict vnfd: The parsed yaml VNF descriptor.
300 # Currently, the call to Relate() is made automatically after the
301 # deployment of each charm; if the relation depends on a charm that
302 # hasn't been deployed yet, the call will fail silently. This will
303 # prevent an API breakage, with the intent of making this an explicitly
304 # required call in a more object-oriented refactor of the N2VC API.
307 vnf_config
= vnfd
.get("vnf-configuration")
309 juju
= vnf_config
['juju']
311 configs
.append(vnf_config
)
313 for vdu
in vnfd
['vdu']:
314 vdu_config
= vdu
.get('vdu-configuration')
316 juju
= vdu_config
['juju']
318 configs
.append(vdu_config
)
320 def _get_application_name(name
):
321 """Get the application name that's mapped to a vnf/vdu."""
323 vnf_name
= vnfd
['name']
325 for vdu
in vnfd
.get('vdu'):
326 # Compare the named portion of the relation to the vdu's id
327 if vdu
['id'] == name
:
328 application_name
= self
.FormatApplicationName(
331 str(vnf_member_index
),
333 return application_name
335 vnf_member_index
+= 1
339 # Loop through relations
342 if 'relation' in juju
:
343 for rel
in juju
['relation']:
346 # get the application name for the provides
347 (name
, endpoint
) = rel
['provides'].split(':')
348 application_name
= _get_application_name(name
)
350 provides
= "{}:{}".format(
355 # get the application name for thr requires
356 (name
, endpoint
) = rel
['requires'].split(':')
357 application_name
= _get_application_name(name
)
359 requires
= "{}:{}".format(
363 self
.log
.debug("Relation: {} <-> {}".format(
367 await self
.add_relation(
372 except Exception as e
:
373 self
.log
.debug("Exception: {}".format(e
))
377 async def DeployCharms(self
, model_name
, application_name
, vnfd
,
378 charm_path
, params
={}, machine_spec
={},
379 callback
=None, *callback_args
):
380 """Deploy one or more charms associated with a VNF.
382 Deploy the charm(s) referenced in a VNF Descriptor.
384 :param str model_name: The name or unique id of the network service.
385 :param str application_name: The name of the application
386 :param dict vnfd: The name of the application
387 :param str charm_path: The path to the Juju charm
388 :param dict params: A dictionary of runtime parameters
391 'rw_mgmt_ip': '1.2.3.4',
392 # Pass the initial-config-primitives section of the vnf or vdu
393 'initial-config-primitives': {...}
394 'user_values': dictionary with the day-1 parameters provided at instantiation time. It will replace values
395 inside < >. rw_mgmt_ip will be included here also
397 :param dict machine_spec: A dictionary describing the machine to
401 'hostname': '1.2.3.4',
402 'username': 'ubuntu',
404 :param obj callback: A callback function to receive status changes.
405 :param tuple callback_args: A list of arguments to be passed to the
409 ########################################################
410 # Verify the path to the charm exists and is readable. #
411 ########################################################
412 if not os
.path
.exists(charm_path
):
413 self
.log
.debug("Charm path doesn't exist: {}".format(charm_path
))
414 self
.notify_callback(
421 raise JujuCharmNotFound("No artifacts configured.")
423 ################################
424 # Login to the Juju controller #
425 ################################
426 if not self
.authenticated
:
427 self
.log
.debug("Authenticating with Juju")
430 ##########################################
431 # Get the model for this network service #
432 ##########################################
433 model
= await self
.get_model(model_name
)
435 ########################################
436 # Verify the application doesn't exist #
437 ########################################
438 app
= await self
.get_application(model
, application_name
)
440 raise JujuApplicationExists("Can't deploy application \"{}\" to model \"{}\" because it already exists.".format(application_name
, model_name
))
442 ################################################################
443 # Register this application with the model-level event monitor #
444 ################################################################
446 self
.monitors
[model_name
].AddApplication(
452 ########################################################
453 # Check for specific machine placement (native charms) #
454 ########################################################
456 if machine_spec
.keys():
457 if all(k
in machine_spec
for k
in ['host', 'user']):
458 # Enlist an existing machine as a Juju unit
459 machine
= await model
.add_machine(spec
='ssh:{}@{}:{}'.format(
460 machine_spec
['user'],
461 machine_spec
['host'],
462 self
.GetPrivateKeyPath(),
466 #######################################
467 # Get the initial charm configuration #
468 #######################################
471 if 'rw_mgmt_ip' in params
:
472 rw_mgmt_ip
= params
['rw_mgmt_ip']
474 if 'initial-config-primitive' not in params
:
475 params
['initial-config-primitive'] = {}
477 initial_config
= self
._get
_config
_from
_dict
(
478 params
['initial-config-primitive'],
479 {'<rw_mgmt_ip>': rw_mgmt_ip
}
482 self
.log
.debug("JujuApi: Deploying charm ({}/{}) from {}".format(
489 ########################################################
490 # Deploy the charm and apply the initial configuration #
491 ########################################################
492 app
= await model
.deploy(
493 # We expect charm_path to be either the path to the charm on disk
494 # or in the format of cs:series/name
496 # This is the formatted, unique name for this charm
497 application_name
=application_name
,
498 # Proxy charms should use the current LTS. This will need to be
499 # changed for native charms.
501 # Apply the initial 'config' primitive during deployment
502 config
=initial_config
,
503 # Where to deploy the charm to.
507 # Map the vdu id<->app name,
509 await self
.Relate(model_name
, vnfd
)
511 # #######################################
512 # # Execute initial config primitive(s) #
513 # #######################################
514 uuids
= await self
.ExecuteInitialPrimitives(
523 # # Build a sequential list of the primitives to execute
524 # for primitive in params['initial-config-primitive']:
526 # if primitive['name'] == 'config':
527 # # This is applied when the Application is deployed
530 # seq = primitive['seq']
533 # if 'parameter' in primitive:
534 # params = primitive['parameter']
536 # primitives[seq] = {
537 # 'name': primitive['name'],
538 # 'parameters': self._map_primitive_parameters(
540 # {'<rw_mgmt_ip>': rw_mgmt_ip}
544 # for primitive in sorted(primitives):
545 # await self.ExecutePrimitive(
548 # primitives[primitive]['name'],
551 # **primitives[primitive]['parameters'],
553 # except N2VCPrimitiveExecutionFailed as e:
555 # "[N2VC] Exception executing primitive: {}".format(e)
559 async def GetPrimitiveStatus(self
, model_name
, uuid
):
560 """Get the status of an executed Primitive.
562 The status of an executed Primitive will be one of three values:
569 if not self
.authenticated
:
572 model
= await self
.get_model(model_name
)
574 results
= await model
.get_action_status(uuid
)
577 status
= results
[uuid
]
579 except Exception as e
:
581 "Caught exception while getting primitive status: {}".format(e
)
583 raise N2VCPrimitiveExecutionFailed(e
)
587 async def GetPrimitiveOutput(self
, model_name
, uuid
):
588 """Get the output of an executed Primitive.
590 Note: this only returns output for a successfully executed primitive.
594 if not self
.authenticated
:
597 model
= await self
.get_model(model_name
)
598 results
= await model
.get_action_output(uuid
, 60)
599 except Exception as e
:
601 "Caught exception while getting primitive status: {}".format(e
)
603 raise N2VCPrimitiveExecutionFailed(e
)
607 # async def ProvisionMachine(self, model_name, hostname, username):
608 # """Provision machine for usage with Juju.
610 # Provisions a previously instantiated machine for use with Juju.
613 # if not self.authenticated:
616 # # FIXME: This is hard-coded until model-per-ns is added
617 # model_name = 'default'
619 # model = await self.get_model(model_name)
620 # model.add_machine(spec={})
622 # machine = await model.add_machine(spec='ssh:{}@{}:{}'.format(
629 # except Exception as e:
631 # "Caught exception while getting primitive status: {}".format(e)
633 # raise N2VCPrimitiveExecutionFailed(e)
635 def GetPrivateKeyPath(self
):
636 homedir
= os
.environ
['HOME']
637 sshdir
= "{}/.ssh".format(homedir
)
638 private_key_path
= "{}/id_n2vc_rsa".format(sshdir
)
639 return private_key_path
641 async def GetPublicKey(self
):
642 """Get the N2VC SSH public key.abs
644 Returns the SSH public key, to be injected into virtual machines to
645 be managed by the VCA.
647 The first time this is run, a ssh keypair will be created. The public
648 key is injected into a VM so that we can provision the machine with
649 Juju, after which Juju will communicate with the VM directly via the
654 # Find the path to where we expect our key to live.
655 homedir
= os
.environ
['HOME']
656 sshdir
= "{}/.ssh".format(homedir
)
657 if not os
.path
.exists(sshdir
):
660 private_key_path
= "{}/id_n2vc_rsa".format(sshdir
)
661 public_key_path
= "{}.pub".format(private_key_path
)
663 # If we don't have a key generated, generate it.
664 if not os
.path
.exists(private_key_path
):
665 cmd
= "ssh-keygen -t {} -b {} -N '' -f {}".format(
670 subprocess
.check_output(shlex
.split(cmd
))
672 # Read the public key
673 with
open(public_key_path
, "r") as f
:
674 public_key
= f
.readline()
678 async def ExecuteInitialPrimitives(self
, model_name
, application_name
,
679 params
, callback
=None, *callback_args
):
680 """Execute multiple primitives.
682 Execute multiple primitives as declared in initial-config-primitive.
683 This is useful in cases where the primitives initially failed -- for
684 example, if the charm is a proxy but the proxy hasn't been configured
690 # Build a sequential list of the primitives to execute
691 for primitive
in params
['initial-config-primitive']:
693 if primitive
['name'] == 'config':
696 seq
= primitive
['seq']
699 if 'parameter' in primitive
:
700 params_
= primitive
['parameter']
702 user_values
= params
.get("user_values", {})
703 if 'rw_mgmt_ip' not in user_values
:
704 user_values
['rw_mgmt_ip'] = None
705 # just for backward compatibility, because it will be provided always by modern version of LCM
708 'name': primitive
['name'],
709 'parameters': self
._map
_primitive
_parameters
(
715 for primitive
in sorted(primitives
):
717 await self
.ExecutePrimitive(
720 primitives
[primitive
]['name'],
723 **primitives
[primitive
]['parameters'],
726 except N2VCPrimitiveExecutionFailed
as e
:
728 "[N2VC] Exception executing primitive: {}".format(e
)
733 async def ExecutePrimitive(self
, model_name
, application_name
, primitive
,
734 callback
, *callback_args
, **params
):
735 """Execute a primitive of a charm for Day 1 or Day 2 configuration.
737 Execute a primitive defined in the VNF descriptor.
739 :param str model_name: The name or unique id of the network service.
740 :param str application_name: The name of the application
741 :param str primitive: The name of the primitive to execute.
742 :param obj callback: A callback function to receive status changes.
743 :param tuple callback_args: A list of arguments to be passed to the
745 :param dict params: A dictionary of key=value pairs representing the
746 primitive's parameters
749 'rw_mgmt_ip': '1.2.3.4',
750 # Pass the initial-config-primitives section of the vnf or vdu
751 'initial-config-primitives': {...}
754 self
.log
.debug("Executing primitive={} params={}".format(primitive
, params
))
757 if not self
.authenticated
:
760 model
= await self
.get_model(model_name
)
762 if primitive
== 'config':
763 # config is special, and expecting params to be a dictionary
764 await self
.set_config(
770 app
= await self
.get_application(model
, application_name
)
772 # Run against the first (and probably only) unit in the app
775 action
= await unit
.run_action(primitive
, **params
)
777 except Exception as e
:
779 "Caught exception while executing primitive: {}".format(e
)
781 raise N2VCPrimitiveExecutionFailed(e
)
784 async def RemoveCharms(self
, model_name
, application_name
, callback
=None,
786 """Remove a charm from the VCA.
788 Remove a charm referenced in a VNF Descriptor.
790 :param str model_name: The name of the network service.
791 :param str application_name: The name of the application
792 :param obj callback: A callback function to receive status changes.
793 :param tuple callback_args: A list of arguments to be passed to the
797 if not self
.authenticated
:
800 model
= await self
.get_model(model_name
)
801 app
= await self
.get_application(model
, application_name
)
803 # Remove this application from event monitoring
804 self
.monitors
[model_name
].RemoveApplication(application_name
)
806 # self.notify_callback(model_name, application_name, "removing", callback, *callback_args)
808 "Removing the application {}".format(application_name
)
812 await self
.disconnect_model(self
.monitors
[model_name
])
814 self
.notify_callback(
818 "Removing charm {}".format(application_name
),
823 except Exception as e
:
824 print("Caught exception: {}".format(e
))
828 async def CreateNetworkService(self
, ns_uuid
):
829 """Create a new Juju model for the Network Service.
831 Creates a new Model in the Juju Controller.
833 :param str ns_uuid: A unique id representing an instaance of a
836 :returns: True if the model was created. Raises JujuError on failure.
838 if not self
.authenticated
:
841 models
= await self
.controller
.list_models()
842 if ns_uuid
not in models
:
844 self
.models
[ns_uuid
] = await self
.controller
.add_model(
847 except JujuError
as e
:
848 if "already exists" not in e
.message
:
851 # Create an observer for this model
852 await self
.create_model_monitor(ns_uuid
)
856 async def DestroyNetworkService(self
, ns_uuid
):
857 """Destroy a Network Service.
859 Destroy the Network Service and any deployed charms.
861 :param ns_uuid The unique id of the Network Service
863 :returns: True if the model was created. Raises JujuError on failure.
866 # Do not delete the default model. The default model was used by all
867 # Network Services, prior to the implementation of a model per NS.
868 if ns_uuid
.lower() == "default":
871 if not self
.authenticated
:
872 self
.log
.debug("Authenticating with Juju")
875 # Disconnect from the Model
876 if ns_uuid
in self
.models
:
877 await self
.disconnect_model(self
.models
[ns_uuid
])
880 await self
.controller
.destroy_models(ns_uuid
)
882 raise NetworkServiceDoesNotExist(
883 "The Network Service '{}' does not exist".format(ns_uuid
)
888 async def GetMetrics(self
, model_name
, application_name
):
889 """Get the metrics collected by the VCA.
891 :param model_name The name or unique id of the network service
892 :param application_name The name of the application
895 model
= await self
.get_model(model_name
)
896 app
= await self
.get_application(model
, application_name
)
898 metrics
= await app
.get_metrics()
902 async def HasApplication(self
, model_name
, application_name
):
903 model
= await self
.get_model(model_name
)
904 app
= await self
.get_application(model
, application_name
)
910 async def add_relation(self
, model_name
, relation1
, relation2
):
912 Add a relation between two application endpoints.
914 :param str model_name: The name or unique id of the network service
915 :param str relation1: '<application>[:<relation_name>]'
916 :param str relation2: '<application>[:<relation_name>]'
919 if not self
.authenticated
:
922 m
= await self
.get_model(model_name
)
924 await m
.add_relation(relation1
, relation2
)
925 except JujuAPIError
as e
:
926 # If one of the applications in the relationship doesn't exist,
927 # or the relation has already been added, let the operation fail
929 if 'not found' in e
.message
:
931 if 'already exists' in e
.message
:
936 # async def apply_config(self, config, application):
937 # """Apply a configuration to the application."""
938 # print("JujuApi: Applying configuration to {}.".format(
941 # return await self.set_config(application=application, config=config)
943 def _get_config_from_dict(self
, config_primitive
, values
):
944 """Transform the yang config primitive to dict.
953 for primitive
in config_primitive
:
954 if primitive
['name'] == 'config':
955 # config = self._map_primitive_parameters()
956 for parameter
in primitive
['parameter']:
957 param
= str(parameter
['name'])
958 if parameter
['value'] == "<rw_mgmt_ip>":
959 config
[param
] = str(values
[parameter
['value']])
961 config
[param
] = str(parameter
['value'])
965 def _map_primitive_parameters(self
, parameters
, user_values
):
967 for parameter
in parameters
:
968 param
= str(parameter
['name'])
969 value
= parameter
.get('value')
971 # map parameters inside a < >; e.g. <rw_mgmt_ip>. with the provided user_values.
972 # Must exist at user_values except if there is a default value
973 if isinstance(value
, str) and value
.startswith("<") and value
.endswith(">"):
974 if parameter
['value'][1:-1] in user_values
:
975 value
= user_values
[parameter
['value'][1:-1]]
976 elif 'default-value' in parameter
:
977 value
= parameter
['default-value']
979 raise KeyError("parameter {}='{}' not supplied ".format(param
, value
))
981 # If there's no value, use the default-value (if set)
982 if value
is None and 'default-value' in parameter
:
983 value
= parameter
['default-value']
985 # Typecast parameter value, if present
988 if 'data-type' in parameter
:
989 paramtype
= str(parameter
['data-type']).lower()
991 if paramtype
== "integer":
993 elif paramtype
== "boolean":
998 # If there's no data-type, assume the value is a string
1001 raise ValueError("parameter {}='{}' cannot be converted to type {}".format(param
, value
, paramtype
))
1003 params
[param
] = value
1006 def _get_config_from_yang(self
, config_primitive
, values
):
1007 """Transform the yang config primitive to dict."""
1009 for primitive
in config_primitive
.values():
1010 if primitive
['name'] == 'config':
1011 for parameter
in primitive
['parameter'].values():
1012 param
= str(parameter
['name'])
1013 if parameter
['value'] == "<rw_mgmt_ip>":
1014 config
[param
] = str(values
[parameter
['value']])
1016 config
[param
] = str(parameter
['value'])
1020 def FormatApplicationName(self
, *args
):
1022 Generate a Juju-compatible Application name
1024 :param args tuple: Positional arguments to be used to construct the
1028 - Only accepts characters a-z and non-consequitive dashes (-)
1029 - Application name should not exceed 50 characters
1033 FormatApplicationName("ping_pong_ns", "ping_vnf", "a")
1036 for c
in "-".join(list(args
)):
1038 c
= chr(97 + int(c
))
1039 elif not c
.isalpha():
1042 return re
.sub('-+', '-', appname
.lower())
1044 # def format_application_name(self, nsd_name, vnfr_name, member_vnf_index=0):
1045 # """Format the name of the application
1048 # - Only accepts characters a-z and non-consequitive dashes (-)
1049 # - Application name should not exceed 50 characters
1051 # name = "{}-{}-{}".format(nsd_name, vnfr_name, member_vnf_index)
1055 # c = chr(97 + int(c))
1056 # elif not c.isalpha():
1059 # return re.sub('\-+', '-', new_name.lower())
1061 def format_model_name(self
, name
):
1062 """Format the name of model.
1064 Model names may only contain lowercase letters, digits and hyphens
1067 return name
.replace('_', '-').lower()
1069 async def get_application(self
, model
, application
):
1070 """Get the deployed application."""
1071 if not self
.authenticated
:
1075 if application
and model
:
1076 if model
.applications
:
1077 if application
in model
.applications
:
1078 app
= model
.applications
[application
]
1082 async def get_model(self
, model_name
):
1083 """Get a model from the Juju Controller.
1085 Note: Model objects returned must call disconnected() before it goes
1087 if not self
.authenticated
:
1090 if model_name
not in self
.models
:
1091 # Get the models in the controller
1092 models
= await self
.controller
.list_models()
1094 if model_name
not in models
:
1096 self
.models
[model_name
] = await self
.controller
.add_model(
1099 except JujuError
as e
:
1100 if "already exists" not in e
.message
:
1103 self
.models
[model_name
] = await self
.controller
.get_model(
1107 self
.refcount
['model'] += 1
1109 # Create an observer for this model
1110 await self
.create_model_monitor(model_name
)
1112 return self
.models
[model_name
]
1114 async def create_model_monitor(self
, model_name
):
1115 """Create a monitor for the model, if none exists."""
1116 if not self
.authenticated
:
1119 if model_name
not in self
.monitors
:
1120 self
.monitors
[model_name
] = VCAMonitor(model_name
)
1121 self
.models
[model_name
].add_observer(self
.monitors
[model_name
])
1125 async def login(self
):
1126 """Login to the Juju controller."""
1128 if self
.authenticated
:
1131 self
.connecting
= True
1133 self
.log
.debug("JujuApi: Logging into controller")
1135 self
.controller
= Controller(loop
=self
.loop
)
1139 "Connecting to controller... ws://{}:{} as {}/{}".format(
1146 await self
.controller
.connect(
1147 endpoint
=self
.endpoint
,
1149 password
=self
.secret
,
1150 cacert
=self
.ca_cert
,
1152 self
.refcount
['controller'] += 1
1154 # current_controller no longer exists
1155 # self.log.debug("Connecting to current controller...")
1156 # await self.controller.connect_current()
1157 # await self.controller.connect(
1158 # endpoint=self.endpoint,
1159 # username=self.user,
1162 self
.log
.fatal("VCA credentials not configured.")
1164 self
.authenticated
= True
1165 self
.log
.debug("JujuApi: Logged into controller")
1167 async def logout(self
):
1168 """Logout of the Juju controller."""
1169 if not self
.authenticated
:
1173 for model
in self
.models
:
1174 await self
.disconnect_model(model
)
1177 self
.log
.debug("Disconnecting controller {}".format(
1180 await self
.controller
.disconnect()
1181 self
.refcount
['controller'] -= 1
1182 self
.controller
= None
1184 self
.authenticated
= False
1186 self
.log
.debug(self
.refcount
)
1188 except Exception as e
:
1190 "Fatal error logging out of Juju Controller: {}".format(e
)
1195 async def disconnect_model(self
, model
):
1196 self
.log
.debug("Disconnecting model {}".format(model
))
1197 if model
in self
.models
:
1198 print("Disconnecting model")
1199 await self
.models
[model
].disconnect()
1200 self
.refcount
['model'] -= 1
1201 self
.models
[model
] = None
1203 # async def remove_application(self, name):
1204 # """Remove the application."""
1205 # if not self.authenticated:
1206 # await self.login()
1208 # app = await self.get_application(name)
1210 # self.log.debug("JujuApi: Destroying application {}".format(
1214 # await app.destroy()
1216 async def remove_relation(self
, a
, b
):
1218 Remove a relation between two application endpoints
1220 :param a An application endpoint
1221 :param b An application endpoint
1223 if not self
.authenticated
:
1226 m
= await self
.get_model()
1228 m
.remove_relation(a
, b
)
1230 await m
.disconnect()
1232 async def resolve_error(self
, model_name
, application
=None):
1233 """Resolve units in error state."""
1234 if not self
.authenticated
:
1237 model
= await self
.get_model(model_name
)
1239 app
= await self
.get_application(model
, application
)
1242 "JujuApi: Resolving errors for application {}".format(
1247 for unit
in app
.units
:
1248 app
.resolved(retry
=True)
1250 async def run_action(self
, model_name
, application
, action_name
, **params
):
1251 """Execute an action and return an Action object."""
1252 if not self
.authenticated
:
1262 model
= await self
.get_model(model_name
)
1264 app
= await self
.get_application(model
, application
)
1266 # We currently only have one unit per application
1267 # so use the first unit available.
1271 "JujuApi: Running Action {} against Application {}".format(
1277 action
= await unit
.run_action(action_name
, **params
)
1279 # Wait for the action to complete
1282 result
['status'] = action
.status
1283 result
['action']['tag'] = action
.data
['id']
1284 result
['action']['results'] = action
.results
1288 async def set_config(self
, model_name
, application
, config
):
1289 """Apply a configuration to the application."""
1290 if not self
.authenticated
:
1293 app
= await self
.get_application(model_name
, application
)
1295 self
.log
.debug("JujuApi: Setting config for Application {}".format(
1298 await app
.set_config(config
)
1300 # Verify the config is set
1301 newconf
= await app
.get_config()
1303 if config
[key
] != newconf
[key
]['value']:
1304 self
.log
.debug("JujuApi: Config not set! Key {} Value {} doesn't match {}".format(key
, config
[key
], newconf
[key
]))
1306 # async def set_parameter(self, parameter, value, application=None):
1307 # """Set a config parameter for a service."""
1308 # if not self.authenticated:
1309 # await self.login()
1311 # self.log.debug("JujuApi: Setting {}={} for Application {}".format(
1316 # return await self.apply_config(
1317 # {parameter: value},
1318 # application=application,
1321 async def wait_for_application(self
, model_name
, application_name
,
1323 """Wait for an application to become active."""
1324 if not self
.authenticated
:
1327 model
= await self
.get_model(model_name
)
1329 app
= await self
.get_application(model
, application_name
)
1330 self
.log
.debug("Application: {}".format(app
))
1333 "JujuApi: Waiting {} seconds for Application {}".format(
1339 await model
.block_until(
1341 unit
.agent_status
== 'idle' and unit
.workload_status
in
1342 ['active', 'unknown'] for unit
in app
.units