0ad877e480aabfaa434de927892039f0807981a8
[osm/SO.git] / rwlaunchpad / plugins / rwnsm / rift / tasklets / rwnsmtasklet / openmano_nsm.py
1
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18 import asyncio
19 import os
20 import sys
21 import time
22 import yaml
23
24 import gi
25 gi.require_version('RwDts', '1.0')
26 gi.require_version('RwVnfrYang', '1.0')
27 from gi.repository import (
28 RwDts as rwdts,
29 RwVnfrYang,
30 )
31
32 import rift.openmano.rift2openmano as rift2openmano
33 import rift.openmano.openmano_client as openmano_client
34 from . import rwnsmplugin
35 from enum import Enum
36
37
38 import rift.tasklets
39
40 if sys.version_info < (3, 4, 4):
41 asyncio.ensure_future = asyncio.async
42
43
44 DUMP_OPENMANO_DIR = os.path.join(
45 os.environ["RIFT_ARTIFACTS"],
46 "openmano_descriptors"
47 )
48
49
50 def dump_openmano_descriptor(name, descriptor_str):
51 filename = "{}_{}.yaml".format(
52 time.strftime("%Y%m%d-%H%M%S"),
53 name
54 )
55
56 filepath = os.path.join(
57 DUMP_OPENMANO_DIR,
58 filename
59 )
60
61 try:
62 if not os.path.exists(DUMP_OPENMANO_DIR):
63 os.makedirs(DUMP_OPENMANO_DIR)
64
65 with open(filepath, 'w') as hdl:
66 hdl.write(descriptor_str)
67
68 except OSError as e:
69 print("Failed to dump openmano descriptor: %s" % str(e))
70
71 return filepath
72
73 class VnfrConsoleOperdataDtsHandler(object):
74 """ registers 'D,/vnfr:vnfr-console/vnfr:vnfr[id]/vdur[id]' and handles CRUD from DTS"""
75 @property
76 def vnfr_vdu_console_xpath(self):
77 """ path for resource-mgr"""
78 return ("D,/rw-vnfr:vnfr-console/rw-vnfr:vnfr[rw-vnfr:id='{}']/rw-vnfr:vdur[vnfr:id='{}']".format(self._vnfr_id,self._vdur_id))
79
80 def __init__(self, dts, log, loop, nsr, vnfr_id, vdur_id, vdu_id):
81 self._dts = dts
82 self._log = log
83 self._loop = loop
84 self._regh = None
85 self._nsr = nsr
86
87 self._vnfr_id = vnfr_id
88 self._vdur_id = vdur_id
89 self._vdu_id = vdu_id
90
91 @asyncio.coroutine
92 def register(self):
93 """ Register for VNFR VDU Operational Data read from dts """
94
95 @asyncio.coroutine
96 def on_prepare(xact_info, action, ks_path, msg):
97 """ prepare callback from dts """
98 xpath = ks_path.to_xpath(RwVnfrYang.get_schema())
99 self._log.debug(
100 "Got VNFR VDU Opdata xact_info: %s, action: %s): %s:%s",
101 xact_info, action, xpath, msg
102 )
103
104 if action == rwdts.QueryAction.READ:
105 schema = RwVnfrYang.YangData_RwVnfr_VnfrConsole_Vnfr_Vdur.schema()
106 path_entry = schema.keyspec_to_entry(ks_path)
107
108 try:
109 console_url = yield from self._loop.run_in_executor(
110 None,
111 self._nsr._http_api.get_instance_vm_console_url,
112 self._nsr._nsr_uuid,
113 self._vdur_id
114 )
115
116 self._log.debug("Got console response: %s for NSR ID %s vdur ID %s",
117 console_url,
118 self._nsr._nsr_uuid,
119 self._vdur_id
120 )
121 vdur_console = RwVnfrYang.YangData_RwVnfr_VnfrConsole_Vnfr_Vdur()
122 vdur_console.id = self._vdur_id
123 if console_url:
124 vdur_console.console_url = console_url
125 else:
126 vdur_console.console_url = 'none'
127 self._log.debug("Recevied console URL for vdu {} is {}".format(self._vdu_id,vdur_console))
128 except openmano_client.InstanceStatusError as e:
129 self._log.error("Could not get NS instance console URL: %s",
130 str(e))
131 vdur_console = RwVnfrYang.YangData_RwVnfr_VnfrConsole_Vnfr_Vdur()
132 vdur_console.id = self._vdur_id
133 vdur_console.console_url = 'none'
134
135 xact_info.respond_xpath(rsp_code=rwdts.XactRspCode.ACK,
136 xpath=self.vnfr_vdu_console_xpath,
137 msg=vdur_console)
138 else:
139 #raise VnfRecordError("Not supported operation %s" % action)
140 self._log.error("Not supported operation %s" % action)
141 xact_info.respond_xpath(rsp_code=rwdts.XactRspCode.ACK)
142 return
143
144 self._log.debug("Registering for VNFR VDU using xpath: %s",
145 self.vnfr_vdu_console_xpath)
146 hdl = rift.tasklets.DTS.RegistrationHandler(on_prepare=on_prepare,)
147 with self._dts.group_create() as group:
148 self._regh = group.register(xpath=self.vnfr_vdu_console_xpath,
149 handler=hdl,
150 flags=rwdts.Flag.PUBLISHER,
151 )
152
153
154
155 class OpenmanoVnfr(object):
156 def __init__(self, log, loop, cli_api, vnfr, nsd):
157 self._log = log
158 self._loop = loop
159 self._cli_api = cli_api
160 self._vnfr = vnfr
161 self._vnfd_id = vnfr.vnfd.id
162
163 self._vnf_id = None
164
165 self._created = False
166
167 self.nsd = nsd
168
169 @property
170 def vnfd(self):
171 return rift2openmano.RiftVNFD(self._vnfr.vnfd)
172
173 @property
174 def vnfr(self):
175 return self._vnfr
176
177 @property
178 def rift_vnfd_id(self):
179 return self._vnfd_id
180
181 @property
182 def openmano_vnfd_id(self):
183 return self._vnf_id
184
185 @property
186 def openmano_vnfd(self):
187 self._log.debug("Converting vnfd %s from rift to openmano", self.vnfd.id)
188 openmano_vnfd = rift2openmano.rift2openmano_vnfd(self.vnfd, self.nsd)
189 return openmano_vnfd
190
191 @property
192 def openmano_vnfd_yaml(self):
193 return yaml.safe_dump(self.openmano_vnfd, default_flow_style=False)
194
195 @asyncio.coroutine
196 def create(self):
197 self._log.debug("Creating openmano vnfd")
198 openmano_vnfd = self.openmano_vnfd
199 name = openmano_vnfd["vnf"]["name"]
200
201 # If the name already exists, get the openmano vnfd id
202 name_uuid_map = yield from self._loop.run_in_executor(
203 None,
204 self._cli_api.vnf_list,
205 )
206
207 if name in name_uuid_map:
208 vnf_id = name_uuid_map[name]
209 self._log.debug("Vnf already created. Got existing openmano vnfd id: %s", vnf_id)
210 self._vnf_id = vnf_id
211 return
212
213 self._vnf_id, _ = yield from self._loop.run_in_executor(
214 None,
215 self._cli_api.vnf_create,
216 self.openmano_vnfd_yaml,
217 )
218
219 fpath = dump_openmano_descriptor(
220 "{}_vnf".format(name),
221 self.openmano_vnfd_yaml
222 )
223
224 self._log.debug("Dumped Openmano VNF descriptor to: %s", fpath)
225
226 self._created = True
227
228 def delete(self):
229 if not self._created:
230 return
231
232 self._log.debug("Deleting openmano vnfd")
233 if self._vnf_id is None:
234 self._log.warning("Openmano vnf id not set. Cannot delete.")
235 return
236
237 self._cli_api.vnf_delete(self._vnf_id)
238
239
240 class OpenmanoNSRecordState(Enum):
241 """ Network Service Record State """
242 # Make sure the values match with NetworkServiceRecordState
243 INIT = 101
244 INSTANTIATION_PENDING = 102
245 RUNNING = 106
246 SCALING_OUT = 107
247 SCALING_IN = 108
248 TERMINATE = 109
249 TERMINATE_RCVD = 110
250 TERMINATED = 114
251 FAILED = 115
252 VL_INSTANTIATE = 116
253 VL_TERMINATE = 117
254
255
256 class OpenmanoNsr(object):
257 TIMEOUT_SECS = 300
258 INSTANCE_TERMINATE_TIMEOUT = 60
259
260 def __init__(self, dts, log, loop, publisher, cli_api, http_api, nsd_msg, nsr_config_msg,key_pairs):
261 self._dts = dts
262 self._log = log
263 self._loop = loop
264 self._publisher = publisher
265 self._cli_api = cli_api
266 self._http_api = http_api
267
268 self._nsd_msg = nsd_msg
269 self._nsr_config_msg = nsr_config_msg
270
271 self._vlrs = []
272 self._vnfrs = []
273 self._vdur_console_handler = {}
274 self._key_pairs = key_pairs
275
276 self._nsd_uuid = None
277 self._nsr_uuid = None
278
279 self._nsr_msg = None
280
281 self._created = False
282
283 self._monitor_task = None
284 self._state = OpenmanoNSRecordState.INIT
285
286 @property
287 def nsd(self):
288 return rift2openmano.RiftNSD(self._nsd_msg)
289
290 @property
291 def vnfds(self):
292 return {v.rift_vnfd_id: v.vnfd for v in self._vnfrs}
293
294 @property
295 def vnfr_ids(self):
296 return {v.rift_vnfd_id: v.openmano_vnfd_id for v in self._vnfrs}
297
298 @property
299 def vnfrs(self):
300 return self._vnfrs
301
302 @property
303 def openmano_nsd_yaml(self):
304 self._log.debug("Converting nsd %s from rift to openmano", self.nsd.id)
305 openmano_nsd = rift2openmano.rift2openmano_nsd(self.nsd, self.vnfds,self.vnfr_ids)
306 return yaml.safe_dump(openmano_nsd, default_flow_style=False)
307
308 def get_ssh_key_pairs(self):
309 cloud_config = {}
310 key_pairs = list()
311 for authorized_key in self._nsr_config_msg.ssh_authorized_key:
312 self._log.debug("Key pair ref present is %s",authorized_key.key_pair_ref)
313 if authorized_key.key_pair_ref in self._key_pairs:
314 key_pairs.append(self._key_pairs[authorized_key.key_pair_ref].key)
315
316 for authorized_key in self._nsd_msg.key_pair:
317 self._log.debug("Key pair NSD is %s",authorized_key)
318 key_pairs.append(authorized_key.key)
319
320 if key_pairs:
321 cloud_config["key-pairs"] = key_pairs
322
323 users = list()
324 for user_entry in self._nsr_config_msg.user:
325 self._log.debug("User present is %s",user_entry)
326 user = {}
327 user["name"] = user_entry.name
328 user["key-pairs"] = list()
329 for ssh_key in user_entry.ssh_authorized_key:
330 if ssh_key.key_pair_ref in self._key_pairs:
331 user["key-pairs"].append(self._key_pairs[ssh_key.key_pair_ref].key)
332 users.append(user)
333
334 for user_entry in self._nsd_msg.user:
335 self._log.debug("User present in NSD is %s",user_entry)
336 user = {}
337 user["name"] = user_entry.name
338 user["key-pairs"] = list()
339 for ssh_key in user_entry.key_pair:
340 user["key-pairs"].append(ssh_key.key)
341 users.append(user)
342
343 if users:
344 cloud_config["users"] = users
345
346 self._log.debug("Cloud config formed is %s",cloud_config)
347 return cloud_config
348
349
350 @property
351 def openmano_instance_create_yaml(self):
352 self._log.debug("Creating instance-scenario-create input file for nsd %s with name %s", self.nsd.id, self._nsr_config_msg.name)
353 openmano_instance_create = {}
354 openmano_instance_create["name"] = self._nsr_config_msg.name
355 openmano_instance_create["description"] = self._nsr_config_msg.description
356 openmano_instance_create["scenario"] = self._nsd_uuid
357
358 cloud_config = self.get_ssh_key_pairs()
359 if cloud_config:
360 openmano_instance_create["cloud-config"] = cloud_config
361 if self._nsr_config_msg.has_field("om_datacenter"):
362 openmano_instance_create["datacenter"] = self._nsr_config_msg.om_datacenter
363 openmano_instance_create["vnfs"] = {}
364 for vnfr in self._vnfrs:
365 if "om_datacenter" in vnfr.vnfr.vnfr_msg:
366 vnfr_name = vnfr.vnfr.vnfd.name + "__" + str(vnfr.vnfr.vnfr_msg.member_vnf_index_ref)
367 openmano_instance_create["vnfs"][vnfr_name] = {"datacenter": vnfr.vnfr.vnfr_msg.om_datacenter}
368 openmano_instance_create["networks"] = {}
369 for vld_msg in self._nsd_msg.vld:
370 openmano_instance_create["networks"][vld_msg.name] = {}
371 openmano_instance_create["networks"][vld_msg.name]["sites"] = list()
372 for vlr in self._vlrs:
373 if vlr.vld_msg.name == vld_msg.name:
374 self._log.debug("Received VLR name %s, VLR DC: %s for VLD: %s",vlr.vld_msg.name,
375 vlr.om_datacenter_name,vld_msg.name)
376 #network["vim-network-name"] = vld_msg.name
377 network = {}
378 ip_profile = {}
379 if vld_msg.vim_network_name:
380 network["netmap-use"] = vld_msg.vim_network_name
381 elif vlr._ip_profile and vlr._ip_profile.has_field("ip_profile_params"):
382 ip_profile_params = vlr._ip_profile.ip_profile_params
383 if ip_profile_params.ip_version == "ipv6":
384 ip_profile['ip-version'] = "IPv6"
385 else:
386 ip_profile['ip-version'] = "IPv4"
387 if ip_profile_params.has_field('subnet_address'):
388 ip_profile['subnet-address'] = ip_profile_params.subnet_address
389 if ip_profile_params.has_field('gateway_address'):
390 ip_profile['gateway-address'] = ip_profile_params.gateway_address
391 if ip_profile_params.has_field('dns_server') and len(ip_profile_params.dns_server) > 0:
392 ip_profile['dns-address'] = ip_profile_params.dns_server[0].address
393 if ip_profile_params.has_field('dhcp_params'):
394 ip_profile['dhcp'] = {}
395 ip_profile['dhcp']['enabled'] = ip_profile_params.dhcp_params.enabled
396 ip_profile['dhcp']['start-address'] = ip_profile_params.dhcp_params.start_address
397 ip_profile['dhcp']['count'] = ip_profile_params.dhcp_params.count
398 else:
399 network["netmap-create"] = vlr.name
400 if vlr.om_datacenter_name:
401 network["datacenter"] = vlr.om_datacenter_name
402 elif vld_msg.has_field("om_datacenter"):
403 network["datacenter"] = vld_msg.om_datacenter
404 elif "datacenter" in openmano_instance_create:
405 network["datacenter"] = openmano_instance_create["datacenter"]
406 if network:
407 openmano_instance_create["networks"][vld_msg.name]["sites"].append(network)
408 if ip_profile:
409 openmano_instance_create["networks"][vld_msg.name]['ip-profile'] = ip_profile
410
411 return yaml.safe_dump(openmano_instance_create, default_flow_style=False,width=1000)
412
413 @asyncio.coroutine
414 def add_vlr(self, vlr):
415 self._vlrs.append(vlr)
416 yield from self._publisher.publish_vlr(None, vlr.vlr_msg)
417 yield from asyncio.sleep(1, loop=self._loop)
418
419 @asyncio.coroutine
420 def remove_vlr(self, vlr):
421 if vlr in self._vlrs:
422 self._vlrs.remove(vlr)
423 yield from self._publisher.unpublish_vlr(None, vlr.vlr_msg)
424 yield from asyncio.sleep(1, loop=self._loop)
425
426 @asyncio.coroutine
427 def delete_vlr(self, vlr):
428 if vlr in self._vlrs:
429 self._vlrs.remove(vlr)
430 if not vlr.vld_msg.vim_network_name:
431 yield from self._loop.run_in_executor(
432 None,
433 self._cli_api.ns_vim_network_delete,
434 vlr.name,
435 vlr.om_datacenter_name)
436 yield from self._publisher.unpublish_vlr(None, vlr.vlr_msg)
437 yield from asyncio.sleep(1, loop=self._loop)
438
439 @asyncio.coroutine
440 def add_vnfr(self, vnfr):
441 vnfr = OpenmanoVnfr(self._log, self._loop, self._cli_api, vnfr, nsd=self.nsd)
442 yield from vnfr.create()
443 self._vnfrs.append(vnfr)
444
445 def delete(self):
446 if not self._created:
447 self._log.debug("NSD wasn't created. Skipping delete.")
448 return
449
450 self._log.debug("Deleting openmano nsr")
451 self._cli_api.ns_delete(self._nsd_uuid)
452
453 self._log.debug("Deleting openmano vnfrs")
454 deleted_vnf_id_list = []
455 for vnfr in self._vnfrs:
456 if vnfr.vnfr.vnfd.id not in deleted_vnf_id_list:
457 vnfr.delete()
458 deleted_vnf_id_list.append(vnfr.vnfr.vnfd.id)
459
460
461 @asyncio.coroutine
462 def create(self):
463 self._log.debug("Creating openmano scenario")
464 name_uuid_map = yield from self._loop.run_in_executor(
465 None,
466 self._cli_api.ns_list,
467 )
468
469 if self._nsd_msg.name in name_uuid_map:
470 self._log.debug("Found existing openmano scenario")
471 self._nsd_uuid = name_uuid_map[self._nsd_msg.name]
472 return
473
474
475 # Use the nsd uuid as the scenario name to rebind to existing
476 # scenario on reload or to support muliple instances of the name
477 # nsd
478 self._nsd_uuid, _ = yield from self._loop.run_in_executor(
479 None,
480 self._cli_api.ns_create,
481 self.openmano_nsd_yaml,
482 self._nsd_msg.name
483 )
484 fpath = dump_openmano_descriptor(
485 "{}_nsd".format(self._nsd_msg.name),
486 self.openmano_nsd_yaml,
487 )
488
489 self._log.debug("Dumped Openmano NS descriptor to: %s", fpath)
490
491 self._created = True
492
493 @asyncio.coroutine
494 def instance_monitor_task(self):
495 self._log.debug("Starting Instance monitoring task")
496
497 start_time = time.time()
498 active_vnfs = []
499
500 while True:
501 yield from asyncio.sleep(1, loop=self._loop)
502
503 try:
504 instance_resp_json = yield from self._loop.run_in_executor(
505 None,
506 self._http_api.get_instance,
507 self._nsr_uuid,
508 )
509
510 self._log.debug("Got instance response: %s for NSR ID %s",
511 instance_resp_json,
512 self._nsr_uuid)
513
514 except openmano_client.InstanceStatusError as e:
515 self._log.error("Could not get NS instance status: %s", str(e))
516 continue
517
518 def all_vms_active(vnf):
519 for vm in vnf["vms"]:
520 vm_status = vm["status"]
521 vm_uuid = vm["uuid"]
522 if vm_status != "ACTIVE":
523 self._log.debug("VM is not yet active: %s (status: %s)", vm_uuid, vm_status)
524 return False
525
526 return True
527
528 def any_vm_active_nomgmtip(vnf):
529 for vm in vnf["vms"]:
530 vm_status = vm["status"]
531 vm_uuid = vm["uuid"]
532 if vm_status != "ACTIVE":
533 self._log.debug("VM is not yet active: %s (status: %s)", vm_uuid, vm_status)
534 return False
535
536 return True
537
538 def any_vms_error(vnf):
539 for vm in vnf["vms"]:
540 vm_status = vm["status"]
541 vm_vim_info = vm["vim_info"]
542 vm_uuid = vm["uuid"]
543 if vm_status == "ERROR":
544 self._log.error("VM Error: %s (vim_info: %s)", vm_uuid, vm_vim_info)
545 return True
546
547 return False
548
549 def get_vnf_ip_address(vnf):
550 if "ip_address" in vnf:
551 return vnf["ip_address"].strip()
552 return None
553
554 def get_vnf_mac_address(vnf):
555 if "mac_address" in vnf:
556 return vnf["mac_address"].strip()
557 return None
558
559 def get_ext_cp_info(vnf):
560 cp_info_list = []
561 for vm in vnf["vms"]:
562 if "interfaces" not in vm:
563 continue
564
565 for intf in vm["interfaces"]:
566 if "external_name" not in intf:
567 continue
568
569 if not intf["external_name"]:
570 continue
571
572 ip_address = intf["ip_address"]
573 if ip_address is None:
574 ip_address = "0.0.0.0"
575
576 mac_address = intf["mac_address"]
577 if mac_address is None:
578 mac_address="00:00:00:00:00:00"
579
580 cp_info_list.append((intf["external_name"], ip_address, mac_address))
581
582 return cp_info_list
583
584 def get_vnf_status(vnfr):
585 # When we create an openmano descriptor we use <name>__<idx>
586 # to come up with openmano constituent VNF name. Use this
587 # knowledge to map the vnfr back.
588 openmano_vnfr_suffix = "__{}".format(
589 vnfr.vnfr.vnfr_msg.member_vnf_index_ref
590 )
591
592 for vnf in instance_resp_json["vnfs"]:
593 if vnf["vnf_name"].endswith(openmano_vnfr_suffix):
594 return vnf
595
596 self._log.warning("Could not find vnf status with name that ends with: %s",
597 openmano_vnfr_suffix)
598 return None
599
600 for vnfr in self._vnfrs:
601 if vnfr in active_vnfs:
602 # Skipping, so we don't re-publish the same VNF message.
603 continue
604
605 vnfr_msg = vnfr.vnfr.vnfr_msg.deep_copy()
606 vnfr_msg.operational_status = "init"
607
608 try:
609 vnf_status = get_vnf_status(vnfr)
610 self._log.debug("Found VNF status: %s", vnf_status)
611 if vnf_status is None:
612 self._log.error("Could not find VNF status from openmano")
613 self._state = OpenmanoNSRecordState.FAILED
614 vnfr_msg.operational_status = "failed"
615 yield from self._publisher.publish_vnfr(None, vnfr_msg)
616 return
617
618 # If there was a VNF that has a errored VM, then just fail the VNF and stop monitoring.
619 if any_vms_error(vnf_status):
620 self._log.debug("VM was found to be in error state. Marking as failed.")
621 self._state = OpenmanoNSRecordState.FAILED
622 vnfr_msg.operational_status = "failed"
623 yield from self._publisher.publish_vnfr(None, vnfr_msg)
624 return
625
626 if (time.time() - start_time) > OpenmanoNsr.TIMEOUT_SECS:
627 self._log.error("NSR timed out before reaching running state")
628 self._state = OpenmanoNSRecordState.FAILED
629 vnfr_msg.operational_status = "failed"
630 yield from self._publisher.publish_vnfr(None, vnfr_msg)
631 return
632
633 if all_vms_active(vnf_status):
634 vnf_ip_address = get_vnf_ip_address(vnf_status)
635 vnf_mac_address = get_vnf_mac_address(vnf_status)
636
637 if vnf_ip_address is None:
638 self._log.warning("No IP address obtained "
639 "for VNF: {}, will retry.".format(
640 vnf_status['vnf_name']))
641 continue
642
643 self._log.debug("All VMs in VNF are active. Marking as running.")
644 vnfr_msg.operational_status = "running"
645
646 self._log.debug("Got VNF ip address: %s, mac-address: %s", vnf_ip_address, vnf_mac_address)
647 vnfr_msg.mgmt_interface.ip_address = vnf_ip_address
648 vnfr_msg.vnf_configuration.config_access.mgmt_ip_address = vnf_ip_address
649
650
651 for vm in vnf_status["vms"]:
652 if vm["uuid"] not in self._vdur_console_handler:
653 vdur_console_handler = VnfrConsoleOperdataDtsHandler(self._dts, self._log, self._loop,
654 self, vnfr_msg.id,vm["uuid"],vm["name"])
655 yield from vdur_console_handler.register()
656 self._vdur_console_handler[vm["uuid"]] = vdur_console_handler
657
658 vdur_msg = vnfr_msg.vdur.add()
659 vdur_msg.vim_id = vm["vim_vm_id"]
660 vdur_msg.id = vm["uuid"]
661
662 # Add connection point information for the config manager
663 cp_info_list = get_ext_cp_info(vnf_status)
664 for (cp_name, cp_ip, cp_mac_addr) in cp_info_list:
665 cp = vnfr_msg.connection_point.add()
666 cp.name = cp_name
667 cp.short_name = cp_name
668 cp.ip_address = cp_ip
669 cp.mac_address = cp_mac_addr
670
671 yield from self._publisher.publish_vnfr(None, vnfr_msg)
672 active_vnfs.append(vnfr)
673
674 except Exception as e:
675 vnfr_msg.operational_status = "failed"
676 self._state = OpenmanoNSRecordState.FAILED
677 yield from self._publisher.publish_vnfr(None, vnfr_msg)
678 self._log.exception("Caught exception publishing vnfr info: %s", str(e))
679 return
680
681 if len(active_vnfs) == len(self._vnfrs):
682 self._state = OpenmanoNSRecordState.RUNNING
683 self._log.info("All VNF's are active. Exiting NSR monitoring task")
684 return
685
686 @asyncio.coroutine
687 def deploy(self,nsr_msg):
688 if self._nsd_uuid is None:
689 raise ValueError("Cannot deploy an uncreated nsd")
690
691 self._log.debug("Deploying openmano scenario")
692
693 name_uuid_map = yield from self._loop.run_in_executor(
694 None,
695 self._cli_api.ns_instance_list,
696 )
697
698 if self._nsr_config_msg.name in name_uuid_map:
699 self._log.debug("Found existing instance with nsr name: %s", self._nsr_config_msg.name)
700 self._nsr_uuid = name_uuid_map[self._nsr_config_msg.name]
701 else:
702 self._nsr_msg = nsr_msg
703 fpath = dump_openmano_descriptor(
704 "{}_instance_sce_create".format(self._nsr_config_msg.name),
705 self.openmano_instance_create_yaml,
706 )
707 self._log.debug("Dumped Openmano NS Scenario Cretae to: %s", fpath)
708
709 self._nsr_uuid = yield from self._loop.run_in_executor(
710 None,
711 self._cli_api.ns_instance_scenario_create,
712 self.openmano_instance_create_yaml)
713
714 self._state = OpenmanoNSRecordState.INSTANTIATION_PENDING
715
716 self._monitor_task = asyncio.ensure_future(
717 self.instance_monitor_task(), loop=self._loop
718 )
719
720 def terminate(self):
721 if self._nsr_uuid is None:
722 start_time = time.time()
723 while ((time.time() - start_time) < OpenmanoNsr.INSTANCE_TERMINATE_TIMEOUT) and (self._nsr_uuid is None):
724 time.sleep(5)
725 self._log.warning("Waiting for nsr to get instatiated")
726 if self._nsr_uuid is None:
727 self._log.warning("Cannot terminate an un-instantiated nsr")
728 return
729
730 if self._monitor_task is not None:
731 self._monitor_task.cancel()
732 self._monitor_task = None
733
734 self._log.debug("Terminating openmano nsr")
735 self._cli_api.ns_terminate(self._nsr_uuid)
736
737 @asyncio.coroutine
738 def create_vlr(self,vlr):
739 self._log.debug("Creating openmano vim network VLR name %s, VLR DC: %s",vlr.vld_msg.name,
740 vlr.om_datacenter_name)
741 net_create = {}
742 net = {}
743 net['name'] = vlr.name
744 net['shared'] = True
745 net['type'] = 'bridge'
746 self._log.debug("Received ip profile is %s",vlr._ip_profile)
747 if vlr._ip_profile and vlr._ip_profile.has_field("ip_profile_params"):
748 ip_profile_params = vlr._ip_profile.ip_profile_params
749 ip_profile = {}
750 if ip_profile_params.ip_version == "ipv6":
751 ip_profile['ip_version'] = "IPv6"
752 else:
753 ip_profile['ip_version'] = "IPv4"
754 if ip_profile_params.has_field('subnet_address'):
755 ip_profile['subnet_address'] = ip_profile_params.subnet_address
756 if ip_profile_params.has_field('gateway_address'):
757 ip_profile['gateway_address'] = ip_profile_params.gateway_address
758 if ip_profile_params.has_field('dns_server') and len(ip_profile_params.dns_server) > 0:
759 ip_profile['dns_address'] = ip_profile_params.dns_server[0].address
760 if ip_profile_params.has_field('dhcp_params'):
761 ip_profile['dhcp_enabled'] = ip_profile_params.dhcp_params.enabled
762 ip_profile['dhcp_start_address'] = ip_profile_params.dhcp_params.start_address
763 ip_profile['dhcp_count'] = ip_profile_params.dhcp_params.count
764 net['ip_profile'] = ip_profile
765 net_create["network"]= net
766
767 net_create_msg = yaml.safe_dump(net_create,default_flow_style=False)
768 fpath = dump_openmano_descriptor(
769 "{}_vim_net_create_{}".format(self._nsr_config_msg.name,vlr.name),
770 net_create_msg)
771 self._log.debug("Dumped Openmano VIM Net create to: %s", fpath)
772
773 vim_network_uuid = yield from self._loop.run_in_executor(
774 None,
775 self._cli_api.ns_vim_network_create,
776 net_create_msg,
777 vlr.om_datacenter_name)
778 self._vlrs.append(vlr)
779
780
781
782 class OpenmanoNsPlugin(rwnsmplugin.NsmPluginBase):
783 """
784 RW Implentation of the NsmPluginBase
785 """
786 def __init__(self, dts, log, loop, publisher, ro_account):
787 self._dts = dts
788 self._log = log
789 self._loop = loop
790 self._publisher = publisher
791
792 self._cli_api = None
793 self._http_api = None
794 self._openmano_nsrs = {}
795 self._vnfr_uptime_tasks = {}
796
797 self._set_ro_account(ro_account)
798
799 def _set_ro_account(self, ro_account):
800 self._log.debug("Setting openmano plugin cloud account: %s", ro_account)
801 self._cli_api = openmano_client.OpenmanoCliAPI(
802 self.log,
803 ro_account.openmano.host,
804 ro_account.openmano.port,
805 ro_account.openmano.tenant_id,
806 )
807
808 self._http_api = openmano_client.OpenmanoHttpAPI(
809 self.log,
810 ro_account.openmano.host,
811 ro_account.openmano.port,
812 ro_account.openmano.tenant_id,
813 )
814
815 def set_state(self, nsr_id, state):
816 # Currently we update only during terminate to
817 # decide how to handle VL terminate
818 if state.value == OpenmanoNSRecordState.TERMINATE.value:
819 self._openmano_nsrs[nsr_id]._state = \
820 [member.value for name, member in \
821 OpenmanoNSRecordState.__members__.items() \
822 if member.value == state.value]
823
824 def create_nsr(self, nsr_config_msg, nsd_msg, key_pairs=None):
825 """
826 Create Network service record
827 """
828 openmano_nsr = OpenmanoNsr(
829 self._dts,
830 self._log,
831 self._loop,
832 self._publisher,
833 self._cli_api,
834 self._http_api,
835 nsd_msg,
836 nsr_config_msg,
837 key_pairs
838 )
839 self._openmano_nsrs[nsr_config_msg.id] = openmano_nsr
840
841 @asyncio.coroutine
842 def deploy(self, nsr_msg):
843 self._log.debug("Received NSR Deploy msg : %s", nsr_msg)
844 openmano_nsr = self._openmano_nsrs[nsr_msg.ns_instance_config_ref]
845 yield from openmano_nsr.create()
846 yield from openmano_nsr.deploy(nsr_msg)
847
848 @asyncio.coroutine
849 def instantiate_ns(self, nsr, xact):
850 """
851 Instantiate NSR with the passed nsr id
852 """
853 yield from nsr.instantiate(xact)
854
855 @asyncio.coroutine
856 def instantiate_vnf(self, nsr, vnfr):
857 """
858 Instantiate NSR with the passed nsr id
859 """
860 openmano_nsr = self._openmano_nsrs[nsr.id]
861 yield from openmano_nsr.add_vnfr(vnfr)
862
863 # Mark the VNFR as running
864 # TODO: Create a task to monitor nsr/vnfr status
865 vnfr_msg = vnfr.vnfr_msg.deep_copy()
866 vnfr_msg.operational_status = "init"
867
868 self._log.debug("Attempting to publish openmano vnf: %s", vnfr_msg)
869 with self._dts.transaction() as xact:
870 yield from self._publisher.publish_vnfr(xact, vnfr_msg)
871 self._log.debug("Creating a task to update uptime for vnfr: %s", vnfr.id)
872 self._vnfr_uptime_tasks[vnfr.id] = self._loop.create_task(self.vnfr_uptime_update(vnfr))
873
874 def vnfr_uptime_update(self, vnfr):
875 try:
876 vnfr_ = RwVnfrYang.YangData_Vnfr_VnfrCatalog_Vnfr.from_dict({'id': vnfr.id})
877 while True:
878 vnfr_.uptime = int(time.time()) - vnfr._create_time
879 yield from self._publisher.publish_vnfr(None, vnfr_)
880 yield from asyncio.sleep(2, loop=self._loop)
881 except asyncio.CancelledError:
882 self._log.debug("Received cancellation request for vnfr_uptime_update task")
883
884 @asyncio.coroutine
885 def instantiate_vl(self, nsr, vlr):
886 """
887 Instantiate NSR with the passed nsr id
888 """
889 self._log.debug("Received instantiate VL for NSR {}; VLR {}".format(nsr.id,vlr))
890 openmano_nsr = self._openmano_nsrs[nsr.id]
891 if openmano_nsr._state == OpenmanoNSRecordState.RUNNING:
892 yield from openmano_nsr.create_vlr(vlr)
893 yield from self._publisher.publish_vlr(None, vlr.vlr_msg)
894 else:
895 yield from openmano_nsr.add_vlr(vlr)
896
897 @asyncio.coroutine
898 def terminate_ns(self, nsr):
899 """
900 Terminate the network service
901 """
902 nsr_id = nsr.id
903 openmano_nsr = self._openmano_nsrs[nsr_id]
904
905 for _,handler in openmano_nsr._vdur_console_handler.items():
906 handler._regh.deregister()
907
908 yield from self._loop.run_in_executor(
909 None,
910 self.terminate,
911 openmano_nsr,
912 )
913
914 with self._dts.transaction() as xact:
915 for vnfr in openmano_nsr.vnfrs:
916 self._log.debug("Unpublishing VNFR: %s", vnfr.vnfr.vnfr_msg)
917 yield from self._publisher.unpublish_vnfr(xact, vnfr.vnfr.vnfr_msg)
918
919 del self._openmano_nsrs[nsr_id]
920
921 def terminate(self, openmano_nsr):
922 openmano_nsr.terminate()
923 openmano_nsr.delete()
924
925 @asyncio.coroutine
926 def terminate_vnf(self, vnfr):
927 """
928 Terminate the network service
929 """
930 if vnfr.id in self._vnfr_uptime_tasks:
931 self._vnfr_uptime_tasks[vnfr.id].cancel()
932
933 @asyncio.coroutine
934 def terminate_vl(self, vlr):
935 """
936 Terminate the virtual link
937 """
938 self._log.debug("Received terminate VL for VLR {}".format(vlr))
939 openmano_nsr = self._openmano_nsrs[vlr._nsr_id]
940 if openmano_nsr._state == OpenmanoNSRecordState.RUNNING:
941 yield from openmano_nsr.delete_vlr(vlr)
942 else:
943 yield from openmano_nsr.remove_vlr(vlr)