blob: 11ce3c82cc1a1dad5f9cc9cc0bf6c0e60d194723 [file] [log] [blame]
Adam Israel5e08a0e2018-09-06 19:22:47 -04001import asyncio
Adam Israelc3e6c2e2018-03-01 09:31:50 -05002import logging
3import os
4import os.path
5import re
Adam Israelfa329072018-09-14 11:26:13 -04006import shlex
Adam Israelc3e6c2e2018-03-01 09:31:50 -05007import ssl
Adam Israelfa329072018-09-14 11:26:13 -04008import subprocess
Adam Israelc3e6c2e2018-03-01 09:31:50 -05009import sys
Adam Israel5e08a0e2018-09-06 19:22:47 -040010# import time
Adam Israelc3e6c2e2018-03-01 09:31:50 -050011
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
15path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
16path = os.path.join(path, "modules/libjuju/")
17if path not in sys.path:
18 sys.path.insert(1, path)
19
20from juju.controller import Controller
Adam Israel5e08a0e2018-09-06 19:22:47 -040021from juju.model import ModelObserver
Adam Israel6d84dbd2019-03-08 18:33:35 -050022from juju.errors import JujuAPIError, JujuError
Adam Israelc3e6c2e2018-03-01 09:31:50 -050023
24# We might need this to connect to the websocket securely, but test and verify.
25try:
26 ssl._create_default_https_context = ssl._create_unverified_context
27except 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
34class JujuCharmNotFound(Exception):
35 """The Charm can't be found or is not readable."""
36
37
38class JujuApplicationExists(Exception):
39 """The Application already exists."""
40
Adam Israelb5214512018-05-03 10:00:04 -040041
Adam Israel88a49632018-04-10 13:04:57 -060042class N2VCPrimitiveExecutionFailed(Exception):
43 """Something failed while attempting to execute a primitive."""
44
Adam Israelc3e6c2e2018-03-01 09:31:50 -050045
Adam Israel6d84dbd2019-03-08 18:33:35 -050046class NetworkServiceDoesNotExist(Exception):
47 """The Network Service being acted against does not exist."""
48
49
Adam Israelc3e6c2e2018-03-01 09:31:50 -050050# Quiet the debug logging
51logging.getLogger('websockets.protocol').setLevel(logging.INFO)
52logging.getLogger('juju.client.connection').setLevel(logging.WARN)
53logging.getLogger('juju.model').setLevel(logging.WARN)
54logging.getLogger('juju.machine').setLevel(logging.WARN)
55
Adam Israelb5214512018-05-03 10:00:04 -040056
Adam Israelc3e6c2e2018-03-01 09:31:50 -050057class VCAMonitor(ModelObserver):
58 """Monitor state changes within the Juju Model."""
Adam Israelc3e6c2e2018-03-01 09:31:50 -050059 log = None
Adam Israelc3e6c2e2018-03-01 09:31:50 -050060
Adam Israel28a43c02018-04-23 16:04:54 -040061 def __init__(self, ns_name):
Adam Israelc3e6c2e2018-03-01 09:31:50 -050062 self.log = logging.getLogger(__name__)
63
64 self.ns_name = ns_name
Adam Israeld420a8b2019-04-09 16:07:53 -040065 self.applications = {}
Adam Israel28a43c02018-04-23 16:04:54 -040066
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 Israelc3e6c2e2018-03-01 09:31:50 -050077
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 Israel28a43c02018-04-23 16:04:54 -040082 # Ignore change events from other applications
83 if delta.data['application'] not in self.applications.keys():
84 return
85
Adam Israelc3e6c2e2018-03-01 09:31:50 -050086 try:
Adam Israel28a43c02018-04-23 16:04:54 -040087
88 application_name = delta.data['application']
89
90 callback = self.applications[application_name]['callback']
Adam Israel5e08a0e2018-09-06 19:22:47 -040091 callback_args = \
92 self.applications[application_name]['callback_args']
Adam Israel28a43c02018-04-23 16:04:54 -040093
Adam Israelc3e6c2e2018-03-01 09:31:50 -050094 if old and new:
Adam Israelfc511ed2018-09-21 14:20:55 +020095 # 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 Israel28a43c02018-04-23 16:04:54 -0400103
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 Israel9562f432018-05-09 13:55:28 -0400111 "",
Adam Israel28a43c02018-04-23 16:04:54 -0400112 *callback_args)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500113 except Exception as e:
Adam Israel5e08a0e2018-09-06 19:22:47 -0400114 self.log.debug("[1] notify_callback exception: {}".format(e))
115
Adam Israel88a49632018-04-10 13:04:57 -0600116 elif delta.entity == "action":
117 # TODO: Decide how we want to notify the user of actions
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500118
Adam Israel88a49632018-04-10 13:04:57 -0600119 # 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 Israelc3e6c2e2018-03-01 09:31:50 -0500133
134########
135# TODO
136#
137# Create unique models per network service
138# Document all public functions
139
Adam Israelb5214512018-05-03 10:00:04 -0400140
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500141class N2VC:
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500142 def __init__(self,
143 log=None,
144 server='127.0.0.1',
145 port=17070,
146 user='admin',
147 secret=None,
Adam Israel5e08a0e2018-09-06 19:22:47 -0400148 artifacts=None,
149 loop=None,
Adam Israelb2a07f52019-04-25 17:17:05 -0400150 juju_public_key=None,
151 ca_cert=None,
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500152 ):
153 """Initialize N2VC
Adam Israelb2a07f52019-04-25 17:17:05 -0400154 :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
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500160 stored.
Adam Israelb2a07f52019-04-25 17:17:05 -0400161 :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
164
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500165
166 :Example:
Adam Israelb2a07f52019-04-25 17:17:05 -0400167 client = n2vc.vnf.N2VC(
168 log=log,
169 server='10.1.1.28',
170 port=17070,
171 user='admin',
172 secret='admin',
173 artifacts='/app/storage/myvnf/charms',
174 loop=loop,
175 juju_public_key='<contents of the juju public key>',
176 ca_cert='<contents of CA certificate>',
177 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500178 """
179
Adam Israel5e08a0e2018-09-06 19:22:47 -0400180 # Initialize instance-level variables
181 self.api = None
182 self.log = None
183 self.controller = None
184 self.connecting = False
185 self.authenticated = False
186
Adam Israelfc511ed2018-09-21 14:20:55 +0200187 # For debugging
188 self.refcount = {
189 'controller': 0,
190 'model': 0,
191 }
192
Adam Israel5e08a0e2018-09-06 19:22:47 -0400193 self.models = {}
Adam Israel5e08a0e2018-09-06 19:22:47 -0400194
195 # Model Observers
196 self.monitors = {}
197
198 # VCA config
199 self.hostname = ""
200 self.port = 17070
201 self.username = ""
202 self.secret = ""
203
Adam Israelb2a07f52019-04-25 17:17:05 -0400204 self.juju_public_key = juju_public_key
205 if juju_public_key:
206 self._create_juju_public_key(juju_public_key)
207
208 self.ca_cert = ca_cert
209
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500210 if log:
211 self.log = log
212 else:
213 self.log = logging.getLogger(__name__)
214
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)
220
221 self.log.debug('JujuApi: instantiated')
222
223 self.server = server
224 self.port = port
225
226 self.secret = secret
227 if user.startswith('user-'):
228 self.user = user
229 else:
230 self.user = 'user-{}'.format(user)
231
232 self.endpoint = '%s:%d' % (server, int(port))
233
234 self.artifacts = artifacts
235
Adam Israel5e08a0e2018-09-06 19:22:47 -0400236 self.loop = loop or asyncio.get_event_loop()
237
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500238 def __del__(self):
239 """Close any open connections."""
240 yield self.logout()
241
Adam Israelb2a07f52019-04-25 17:17:05 -0400242 def _create_juju_public_key(self, public_key):
243 """Recreate the Juju public key on disk.
244
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
248 """
Adam Israele3a05f82019-04-26 13:12:47 -0400249 # Make sure that we have a public key before writing to disk
Adam Israelb2a07f52019-04-25 17:17:05 -0400250 if public_key is None or len(public_key) == 0:
Adam Israele3a05f82019-04-26 13:12:47 -0400251 if 'OSM_VCA_PUBKEY' in os.environ:
252 public_key = os.getenv('OSM_VCA_PUBKEY', '')
253 if len(public_key == 0):
254 return
255 else:
256 return
257
Adam Israelb2a07f52019-04-25 17:17:05 -0400258 path = "{}/.local/share/juju/ssh".format(
259 os.path.expanduser('~'),
260 )
261 if not os.path.exists(path):
262 os.makedirs(path)
263
264 with open('{}/juju_id_rsa.pub'.format(path), 'w') as f:
265 f.write(public_key)
266
Adam Israel5e08a0e2018-09-06 19:22:47 -0400267 def notify_callback(self, model_name, application_name, status, message,
268 callback=None, *callback_args):
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500269 try:
270 if callback:
Adam Israel5e08a0e2018-09-06 19:22:47 -0400271 callback(
272 model_name,
273 application_name,
274 status, message,
275 *callback_args,
276 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500277 except Exception as e:
278 self.log.error("[0] notify_callback exception {}".format(e))
Adam Israel88a49632018-04-10 13:04:57 -0600279 raise e
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500280 return True
281
282 # Public methods
Adam Israel85a4b212018-11-29 20:30:24 -0500283 async def Relate(self, model_name, vnfd):
Adam Israel136186e2018-09-14 12:01:12 -0400284 """Create a relation between the charm-enabled VDUs in a VNF.
285
286 The Relation mapping has two parts: the id of the vdu owning the endpoint, and the name of the endpoint.
287
288 vdu:
289 ...
290 relation:
291 - provides: dataVM:db
292 requires: mgmtVM:app
293
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.
295
296 :param str ns_name: The name of the network service.
297 :param dict vnfd: The parsed yaml VNF descriptor.
298 """
299
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.
305
306 configs = []
307 vnf_config = vnfd.get("vnf-configuration")
308 if vnf_config:
309 juju = vnf_config['juju']
310 if juju:
311 configs.append(vnf_config)
312
313 for vdu in vnfd['vdu']:
314 vdu_config = vdu.get('vdu-configuration')
315 if vdu_config:
316 juju = vdu_config['juju']
317 if juju:
318 configs.append(vdu_config)
319
320 def _get_application_name(name):
321 """Get the application name that's mapped to a vnf/vdu."""
322 vnf_member_index = 0
323 vnf_name = vnfd['name']
324
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(
Adam Israel85a4b212018-11-29 20:30:24 -0500329 model_name,
Adam Israel136186e2018-09-14 12:01:12 -0400330 vnf_name,
331 str(vnf_member_index),
332 )
333 return application_name
334 else:
335 vnf_member_index += 1
336
337 return None
338
339 # Loop through relations
340 for cfg in configs:
341 if 'juju' in cfg:
Adam Israelc92163f2019-05-27 08:39:19 -0400342 juju = cfg['juju']
Adam Israel136186e2018-09-14 12:01:12 -0400343 if 'relation' in juju:
344 for rel in juju['relation']:
345 try:
346
347 # get the application name for the provides
348 (name, endpoint) = rel['provides'].split(':')
349 application_name = _get_application_name(name)
350
351 provides = "{}:{}".format(
352 application_name,
353 endpoint
354 )
355
356 # get the application name for thr requires
357 (name, endpoint) = rel['requires'].split(':')
358 application_name = _get_application_name(name)
359
360 requires = "{}:{}".format(
361 application_name,
362 endpoint
363 )
364 self.log.debug("Relation: {} <-> {}".format(
365 provides,
366 requires
367 ))
368 await self.add_relation(
Adam Israel85a4b212018-11-29 20:30:24 -0500369 model_name,
Adam Israel136186e2018-09-14 12:01:12 -0400370 provides,
371 requires,
372 )
373 except Exception as e:
374 self.log.debug("Exception: {}".format(e))
375
376 return
377
Adam Israel5e08a0e2018-09-06 19:22:47 -0400378 async def DeployCharms(self, model_name, application_name, vnfd,
379 charm_path, params={}, machine_spec={},
380 callback=None, *callback_args):
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500381 """Deploy one or more charms associated with a VNF.
382
383 Deploy the charm(s) referenced in a VNF Descriptor.
384
Adam Israel85a4b212018-11-29 20:30:24 -0500385 :param str model_name: The name or unique id of the network service.
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500386 :param str application_name: The name of the application
387 :param dict vnfd: The name of the application
388 :param str charm_path: The path to the Juju charm
389 :param dict params: A dictionary of runtime parameters
390 Examples::
391 {
Adam Israel88a49632018-04-10 13:04:57 -0600392 'rw_mgmt_ip': '1.2.3.4',
393 # Pass the initial-config-primitives section of the vnf or vdu
394 'initial-config-primitives': {...}
tierno1afb30a2018-12-21 13:42:43 +0000395 'user_values': dictionary with the day-1 parameters provided at instantiation time. It will replace values
396 inside < >. rw_mgmt_ip will be included here also
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500397 }
Adam Israel5e08a0e2018-09-06 19:22:47 -0400398 :param dict machine_spec: A dictionary describing the machine to
399 install to
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500400 Examples::
401 {
402 'hostname': '1.2.3.4',
403 'username': 'ubuntu',
404 }
405 :param obj callback: A callback function to receive status changes.
Adam Israel5e08a0e2018-09-06 19:22:47 -0400406 :param tuple callback_args: A list of arguments to be passed to the
407 callback
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500408 """
409
410 ########################################################
411 # Verify the path to the charm exists and is readable. #
412 ########################################################
413 if not os.path.exists(charm_path):
414 self.log.debug("Charm path doesn't exist: {}".format(charm_path))
Adam Israel5e08a0e2018-09-06 19:22:47 -0400415 self.notify_callback(
416 model_name,
417 application_name,
418 "failed",
419 callback,
420 *callback_args,
421 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500422 raise JujuCharmNotFound("No artifacts configured.")
423
424 ################################
425 # Login to the Juju controller #
426 ################################
427 if not self.authenticated:
428 self.log.debug("Authenticating with Juju")
429 await self.login()
430
431 ##########################################
432 # Get the model for this network service #
433 ##########################################
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500434 model = await self.get_model(model_name)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500435
436 ########################################
437 # Verify the application doesn't exist #
438 ########################################
439 app = await self.get_application(model, application_name)
440 if app:
Adam Israel42d88e62018-07-16 14:18:41 -0400441 raise JujuApplicationExists("Can't deploy application \"{}\" to model \"{}\" because it already exists.".format(application_name, model_name))
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500442
Adam Israel28a43c02018-04-23 16:04:54 -0400443 ################################################################
444 # Register this application with the model-level event monitor #
445 ################################################################
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500446 if callback:
Adam Israel04eee1f2019-04-29 14:59:45 -0400447 self.log.debug("JujuApi: Registering callback for {}".format(
Adam Israel28a43c02018-04-23 16:04:54 -0400448 application_name,
Adam Israel04eee1f2019-04-29 14:59:45 -0400449 ))
450 await self.Subscribe(model_name, application_name, callback, *callback_args)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500451
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500452 ########################################################
453 # Check for specific machine placement (native charms) #
454 ########################################################
455 to = ""
456 if machine_spec.keys():
Adam Israel5963cb42018-09-14 11:26:13 -0400457 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(
Adam Israelce31bc32019-05-22 16:30:25 -0400460 machine_spec['username'],
461 machine_spec['hostname'],
Adam Israel5963cb42018-09-14 11:26:13 -0400462 self.GetPrivateKeyPath(),
463 ))
Adam Israelfa329072018-09-14 11:26:13 -0400464 to = machine.id
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500465
466 #######################################
467 # Get the initial charm configuration #
468 #######################################
469
470 rw_mgmt_ip = None
471 if 'rw_mgmt_ip' in params:
472 rw_mgmt_ip = params['rw_mgmt_ip']
473
Adam Israel5afe0542018-08-08 12:54:55 -0400474 if 'initial-config-primitive' not in params:
475 params['initial-config-primitive'] = {}
476
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500477 initial_config = self._get_config_from_dict(
Adam Israel88a49632018-04-10 13:04:57 -0600478 params['initial-config-primitive'],
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500479 {'<rw_mgmt_ip>': rw_mgmt_ip}
480 )
481
Adam Israel85a4b212018-11-29 20:30:24 -0500482 self.log.debug("JujuApi: Deploying charm ({}/{}) from {}".format(
483 model_name,
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500484 application_name,
485 charm_path,
486 to=to,
487 ))
488
489 ########################################################
490 # Deploy the charm and apply the initial configuration #
491 ########################################################
492 app = await model.deploy(
Adam Israel88a49632018-04-10 13:04:57 -0600493 # We expect charm_path to be either the path to the charm on disk
494 # or in the format of cs:series/name
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500495 charm_path,
Adam Israel88a49632018-04-10 13:04:57 -0600496 # This is the formatted, unique name for this charm
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500497 application_name=application_name,
Adam Israel88a49632018-04-10 13:04:57 -0600498 # Proxy charms should use the current LTS. This will need to be
499 # changed for native charms.
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500500 series='xenial',
Adam Israel88a49632018-04-10 13:04:57 -0600501 # Apply the initial 'config' primitive during deployment
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500502 config=initial_config,
Adam Israelfa329072018-09-14 11:26:13 -0400503 # Where to deploy the charm to.
504 to=to,
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500505 )
506
Adam Israel136186e2018-09-14 12:01:12 -0400507 # Map the vdu id<->app name,
508 #
509 await self.Relate(model_name, vnfd)
510
Adam Israel88a49632018-04-10 13:04:57 -0600511 # #######################################
512 # # Execute initial config primitive(s) #
513 # #######################################
Adam Israelcf253202018-10-31 16:29:09 -0700514 uuids = await self.ExecuteInitialPrimitives(
Adam Israel5e08a0e2018-09-06 19:22:47 -0400515 model_name,
516 application_name,
517 params,
518 )
Adam Israelcf253202018-10-31 16:29:09 -0700519 return uuids
Adam Israel5e08a0e2018-09-06 19:22:47 -0400520
521 # primitives = {}
522 #
523 # # Build a sequential list of the primitives to execute
524 # for primitive in params['initial-config-primitive']:
525 # try:
526 # if primitive['name'] == 'config':
527 # # This is applied when the Application is deployed
528 # pass
529 # else:
530 # seq = primitive['seq']
531 #
532 # params = {}
533 # if 'parameter' in primitive:
534 # params = primitive['parameter']
535 #
536 # primitives[seq] = {
537 # 'name': primitive['name'],
538 # 'parameters': self._map_primitive_parameters(
539 # params,
540 # {'<rw_mgmt_ip>': rw_mgmt_ip}
541 # ),
542 # }
543 #
544 # for primitive in sorted(primitives):
545 # await self.ExecutePrimitive(
546 # model_name,
547 # application_name,
548 # primitives[primitive]['name'],
549 # callback,
550 # callback_args,
551 # **primitives[primitive]['parameters'],
552 # )
553 # except N2VCPrimitiveExecutionFailed as e:
554 # self.log.debug(
555 # "[N2VC] Exception executing primitive: {}".format(e)
556 # )
557 # raise
558
559 async def GetPrimitiveStatus(self, model_name, uuid):
560 """Get the status of an executed Primitive.
561
562 The status of an executed Primitive will be one of three values:
563 - completed
564 - failed
565 - running
566 """
567 status = None
568 try:
569 if not self.authenticated:
570 await self.login()
571
Adam Israel5e08a0e2018-09-06 19:22:47 -0400572 model = await self.get_model(model_name)
573
574 results = await model.get_action_status(uuid)
575
576 if uuid in results:
577 status = results[uuid]
578
579 except Exception as e:
580 self.log.debug(
581 "Caught exception while getting primitive status: {}".format(e)
582 )
583 raise N2VCPrimitiveExecutionFailed(e)
584
585 return status
586
587 async def GetPrimitiveOutput(self, model_name, uuid):
588 """Get the output of an executed Primitive.
589
590 Note: this only returns output for a successfully executed primitive.
591 """
592 results = None
593 try:
594 if not self.authenticated:
595 await self.login()
596
Adam Israel5e08a0e2018-09-06 19:22:47 -0400597 model = await self.get_model(model_name)
598 results = await model.get_action_output(uuid, 60)
599 except Exception as e:
600 self.log.debug(
601 "Caught exception while getting primitive status: {}".format(e)
602 )
603 raise N2VCPrimitiveExecutionFailed(e)
604
605 return results
606
Adam Israelfa329072018-09-14 11:26:13 -0400607 # async def ProvisionMachine(self, model_name, hostname, username):
608 # """Provision machine for usage with Juju.
609 #
610 # Provisions a previously instantiated machine for use with Juju.
611 # """
612 # try:
613 # if not self.authenticated:
614 # await self.login()
615 #
616 # # FIXME: This is hard-coded until model-per-ns is added
617 # model_name = 'default'
618 #
619 # model = await self.get_model(model_name)
620 # model.add_machine(spec={})
621 #
622 # machine = await model.add_machine(spec='ssh:{}@{}:{}'.format(
623 # "ubuntu",
624 # host['address'],
625 # private_key_path,
626 # ))
627 # return machine.id
628 #
629 # except Exception as e:
630 # self.log.debug(
631 # "Caught exception while getting primitive status: {}".format(e)
632 # )
633 # raise N2VCPrimitiveExecutionFailed(e)
634
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
640
641 async def GetPublicKey(self):
642 """Get the N2VC SSH public key.abs
643
644 Returns the SSH public key, to be injected into virtual machines to
645 be managed by the VCA.
646
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
650 juju agent.
651 """
652 public_key = ""
653
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):
658 os.mkdir(sshdir)
659
660 private_key_path = "{}/id_n2vc_rsa".format(sshdir)
661 public_key_path = "{}.pub".format(private_key_path)
662
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(
666 "rsa",
667 "4096",
668 private_key_path
669 )
670 subprocess.check_output(shlex.split(cmd))
671
672 # Read the public key
673 with open(public_key_path, "r") as f:
674 public_key = f.readline()
675
676 return public_key
677
Adam Israel5e08a0e2018-09-06 19:22:47 -0400678 async def ExecuteInitialPrimitives(self, model_name, application_name,
679 params, callback=None, *callback_args):
680 """Execute multiple primitives.
681
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
685 yet.
686 """
687 uuids = []
Adam Israel88a49632018-04-10 13:04:57 -0600688 primitives = {}
689
690 # Build a sequential list of the primitives to execute
691 for primitive in params['initial-config-primitive']:
692 try:
693 if primitive['name'] == 'config':
Adam Israel88a49632018-04-10 13:04:57 -0600694 pass
695 else:
Adam Israel88a49632018-04-10 13:04:57 -0600696 seq = primitive['seq']
697
tierno1afb30a2018-12-21 13:42:43 +0000698 params_ = {}
Adam Israel42d88e62018-07-16 14:18:41 -0400699 if 'parameter' in primitive:
tierno1afb30a2018-12-21 13:42:43 +0000700 params_ = primitive['parameter']
701
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
Adam Israel42d88e62018-07-16 14:18:41 -0400706
Adam Israel88a49632018-04-10 13:04:57 -0600707 primitives[seq] = {
708 'name': primitive['name'],
709 'parameters': self._map_primitive_parameters(
tierno1afb30a2018-12-21 13:42:43 +0000710 params_,
711 user_values
Adam Israel88a49632018-04-10 13:04:57 -0600712 ),
713 }
714
715 for primitive in sorted(primitives):
Adam Israel5e08a0e2018-09-06 19:22:47 -0400716 uuids.append(
717 await self.ExecutePrimitive(
718 model_name,
719 application_name,
720 primitives[primitive]['name'],
721 callback,
722 callback_args,
723 **primitives[primitive]['parameters'],
724 )
Adam Israel88a49632018-04-10 13:04:57 -0600725 )
726 except N2VCPrimitiveExecutionFailed as e:
Adam Israel7d871fb2018-07-17 12:17:06 -0400727 self.log.debug(
Adam Israel88a49632018-04-10 13:04:57 -0600728 "[N2VC] Exception executing primitive: {}".format(e)
729 )
730 raise
Adam Israel5e08a0e2018-09-06 19:22:47 -0400731 return uuids
Adam Israel88a49632018-04-10 13:04:57 -0600732
Adam Israel5e08a0e2018-09-06 19:22:47 -0400733 async def ExecutePrimitive(self, model_name, application_name, primitive,
734 callback, *callback_args, **params):
Adam Israelc9df96f2018-05-03 14:49:56 -0400735 """Execute a primitive of a charm for Day 1 or Day 2 configuration.
Adam Israel6817f612018-04-13 08:41:43 -0600736
Adam Israelc9df96f2018-05-03 14:49:56 -0400737 Execute a primitive defined in the VNF descriptor.
738
Adam Israel85a4b212018-11-29 20:30:24 -0500739 :param str model_name: The name or unique id of the network service.
Adam Israelc9df96f2018-05-03 14:49:56 -0400740 :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.
Adam Israel5e08a0e2018-09-06 19:22:47 -0400743 :param tuple callback_args: A list of arguments to be passed to the
744 callback function.
745 :param dict params: A dictionary of key=value pairs representing the
746 primitive's parameters
Adam Israelc9df96f2018-05-03 14:49:56 -0400747 Examples::
748 {
749 'rw_mgmt_ip': '1.2.3.4',
750 # Pass the initial-config-primitives section of the vnf or vdu
751 'initial-config-primitives': {...}
752 }
Adam Israel6817f612018-04-13 08:41:43 -0600753 """
tierno1afb30a2018-12-21 13:42:43 +0000754 self.log.debug("Executing primitive={} params={}".format(primitive, params))
Adam Israel6817f612018-04-13 08:41:43 -0600755 uuid = None
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500756 try:
757 if not self.authenticated:
758 await self.login()
759
Adam Israel5e08a0e2018-09-06 19:22:47 -0400760 model = await self.get_model(model_name)
Adam Israelb5214512018-05-03 10:00:04 -0400761
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500762 if primitive == 'config':
763 # config is special, and expecting params to be a dictionary
Adam Israelb0943662018-08-02 15:32:00 -0400764 await self.set_config(
765 model,
766 application_name,
767 params['params'],
768 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500769 else:
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500770 app = await self.get_application(model, application_name)
771 if app:
772 # Run against the first (and probably only) unit in the app
773 unit = app.units[0]
774 if unit:
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500775 action = await unit.run_action(primitive, **params)
Adam Israel6817f612018-04-13 08:41:43 -0600776 uuid = action.id
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500777 except Exception as e:
Adam Israelb0943662018-08-02 15:32:00 -0400778 self.log.debug(
779 "Caught exception while executing primitive: {}".format(e)
780 )
Adam Israel7d871fb2018-07-17 12:17:06 -0400781 raise N2VCPrimitiveExecutionFailed(e)
Adam Israel6817f612018-04-13 08:41:43 -0600782 return uuid
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500783
Adam Israel5e08a0e2018-09-06 19:22:47 -0400784 async def RemoveCharms(self, model_name, application_name, callback=None,
785 *callback_args):
Adam Israelc9df96f2018-05-03 14:49:56 -0400786 """Remove a charm from the VCA.
787
788 Remove a charm referenced in a VNF Descriptor.
789
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.
Adam Israel5e08a0e2018-09-06 19:22:47 -0400793 :param tuple callback_args: A list of arguments to be passed to the
794 callback function.
Adam Israelc9df96f2018-05-03 14:49:56 -0400795 """
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500796 try:
797 if not self.authenticated:
798 await self.login()
799
800 model = await self.get_model(model_name)
801 app = await self.get_application(model, application_name)
802 if app:
Adam Israel28a43c02018-04-23 16:04:54 -0400803 # Remove this application from event monitoring
Adam Israel04eee1f2019-04-29 14:59:45 -0400804 await self.Unsubscribe(model_name, application_name)
Adam Israel28a43c02018-04-23 16:04:54 -0400805
806 # self.notify_callback(model_name, application_name, "removing", callback, *callback_args)
Adam Israel5e08a0e2018-09-06 19:22:47 -0400807 self.log.debug(
808 "Removing the application {}".format(application_name)
809 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500810 await app.remove()
Adam Israel28a43c02018-04-23 16:04:54 -0400811
Adam Israel85a4b212018-11-29 20:30:24 -0500812 await self.disconnect_model(self.monitors[model_name])
813
Adam Israel5e08a0e2018-09-06 19:22:47 -0400814 self.notify_callback(
815 model_name,
816 application_name,
817 "removed",
Adam Israelc4f393e2019-03-19 16:33:30 -0400818 "Removing charm {}".format(application_name),
Adam Israel5e08a0e2018-09-06 19:22:47 -0400819 callback,
820 *callback_args,
821 )
Adam Israel28a43c02018-04-23 16:04:54 -0400822
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500823 except Exception as e:
824 print("Caught exception: {}".format(e))
Adam Israel88a49632018-04-10 13:04:57 -0600825 self.log.debug(e)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500826 raise e
827
Adam Israel6d84dbd2019-03-08 18:33:35 -0500828 async def CreateNetworkService(self, ns_uuid):
829 """Create a new Juju model for the Network Service.
830
831 Creates a new Model in the Juju Controller.
832
833 :param str ns_uuid: A unique id representing an instaance of a
834 Network Service.
835
836 :returns: True if the model was created. Raises JujuError on failure.
837 """
838 if not self.authenticated:
839 await self.login()
840
841 models = await self.controller.list_models()
842 if ns_uuid not in models:
843 try:
844 self.models[ns_uuid] = await self.controller.add_model(
845 ns_uuid
846 )
847 except JujuError as e:
848 if "already exists" not in e.message:
849 raise e
Adam Israel7bf2f4d2019-03-15 15:28:47 -0400850
851 # Create an observer for this model
852 await self.create_model_monitor(ns_uuid)
853
Adam Israel6d84dbd2019-03-08 18:33:35 -0500854 return True
855
856 async def DestroyNetworkService(self, ns_uuid):
857 """Destroy a Network Service.
858
859 Destroy the Network Service and any deployed charms.
860
861 :param ns_uuid The unique id of the Network Service
862
863 :returns: True if the model was created. Raises JujuError on failure.
864 """
865
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.
Adam Israelc4f393e2019-03-19 16:33:30 -0400868 if ns_uuid.lower() == "default":
Adam Israel6d84dbd2019-03-08 18:33:35 -0500869 return False
870
871 if not self.authenticated:
872 self.log.debug("Authenticating with Juju")
873 await self.login()
874
875 # Disconnect from the Model
876 if ns_uuid in self.models:
877 await self.disconnect_model(self.models[ns_uuid])
878
879 try:
880 await self.controller.destroy_models(ns_uuid)
Adam Israelc4f393e2019-03-19 16:33:30 -0400881 except JujuError:
Adam Israel6d84dbd2019-03-08 18:33:35 -0500882 raise NetworkServiceDoesNotExist(
883 "The Network Service '{}' does not exist".format(ns_uuid)
884 )
885
886 return True
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500887
Adam Israelb5214512018-05-03 10:00:04 -0400888 async def GetMetrics(self, model_name, application_name):
889 """Get the metrics collected by the VCA.
890
Adam Israel85a4b212018-11-29 20:30:24 -0500891 :param model_name The name or unique id of the network service
Adam Israelb5214512018-05-03 10:00:04 -0400892 :param application_name The name of the application
893 """
894 metrics = {}
895 model = await self.get_model(model_name)
896 app = await self.get_application(model, application_name)
897 if app:
898 metrics = await app.get_metrics()
899
900 return metrics
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500901
Adam Israelfa329072018-09-14 11:26:13 -0400902 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)
905 if app:
906 return True
907 return False
908
Adam Israel04eee1f2019-04-29 14:59:45 -0400909 async def Subscribe(self, ns_name, application_name, callback, *callback_args):
910 """Subscribe to callbacks for an application.
911
912 :param ns_name str: The name of the Network Service
913 :param application_name str: The name of the application
914 :param callback obj: The callback method
915 :param callback_args list: The list of arguments to append to calls to
916 the callback method
917 """
918 self.monitors[ns_name].AddApplication(
919 application_name,
920 callback,
921 *callback_args
922 )
923
924 async def Unsubscribe(self, ns_name, application_name):
925 """Unsubscribe to callbacks for an application.
926
927 Unsubscribes the caller from notifications from a deployed application.
928
929 :param ns_name str: The name of the Network Service
930 :param application_name str: The name of the application
931 """
932 self.monitors[ns_name].RemoveApplication(
933 application_name,
934 )
935
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500936 # Non-public methods
Adam Israel136186e2018-09-14 12:01:12 -0400937 async def add_relation(self, model_name, relation1, relation2):
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500938 """
939 Add a relation between two application endpoints.
940
Adam Israel85a4b212018-11-29 20:30:24 -0500941 :param str model_name: The name or unique id of the network service
942 :param str relation1: '<application>[:<relation_name>]'
943 :param str relation2: '<application>[:<relation_name>]'
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500944 """
Adam Israel136186e2018-09-14 12:01:12 -0400945
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500946 if not self.authenticated:
947 await self.login()
948
Adam Israel136186e2018-09-14 12:01:12 -0400949 m = await self.get_model(model_name)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500950 try:
Adam Israel136186e2018-09-14 12:01:12 -0400951 await m.add_relation(relation1, relation2)
952 except JujuAPIError as e:
953 # If one of the applications in the relationship doesn't exist,
954 # or the relation has already been added, let the operation fail
955 # silently.
956 if 'not found' in e.message:
957 return
958 if 'already exists' in e.message:
959 return
960
961 raise e
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500962
Adam Israelb5214512018-05-03 10:00:04 -0400963 # async def apply_config(self, config, application):
964 # """Apply a configuration to the application."""
965 # print("JujuApi: Applying configuration to {}.".format(
966 # application
967 # ))
968 # return await self.set_config(application=application, config=config)
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500969
970 def _get_config_from_dict(self, config_primitive, values):
Adam Israel88a49632018-04-10 13:04:57 -0600971 """Transform the yang config primitive to dict.
972
973 Expected result:
974
975 config = {
976 'config':
977 }
978 """
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500979 config = {}
980 for primitive in config_primitive:
981 if primitive['name'] == 'config':
Adam Israel88a49632018-04-10 13:04:57 -0600982 # config = self._map_primitive_parameters()
Adam Israelc3e6c2e2018-03-01 09:31:50 -0500983 for parameter in primitive['parameter']:
984 param = str(parameter['name'])
985 if parameter['value'] == "<rw_mgmt_ip>":
986 config[param] = str(values[parameter['value']])
987 else:
988 config[param] = str(parameter['value'])
989
990 return config
991
tierno1afb30a2018-12-21 13:42:43 +0000992 def _map_primitive_parameters(self, parameters, user_values):
Adam Israel88a49632018-04-10 13:04:57 -0600993 params = {}
994 for parameter in parameters:
995 param = str(parameter['name'])
tierno1afb30a2018-12-21 13:42:43 +0000996 value = parameter.get('value')
997
998 # map parameters inside a < >; e.g. <rw_mgmt_ip>. with the provided user_values.
999 # Must exist at user_values except if there is a default value
1000 if isinstance(value, str) and value.startswith("<") and value.endswith(">"):
1001 if parameter['value'][1:-1] in user_values:
1002 value = user_values[parameter['value'][1:-1]]
1003 elif 'default-value' in parameter:
1004 value = parameter['default-value']
1005 else:
1006 raise KeyError("parameter {}='{}' not supplied ".format(param, value))
Adam Israel5e08a0e2018-09-06 19:22:47 -04001007
Adam Israelbf793522018-11-20 13:54:13 -05001008 # If there's no value, use the default-value (if set)
tierno1afb30a2018-12-21 13:42:43 +00001009 if value is None and 'default-value' in parameter:
Adam Israelbf793522018-11-20 13:54:13 -05001010 value = parameter['default-value']
1011
Adam Israel5e08a0e2018-09-06 19:22:47 -04001012 # Typecast parameter value, if present
tierno1afb30a2018-12-21 13:42:43 +00001013 paramtype = "string"
1014 try:
1015 if 'data-type' in parameter:
1016 paramtype = str(parameter['data-type']).lower()
Adam Israel5e08a0e2018-09-06 19:22:47 -04001017
tierno1afb30a2018-12-21 13:42:43 +00001018 if paramtype == "integer":
1019 value = int(value)
1020 elif paramtype == "boolean":
1021 value = bool(value)
1022 else:
1023 value = str(value)
Adam Israel5e08a0e2018-09-06 19:22:47 -04001024 else:
tierno1afb30a2018-12-21 13:42:43 +00001025 # If there's no data-type, assume the value is a string
1026 value = str(value)
1027 except ValueError:
1028 raise ValueError("parameter {}='{}' cannot be converted to type {}".format(param, value, paramtype))
Adam Israel5e08a0e2018-09-06 19:22:47 -04001029
tierno1afb30a2018-12-21 13:42:43 +00001030 params[param] = value
Adam Israel88a49632018-04-10 13:04:57 -06001031 return params
1032
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001033 def _get_config_from_yang(self, config_primitive, values):
1034 """Transform the yang config primitive to dict."""
1035 config = {}
1036 for primitive in config_primitive.values():
1037 if primitive['name'] == 'config':
1038 for parameter in primitive['parameter'].values():
1039 param = str(parameter['name'])
1040 if parameter['value'] == "<rw_mgmt_ip>":
1041 config[param] = str(values[parameter['value']])
1042 else:
1043 config[param] = str(parameter['value'])
1044
1045 return config
1046
1047 def FormatApplicationName(self, *args):
1048 """
1049 Generate a Juju-compatible Application name
1050
1051 :param args tuple: Positional arguments to be used to construct the
1052 application name.
1053
1054 Limitations::
1055 - Only accepts characters a-z and non-consequitive dashes (-)
1056 - Application name should not exceed 50 characters
1057
1058 Examples::
1059
1060 FormatApplicationName("ping_pong_ns", "ping_vnf", "a")
1061 """
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001062 appname = ""
1063 for c in "-".join(list(args)):
1064 if c.isdigit():
1065 c = chr(97 + int(c))
1066 elif not c.isalpha():
1067 c = "-"
1068 appname += c
Adam Israel6d84dbd2019-03-08 18:33:35 -05001069 return re.sub('-+', '-', appname.lower())
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001070
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001071 # def format_application_name(self, nsd_name, vnfr_name, member_vnf_index=0):
1072 # """Format the name of the application
1073 #
1074 # Limitations:
1075 # - Only accepts characters a-z and non-consequitive dashes (-)
1076 # - Application name should not exceed 50 characters
1077 # """
1078 # name = "{}-{}-{}".format(nsd_name, vnfr_name, member_vnf_index)
1079 # new_name = ''
1080 # for c in name:
1081 # if c.isdigit():
1082 # c = chr(97 + int(c))
1083 # elif not c.isalpha():
1084 # c = "-"
1085 # new_name += c
1086 # return re.sub('\-+', '-', new_name.lower())
1087
1088 def format_model_name(self, name):
1089 """Format the name of model.
1090
1091 Model names may only contain lowercase letters, digits and hyphens
1092 """
1093
1094 return name.replace('_', '-').lower()
1095
1096 async def get_application(self, model, application):
1097 """Get the deployed application."""
1098 if not self.authenticated:
1099 await self.login()
1100
1101 app = None
1102 if application and model:
1103 if model.applications:
1104 if application in model.applications:
1105 app = model.applications[application]
1106
1107 return app
1108
Adam Israel85a4b212018-11-29 20:30:24 -05001109 async def get_model(self, model_name):
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001110 """Get a model from the Juju Controller.
1111
1112 Note: Model objects returned must call disconnected() before it goes
1113 out of scope."""
1114 if not self.authenticated:
1115 await self.login()
1116
1117 if model_name not in self.models:
Adam Israel85a4b212018-11-29 20:30:24 -05001118 # Get the models in the controller
1119 models = await self.controller.list_models()
1120
1121 if model_name not in models:
Adam Israel6d84dbd2019-03-08 18:33:35 -05001122 try:
1123 self.models[model_name] = await self.controller.add_model(
1124 model_name
1125 )
1126 except JujuError as e:
1127 if "already exists" not in e.message:
1128 raise e
Adam Israel85a4b212018-11-29 20:30:24 -05001129 else:
1130 self.models[model_name] = await self.controller.get_model(
1131 model_name
1132 )
1133
Adam Israelfc511ed2018-09-21 14:20:55 +02001134 self.refcount['model'] += 1
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001135
Adam Israel28a43c02018-04-23 16:04:54 -04001136 # Create an observer for this model
Adam Israel7bf2f4d2019-03-15 15:28:47 -04001137 await self.create_model_monitor(model_name)
1138
1139 return self.models[model_name]
1140
1141 async def create_model_monitor(self, model_name):
1142 """Create a monitor for the model, if none exists."""
1143 if not self.authenticated:
1144 await self.login()
1145
1146 if model_name not in self.monitors:
Adam Israel28a43c02018-04-23 16:04:54 -04001147 self.monitors[model_name] = VCAMonitor(model_name)
1148 self.models[model_name].add_observer(self.monitors[model_name])
1149
Adam Israel7bf2f4d2019-03-15 15:28:47 -04001150 return True
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001151
1152 async def login(self):
1153 """Login to the Juju controller."""
1154
1155 if self.authenticated:
1156 return
1157
1158 self.connecting = True
1159
1160 self.log.debug("JujuApi: Logging into controller")
1161
Adam Israel5e08a0e2018-09-06 19:22:47 -04001162 self.controller = Controller(loop=self.loop)
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001163
1164 if self.secret:
Adam Israel5e08a0e2018-09-06 19:22:47 -04001165 self.log.debug(
1166 "Connecting to controller... ws://{}:{} as {}/{}".format(
1167 self.endpoint,
1168 self.port,
1169 self.user,
1170 self.secret,
1171 )
1172 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001173 await self.controller.connect(
1174 endpoint=self.endpoint,
1175 username=self.user,
1176 password=self.secret,
Adam Israelb2a07f52019-04-25 17:17:05 -04001177 cacert=self.ca_cert,
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001178 )
Adam Israelfc511ed2018-09-21 14:20:55 +02001179 self.refcount['controller'] += 1
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001180 else:
1181 # current_controller no longer exists
1182 # self.log.debug("Connecting to current controller...")
1183 # await self.controller.connect_current()
Adam Israel88a49632018-04-10 13:04:57 -06001184 # await self.controller.connect(
1185 # endpoint=self.endpoint,
1186 # username=self.user,
1187 # cacert=cacert,
1188 # )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001189 self.log.fatal("VCA credentials not configured.")
1190
1191 self.authenticated = True
1192 self.log.debug("JujuApi: Logged into controller")
1193
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001194 async def logout(self):
1195 """Logout of the Juju controller."""
1196 if not self.authenticated:
Adam Israel6d84dbd2019-03-08 18:33:35 -05001197 return False
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001198
1199 try:
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001200 for model in self.models:
Adam Israel85a4b212018-11-29 20:30:24 -05001201 await self.disconnect_model(model)
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001202
1203 if self.controller:
Adam Israel5e08a0e2018-09-06 19:22:47 -04001204 self.log.debug("Disconnecting controller {}".format(
1205 self.controller
1206 ))
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001207 await self.controller.disconnect()
Adam Israelfc511ed2018-09-21 14:20:55 +02001208 self.refcount['controller'] -= 1
Adam Israel5e08a0e2018-09-06 19:22:47 -04001209 self.controller = None
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001210
1211 self.authenticated = False
Adam Israelfc511ed2018-09-21 14:20:55 +02001212
1213 self.log.debug(self.refcount)
1214
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001215 except Exception as e:
Adam Israel5e08a0e2018-09-06 19:22:47 -04001216 self.log.fatal(
1217 "Fatal error logging out of Juju Controller: {}".format(e)
1218 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001219 raise e
Adam Israel6d84dbd2019-03-08 18:33:35 -05001220 return True
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001221
Adam Israel85a4b212018-11-29 20:30:24 -05001222 async def disconnect_model(self, model):
1223 self.log.debug("Disconnecting model {}".format(model))
1224 if model in self.models:
Adam Israel85a4b212018-11-29 20:30:24 -05001225 print("Disconnecting model")
1226 await self.models[model].disconnect()
1227 self.refcount['model'] -= 1
1228 self.models[model] = None
1229
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001230 # async def remove_application(self, name):
1231 # """Remove the application."""
1232 # if not self.authenticated:
1233 # await self.login()
1234 #
1235 # app = await self.get_application(name)
1236 # if app:
1237 # self.log.debug("JujuApi: Destroying application {}".format(
1238 # name,
1239 # ))
1240 #
1241 # await app.destroy()
1242
1243 async def remove_relation(self, a, b):
1244 """
1245 Remove a relation between two application endpoints
1246
1247 :param a An application endpoint
1248 :param b An application endpoint
1249 """
1250 if not self.authenticated:
1251 await self.login()
1252
1253 m = await self.get_model()
1254 try:
1255 m.remove_relation(a, b)
1256 finally:
1257 await m.disconnect()
1258
Adam Israel85a4b212018-11-29 20:30:24 -05001259 async def resolve_error(self, model_name, application=None):
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001260 """Resolve units in error state."""
1261 if not self.authenticated:
1262 await self.login()
1263
Adam Israel85a4b212018-11-29 20:30:24 -05001264 model = await self.get_model(model_name)
1265
1266 app = await self.get_application(model, application)
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001267 if app:
Adam Israel5e08a0e2018-09-06 19:22:47 -04001268 self.log.debug(
1269 "JujuApi: Resolving errors for application {}".format(
1270 application,
1271 )
1272 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001273
1274 for unit in app.units:
1275 app.resolved(retry=True)
1276
Adam Israel85a4b212018-11-29 20:30:24 -05001277 async def run_action(self, model_name, application, action_name, **params):
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001278 """Execute an action and return an Action object."""
1279 if not self.authenticated:
1280 await self.login()
1281 result = {
1282 'status': '',
1283 'action': {
1284 'tag': None,
1285 'results': None,
1286 }
1287 }
Adam Israel85a4b212018-11-29 20:30:24 -05001288
1289 model = await self.get_model(model_name)
1290
1291 app = await self.get_application(model, application)
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001292 if app:
1293 # We currently only have one unit per application
1294 # so use the first unit available.
1295 unit = app.units[0]
1296
Adam Israel5e08a0e2018-09-06 19:22:47 -04001297 self.log.debug(
1298 "JujuApi: Running Action {} against Application {}".format(
1299 action_name,
1300 application,
1301 )
1302 )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001303
1304 action = await unit.run_action(action_name, **params)
1305
1306 # Wait for the action to complete
1307 await action.wait()
1308
1309 result['status'] = action.status
1310 result['action']['tag'] = action.data['id']
1311 result['action']['results'] = action.results
1312
1313 return result
1314
Adam Israelb5214512018-05-03 10:00:04 -04001315 async def set_config(self, model_name, application, config):
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001316 """Apply a configuration to the application."""
1317 if not self.authenticated:
1318 await self.login()
1319
Adam Israelb5214512018-05-03 10:00:04 -04001320 app = await self.get_application(model_name, application)
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001321 if app:
1322 self.log.debug("JujuApi: Setting config for Application {}".format(
1323 application,
1324 ))
1325 await app.set_config(config)
1326
1327 # Verify the config is set
1328 newconf = await app.get_config()
1329 for key in config:
1330 if config[key] != newconf[key]['value']:
1331 self.log.debug("JujuApi: Config not set! Key {} Value {} doesn't match {}".format(key, config[key], newconf[key]))
1332
Adam Israelb5214512018-05-03 10:00:04 -04001333 # async def set_parameter(self, parameter, value, application=None):
1334 # """Set a config parameter for a service."""
1335 # if not self.authenticated:
1336 # await self.login()
1337 #
1338 # self.log.debug("JujuApi: Setting {}={} for Application {}".format(
1339 # parameter,
1340 # value,
1341 # application,
1342 # ))
1343 # return await self.apply_config(
1344 # {parameter: value},
1345 # application=application,
1346 # )
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001347
Adam Israel5e08a0e2018-09-06 19:22:47 -04001348 async def wait_for_application(self, model_name, application_name,
1349 timeout=300):
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001350 """Wait for an application to become active."""
1351 if not self.authenticated:
1352 await self.login()
1353
Adam Israel5e08a0e2018-09-06 19:22:47 -04001354 model = await self.get_model(model_name)
1355
1356 app = await self.get_application(model, application_name)
1357 self.log.debug("Application: {}".format(app))
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001358 if app:
1359 self.log.debug(
1360 "JujuApi: Waiting {} seconds for Application {}".format(
1361 timeout,
Adam Israel5e08a0e2018-09-06 19:22:47 -04001362 application_name,
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001363 )
1364 )
1365
Adam Israel5e08a0e2018-09-06 19:22:47 -04001366 await model.block_until(
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001367 lambda: all(
Adam Israel5e08a0e2018-09-06 19:22:47 -04001368 unit.agent_status == 'idle' and unit.workload_status in
1369 ['active', 'unknown'] for unit in app.units
Adam Israelc3e6c2e2018-03-01 09:31:50 -05001370 ),
1371 timeout=timeout
1372 )