2 # Copyright 2016 RIFT.IO Inc
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
24 import rift
.mano
.utils
.juju_api
as juju
25 from . import riftcm_config_plugin
28 # Charm service name accepts only a to z and -.
29 def get_vnf_unique_name(nsr_name
, vnfr_name
, member_vnf_index
):
30 name
= "{}-{}-{}".format(nsr_name
, vnfr_name
, member_vnf_index
)
38 return new_name
.lower()
41 class JujuConfigPlugin(riftcm_config_plugin
.RiftCMConfigPluginBase
):
43 Juju implementation of the riftcm_config_plugin.RiftCMConfigPluginBase
45 def __init__(self
, dts
, log
, loop
, project
, account
):
46 riftcm_config_plugin
.RiftCMConfigPluginBase
.__init
__(self
, dts
, log
, loop
,
48 self
._name
= account
.name
50 self
._ip
_address
= account
.juju
.ip_address
51 self
._port
= account
.juju
.port
52 self
._user
= account
.juju
.user
53 self
._secret
= account
.juju
.secret
54 self
._rift
_install
_dir
= os
.environ
['RIFT_INSTALL']
55 self
._rift
_var
_root
_dir
= os
.environ
['RIFT_VAR_ROOT']
57 ############################################################
58 # This is wrongfully overloaded with 'juju' private data. #
59 # Really need to separate agent_vnfr from juju vnfr data. #
60 # Currently, this holds agent_vnfr, which has actual vnfr, #
61 # then this juju overloads actual vnfr with its own #
62 # dictionary elemetns (WRONG!!!) #
64 ############################################################
67 self
._api
= juju
.JujuApi(log
, loop
,
68 self
._ip
_address
, self
._port
,
69 self
._user
, self
._secret
)
88 host
=self
._ip
_address
,
94 def vnfr(self
, vnfr_id
):
96 vnfr
= self
._juju
_vnfs
[vnfr_id
].vnfr
98 self
._log
.error("jujuCA: Did not find VNFR %s in juju plugin", vnfr_id
)
103 def get_service_name(self
, vnfr_id
):
104 vnfr
= self
.vnfr(vnfr_id
)
105 if vnfr
and 'vnf_juju_name' in vnfr
:
106 return vnfr
['vnf_juju_name']
109 def juju_log(self
, level
, name
, log_str
, *args
):
111 g_log_str
= 'jujuCA:({}) {}'.format(name
, log_str
)
113 g_log_str
= 'jujuCA: {}'.format(log_str
)
114 getattr(self
._log
, level
)(g_log_str
, *args
)
116 # TBD: Do a better, similar to config manager
117 def xlate(self
, tag
, tags
):
122 if re
.search('<.*>', tag
):
123 self
._log
.debug("jujuCA: Xlate value %s", tag
)
125 if tag
== '<rw_mgmt_ip>':
126 val
= tags
['rw_mgmt_ip']
127 except KeyError as e
:
128 self
._log
.info("jujuCA: Did not get a value for tag %s, e=%s",
133 def notify_create_vlr(self
, agent_nsr
, agent_vnfr
, vld
, vlr
):
135 Notification of create VL record
140 def notify_create_vnfr(self
, agent_nsr
, agent_vnfr
):
142 Notification of create Network VNF record
143 Returns True if configured using config_agent
145 # Deploy the charm if specified for the vnf
146 self
._log
.debug("jujuCA: create vnfr nsr=%s vnfr=%s",
147 agent_nsr
.name
, agent_vnfr
.name
)
148 self
._log
.debug("jujuCA: Config = %s",
149 agent_vnfr
.vnf_configuration
)
151 vnf_config
= agent_vnfr
.vnfr_msg
.vnf_configuration
152 self
._log
.debug("jujuCA: vnf_configuration = %s", vnf_config
)
153 if not vnf_config
.has_field('juju'):
155 charm
= vnf_config
.juju
.charm
156 self
._log
.debug("jujuCA: charm = %s", charm
)
157 except Exception as e
:
158 self
._log
.Error("jujuCA: vnf_configuration error for vnfr {}: {}".
159 format(agent_vnfr
.name
, e
))
162 # Prepare unique name for this VNF
163 vnf_unique_name
= get_vnf_unique_name(agent_nsr
.name
,
165 agent_vnfr
.member_vnf_index
)
166 if vnf_unique_name
in self
._tasks
:
167 self
._log
.warn("jujuCA: Service %s already deployed",
170 vnfr_dict
= agent_vnfr
.vnfr
171 vnfr_dict
.update({'vnf_juju_name': vnf_unique_name
,
173 'nsr_id': agent_nsr
.id,
174 'member_vnf_index': agent_vnfr
.member_vnf_index
,
177 'config': vnf_config
,
178 'vnfr_name': agent_vnfr
.name
})
179 self
._log
.debug("jujuCA: Charm %s for vnf %s to be deployed as %s",
180 charm
, agent_vnfr
.name
, vnf_unique_name
)
182 # Find the charm directory
184 path
= os
.path
.join(self
._rift
_var
_root
_dir
,
185 'launchpad/packages/vnfd',
187 agent_vnfr
.vnfr_msg
.vnfd
.id,
190 self
._log
.debug("jujuCA: Charm dir is {}".format(path
))
191 if not os
.path
.isdir(path
):
192 self
._log
.error("jujuCA: Did not find the charm directory at {}".
195 except Exception as e
:
196 self
.log
.exception(e
)
199 if vnf_unique_name
not in self
._tasks
:
200 self
._tasks
[vnf_unique_name
] = {}
202 self
._tasks
[vnf_unique_name
]['deploy'] = self
.loop
.create_task(
203 self
.api
.deploy_application(charm
, vnf_unique_name
, path
=path
))
205 self
._log
.debug("jujuCA: Deploying service %s",
211 def notify_instantiate_vnfr(self
, agent_nsr
, agent_vnfr
):
213 Notification of Instantiate NSR with the passed nsr id
218 def notify_instantiate_vlr(self
, agent_nsr
, agent_vnfr
, vlr
):
220 Notification of Instantiate NSR with the passed nsr id
225 def notify_terminate_nsr(self
, agent_nsr
, agent_vnfr
):
227 Notification of Terminate the network service
232 def notify_terminate_vnfr(self
, agent_nsr
, agent_vnfr
):
234 Notification of Terminate the network service
236 self
._log
.debug("jujuCA: Terminate VNFr {}, current vnfrs={}".
237 format(agent_vnfr
.name
, self
._juju
_vnfs
))
239 vnfr
= agent_vnfr
.vnfr
240 service
= vnfr
['vnf_juju_name']
242 self
._log
.debug ("jujuCA: Terminating VNFr %s, %s",
243 agent_vnfr
.name
, service
)
244 self
._tasks
[service
]['destroy'] = self
.loop
.create_task(
245 self
.api
.remove_application(service
)
248 del self
._juju
_vnfs
[agent_vnfr
.id]
249 self
._log
.debug ("jujuCA: current vnfrs={}".
250 format(self
._juju
_vnfs
))
251 if service
in self
._tasks
:
253 for action
in self
._tasks
[service
].keys():
254 #if self.check_task_status(service, action):
257 except KeyError as e
:
258 self
._log
.debug ("jujuCA: Terminating charm service for VNFr {}, e={}".
259 format(agent_vnfr
.name
, e
))
260 except Exception as e
:
261 self
._log
.error("jujuCA: Exception terminating charm service for VNFR {}: {}".
262 format(agent_vnfr
.name
, e
))
267 def notify_terminate_vlr(self
, agent_nsr
, agent_vnfr
, vlr
):
269 Notification of Terminate the virtual link
273 def check_task_status(self
, service
, action
):
274 #self.log.debug("jujuCA: check task status for %s, %s" % (service, action))
276 task
= self
._tasks
[service
][action
]
278 self
.log
.debug("jujuCA: Task for %s, %s done" % (service
, action
))
281 self
.log
.error("jujuCA: Error in task for {} and {} : {}".
282 format(service
, action
, e
))
286 self
.log
.debug("jujuCA: Task for {} and {}, returned {}".
287 format(service
, action
,r
))
290 self
.log
.debug("jujuCA: task {}, {} not done".
291 format(service
, action
))
293 except KeyError as e
:
294 self
.log
.error("jujuCA: KeyError for task for {} and {}: {}".
295 format(service
, action
, e
))
296 except Exception as e
:
297 self
.log
.error("jujuCA: Error for task for {} and {}: {}".
298 format(service
, action
, e
))
303 def _vnf_config_primitive(self
, nsr_id
, vnfr_id
, primitive
,
304 vnf_config
=None, wait
=False):
305 self
._log
.debug("jujuCA: VNF config primitive {} for nsr {}, "
307 format(primitive
, nsr_id
, vnfr_id
))
309 if vnf_config
is None:
310 vnfr_msg
= yield from self
.get_vnfr(vnfr_id
)
312 msg
= "Unable to get VNFR {} through DTS".format(vnfr_id
)
316 vnf_config
= vnfr_msg
.vnf_configuration
317 self
._log
.debug("VNF config= %s", vnf_config
.as_dict())
320 service
= vnfr
['vnf_juju_name']
321 self
._log
.debug("VNF config %s", vnf_config
)
322 configs
= vnf_config
.config_primitive
323 for config
in configs
:
324 if config
.name
== primitive
.name
:
325 self
._log
.debug("jujuCA: Found the config primitive %s",
328 for parameter
in config
.parameter
:
330 for p
in primitive
.parameter
:
331 if p
.name
== parameter
.name
:
333 val
= self
.xlate(p
.value
, vnfr
['tags'])
337 val
= parameter
.default_value
340 # Check if mandatory parameter
341 if parameter
.mandatory
:
342 msg
= "VNFR {}: Primitive {} called " \
343 "without mandatory parameter {}". \
344 format(vnfr_msg
.name
, config
.name
,
347 return 'failed', '', msg
350 val
= self
.convert_value(val
, parameter
.data_type
)
351 params
.update({parameter
.name
: val
})
356 if config
.name
== 'config':
359 self
._log
.debug("jujuCA: applying config with "
360 "params {} for service {}".
361 format(params
, service
))
363 rc
= yield from self
.api
.apply_config(params
, application
=service
)
367 self
._log
.debug("jujuCA: applied config {} "
368 "on {}".format(params
, service
))
372 'Failed to apply config: {}'.format(params
)
373 self
._log
.error("jujuCA: Error applying "
374 "config {} on service {}".
375 format(params
, service
))
377 self
._log
.warn("jujuCA: Did not find valid "
378 "parameters for config : {}".
379 format(primitive
.parameter
))
382 self
._log
.debug("jujuCA: Execute action {} on "
383 "service {} with params {}".
384 format(config
.name
, service
, params
))
386 resp
= yield from self
.api
.execute_action(
394 details
= resp
['error']['message']
396 exec_id
= resp
['action']['tag']
399 details
= resp
['message']
401 self
._log
.debug("jujuCA: execute action {} on "
402 "service {} returned {}".
403 format(config
.name
, service
, rc
))
405 self
._log
.error("jujuCA: error executing action "
407 format(config
.name
, service
,
411 details
= "Failed to queue the action"
414 except KeyError as e
:
415 msg
= "VNF %s does not have config primitives, e=%s", \
417 self
._log
.exception(msg
)
418 raise ValueError(msg
)
420 while wait
and (rc
in ['pending', 'running']):
421 self
._log
.debug("JujuCA: action {}, rc {}".
423 yield from asyncio
.sleep(0.2, loop
=self
._loop
)
424 status
= yield from self
.api
.get_action_status(exec_id
)
425 rc
= status
['status']
427 return rc
, exec_id
, details
430 def vnf_config_primitive(self
, nsr_id
, vnfr_id
, primitive
, output
):
432 vnfr
= self
._juju
_vnfs
[vnfr_id
].vnfr
434 msg
= "Did not find VNFR {} in Juju plugin".format(vnfr_id
)
438 output
.execution_status
= "failed"
439 output
.execution_id
= ''
440 output
.execution_error_details
= ''
442 rc
, exec_id
, err
= yield from self
._vnf
_config
_primitive
(
447 self
._log
.debug("VNFR {} primitive {} exec status: {}".
448 format(vnfr
.name
, primitive
.name
, rc
))
449 output
.execution_status
= rc
450 output
.execution_id
= exec_id
451 output
.execution_error_details
= err
454 def apply_config(self
, agent_nsr
, agent_vnfr
, config
, rpc_ip
):
455 """ Notification on configuration of an NSR """
459 def apply_ns_config(self
, agent_nsr
, agent_vnfrs
, rpc_ip
):
462 ###### TBD - This really does not belong here. Looks more like NS level script ####
463 ###### apply_config should be called for a particular VNF only here ###############
465 Hook: Runs the user defined script. Feeds all the necessary data
466 for the script thro' yaml file.
469 rpc_ip (YangInput_Nsr_ExecNsConfigPrimitive): The input data.
470 nsr (NetworkServiceRecord): Description
471 vnfrs (dict): VNFR ID => VirtualNetworkFunctionRecord
474 def get_meta(agent_nsr
):
475 unit_names
, initial_params
, vnfr_index_map
= {}, {}, {}
477 for vnfr_id
in agent_nsr
.vnfr_ids
:
478 juju_vnf
= self
._juju
_vnfs
[vnfr_id
].vnfr
481 vnfr_index_map
[vnfr_id
] = juju_vnf
['member_vnf_index']
484 unit_names
[vnfr_id
] = juju_vnf
['vnf_juju_name']
486 # Flatten the data for simplicity
488 self
._log
.debug("Juju Config:%s", juju_vnf
['config'])
489 for primitive
in juju_vnf
['config'].initial_config_primitive
:
490 for parameter
in primitive
.parameter
:
491 value
= self
.xlate(parameter
.value
, juju_vnf
['tags'])
492 param_data
[parameter
.name
] = value
494 initial_params
[vnfr_id
] = param_data
497 return unit_names
, initial_params
, vnfr_index_map
499 unit_names
, init_data
, vnfr_index_map
= get_meta(agent_nsr
)
501 # The data consists of 4 sections
503 # 2. The input passed.
504 # 3. Juju unit names (keyed by vnfr ID).
505 # 4. Initial config data (keyed by vnfr ID).
507 data
['config_agent'] = dict(
509 host
=self
._ip
_address
,
514 data
["rpc_ip"] = rpc_ip
.as_dict()
515 data
["unit_names"] = unit_names
516 data
["init_config"] = init_data
517 data
["vnfr_index_map"] = vnfr_index_map
520 with tempfile
.NamedTemporaryFile(delete
=False) as tmp_file
:
521 tmp_file
.write(yaml
.dump(data
, default_flow_style
=True)
524 self
._log
.debug("jujuCA: Creating a temp file: {} with input data".format(
527 # Get the full path to the script
529 if rpc_ip
.user_defined_script
[0] == '/':
530 # The script has full path, use as is
531 script
= rpc_ip
.user_defined_script
533 script
= os
.path
.join(self
._rift
_var
_root
_dir
, 'launchpad/nsd',
535 agent_nsr
.id, 'scripts',
536 rpc_ip
.user_defined_script
)
537 self
.log
.debug("jujuCA: Checking for script in %s", script
)
538 if not os
.path
.exists(script
):
539 script
= os
.path
.join(self
._rift
_install
_dir
, 'usr/bin', rpc_ip
.user_defined_script
)
541 cmd
= "{} {}".format(rpc_ip
.user_defined_script
, tmp_file
.name
)
542 self
._log
.debug("jujuCA: Running the CMD: {}".format(cmd
))
544 coro
= asyncio
.create_subprocess_shell(cmd
, loop
=self
._loop
,
545 stderr
=asyncio
.subprocess
.PIPE
)
546 process
= yield from coro
547 err
= yield from process
.stderr
.read()
548 task
= self
._loop
.create_task(process
.wait())
553 def apply_initial_config(self
, agent_nsr
, agent_vnfr
):
555 Apply the initial configuration
556 Expect config directives mostly, not actions
557 Actions in initial config may not work based on charm design
561 vnfr
= self
._juju
_vnfs
[agent_vnfr
.id].vnfr
563 self
._log
.debug("Did not find VNFR %s in Juju plugin",
567 vnfr_msg
= yield from self
.get_vnfr(agent_vnfr
.id)
569 msg
= "Unable to get VNFR {} ({}) through DTS". \
570 format(agent_vnfr
.id, agent_vnfr
.name
)
572 raise RuntimeError(msg
)
574 vnf_config
= vnfr_msg
.vnf_configuration
575 self
._log
.debug("VNFR %s config: %s", vnfr_msg
.name
,
576 vnf_config
.as_dict())
578 # Sort the primitive based on the sequence number
579 primitives
= sorted(vnf_config
.initial_config_primitive
,
582 self
._log
.debug("VNFR {}: No initial-config-primitive specified".
583 format(vnfr_msg
.name
))
586 rc
= yield from self
.api
.is_application_up(application
=service
)
591 if vnfr_msg
.mgmt_interface
.ip_address
:
592 vnfr
['tags'].update({'rw_mgmt_ip': vnfr_msg
.mgmt_interface
.ip_address
})
593 self
._log
.debug("jujuCA:(%s) tags: %s", vnfr
['vnf_juju_name'], vnfr
['tags'])
595 for primitive
in primitives
:
596 self
._log
.debug("(%s) Initial config primitive %s",
597 vnfr
['vnf_juju_name'], primitive
.as_dict())
598 if primitive
.config_primitive_ref
:
599 # Reference to a primitive in config primitive
601 def __init__(self
, name
):
606 prim
= Primitive(primitive
.config_primitive_ref
)
607 rc
, eid
, err
= yield from self
._vnf
_config
_primitive
(
615 msg
= "Error executing initial config primitive" \
616 " {} in VNFR {}: rc={}, stderr={}". \
617 format(prim
.name
, vnfr_msg
.name
, rc
, err
)
621 elif rc
== "pending":
622 action_ids
.append(eid
)
626 if primitive
.name
== 'config':
627 for param
in primitive
.parameter
:
629 val
= self
.xlate(param
.value
,
631 config
.update({param
.name
: val
})
634 self
.juju_log('info', vnfr
['vnf_juju_name'],
635 "Applying Initial config:%s",
638 rc
= yield from self
.api
.apply_config(
643 self
.log
.error("Service {} is in error state".format(service
))
646 # Apply any actions specified as part of initial config
647 for primitive
in vnfr
['config'].initial_config_primitive
:
648 if primitive
.name
!= 'config':
649 self
._log
.debug("jujuCA:(%s) Initial config action primitive %s",
650 vnfr
['vnf_juju_name'], primitive
)
651 action
= primitive
.name
653 for param
in primitive
.parameter
:
654 val
= self
.xlate(param
.value
, vnfr
['tags'])
655 params
.update({param
.name
: val
})
657 self
._log
.info("jujuCA:(%s) Action %s with params %s",
658 vnfr
['vnf_juju_name'], action
, params
)
659 self
._log
.debug("executing action")
660 resp
= yield from self
.api
.execute_action(
665 self
._log
.debug("executed action")
667 self
._log
.error("Applying initial config on {} failed for {} with {}: {}".
668 format(vnfr
['vnf_juju_name'], action
, params
, resp
))
670 except KeyError as e
:
671 self
._log
.info("Juju config agent(%s): VNFR %s not managed by Juju",
672 vnfr
['vnf_juju_name'], agent_vnfr
.id)
674 except Exception as e
:
675 self
._log
.exception("jujuCA:(%s) Exception juju "
676 "apply_initial_config for VNFR {}: {}".
677 format(vnfr
['vnf_juju_name'],
683 def add_vnfr_managed(self
, agent_vnfr
):
684 if agent_vnfr
.id not in self
._juju
_vnfs
.keys():
685 self
._log
.info("juju config agent: add vnfr={}/{}".
686 format(agent_vnfr
.name
, agent_vnfr
.id))
687 self
._juju
_vnfs
[agent_vnfr
.id] = agent_vnfr
689 def is_vnfr_managed(self
, vnfr_id
):
691 if vnfr_id
in self
._juju
_vnfs
:
693 except Exception as e
:
694 self
._log
.debug("jujuCA: Is VNFR {} managed: {}".
699 def is_configured(self
, vnfr_id
):
701 agent_vnfr
= self
._juju
_vnfs
[vnfr_id
]
702 vnfr
= agent_vnfr
.vnfr
706 vnfr
= self
._juju
_vnfs
[vnfr_id
].vnfr
707 service
= vnfr
['vnf_juju_name']
708 resp
= self
.api
.is_application_active(application
=service
)
709 self
._juju
_vnfs
[vnfr_id
]['active'] = resp
710 self
._log
.debug("jujuCA: Service state for {} is {}".
711 format(service
, resp
))
715 self
._log
.debug("jujuCA: VNFR id {} not found in config agent".
718 except Exception as e
:
719 self
._log
.error("jujuCA: VNFR id {} is_configured: {}".
724 def get_config_status(self
, agent_nsr
, agent_vnfr
):
725 """Get the configuration status for the VNF"""
729 vnfr
= agent_vnfr
.vnfr
730 service
= vnfr
['vnf_juju_name']
732 # This VNF is not managed by Juju
737 if not self
.check_task_status(service
, 'deploy'):
741 resp
= yield from self
.api
.get_service_status(application
=service
)
742 self
._log
.debug("jujuCA: Get service %s status? %s", service
, resp
)
749 self
._log
.error("jujuCA: Check unknown service %s status", service
)
750 except Exception as e
:
751 self
._log
.error("jujuCA: Caught exception when checking for service is active: %s", e
)
752 self
._log
.exception(e
)
756 def get_action_status(self
, execution_id
):
757 ''' Get the action status for an execution ID
758 *** Make sure this is NOT a asyncio coroutine function ***
762 self
._log
.debug("jujuCA: Get action status for {}".format(execution_id
))
763 resp
= self
.api
._get
_action
_status
(execution_id
)
764 self
._log
.debug("jujuCA: Action status: {}".format(resp
))
766 except Exception as e
:
767 self
._log
.error("jujuCA: Error fetching execution status for %s",
769 self
._log
.exception(e
)
772 def get_service_status(self
, vnfr_id
):
773 '''Get the service status, used by job status handle
774 Make sure this is NOT a coroutine
776 service
= self
.get_service_name(vnfr_id
)
778 self
._log
.error("jujuCA: VNFR {} not managed by this Juju agent".
782 # Delay for 3 seconds before checking as config apply takes a
783 # few seconds to transfer to the service
785 return self
.api
._get
_service
_status
(service
=service
)