Add MANO project role support
[osm/SO.git] / common / python / rift / mano / config_agent / operdata.py
1 #
2 # Copyright 2016 RIFT.IO Inc
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 import asyncio
18 import concurrent.futures
19 import time
20
21 from gi.repository import (
22 NsrYang,
23 RwTypes,
24 RwcalYang,
25 RwNsrYang,
26 RwConfigAgentYang,
27 RwDts as rwdts)
28
29 import rift.tasklets
30 import rift.mano.utils.juju_api as juju
31
32
33 class ConfigAgentAccountNotFound(Exception):
34 pass
35
36 class JujuClient(object):
37 def __init__(self, log, ip, port, user, passwd):
38 self._log = log
39 self._ip = ip
40 self._port = port
41 self._user = user
42 self._passwd = passwd
43
44 self._api = juju.JujuApi(log=log,
45 server=ip, port=port,
46 user=user, secret=passwd)
47
48
49 def validate_account_creds(self):
50 status = RwcalYang.CloudConnectionStatus()
51 try:
52 env = self._api._get_env()
53 except juju.JujuEnvError as e:
54 msg = "JujuClient: Invalid account credentials: %s", str(e)
55 self._log.error(msg)
56 raise Exception(msg)
57 except ConnectionRefusedError as e:
58 msg = "JujuClient: Wrong IP or Port: %s", str(e)
59 self._log.error(msg)
60 raise Exception(msg)
61 except Exception as e:
62 msg = "JujuClient: Connection Failed: %s", str(e)
63 self._log.error(msg)
64 raise Exception(msg)
65 else:
66 status.status = "success"
67 status.details = "Connection was successful"
68 self._log.info("JujuClient: Connection Successful")
69
70 return status
71
72
73 class ConfigAgentAccount(object):
74 def __init__(self, log, account_msg):
75 self._log = log
76 self._account_msg = account_msg.deep_copy()
77
78 if account_msg.account_type == "juju":
79 self._cfg_agent_client_plugin = JujuClient(
80 log,
81 account_msg.juju.ip_address,
82 account_msg.juju.port,
83 account_msg.juju.user,
84 account_msg.juju.secret)
85 else:
86 self._cfg_agent_client_plugin = None
87
88 self._status = RwConfigAgentYang.ConfigAgentAccount_ConnectionStatus(
89 status="unknown",
90 details="Connection status lookup not started"
91 )
92
93 self._validate_task = None
94
95 @property
96 def name(self):
97 return self._account_msg.name
98
99 @property
100 def account_msg(self):
101 return self._account_msg
102
103 @property
104 def account_type(self):
105 return self._account_msg.account_type
106
107 @property
108 def connection_status(self):
109 return self._status
110
111 def update_from_cfg(self, cfg):
112 self._log.debug("Updating parent ConfigAgentAccount to %s", cfg)
113 raise NotImplementedError("Update config agent account not yet supported")
114
115 @asyncio.coroutine
116 def validate_cfg_agent_account_credentials(self, loop):
117 self._log.debug("Validating Config Agent Account %s, credential status %s", self._account_msg, self._status)
118
119 self._status = RwConfigAgentYang.ConfigAgentAccount_ConnectionStatus(
120 status="validating",
121 details="Config Agent account connection validation in progress"
122 )
123
124 if self._cfg_agent_client_plugin is None:
125 self._status = RwConfigAgentYang.ConfigAgentAccount_ConnectionStatus(
126 status="unknown",
127 details="Config Agent account does not support validation of account creds"
128 )
129 else:
130 try:
131 status = yield from loop.run_in_executor(
132 None,
133 self._cfg_agent_client_plugin.validate_account_creds
134 )
135 self._status = RwConfigAgentYang.ConfigAgentAccount_ConnectionStatus.from_dict(status.as_dict())
136 except Exception as e:
137 self._status = RwConfigAgentYang.ConfigAgentAccount_ConnectionStatus(
138 status="failure",
139 details="Error - " + str(e)
140 )
141
142 self._log.info("Got config agent account validation response: %s", self._status)
143
144 def start_validate_credentials(self, loop):
145 if self._validate_task is not None:
146 self._validate_task.cancel()
147 self._validate_task = None
148
149 self._validate_task = asyncio.ensure_future(
150 self.validate_cfg_agent_account_credentials(loop),
151 loop=loop
152 )
153
154 class CfgAgentDtsOperdataHandler(object):
155 def __init__(self, dts, log, loop, project):
156 self._dts = dts
157 self._log = log
158 self._loop = loop
159 self._project = project
160
161 self.cfg_agent_accounts = {}
162 self._show_reg = None
163 self._rpc_reg = None
164
165 def add_cfg_agent_account(self, account_msg):
166 account = ConfigAgentAccount(self._log, account_msg)
167 self.cfg_agent_accounts[account.name] = account
168 self._log.info("ConfigAgent Operdata Handler added. Starting account validation")
169
170 account.start_validate_credentials(self._loop)
171
172 def delete_cfg_agent_account(self, account_name):
173 del self.cfg_agent_accounts[account_name]
174 self._log.info("ConfigAgent Operdata Handler deleted.")
175
176 def get_saved_cfg_agent_accounts(self, cfg_agent_account_name):
177 ''' Get Config Agent Account corresponding to passed name, or all saved accounts if name is None'''
178 saved_cfg_agent_accounts = []
179
180 if cfg_agent_account_name is None or cfg_agent_account_name == "":
181 cfg_agent_accounts = list(self.cfg_agent_accounts.values())
182 saved_cfg_agent_accounts.extend(cfg_agent_accounts)
183 elif cfg_agent_account_name in self.cfg_agent_accounts:
184 account = self.cfg_agent_accounts[cfg_agent_account_name]
185 saved_cfg_agent_accounts.append(account)
186 else:
187 errstr = "Config Agent account {} does not exist".format(cfg_agent_account_name)
188 raise KeyError(errstr)
189
190 return saved_cfg_agent_accounts
191
192
193 def _register_show_status(self):
194 def get_xpath(cfg_agent_name=None):
195 return "D,/rw-config-agent:config-agent/account{}/connection-status".format(
196 "[name='%s']" % cfg_agent_name if cfg_agent_name is not None else ''
197 )
198
199 @asyncio.coroutine
200 def on_prepare(xact_info, action, ks_path, msg):
201 path_entry = RwConfigAgentYang.ConfigAgentAccount.schema().keyspec_to_entry(ks_path)
202 cfg_agent_account_name = path_entry.key00.name
203 self._log.debug("Got show cfg_agent connection status request: %s", ks_path.create_string())
204
205 try:
206 saved_accounts = self.get_saved_cfg_agent_accounts(cfg_agent_account_name)
207 for account in saved_accounts:
208 connection_status = account.connection_status
209 self._log.debug("Responding to config agent connection status request: %s", connection_status)
210 xpath = self._project.add_project(get_xpath(account.name))
211 xact_info.respond_xpath(
212 rwdts.XactRspCode.MORE,
213 xpath=xpath,
214 msg=account.connection_status,
215 )
216 except KeyError as e:
217 self._log.warning(str(e))
218 xact_info.respond_xpath(rwdts.XactRspCode.NA)
219 return
220
221 xact_info.respond_xpath(rwdts.XactRspCode.ACK)
222
223 xpath = self._project.add_project(get_xpath())
224 self._show_reg = yield from self._dts.register(
225 xpath=xpath,
226 handler=rift.tasklets.DTS.RegistrationHandler(
227 on_prepare=on_prepare),
228 flags=rwdts.Flag.PUBLISHER,
229 )
230
231 def _register_validate_rpc(self):
232 def get_xpath():
233 return "/rw-config-agent:update-cfg-agent-status"
234
235 @asyncio.coroutine
236 def on_prepare(xact_info, action, ks_path, msg):
237 if not msg.has_field("cfg_agent_account"):
238 raise ConfigAgentAccountNotFound("Config Agent account name not provided")
239
240 cfg_agent_account_name = msg.cfg_agent_account
241
242 if not self._project.rpc_check(msg, xact_info=xact_info):
243 return
244
245 try:
246 account = self.cfg_agent_accounts[cfg_agent_account_name]
247 except KeyError:
248 raise ConfigAgentAccountNotFound("Config Agent account name %s not found" % cfg_agent_account_name)
249
250 account.start_validate_credentials(self._loop)
251
252 xact_info.respond_xpath(rwdts.XactRspCode.ACK)
253
254 self._rpc_reg = yield from self._dts.register(
255 xpath=get_xpath(),
256 handler=rift.tasklets.DTS.RegistrationHandler(
257 on_prepare=on_prepare
258 ),
259 flags=rwdts.Flag.PUBLISHER,
260 )
261
262 @asyncio.coroutine
263 def register(self):
264 yield from self._register_show_status()
265 yield from self._register_validate_rpc()
266
267 def deregister(self):
268 self._show_reg.deregister()
269 self._rpc_reg.deregister()
270
271
272 class ConfigAgentJob(object):
273 """A wrapper over the config agent job object, providing some
274 convenience functions.
275
276 YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob contains
277 ||
278 ==> VNFRS
279 ||
280 ==> Primitives
281
282 """
283 # The normalizes the state terms from Juju to our yang models
284 # Juju : Yang model
285 STATUS_MAP = {"completed": "success",
286 "pending" : "pending",
287 "running" : "pending",
288 "failed" : "failure"}
289
290 def __init__(self, nsr_id, job, project, tasks=None):
291 """
292 Args:
293 nsr_id (uuid): ID of NSR record
294 job (YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob): Gi object
295 tasks: List of asyncio.tasks. If provided the job monitor will
296 use it to monitor the tasks instead of the execution IDs
297 """
298 self._job = job
299 self.nsr_id = nsr_id
300 self.tasks = tasks
301 self._project = project
302
303 self._regh = None
304
305 @property
306 def id(self):
307 """Job id"""
308 return self._job.job_id
309
310 @property
311 def name(self):
312 """Job name"""
313 return self._job.job_name
314
315 @property
316 def job_status(self):
317 """Status of the job (success|pending|failure)"""
318 return self._job.job_status
319
320 @job_status.setter
321 def job_status(self, value):
322 """Setter for job status"""
323 self._job.job_status = value
324
325 @property
326 def job(self):
327 """Gi object"""
328 return self._job
329
330 @property
331 def xpath(self):
332 """Xpath of the job"""
333 return self._project.add_project(("D,/nsr:ns-instance-opdata" +
334 "/nsr:nsr[nsr:ns-instance-config-ref='{}']" +
335 "/nsr:config-agent-job[nsr:job-id='{}']"
336 ).format(self.nsr_id, self.id))
337
338 @property
339 def regh(self):
340 """Registration handle for the job"""
341 return self._regh
342
343 @regh.setter
344 def regh(self, hdl):
345 """Setter for registration handle"""
346 self._regh = hdl
347
348 @staticmethod
349 def convert_rpc_input_to_job(nsr_id, rpc_output, tasks):
350 """A helper function to convert the YangOutput_Nsr_ExecNsConfigPrimitive
351 to YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob (NsrYang)
352
353 Args:
354 nsr_id (uuid): NSR ID
355 rpc_output (YangOutput_Nsr_ExecNsConfigPrimitive): RPC output
356 tasks (list): A list of asyncio.Tasks
357
358 Returns:
359 ConfigAgentJob
360 """
361 # Shortcuts to prevent the HUUGE names.
362 CfgAgentJob = NsrYang.YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob
363 CfgAgentVnfr = NsrYang.YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob_Vnfr
364 CfgAgentPrimitive = NsrYang.YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob_Vnfr_Primitive
365 CfgAgentPrimitiveParam = NsrYang.YangData_RwProject_Project_NsInstanceOpdata_Nsr_ConfigAgentJob_Vnfr_Primitive_Parameter
366
367 job = CfgAgentJob.from_dict({
368 "job_id": rpc_output.job_id,
369 "job_name" : rpc_output.name,
370 "job_status": "pending",
371 "triggered_by": rpc_output.triggered_by,
372 "create_time": rpc_output.create_time,
373 "job_status_details": rpc_output.job_status_details if rpc_output.job_status_details is not None else None,
374 "parameter": [param.as_dict() for param in rpc_output.parameter],
375 "parameter_group": [pg.as_dict() for pg in rpc_output.parameter_group]
376 })
377
378 for vnfr in rpc_output.vnf_out_list:
379 vnfr_job = CfgAgentVnfr.from_dict({
380 "id": vnfr.vnfr_id_ref,
381 "vnf_job_status": "pending",
382 })
383
384 for primitive in vnfr.vnf_out_primitive:
385 vnf_primitive = CfgAgentPrimitive.from_dict({
386 "name": primitive.name,
387 "execution_status": ConfigAgentJob.STATUS_MAP[primitive.execution_status],
388 "execution_id": primitive.execution_id
389 })
390
391 # Copy over the input param
392 for param in primitive.parameter:
393 vnf_primitive.parameter.append(
394 CfgAgentPrimitiveParam.from_dict({
395 "name": param.name,
396 "value": param.value
397 }))
398
399 vnfr_job.primitive.append(vnf_primitive)
400
401 job.vnfr.append(vnfr_job)
402
403 return ConfigAgentJob(nsr_id, job, project, tasks)
404
405
406 class ConfigAgentJobMonitor(object):
407 """Job monitor: Polls the Juju controller and get the status.
408 Rules:
409 If all Primitive are success, then vnf & nsr status will be "success"
410 If any one Primitive reaches a failed state then both vnf and nsr will fail.
411 """
412 POLLING_PERIOD = 2
413
414 def __init__(self, dts, log, job, executor, loop, config_plugin):
415 """
416 Args:
417 dts : DTS handle
418 log : log handle
419 job (ConfigAgentJob): ConfigAgentJob instance
420 executor (concurrent.futures): Executor for juju status api calls
421 loop (eventloop): Current event loop instance
422 config_plugin : Config plugin to be used.
423 """
424 self.job = job
425 self.log = log
426 self.loop = loop
427 self.executor = executor
428 self.polling_period = ConfigAgentJobMonitor.POLLING_PERIOD
429 self.config_plugin = config_plugin
430 self.dts = dts
431
432 @asyncio.coroutine
433 def _monitor_processes(self, registration_handle):
434 result = 0
435 errs = ""
436 for process in self.job.tasks:
437 if isinstance(process, asyncio.subprocess.Process):
438 rc = yield from process.wait()
439 err = yield from process.stderr.read()
440
441 else:
442 # Task instance
443 rc = yield from process
444 err = ''
445
446 self.log.debug("Process {} returned rc: {}, err: {}".
447 format(process, rc, err))
448
449 if len(err):
450 errs += "<error>{}</error>".format(err)
451 result |= rc
452
453 if result == 0:
454 self.job.job_status = "success"
455 else:
456 self.job.job_status = "failure"
457
458 if len(errs):
459 self.job.job.job_status_details = errs
460
461 registration_handle.update_element(self.job.xpath, self.job.job)
462
463 def get_error_details(self):
464 '''Get the error details from failed primitives'''
465 errs = ''
466 for vnfr in self.job.job.vnfr:
467 if vnfr.vnf_job_status != "failure":
468 continue
469
470 for primitive in vnfr.primitive:
471 if primitive.execution_status == "failure":
472 errs += '<error>'
473 if primitive.execution_error_details:
474 errs += primitive.execution_error_details
475 else:
476 errs += '{}: Unknown error'.format(primitive.name)
477 errs += "</error>"
478
479 return errs
480
481 @asyncio.coroutine
482 def publish_action_status(self):
483 """
484 Starts publishing the status for jobs/primitives
485 """
486 registration_handle = yield from self.dts.register(
487 xpath=self.job.xpath,
488 handler=rift.tasklets.DTS.RegistrationHandler(),
489 flags=(rwdts.Flag.PUBLISHER | rwdts.Flag.NO_PREP_READ),
490 )
491
492 self.log.debug('preparing to publish job status for {}'.format(self.job.xpath))
493 self.job.regh = registration_handle
494
495 try:
496 registration_handle.create_element(self.job.xpath, self.job.job)
497
498 # If the config is done via a user defined script
499 if self.job.tasks is not None:
500 yield from self._monitor_processes(registration_handle)
501 return
502
503 prev = time.time()
504 # Run until pending moves to either failure/success
505 while self.job.job_status == "pending":
506 curr = time.time()
507
508 if curr - prev < self.polling_period:
509 pause = self.polling_period - (curr - prev)
510 yield from asyncio.sleep(pause, loop=self.loop)
511
512 prev = time.time()
513
514 tasks = []
515 for vnfr in self.job.job.vnfr:
516 task = self.loop.create_task(self.get_vnfr_status(vnfr))
517 tasks.append(task)
518
519 # Exit, if no tasks are found
520 if not tasks:
521 break
522
523 yield from asyncio.wait(tasks, loop=self.loop)
524
525 job_status = [task.result() for task in tasks]
526
527 if "failure" in job_status:
528 self.job.job_status = "failure"
529 errs = self.get_error_details()
530 if len(errs):
531 self.job.job.job_status_details = errs
532 elif "pending" in job_status:
533 self.job.job_status = "pending"
534 else:
535 self.job.job_status = "success"
536
537 # self.log.debug("Publishing job status: {} at {} for nsr id: {}".format(
538 # self.job.job_status,
539 # self.job.xpath,
540 # self.job.nsr_id))
541
542 registration_handle.update_element(self.job.xpath, self.job.job)
543
544
545 except Exception as e:
546 self.log.exception(e)
547 raise
548
549
550 @asyncio.coroutine
551 def get_vnfr_status(self, vnfr):
552 """Schedules tasks for all containing primitives and updates it's own
553 status.
554
555 Args:
556 vnfr : Vnfr job record containing primitives.
557
558 Returns:
559 (str): "success|failure|pending"
560 """
561 tasks = []
562 job_status = []
563
564 for primitive in vnfr.primitive:
565 if primitive.execution_status != 'pending':
566 continue
567
568 if primitive.execution_id == "":
569 # Actions which failed to queue can have empty id
570 job_status.append(primitive.execution_status)
571 continue
572
573 elif primitive.execution_id == "config":
574 # Config job. Check if service is active
575 task = self.loop.create_task(self.get_service_status(vnfr.id, primitive))
576
577 else:
578 task = self.loop.create_task(self.get_primitive_status(primitive))
579
580 tasks.append(task)
581
582 if tasks:
583 yield from asyncio.wait(tasks, loop=self.loop)
584
585 job_status.extend([task.result() for task in tasks])
586 if "failure" in job_status:
587 vnfr.vnf_job_status = "failure"
588 return "failure"
589
590 elif "pending" in job_status:
591 vnfr.vnf_job_status = "pending"
592 return "pending"
593
594 else:
595 vnfr.vnf_job_status = "success"
596 return "success"
597
598 @asyncio.coroutine
599 def get_service_status(self, vnfr_id, primitive):
600 try:
601 status = yield from self.loop.run_in_executor(
602 self.executor,
603 self.config_plugin.get_service_status,
604 vnfr_id
605 )
606
607 self.log.debug("Service status: {}".format(status))
608 if status in ['error', 'blocked']:
609 self.log.warning("Execution of config {} failed: {}".
610 format(primitive.execution_id, status))
611 primitive.execution_error_details = 'Config failed'
612 status = 'failure'
613 elif status in ['active']:
614 status = 'success'
615 elif status is None:
616 status = 'failure'
617 else:
618 status = 'pending'
619
620 except Exception as e:
621 self.log.exception(e)
622 status = "failed"
623
624 primitive.execution_status = status
625 return primitive.execution_status
626
627 @asyncio.coroutine
628 def get_primitive_status(self, primitive):
629 """
630 Queries the juju api and gets the status of the execution id.
631
632 Args:
633 primitive : Primitive containing the execution ID.
634 """
635
636 try:
637 resp = yield from self.loop.run_in_executor(
638 self.executor,
639 self.config_plugin.get_action_status,
640 primitive.execution_id
641 )
642
643 self.log.debug("Action status: {}".format(resp))
644 status = resp['status']
645 if status == 'failed':
646 self.log.warning("Execution of action {} failed: {}".
647 format(primitive.execution_id, resp))
648 primitive.execution_error_details = resp['message']
649
650 except Exception as e:
651 self.log.exception(e)
652 status = "failed"
653
654 # Handle case status is None
655 if status:
656 primitive.execution_status = ConfigAgentJob.STATUS_MAP[status]
657 else:
658 primitive.execution_status = "failure"
659
660 return primitive.execution_status
661
662
663 class CfgAgentJobDtsHandler(object):
664 """Dts Handler for CfgAgent"""
665 XPATH = "D,/nsr:ns-instance-opdata/nsr:nsr/nsr:config-agent-job"
666
667 def __init__(self, dts, log, loop, nsm, cfgm):
668 """
669 Args:
670 dts : Dts Handle.
671 log : Log handle.
672 loop : Event loop.
673 nsm : NsmManager.
674 cfgm : ConfigManager.
675 """
676 self._dts = dts
677 self._log = log
678 self._loop = loop
679 self._cfgm = cfgm
680 self._nsm = nsm
681
682 self._regh = None
683 self._nsr_regh = None
684 self._project = cfgm.project
685
686 @property
687 def regh(self):
688 """ Return registration handle """
689 return self._regh
690
691 @property
692 def nsm(self):
693 """ Return the NSManager manager instance """
694 return self._nsm
695
696 @property
697 def cfgm(self):
698 """ Return the ConfigManager manager instance """
699 return self._cfgm
700
701 @staticmethod
702 def cfg_job_xpath(nsr_id, job_id):
703 return self._project.add_project(("D,/nsr:ns-instance-opdata" +
704 "/nsr:nsr[nsr:ns-instance-config-ref = '{}']" +
705 "/nsr:config-agent-job[nsr:job-id='{}']").format(nsr_id, job_id))
706
707 @asyncio.coroutine
708 def register(self):
709 """ Register for NS monitoring read from dts """
710
711 @asyncio.coroutine
712 def on_prepare(xact_info, action, ks_path, msg):
713 """ prepare callback from dts """
714 xpath = ks_path.to_xpath(RwNsrYang.get_schema())
715 if action == rwdts.QueryAction.READ:
716 schema = RwNsrYang.YangData_RwProject_Project_NsInstanceOpdata_Nsr.schema()
717 path_entry = schema.keyspec_to_entry(ks_path)
718 try:
719 nsr_id = path_entry.key00.ns_instance_config_ref
720
721 #print("###>>> self.nsm.nsrs:", self.nsm.nsrs)
722 nsr_ids = []
723 if nsr_id is None or nsr_id == "":
724 nsrs = list(self.nsm.nsrs.values())
725 nsr_ids = [nsr.id for nsr in nsrs if nsr is not None]
726 else:
727 nsr_ids = [nsr_id]
728
729 for nsr_id in nsr_ids:
730 jobs = self.cfgm.get_job(nsr_id)
731
732 for job in jobs:
733 xact_info.respond_xpath(
734 rwdts.XactRspCode.MORE,
735 CfgAgentJobDtsHandler.cfg_job_xpath(nsr_id, job.id),
736 job.job)
737
738 except Exception as e:
739 self._log.exception("Caught exception:%s", str(e))
740 xact_info.respond_xpath(rwdts.XactRspCode.ACK)
741
742 else:
743 xact_info.respond_xpath(rwdts.XactRspCode.NA)
744
745 hdl = rift.tasklets.DTS.RegistrationHandler(on_prepare=on_prepare,)
746 with self._dts.group_create() as group:
747 self._regh = group.register(xpath=self._project.add_project(
748 CfgAgentJobDtsHandler.XPATH),
749 handler=hdl,
750 flags=rwdts.Flag.PUBLISHER,
751 )
752
753 @asyncio.coroutine
754 def _terminate_nsr(self, nsr_id):
755 self._log.debug("NSR {} being terminated".format(nsr_id))
756 jobs = self.cfgm.get_job(nsr_id)
757 for job in jobs:
758 path = CfgAgentJobDtsHandler.cfg_job_xpath(nsr_id, job.id)
759 with self._dts.transaction() as xact:
760 self._log.debug("Deleting job: {}".format(path))
761 job.regh.delete_element(path)
762 self._log.debug("Deleted job: {}".format(path))
763
764 # Remove the NSR id in manager
765 self.cfgm.del_nsr(nsr_id)
766
767 @property
768 def nsr_xpath(self):
769 return self._project.add_project("D,/nsr:ns-instance-opdata/nsr:nsr")
770
771 @asyncio.coroutine
772 def register_for_nsr(self):
773 """ Register for NSR changes """
774
775 @asyncio.coroutine
776 def on_prepare(xact_info, query_action, ks_path, msg):
777 """ This NSR is created """
778 self._log.debug("Received NSR instantiate on_prepare (%s:%s:%s)",
779 query_action,
780 ks_path,
781 msg)
782
783 if (query_action == rwdts.QueryAction.UPDATE or
784 query_action == rwdts.QueryAction.CREATE):
785 pass
786 elif query_action == rwdts.QueryAction.DELETE:
787 nsr_id = msg.ns_instance_config_ref
788 asyncio.ensure_future(self._terminate_nsr(nsr_id), loop=self._loop)
789 else:
790 raise NotImplementedError(
791 "%s action on cm-state not supported",
792 query_action)
793
794 xact_info.respond_xpath(rwdts.XactRspCode.ACK)
795
796 try:
797 handler = rift.tasklets.DTS.RegistrationHandler(on_prepare=on_prepare)
798 self._nsr_regh = yield from self._dts.register(self.nsr_xpath,
799 flags=rwdts.Flag.SUBSCRIBER | rwdts.Flag.DELTA_READY,
800 handler=handler)
801 except Exception as e:
802 self._log.error("Failed to register for NSR changes as %s", str(e))
803
804 def deregister(self):
805 self._log.debug("De-register config agent job for project".
806 format(self._project.name))
807 if self._regh:
808 self._regh.deregister()
809 self._regh = None
810
811 if self._nsr_regh:
812 self._nsr_regh.deregister()
813 self._nsr_regh = None
814
815
816 class ConfigAgentJobManager(object):
817 """A central class that manager all the Config Agent related data,
818 Including updating the status
819
820 TODO: Needs to support multiple config agents.
821 """
822 def __init__(self, dts, log, loop, project, nsm):
823 """
824 Args:
825 dts : Dts handle
826 log : Log handler
827 loop : Event loop
828 nsm : NsmTasklet instance
829 """
830 self.jobs = {}
831 self.dts = dts
832 self.log = log
833 self.loop = loop
834 self.nsm = nsm
835 self.project = project
836 self.handler = CfgAgentJobDtsHandler(dts, log, loop, nsm, self)
837 self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
838
839 def add_job(self, rpc_output, tasks=None):
840 """Once an RPC is triggered, add a new job
841
842 Args:
843 rpc_output (YangOutput_Nsr_ExecNsConfigPrimitive): Rpc output
844 rpc_input (YangInput_Nsr_ExecNsConfigPrimitive): Rpc input
845 tasks(list) A list of asyncio.Tasks
846
847 """
848 nsr_id = rpc_output.nsr_id_ref
849
850 job = ConfigAgentJob.convert_rpc_input_to_job(nsr_id, rpc_output,
851 tasks, self.project)
852
853 self.log.debug("Creating a job monitor for Job id: {}".format(
854 rpc_output.job_id))
855
856 if nsr_id not in self.jobs:
857 self.jobs[nsr_id] = [job]
858 else:
859 self.jobs[nsr_id].append(job)
860
861 # If the tasks are none, assume juju actions
862 # TBD: This logic need to be revisited
863 ca = self.nsm.config_agent_plugins[0]
864 if tasks is None:
865 for agent in self.nsm.config_agent_plugins:
866 if agent.agent_type == 'juju':
867 ca = agent
868 break
869
870 # For every Job we will schedule a new monitoring process.
871 job_monitor = ConfigAgentJobMonitor(
872 self.dts,
873 self.log,
874 job,
875 self.executor,
876 self.loop,
877 ca
878 )
879 task = self.loop.create_task(job_monitor.publish_action_status())
880
881 def get_job(self, nsr_id):
882 """Get the job associated with the NSR Id, if present."""
883 try:
884 return self.jobs[nsr_id]
885 except KeyError:
886 return []
887
888 def del_nsr(self, nsr_id):
889 """Delete a NSR id from the jobs list"""
890 if nsr_id in self.jobs:
891 self.jobs.pop(nsr_id)
892
893 @asyncio.coroutine
894 def register(self):
895 yield from self.handler.register()
896 yield from self.handler.register_for_nsr()
897
898 def deregister(self):
899 yield from self.handler.deregister()