| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1 | import asyncio |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 2 | import logging |
| 3 | import os |
| 4 | import os.path |
| 5 | import re |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 6 | import shlex |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 7 | import ssl |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 8 | import subprocess |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 9 | import sys |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 10 | # import time |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 11 | |
| 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) |
| 19 | |
| 20 | from juju.controller import Controller |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 21 | from juju.model import ModelObserver |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 22 | from juju.errors import JujuAPIError, JujuError |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 23 | |
| 24 | # We might need this to connect to the websocket securely, but test and verify. |
| 25 | try: |
| 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/ |
| 30 | pass |
| 31 | |
| 32 | |
| 33 | # Custom exceptions |
| 34 | class JujuCharmNotFound(Exception): |
| 35 | """The Charm can't be found or is not readable.""" |
| 36 | |
| 37 | |
| 38 | class JujuApplicationExists(Exception): |
| 39 | """The Application already exists.""" |
| 40 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 41 | |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 42 | class N2VCPrimitiveExecutionFailed(Exception): |
| 43 | """Something failed while attempting to execute a primitive.""" |
| 44 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 45 | |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 46 | class NetworkServiceDoesNotExist(Exception): |
| 47 | """The Network Service being acted against does not exist.""" |
| 48 | |
| 49 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 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) |
| 55 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 56 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 57 | class VCAMonitor(ModelObserver): |
| 58 | """Monitor state changes within the Juju Model.""" |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 59 | log = None |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 60 | |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 61 | def __init__(self, ns_name): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 62 | self.log = logging.getLogger(__name__) |
| 63 | |
| 64 | self.ns_name = ns_name |
| Adam Israel | d420a8b | 2019-04-09 16:07:53 -0400 | [diff] [blame^] | 65 | self.applications = {} |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 66 | |
| 67 | def AddApplication(self, application_name, callback, *callback_args): |
| 68 | if application_name not in self.applications: |
| 69 | self.applications[application_name] = { |
| 70 | 'callback': callback, |
| 71 | 'callback_args': callback_args |
| 72 | } |
| 73 | |
| 74 | def RemoveApplication(self, application_name): |
| 75 | if application_name in self.applications: |
| 76 | del self.applications[application_name] |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 77 | |
| 78 | async def on_change(self, delta, old, new, model): |
| 79 | """React to changes in the Juju model.""" |
| 80 | |
| 81 | if delta.entity == "unit": |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 82 | # Ignore change events from other applications |
| 83 | if delta.data['application'] not in self.applications.keys(): |
| 84 | return |
| 85 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 86 | try: |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 87 | |
| 88 | application_name = delta.data['application'] |
| 89 | |
| 90 | callback = self.applications[application_name]['callback'] |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 91 | callback_args = \ |
| 92 | self.applications[application_name]['callback_args'] |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 93 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 94 | if old and new: |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 95 | # Fire off a callback with the application state |
| 96 | if callback: |
| 97 | callback( |
| 98 | self.ns_name, |
| 99 | delta.data['application'], |
| 100 | new.workload_status, |
| 101 | new.workload_status_message, |
| 102 | *callback_args) |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 103 | |
| 104 | if old and not new: |
| 105 | # This is a charm being removed |
| 106 | if callback: |
| 107 | callback( |
| 108 | self.ns_name, |
| 109 | delta.data['application'], |
| 110 | "removed", |
| Adam Israel | 9562f43 | 2018-05-09 13:55:28 -0400 | [diff] [blame] | 111 | "", |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 112 | *callback_args) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 113 | except Exception as e: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 114 | self.log.debug("[1] notify_callback exception: {}".format(e)) |
| 115 | |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 116 | elif delta.entity == "action": |
| 117 | # TODO: Decide how we want to notify the user of actions |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 118 | |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 119 | # uuid = delta.data['id'] # The Action's unique id |
| 120 | # msg = delta.data['message'] # The output of the action |
| 121 | # |
| 122 | # if delta.data['status'] == "pending": |
| 123 | # # The action is queued |
| 124 | # pass |
| 125 | # elif delta.data['status'] == "completed"" |
| 126 | # # The action was successful |
| 127 | # pass |
| 128 | # elif delta.data['status'] == "failed": |
| 129 | # # The action failed. |
| 130 | # pass |
| 131 | |
| 132 | pass |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 133 | |
| 134 | ######## |
| 135 | # TODO |
| 136 | # |
| 137 | # Create unique models per network service |
| 138 | # Document all public functions |
| 139 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 140 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 141 | class N2VC: |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 142 | def __init__(self, |
| 143 | log=None, |
| 144 | server='127.0.0.1', |
| 145 | port=17070, |
| 146 | user='admin', |
| 147 | secret=None, |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 148 | artifacts=None, |
| 149 | loop=None, |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 150 | ): |
| 151 | """Initialize N2VC |
| 152 | |
| 153 | :param vcaconfig dict A dictionary containing the VCA configuration |
| 154 | |
| 155 | :param artifacts str The directory where charms required by a vnfd are |
| 156 | stored. |
| 157 | |
| 158 | :Example: |
| 159 | n2vc = N2VC(vcaconfig={ |
| 160 | 'secret': 'MzI3MDJhOTYxYmM0YzRjNTJiYmY1Yzdm', |
| 161 | 'user': 'admin', |
| 162 | 'ip-address': '10.44.127.137', |
| 163 | 'port': 17070, |
| 164 | 'artifacts': '/path/to/charms' |
| 165 | }) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 166 | """ |
| 167 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 168 | # Initialize instance-level variables |
| 169 | self.api = None |
| 170 | self.log = None |
| 171 | self.controller = None |
| 172 | self.connecting = False |
| 173 | self.authenticated = False |
| 174 | |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 175 | # For debugging |
| 176 | self.refcount = { |
| 177 | 'controller': 0, |
| 178 | 'model': 0, |
| 179 | } |
| 180 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 181 | self.models = {} |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 182 | |
| 183 | # Model Observers |
| 184 | self.monitors = {} |
| 185 | |
| 186 | # VCA config |
| 187 | self.hostname = "" |
| 188 | self.port = 17070 |
| 189 | self.username = "" |
| 190 | self.secret = "" |
| 191 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 192 | if log: |
| 193 | self.log = log |
| 194 | else: |
| 195 | self.log = logging.getLogger(__name__) |
| 196 | |
| 197 | # Quiet websocket traffic |
| 198 | logging.getLogger('websockets.protocol').setLevel(logging.INFO) |
| 199 | logging.getLogger('juju.client.connection').setLevel(logging.WARN) |
| 200 | logging.getLogger('model').setLevel(logging.WARN) |
| 201 | # logging.getLogger('websockets.protocol').setLevel(logging.DEBUG) |
| 202 | |
| 203 | self.log.debug('JujuApi: instantiated') |
| 204 | |
| 205 | self.server = server |
| 206 | self.port = port |
| 207 | |
| 208 | self.secret = secret |
| 209 | if user.startswith('user-'): |
| 210 | self.user = user |
| 211 | else: |
| 212 | self.user = 'user-{}'.format(user) |
| 213 | |
| 214 | self.endpoint = '%s:%d' % (server, int(port)) |
| 215 | |
| 216 | self.artifacts = artifacts |
| 217 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 218 | self.loop = loop or asyncio.get_event_loop() |
| 219 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 220 | def __del__(self): |
| 221 | """Close any open connections.""" |
| 222 | yield self.logout() |
| 223 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 224 | def notify_callback(self, model_name, application_name, status, message, |
| 225 | callback=None, *callback_args): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 226 | try: |
| 227 | if callback: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 228 | callback( |
| 229 | model_name, |
| 230 | application_name, |
| 231 | status, message, |
| 232 | *callback_args, |
| 233 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 234 | except Exception as e: |
| 235 | self.log.error("[0] notify_callback exception {}".format(e)) |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 236 | raise e |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 237 | return True |
| 238 | |
| 239 | # Public methods |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 240 | async def Relate(self, model_name, vnfd): |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 241 | """Create a relation between the charm-enabled VDUs in a VNF. |
| 242 | |
| 243 | The Relation mapping has two parts: the id of the vdu owning the endpoint, and the name of the endpoint. |
| 244 | |
| 245 | vdu: |
| 246 | ... |
| 247 | relation: |
| 248 | - provides: dataVM:db |
| 249 | requires: mgmtVM:app |
| 250 | |
| 251 | 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. |
| 252 | |
| 253 | :param str ns_name: The name of the network service. |
| 254 | :param dict vnfd: The parsed yaml VNF descriptor. |
| 255 | """ |
| 256 | |
| 257 | # Currently, the call to Relate() is made automatically after the |
| 258 | # deployment of each charm; if the relation depends on a charm that |
| 259 | # hasn't been deployed yet, the call will fail silently. This will |
| 260 | # prevent an API breakage, with the intent of making this an explicitly |
| 261 | # required call in a more object-oriented refactor of the N2VC API. |
| 262 | |
| 263 | configs = [] |
| 264 | vnf_config = vnfd.get("vnf-configuration") |
| 265 | if vnf_config: |
| 266 | juju = vnf_config['juju'] |
| 267 | if juju: |
| 268 | configs.append(vnf_config) |
| 269 | |
| 270 | for vdu in vnfd['vdu']: |
| 271 | vdu_config = vdu.get('vdu-configuration') |
| 272 | if vdu_config: |
| 273 | juju = vdu_config['juju'] |
| 274 | if juju: |
| 275 | configs.append(vdu_config) |
| 276 | |
| 277 | def _get_application_name(name): |
| 278 | """Get the application name that's mapped to a vnf/vdu.""" |
| 279 | vnf_member_index = 0 |
| 280 | vnf_name = vnfd['name'] |
| 281 | |
| 282 | for vdu in vnfd.get('vdu'): |
| 283 | # Compare the named portion of the relation to the vdu's id |
| 284 | if vdu['id'] == name: |
| 285 | application_name = self.FormatApplicationName( |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 286 | model_name, |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 287 | vnf_name, |
| 288 | str(vnf_member_index), |
| 289 | ) |
| 290 | return application_name |
| 291 | else: |
| 292 | vnf_member_index += 1 |
| 293 | |
| 294 | return None |
| 295 | |
| 296 | # Loop through relations |
| 297 | for cfg in configs: |
| 298 | if 'juju' in cfg: |
| 299 | if 'relation' in juju: |
| 300 | for rel in juju['relation']: |
| 301 | try: |
| 302 | |
| 303 | # get the application name for the provides |
| 304 | (name, endpoint) = rel['provides'].split(':') |
| 305 | application_name = _get_application_name(name) |
| 306 | |
| 307 | provides = "{}:{}".format( |
| 308 | application_name, |
| 309 | endpoint |
| 310 | ) |
| 311 | |
| 312 | # get the application name for thr requires |
| 313 | (name, endpoint) = rel['requires'].split(':') |
| 314 | application_name = _get_application_name(name) |
| 315 | |
| 316 | requires = "{}:{}".format( |
| 317 | application_name, |
| 318 | endpoint |
| 319 | ) |
| 320 | self.log.debug("Relation: {} <-> {}".format( |
| 321 | provides, |
| 322 | requires |
| 323 | )) |
| 324 | await self.add_relation( |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 325 | model_name, |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 326 | provides, |
| 327 | requires, |
| 328 | ) |
| 329 | except Exception as e: |
| 330 | self.log.debug("Exception: {}".format(e)) |
| 331 | |
| 332 | return |
| 333 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 334 | async def DeployCharms(self, model_name, application_name, vnfd, |
| 335 | charm_path, params={}, machine_spec={}, |
| 336 | callback=None, *callback_args): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 337 | """Deploy one or more charms associated with a VNF. |
| 338 | |
| 339 | Deploy the charm(s) referenced in a VNF Descriptor. |
| 340 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 341 | :param str model_name: The name or unique id of the network service. |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 342 | :param str application_name: The name of the application |
| 343 | :param dict vnfd: The name of the application |
| 344 | :param str charm_path: The path to the Juju charm |
| 345 | :param dict params: A dictionary of runtime parameters |
| 346 | Examples:: |
| 347 | { |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 348 | 'rw_mgmt_ip': '1.2.3.4', |
| 349 | # Pass the initial-config-primitives section of the vnf or vdu |
| 350 | 'initial-config-primitives': {...} |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 351 | 'user_values': dictionary with the day-1 parameters provided at instantiation time. It will replace values |
| 352 | inside < >. rw_mgmt_ip will be included here also |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 353 | } |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 354 | :param dict machine_spec: A dictionary describing the machine to |
| 355 | install to |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 356 | Examples:: |
| 357 | { |
| 358 | 'hostname': '1.2.3.4', |
| 359 | 'username': 'ubuntu', |
| 360 | } |
| 361 | :param obj callback: A callback function to receive status changes. |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 362 | :param tuple callback_args: A list of arguments to be passed to the |
| 363 | callback |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 364 | """ |
| 365 | |
| 366 | ######################################################## |
| 367 | # Verify the path to the charm exists and is readable. # |
| 368 | ######################################################## |
| 369 | if not os.path.exists(charm_path): |
| 370 | self.log.debug("Charm path doesn't exist: {}".format(charm_path)) |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 371 | self.notify_callback( |
| 372 | model_name, |
| 373 | application_name, |
| 374 | "failed", |
| 375 | callback, |
| 376 | *callback_args, |
| 377 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 378 | raise JujuCharmNotFound("No artifacts configured.") |
| 379 | |
| 380 | ################################ |
| 381 | # Login to the Juju controller # |
| 382 | ################################ |
| 383 | if not self.authenticated: |
| 384 | self.log.debug("Authenticating with Juju") |
| 385 | await self.login() |
| 386 | |
| 387 | ########################################## |
| 388 | # Get the model for this network service # |
| 389 | ########################################## |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 390 | model = await self.get_model(model_name) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 391 | |
| 392 | ######################################## |
| 393 | # Verify the application doesn't exist # |
| 394 | ######################################## |
| 395 | app = await self.get_application(model, application_name) |
| 396 | if app: |
| Adam Israel | 42d88e6 | 2018-07-16 14:18:41 -0400 | [diff] [blame] | 397 | raise JujuApplicationExists("Can't deploy application \"{}\" to model \"{}\" because it already exists.".format(application_name, model_name)) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 398 | |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 399 | ################################################################ |
| 400 | # Register this application with the model-level event monitor # |
| 401 | ################################################################ |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 402 | if callback: |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 403 | self.monitors[model_name].AddApplication( |
| 404 | application_name, |
| 405 | callback, |
| 406 | *callback_args |
| 407 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 408 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 409 | ######################################################## |
| 410 | # Check for specific machine placement (native charms) # |
| 411 | ######################################################## |
| 412 | to = "" |
| 413 | if machine_spec.keys(): |
| Adam Israel | 5963cb4 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 414 | if all(k in machine_spec for k in ['host', 'user']): |
| 415 | # Enlist an existing machine as a Juju unit |
| 416 | machine = await model.add_machine(spec='ssh:{}@{}:{}'.format( |
| 417 | machine_spec['user'], |
| 418 | machine_spec['host'], |
| 419 | self.GetPrivateKeyPath(), |
| 420 | )) |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 421 | to = machine.id |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 422 | |
| 423 | ####################################### |
| 424 | # Get the initial charm configuration # |
| 425 | ####################################### |
| 426 | |
| 427 | rw_mgmt_ip = None |
| 428 | if 'rw_mgmt_ip' in params: |
| 429 | rw_mgmt_ip = params['rw_mgmt_ip'] |
| 430 | |
| Adam Israel | 5afe054 | 2018-08-08 12:54:55 -0400 | [diff] [blame] | 431 | if 'initial-config-primitive' not in params: |
| 432 | params['initial-config-primitive'] = {} |
| 433 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 434 | initial_config = self._get_config_from_dict( |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 435 | params['initial-config-primitive'], |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 436 | {'<rw_mgmt_ip>': rw_mgmt_ip} |
| 437 | ) |
| 438 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 439 | self.log.debug("JujuApi: Deploying charm ({}/{}) from {}".format( |
| 440 | model_name, |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 441 | application_name, |
| 442 | charm_path, |
| 443 | to=to, |
| 444 | )) |
| 445 | |
| 446 | ######################################################## |
| 447 | # Deploy the charm and apply the initial configuration # |
| 448 | ######################################################## |
| 449 | app = await model.deploy( |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 450 | # We expect charm_path to be either the path to the charm on disk |
| 451 | # or in the format of cs:series/name |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 452 | charm_path, |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 453 | # This is the formatted, unique name for this charm |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 454 | application_name=application_name, |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 455 | # Proxy charms should use the current LTS. This will need to be |
| 456 | # changed for native charms. |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 457 | series='xenial', |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 458 | # Apply the initial 'config' primitive during deployment |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 459 | config=initial_config, |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 460 | # Where to deploy the charm to. |
| 461 | to=to, |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 462 | ) |
| 463 | |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 464 | # Map the vdu id<->app name, |
| 465 | # |
| 466 | await self.Relate(model_name, vnfd) |
| 467 | |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 468 | # ####################################### |
| 469 | # # Execute initial config primitive(s) # |
| 470 | # ####################################### |
| Adam Israel | cf25320 | 2018-10-31 16:29:09 -0700 | [diff] [blame] | 471 | uuids = await self.ExecuteInitialPrimitives( |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 472 | model_name, |
| 473 | application_name, |
| 474 | params, |
| 475 | ) |
| Adam Israel | cf25320 | 2018-10-31 16:29:09 -0700 | [diff] [blame] | 476 | return uuids |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 477 | |
| 478 | # primitives = {} |
| 479 | # |
| 480 | # # Build a sequential list of the primitives to execute |
| 481 | # for primitive in params['initial-config-primitive']: |
| 482 | # try: |
| 483 | # if primitive['name'] == 'config': |
| 484 | # # This is applied when the Application is deployed |
| 485 | # pass |
| 486 | # else: |
| 487 | # seq = primitive['seq'] |
| 488 | # |
| 489 | # params = {} |
| 490 | # if 'parameter' in primitive: |
| 491 | # params = primitive['parameter'] |
| 492 | # |
| 493 | # primitives[seq] = { |
| 494 | # 'name': primitive['name'], |
| 495 | # 'parameters': self._map_primitive_parameters( |
| 496 | # params, |
| 497 | # {'<rw_mgmt_ip>': rw_mgmt_ip} |
| 498 | # ), |
| 499 | # } |
| 500 | # |
| 501 | # for primitive in sorted(primitives): |
| 502 | # await self.ExecutePrimitive( |
| 503 | # model_name, |
| 504 | # application_name, |
| 505 | # primitives[primitive]['name'], |
| 506 | # callback, |
| 507 | # callback_args, |
| 508 | # **primitives[primitive]['parameters'], |
| 509 | # ) |
| 510 | # except N2VCPrimitiveExecutionFailed as e: |
| 511 | # self.log.debug( |
| 512 | # "[N2VC] Exception executing primitive: {}".format(e) |
| 513 | # ) |
| 514 | # raise |
| 515 | |
| 516 | async def GetPrimitiveStatus(self, model_name, uuid): |
| 517 | """Get the status of an executed Primitive. |
| 518 | |
| 519 | The status of an executed Primitive will be one of three values: |
| 520 | - completed |
| 521 | - failed |
| 522 | - running |
| 523 | """ |
| 524 | status = None |
| 525 | try: |
| 526 | if not self.authenticated: |
| 527 | await self.login() |
| 528 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 529 | model = await self.get_model(model_name) |
| 530 | |
| 531 | results = await model.get_action_status(uuid) |
| 532 | |
| 533 | if uuid in results: |
| 534 | status = results[uuid] |
| 535 | |
| 536 | except Exception as e: |
| 537 | self.log.debug( |
| 538 | "Caught exception while getting primitive status: {}".format(e) |
| 539 | ) |
| 540 | raise N2VCPrimitiveExecutionFailed(e) |
| 541 | |
| 542 | return status |
| 543 | |
| 544 | async def GetPrimitiveOutput(self, model_name, uuid): |
| 545 | """Get the output of an executed Primitive. |
| 546 | |
| 547 | Note: this only returns output for a successfully executed primitive. |
| 548 | """ |
| 549 | results = None |
| 550 | try: |
| 551 | if not self.authenticated: |
| 552 | await self.login() |
| 553 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 554 | model = await self.get_model(model_name) |
| 555 | results = await model.get_action_output(uuid, 60) |
| 556 | except Exception as e: |
| 557 | self.log.debug( |
| 558 | "Caught exception while getting primitive status: {}".format(e) |
| 559 | ) |
| 560 | raise N2VCPrimitiveExecutionFailed(e) |
| 561 | |
| 562 | return results |
| 563 | |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 564 | # async def ProvisionMachine(self, model_name, hostname, username): |
| 565 | # """Provision machine for usage with Juju. |
| 566 | # |
| 567 | # Provisions a previously instantiated machine for use with Juju. |
| 568 | # """ |
| 569 | # try: |
| 570 | # if not self.authenticated: |
| 571 | # await self.login() |
| 572 | # |
| 573 | # # FIXME: This is hard-coded until model-per-ns is added |
| 574 | # model_name = 'default' |
| 575 | # |
| 576 | # model = await self.get_model(model_name) |
| 577 | # model.add_machine(spec={}) |
| 578 | # |
| 579 | # machine = await model.add_machine(spec='ssh:{}@{}:{}'.format( |
| 580 | # "ubuntu", |
| 581 | # host['address'], |
| 582 | # private_key_path, |
| 583 | # )) |
| 584 | # return machine.id |
| 585 | # |
| 586 | # except Exception as e: |
| 587 | # self.log.debug( |
| 588 | # "Caught exception while getting primitive status: {}".format(e) |
| 589 | # ) |
| 590 | # raise N2VCPrimitiveExecutionFailed(e) |
| 591 | |
| 592 | def GetPrivateKeyPath(self): |
| 593 | homedir = os.environ['HOME'] |
| 594 | sshdir = "{}/.ssh".format(homedir) |
| 595 | private_key_path = "{}/id_n2vc_rsa".format(sshdir) |
| 596 | return private_key_path |
| 597 | |
| 598 | async def GetPublicKey(self): |
| 599 | """Get the N2VC SSH public key.abs |
| 600 | |
| 601 | Returns the SSH public key, to be injected into virtual machines to |
| 602 | be managed by the VCA. |
| 603 | |
| 604 | The first time this is run, a ssh keypair will be created. The public |
| 605 | key is injected into a VM so that we can provision the machine with |
| 606 | Juju, after which Juju will communicate with the VM directly via the |
| 607 | juju agent. |
| 608 | """ |
| 609 | public_key = "" |
| 610 | |
| 611 | # Find the path to where we expect our key to live. |
| 612 | homedir = os.environ['HOME'] |
| 613 | sshdir = "{}/.ssh".format(homedir) |
| 614 | if not os.path.exists(sshdir): |
| 615 | os.mkdir(sshdir) |
| 616 | |
| 617 | private_key_path = "{}/id_n2vc_rsa".format(sshdir) |
| 618 | public_key_path = "{}.pub".format(private_key_path) |
| 619 | |
| 620 | # If we don't have a key generated, generate it. |
| 621 | if not os.path.exists(private_key_path): |
| 622 | cmd = "ssh-keygen -t {} -b {} -N '' -f {}".format( |
| 623 | "rsa", |
| 624 | "4096", |
| 625 | private_key_path |
| 626 | ) |
| 627 | subprocess.check_output(shlex.split(cmd)) |
| 628 | |
| 629 | # Read the public key |
| 630 | with open(public_key_path, "r") as f: |
| 631 | public_key = f.readline() |
| 632 | |
| 633 | return public_key |
| 634 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 635 | async def ExecuteInitialPrimitives(self, model_name, application_name, |
| 636 | params, callback=None, *callback_args): |
| 637 | """Execute multiple primitives. |
| 638 | |
| 639 | Execute multiple primitives as declared in initial-config-primitive. |
| 640 | This is useful in cases where the primitives initially failed -- for |
| 641 | example, if the charm is a proxy but the proxy hasn't been configured |
| 642 | yet. |
| 643 | """ |
| 644 | uuids = [] |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 645 | primitives = {} |
| 646 | |
| 647 | # Build a sequential list of the primitives to execute |
| 648 | for primitive in params['initial-config-primitive']: |
| 649 | try: |
| 650 | if primitive['name'] == 'config': |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 651 | pass |
| 652 | else: |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 653 | seq = primitive['seq'] |
| 654 | |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 655 | params_ = {} |
| Adam Israel | 42d88e6 | 2018-07-16 14:18:41 -0400 | [diff] [blame] | 656 | if 'parameter' in primitive: |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 657 | params_ = primitive['parameter'] |
| 658 | |
| 659 | user_values = params.get("user_values", {}) |
| 660 | if 'rw_mgmt_ip' not in user_values: |
| 661 | user_values['rw_mgmt_ip'] = None |
| 662 | # just for backward compatibility, because it will be provided always by modern version of LCM |
| Adam Israel | 42d88e6 | 2018-07-16 14:18:41 -0400 | [diff] [blame] | 663 | |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 664 | primitives[seq] = { |
| 665 | 'name': primitive['name'], |
| 666 | 'parameters': self._map_primitive_parameters( |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 667 | params_, |
| 668 | user_values |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 669 | ), |
| 670 | } |
| 671 | |
| 672 | for primitive in sorted(primitives): |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 673 | uuids.append( |
| 674 | await self.ExecutePrimitive( |
| 675 | model_name, |
| 676 | application_name, |
| 677 | primitives[primitive]['name'], |
| 678 | callback, |
| 679 | callback_args, |
| 680 | **primitives[primitive]['parameters'], |
| 681 | ) |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 682 | ) |
| 683 | except N2VCPrimitiveExecutionFailed as e: |
| Adam Israel | 7d871fb | 2018-07-17 12:17:06 -0400 | [diff] [blame] | 684 | self.log.debug( |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 685 | "[N2VC] Exception executing primitive: {}".format(e) |
| 686 | ) |
| 687 | raise |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 688 | return uuids |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 689 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 690 | async def ExecutePrimitive(self, model_name, application_name, primitive, |
| 691 | callback, *callback_args, **params): |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 692 | """Execute a primitive of a charm for Day 1 or Day 2 configuration. |
| Adam Israel | 6817f61 | 2018-04-13 08:41:43 -0600 | [diff] [blame] | 693 | |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 694 | Execute a primitive defined in the VNF descriptor. |
| 695 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 696 | :param str model_name: The name or unique id of the network service. |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 697 | :param str application_name: The name of the application |
| 698 | :param str primitive: The name of the primitive to execute. |
| 699 | :param obj callback: A callback function to receive status changes. |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 700 | :param tuple callback_args: A list of arguments to be passed to the |
| 701 | callback function. |
| 702 | :param dict params: A dictionary of key=value pairs representing the |
| 703 | primitive's parameters |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 704 | Examples:: |
| 705 | { |
| 706 | 'rw_mgmt_ip': '1.2.3.4', |
| 707 | # Pass the initial-config-primitives section of the vnf or vdu |
| 708 | 'initial-config-primitives': {...} |
| 709 | } |
| Adam Israel | 6817f61 | 2018-04-13 08:41:43 -0600 | [diff] [blame] | 710 | """ |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 711 | self.log.debug("Executing primitive={} params={}".format(primitive, params)) |
| Adam Israel | 6817f61 | 2018-04-13 08:41:43 -0600 | [diff] [blame] | 712 | uuid = None |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 713 | try: |
| 714 | if not self.authenticated: |
| 715 | await self.login() |
| 716 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 717 | model = await self.get_model(model_name) |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 718 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 719 | if primitive == 'config': |
| 720 | # config is special, and expecting params to be a dictionary |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 721 | await self.set_config( |
| 722 | model, |
| 723 | application_name, |
| 724 | params['params'], |
| 725 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 726 | else: |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 727 | app = await self.get_application(model, application_name) |
| 728 | if app: |
| 729 | # Run against the first (and probably only) unit in the app |
| 730 | unit = app.units[0] |
| 731 | if unit: |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 732 | action = await unit.run_action(primitive, **params) |
| Adam Israel | 6817f61 | 2018-04-13 08:41:43 -0600 | [diff] [blame] | 733 | uuid = action.id |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 734 | except Exception as e: |
| Adam Israel | b094366 | 2018-08-02 15:32:00 -0400 | [diff] [blame] | 735 | self.log.debug( |
| 736 | "Caught exception while executing primitive: {}".format(e) |
| 737 | ) |
| Adam Israel | 7d871fb | 2018-07-17 12:17:06 -0400 | [diff] [blame] | 738 | raise N2VCPrimitiveExecutionFailed(e) |
| Adam Israel | 6817f61 | 2018-04-13 08:41:43 -0600 | [diff] [blame] | 739 | return uuid |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 740 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 741 | async def RemoveCharms(self, model_name, application_name, callback=None, |
| 742 | *callback_args): |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 743 | """Remove a charm from the VCA. |
| 744 | |
| 745 | Remove a charm referenced in a VNF Descriptor. |
| 746 | |
| 747 | :param str model_name: The name of the network service. |
| 748 | :param str application_name: The name of the application |
| 749 | :param obj callback: A callback function to receive status changes. |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 750 | :param tuple callback_args: A list of arguments to be passed to the |
| 751 | callback function. |
| Adam Israel | c9df96f | 2018-05-03 14:49:56 -0400 | [diff] [blame] | 752 | """ |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 753 | try: |
| 754 | if not self.authenticated: |
| 755 | await self.login() |
| 756 | |
| 757 | model = await self.get_model(model_name) |
| 758 | app = await self.get_application(model, application_name) |
| 759 | if app: |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 760 | # Remove this application from event monitoring |
| 761 | self.monitors[model_name].RemoveApplication(application_name) |
| 762 | |
| 763 | # self.notify_callback(model_name, application_name, "removing", callback, *callback_args) |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 764 | self.log.debug( |
| 765 | "Removing the application {}".format(application_name) |
| 766 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 767 | await app.remove() |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 768 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 769 | await self.disconnect_model(self.monitors[model_name]) |
| 770 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 771 | self.notify_callback( |
| 772 | model_name, |
| 773 | application_name, |
| 774 | "removed", |
| Adam Israel | c4f393e | 2019-03-19 16:33:30 -0400 | [diff] [blame] | 775 | "Removing charm {}".format(application_name), |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 776 | callback, |
| 777 | *callback_args, |
| 778 | ) |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 779 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 780 | except Exception as e: |
| 781 | print("Caught exception: {}".format(e)) |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 782 | self.log.debug(e) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 783 | raise e |
| 784 | |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 785 | async def CreateNetworkService(self, ns_uuid): |
| 786 | """Create a new Juju model for the Network Service. |
| 787 | |
| 788 | Creates a new Model in the Juju Controller. |
| 789 | |
| 790 | :param str ns_uuid: A unique id representing an instaance of a |
| 791 | Network Service. |
| 792 | |
| 793 | :returns: True if the model was created. Raises JujuError on failure. |
| 794 | """ |
| 795 | if not self.authenticated: |
| 796 | await self.login() |
| 797 | |
| 798 | models = await self.controller.list_models() |
| 799 | if ns_uuid not in models: |
| 800 | try: |
| 801 | self.models[ns_uuid] = await self.controller.add_model( |
| 802 | ns_uuid |
| 803 | ) |
| 804 | except JujuError as e: |
| 805 | if "already exists" not in e.message: |
| 806 | raise e |
| Adam Israel | 7bf2f4d | 2019-03-15 15:28:47 -0400 | [diff] [blame] | 807 | |
| 808 | # Create an observer for this model |
| 809 | await self.create_model_monitor(ns_uuid) |
| 810 | |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 811 | return True |
| 812 | |
| 813 | async def DestroyNetworkService(self, ns_uuid): |
| 814 | """Destroy a Network Service. |
| 815 | |
| 816 | Destroy the Network Service and any deployed charms. |
| 817 | |
| 818 | :param ns_uuid The unique id of the Network Service |
| 819 | |
| 820 | :returns: True if the model was created. Raises JujuError on failure. |
| 821 | """ |
| 822 | |
| 823 | # Do not delete the default model. The default model was used by all |
| 824 | # Network Services, prior to the implementation of a model per NS. |
| Adam Israel | c4f393e | 2019-03-19 16:33:30 -0400 | [diff] [blame] | 825 | if ns_uuid.lower() == "default": |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 826 | return False |
| 827 | |
| 828 | if not self.authenticated: |
| 829 | self.log.debug("Authenticating with Juju") |
| 830 | await self.login() |
| 831 | |
| 832 | # Disconnect from the Model |
| 833 | if ns_uuid in self.models: |
| 834 | await self.disconnect_model(self.models[ns_uuid]) |
| 835 | |
| 836 | try: |
| 837 | await self.controller.destroy_models(ns_uuid) |
| Adam Israel | c4f393e | 2019-03-19 16:33:30 -0400 | [diff] [blame] | 838 | except JujuError: |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 839 | raise NetworkServiceDoesNotExist( |
| 840 | "The Network Service '{}' does not exist".format(ns_uuid) |
| 841 | ) |
| 842 | |
| 843 | return True |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 844 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 845 | async def GetMetrics(self, model_name, application_name): |
| 846 | """Get the metrics collected by the VCA. |
| 847 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 848 | :param model_name The name or unique id of the network service |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 849 | :param application_name The name of the application |
| 850 | """ |
| 851 | metrics = {} |
| 852 | model = await self.get_model(model_name) |
| 853 | app = await self.get_application(model, application_name) |
| 854 | if app: |
| 855 | metrics = await app.get_metrics() |
| 856 | |
| 857 | return metrics |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 858 | |
| Adam Israel | fa32907 | 2018-09-14 11:26:13 -0400 | [diff] [blame] | 859 | async def HasApplication(self, model_name, application_name): |
| 860 | model = await self.get_model(model_name) |
| 861 | app = await self.get_application(model, application_name) |
| 862 | if app: |
| 863 | return True |
| 864 | return False |
| 865 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 866 | # Non-public methods |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 867 | async def add_relation(self, model_name, relation1, relation2): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 868 | """ |
| 869 | Add a relation between two application endpoints. |
| 870 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 871 | :param str model_name: The name or unique id of the network service |
| 872 | :param str relation1: '<application>[:<relation_name>]' |
| 873 | :param str relation2: '<application>[:<relation_name>]' |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 874 | """ |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 875 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 876 | if not self.authenticated: |
| 877 | await self.login() |
| 878 | |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 879 | m = await self.get_model(model_name) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 880 | try: |
| Adam Israel | 136186e | 2018-09-14 12:01:12 -0400 | [diff] [blame] | 881 | await m.add_relation(relation1, relation2) |
| 882 | except JujuAPIError as e: |
| 883 | # If one of the applications in the relationship doesn't exist, |
| 884 | # or the relation has already been added, let the operation fail |
| 885 | # silently. |
| 886 | if 'not found' in e.message: |
| 887 | return |
| 888 | if 'already exists' in e.message: |
| 889 | return |
| 890 | |
| 891 | raise e |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 892 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 893 | # async def apply_config(self, config, application): |
| 894 | # """Apply a configuration to the application.""" |
| 895 | # print("JujuApi: Applying configuration to {}.".format( |
| 896 | # application |
| 897 | # )) |
| 898 | # return await self.set_config(application=application, config=config) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 899 | |
| 900 | def _get_config_from_dict(self, config_primitive, values): |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 901 | """Transform the yang config primitive to dict. |
| 902 | |
| 903 | Expected result: |
| 904 | |
| 905 | config = { |
| 906 | 'config': |
| 907 | } |
| 908 | """ |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 909 | config = {} |
| 910 | for primitive in config_primitive: |
| 911 | if primitive['name'] == 'config': |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 912 | # config = self._map_primitive_parameters() |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 913 | for parameter in primitive['parameter']: |
| 914 | param = str(parameter['name']) |
| 915 | if parameter['value'] == "<rw_mgmt_ip>": |
| 916 | config[param] = str(values[parameter['value']]) |
| 917 | else: |
| 918 | config[param] = str(parameter['value']) |
| 919 | |
| 920 | return config |
| 921 | |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 922 | def _map_primitive_parameters(self, parameters, user_values): |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 923 | params = {} |
| 924 | for parameter in parameters: |
| 925 | param = str(parameter['name']) |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 926 | value = parameter.get('value') |
| 927 | |
| 928 | # map parameters inside a < >; e.g. <rw_mgmt_ip>. with the provided user_values. |
| 929 | # Must exist at user_values except if there is a default value |
| 930 | if isinstance(value, str) and value.startswith("<") and value.endswith(">"): |
| 931 | if parameter['value'][1:-1] in user_values: |
| 932 | value = user_values[parameter['value'][1:-1]] |
| 933 | elif 'default-value' in parameter: |
| 934 | value = parameter['default-value'] |
| 935 | else: |
| 936 | raise KeyError("parameter {}='{}' not supplied ".format(param, value)) |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 937 | |
| Adam Israel | bf79352 | 2018-11-20 13:54:13 -0500 | [diff] [blame] | 938 | # If there's no value, use the default-value (if set) |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 939 | if value is None and 'default-value' in parameter: |
| Adam Israel | bf79352 | 2018-11-20 13:54:13 -0500 | [diff] [blame] | 940 | value = parameter['default-value'] |
| 941 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 942 | # Typecast parameter value, if present |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 943 | paramtype = "string" |
| 944 | try: |
| 945 | if 'data-type' in parameter: |
| 946 | paramtype = str(parameter['data-type']).lower() |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 947 | |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 948 | if paramtype == "integer": |
| 949 | value = int(value) |
| 950 | elif paramtype == "boolean": |
| 951 | value = bool(value) |
| 952 | else: |
| 953 | value = str(value) |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 954 | else: |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 955 | # If there's no data-type, assume the value is a string |
| 956 | value = str(value) |
| 957 | except ValueError: |
| 958 | raise ValueError("parameter {}='{}' cannot be converted to type {}".format(param, value, paramtype)) |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 959 | |
| tierno | 1afb30a | 2018-12-21 13:42:43 +0000 | [diff] [blame] | 960 | params[param] = value |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 961 | return params |
| 962 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 963 | def _get_config_from_yang(self, config_primitive, values): |
| 964 | """Transform the yang config primitive to dict.""" |
| 965 | config = {} |
| 966 | for primitive in config_primitive.values(): |
| 967 | if primitive['name'] == 'config': |
| 968 | for parameter in primitive['parameter'].values(): |
| 969 | param = str(parameter['name']) |
| 970 | if parameter['value'] == "<rw_mgmt_ip>": |
| 971 | config[param] = str(values[parameter['value']]) |
| 972 | else: |
| 973 | config[param] = str(parameter['value']) |
| 974 | |
| 975 | return config |
| 976 | |
| 977 | def FormatApplicationName(self, *args): |
| 978 | """ |
| 979 | Generate a Juju-compatible Application name |
| 980 | |
| 981 | :param args tuple: Positional arguments to be used to construct the |
| 982 | application name. |
| 983 | |
| 984 | Limitations:: |
| 985 | - Only accepts characters a-z and non-consequitive dashes (-) |
| 986 | - Application name should not exceed 50 characters |
| 987 | |
| 988 | Examples:: |
| 989 | |
| 990 | FormatApplicationName("ping_pong_ns", "ping_vnf", "a") |
| 991 | """ |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 992 | appname = "" |
| 993 | for c in "-".join(list(args)): |
| 994 | if c.isdigit(): |
| 995 | c = chr(97 + int(c)) |
| 996 | elif not c.isalpha(): |
| 997 | c = "-" |
| 998 | appname += c |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 999 | return re.sub('-+', '-', appname.lower()) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1000 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1001 | # def format_application_name(self, nsd_name, vnfr_name, member_vnf_index=0): |
| 1002 | # """Format the name of the application |
| 1003 | # |
| 1004 | # Limitations: |
| 1005 | # - Only accepts characters a-z and non-consequitive dashes (-) |
| 1006 | # - Application name should not exceed 50 characters |
| 1007 | # """ |
| 1008 | # name = "{}-{}-{}".format(nsd_name, vnfr_name, member_vnf_index) |
| 1009 | # new_name = '' |
| 1010 | # for c in name: |
| 1011 | # if c.isdigit(): |
| 1012 | # c = chr(97 + int(c)) |
| 1013 | # elif not c.isalpha(): |
| 1014 | # c = "-" |
| 1015 | # new_name += c |
| 1016 | # return re.sub('\-+', '-', new_name.lower()) |
| 1017 | |
| 1018 | def format_model_name(self, name): |
| 1019 | """Format the name of model. |
| 1020 | |
| 1021 | Model names may only contain lowercase letters, digits and hyphens |
| 1022 | """ |
| 1023 | |
| 1024 | return name.replace('_', '-').lower() |
| 1025 | |
| 1026 | async def get_application(self, model, application): |
| 1027 | """Get the deployed application.""" |
| 1028 | if not self.authenticated: |
| 1029 | await self.login() |
| 1030 | |
| 1031 | app = None |
| 1032 | if application and model: |
| 1033 | if model.applications: |
| 1034 | if application in model.applications: |
| 1035 | app = model.applications[application] |
| 1036 | |
| 1037 | return app |
| 1038 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1039 | async def get_model(self, model_name): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1040 | """Get a model from the Juju Controller. |
| 1041 | |
| 1042 | Note: Model objects returned must call disconnected() before it goes |
| 1043 | out of scope.""" |
| 1044 | if not self.authenticated: |
| 1045 | await self.login() |
| 1046 | |
| 1047 | if model_name not in self.models: |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1048 | # Get the models in the controller |
| 1049 | models = await self.controller.list_models() |
| 1050 | |
| 1051 | if model_name not in models: |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 1052 | try: |
| 1053 | self.models[model_name] = await self.controller.add_model( |
| 1054 | model_name |
| 1055 | ) |
| 1056 | except JujuError as e: |
| 1057 | if "already exists" not in e.message: |
| 1058 | raise e |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1059 | else: |
| 1060 | self.models[model_name] = await self.controller.get_model( |
| 1061 | model_name |
| 1062 | ) |
| 1063 | |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 1064 | self.refcount['model'] += 1 |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1065 | |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 1066 | # Create an observer for this model |
| Adam Israel | 7bf2f4d | 2019-03-15 15:28:47 -0400 | [diff] [blame] | 1067 | await self.create_model_monitor(model_name) |
| 1068 | |
| 1069 | return self.models[model_name] |
| 1070 | |
| 1071 | async def create_model_monitor(self, model_name): |
| 1072 | """Create a monitor for the model, if none exists.""" |
| 1073 | if not self.authenticated: |
| 1074 | await self.login() |
| 1075 | |
| 1076 | if model_name not in self.monitors: |
| Adam Israel | 28a43c0 | 2018-04-23 16:04:54 -0400 | [diff] [blame] | 1077 | self.monitors[model_name] = VCAMonitor(model_name) |
| 1078 | self.models[model_name].add_observer(self.monitors[model_name]) |
| 1079 | |
| Adam Israel | 7bf2f4d | 2019-03-15 15:28:47 -0400 | [diff] [blame] | 1080 | return True |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1081 | |
| 1082 | async def login(self): |
| 1083 | """Login to the Juju controller.""" |
| 1084 | |
| 1085 | if self.authenticated: |
| 1086 | return |
| 1087 | |
| 1088 | self.connecting = True |
| 1089 | |
| 1090 | self.log.debug("JujuApi: Logging into controller") |
| 1091 | |
| 1092 | cacert = None |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1093 | self.controller = Controller(loop=self.loop) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1094 | |
| 1095 | if self.secret: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1096 | self.log.debug( |
| 1097 | "Connecting to controller... ws://{}:{} as {}/{}".format( |
| 1098 | self.endpoint, |
| 1099 | self.port, |
| 1100 | self.user, |
| 1101 | self.secret, |
| 1102 | ) |
| 1103 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1104 | await self.controller.connect( |
| 1105 | endpoint=self.endpoint, |
| 1106 | username=self.user, |
| 1107 | password=self.secret, |
| 1108 | cacert=cacert, |
| 1109 | ) |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 1110 | self.refcount['controller'] += 1 |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1111 | else: |
| 1112 | # current_controller no longer exists |
| 1113 | # self.log.debug("Connecting to current controller...") |
| 1114 | # await self.controller.connect_current() |
| Adam Israel | 88a4963 | 2018-04-10 13:04:57 -0600 | [diff] [blame] | 1115 | # await self.controller.connect( |
| 1116 | # endpoint=self.endpoint, |
| 1117 | # username=self.user, |
| 1118 | # cacert=cacert, |
| 1119 | # ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1120 | self.log.fatal("VCA credentials not configured.") |
| 1121 | |
| 1122 | self.authenticated = True |
| 1123 | self.log.debug("JujuApi: Logged into controller") |
| 1124 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1125 | async def logout(self): |
| 1126 | """Logout of the Juju controller.""" |
| 1127 | if not self.authenticated: |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 1128 | return False |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1129 | |
| 1130 | try: |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1131 | for model in self.models: |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1132 | await self.disconnect_model(model) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1133 | |
| 1134 | if self.controller: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1135 | self.log.debug("Disconnecting controller {}".format( |
| 1136 | self.controller |
| 1137 | )) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1138 | await self.controller.disconnect() |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 1139 | self.refcount['controller'] -= 1 |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1140 | self.controller = None |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1141 | |
| 1142 | self.authenticated = False |
| Adam Israel | fc511ed | 2018-09-21 14:20:55 +0200 | [diff] [blame] | 1143 | |
| 1144 | self.log.debug(self.refcount) |
| 1145 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1146 | except Exception as e: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1147 | self.log.fatal( |
| 1148 | "Fatal error logging out of Juju Controller: {}".format(e) |
| 1149 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1150 | raise e |
| Adam Israel | 6d84dbd | 2019-03-08 18:33:35 -0500 | [diff] [blame] | 1151 | return True |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1152 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1153 | async def disconnect_model(self, model): |
| 1154 | self.log.debug("Disconnecting model {}".format(model)) |
| 1155 | if model in self.models: |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1156 | print("Disconnecting model") |
| 1157 | await self.models[model].disconnect() |
| 1158 | self.refcount['model'] -= 1 |
| 1159 | self.models[model] = None |
| 1160 | |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1161 | # async def remove_application(self, name): |
| 1162 | # """Remove the application.""" |
| 1163 | # if not self.authenticated: |
| 1164 | # await self.login() |
| 1165 | # |
| 1166 | # app = await self.get_application(name) |
| 1167 | # if app: |
| 1168 | # self.log.debug("JujuApi: Destroying application {}".format( |
| 1169 | # name, |
| 1170 | # )) |
| 1171 | # |
| 1172 | # await app.destroy() |
| 1173 | |
| 1174 | async def remove_relation(self, a, b): |
| 1175 | """ |
| 1176 | Remove a relation between two application endpoints |
| 1177 | |
| 1178 | :param a An application endpoint |
| 1179 | :param b An application endpoint |
| 1180 | """ |
| 1181 | if not self.authenticated: |
| 1182 | await self.login() |
| 1183 | |
| 1184 | m = await self.get_model() |
| 1185 | try: |
| 1186 | m.remove_relation(a, b) |
| 1187 | finally: |
| 1188 | await m.disconnect() |
| 1189 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1190 | async def resolve_error(self, model_name, application=None): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1191 | """Resolve units in error state.""" |
| 1192 | if not self.authenticated: |
| 1193 | await self.login() |
| 1194 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1195 | model = await self.get_model(model_name) |
| 1196 | |
| 1197 | app = await self.get_application(model, application) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1198 | if app: |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1199 | self.log.debug( |
| 1200 | "JujuApi: Resolving errors for application {}".format( |
| 1201 | application, |
| 1202 | ) |
| 1203 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1204 | |
| 1205 | for unit in app.units: |
| 1206 | app.resolved(retry=True) |
| 1207 | |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1208 | async def run_action(self, model_name, application, action_name, **params): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1209 | """Execute an action and return an Action object.""" |
| 1210 | if not self.authenticated: |
| 1211 | await self.login() |
| 1212 | result = { |
| 1213 | 'status': '', |
| 1214 | 'action': { |
| 1215 | 'tag': None, |
| 1216 | 'results': None, |
| 1217 | } |
| 1218 | } |
| Adam Israel | 85a4b21 | 2018-11-29 20:30:24 -0500 | [diff] [blame] | 1219 | |
| 1220 | model = await self.get_model(model_name) |
| 1221 | |
| 1222 | app = await self.get_application(model, application) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1223 | if app: |
| 1224 | # We currently only have one unit per application |
| 1225 | # so use the first unit available. |
| 1226 | unit = app.units[0] |
| 1227 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1228 | self.log.debug( |
| 1229 | "JujuApi: Running Action {} against Application {}".format( |
| 1230 | action_name, |
| 1231 | application, |
| 1232 | ) |
| 1233 | ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1234 | |
| 1235 | action = await unit.run_action(action_name, **params) |
| 1236 | |
| 1237 | # Wait for the action to complete |
| 1238 | await action.wait() |
| 1239 | |
| 1240 | result['status'] = action.status |
| 1241 | result['action']['tag'] = action.data['id'] |
| 1242 | result['action']['results'] = action.results |
| 1243 | |
| 1244 | return result |
| 1245 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 1246 | async def set_config(self, model_name, application, config): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1247 | """Apply a configuration to the application.""" |
| 1248 | if not self.authenticated: |
| 1249 | await self.login() |
| 1250 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 1251 | app = await self.get_application(model_name, application) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1252 | if app: |
| 1253 | self.log.debug("JujuApi: Setting config for Application {}".format( |
| 1254 | application, |
| 1255 | )) |
| 1256 | await app.set_config(config) |
| 1257 | |
| 1258 | # Verify the config is set |
| 1259 | newconf = await app.get_config() |
| 1260 | for key in config: |
| 1261 | if config[key] != newconf[key]['value']: |
| 1262 | self.log.debug("JujuApi: Config not set! Key {} Value {} doesn't match {}".format(key, config[key], newconf[key])) |
| 1263 | |
| Adam Israel | b521451 | 2018-05-03 10:00:04 -0400 | [diff] [blame] | 1264 | # async def set_parameter(self, parameter, value, application=None): |
| 1265 | # """Set a config parameter for a service.""" |
| 1266 | # if not self.authenticated: |
| 1267 | # await self.login() |
| 1268 | # |
| 1269 | # self.log.debug("JujuApi: Setting {}={} for Application {}".format( |
| 1270 | # parameter, |
| 1271 | # value, |
| 1272 | # application, |
| 1273 | # )) |
| 1274 | # return await self.apply_config( |
| 1275 | # {parameter: value}, |
| 1276 | # application=application, |
| 1277 | # ) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1278 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1279 | async def wait_for_application(self, model_name, application_name, |
| 1280 | timeout=300): |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1281 | """Wait for an application to become active.""" |
| 1282 | if not self.authenticated: |
| 1283 | await self.login() |
| 1284 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1285 | model = await self.get_model(model_name) |
| 1286 | |
| 1287 | app = await self.get_application(model, application_name) |
| 1288 | self.log.debug("Application: {}".format(app)) |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1289 | if app: |
| 1290 | self.log.debug( |
| 1291 | "JujuApi: Waiting {} seconds for Application {}".format( |
| 1292 | timeout, |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1293 | application_name, |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1294 | ) |
| 1295 | ) |
| 1296 | |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1297 | await model.block_until( |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1298 | lambda: all( |
| Adam Israel | 5e08a0e | 2018-09-06 19:22:47 -0400 | [diff] [blame] | 1299 | unit.agent_status == 'idle' and unit.workload_status in |
| 1300 | ['active', 'unknown'] for unit in app.units |
| Adam Israel | c3e6c2e | 2018-03-01 09:31:50 -0500 | [diff] [blame] | 1301 | ), |
| 1302 | timeout=timeout |
| 1303 | ) |