REMOVE some comments and unnecessary lines
[osm/RO.git] / osm_ro / vimconn_opennebula.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2017 Telefonica Digital Spain S.L.U.
5 # This file is part of ETSI OSM
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
18 # License for the specific language governing permissions and limitations
19 # under the License.
20 #
21 # For those usages not covered by the Apache License, Version 2.0 please
22 # contact with: patent-office@telefonica.com
23 ##
24
25 """
26 vimconnector implements all the methods to interact with OpenNebula using the XML-RPC API.
27 """
28 __author__ = "Jose Maria Carmona Perez,Juan Antonio Hernando Labajo, Emilio Abraham Garrido Garcia,Alberto Florez " \
29 "Pages, Andres Pozo Munoz, Santiago Perez Marin, Onlife Networks Telefonica I+D Product Innovation "
30 __date__ = "$13-dec-2017 11:09:29$"
31 import vimconn
32 import requests
33 import logging
34 import oca
35 import untangle
36 import math
37 import random
38
39
40 class vimconnector(vimconn.vimconnector):
41 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
42 log_level="DEBUG", config={}, persistent_info={}):
43 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
44 config)
45 self.tenant = None
46 self.headers_req = {'content-type': 'application/json'}
47 self.logger = logging.getLogger('openmano.vim.opennebula')
48 self.persistent_info = persistent_info
49 if tenant_id:
50 self.tenant = tenant_id
51
52 def __setitem__(self, index, value):
53 """Set individuals parameters
54 Throw TypeError, KeyError
55 """
56 if index == 'tenant_id':
57 self.tenant = value
58 elif index == 'tenant_name':
59 self.tenant = None
60 vimconn.vimconnector.__setitem__(self, index, value)
61
62 def new_tenant(self, tenant_name, tenant_description):
63 # '''Adds a new tenant to VIM with this name and description, returns the tenant identifier'''
64 try:
65 client = oca.Client(self.user + ':' + self.passwd, self.url)
66 group_list = oca.GroupPool(client)
67 user_list = oca.UserPool(client)
68 group_list.info()
69 user_list.info()
70 create_primarygroup = 1
71 # create group-tenant
72 for group in group_list:
73 if str(group.name) == str(tenant_name):
74 create_primarygroup = 0
75 break
76 if create_primarygroup == 1:
77 oca.Group.allocate(client, tenant_name)
78 group_list.info()
79 # set to primary_group the tenant_group and oneadmin to secondary_group
80 for group in group_list:
81 if str(group.name) == str(tenant_name):
82 for user in user_list:
83 if str(user.name) == str(self.user):
84 if user.name == "oneadmin":
85 return str(0)
86 else:
87 self._add_secondarygroup(user.id, group.id)
88 user.chgrp(group.id)
89 return str(group.id)
90 except Exception as e:
91 self.logger.error("Create new tenant error: " + str(e))
92 raise vimconn.vimconnException(e)
93
94 def _add_secondarygroup(self, id_user, id_group):
95 # change secondary_group to primary_group
96 params = '<?xml version="1.0"?> \
97 <methodCall>\
98 <methodName>one.user.addgroup</methodName>\
99 <params>\
100 <param>\
101 <value><string>{}:{}</string></value>\
102 </param>\
103 <param>\
104 <value><int>{}</int></value>\
105 </param>\
106 <param>\
107 <value><int>{}</int></value>\
108 </param>\
109 </params>\
110 </methodCall>'.format(self.user, self.passwd, (str(id_user)), (str(id_group)))
111 requests.post(self.url, params)
112
113 def delete_tenant(self, tenant_id):
114 """Delete a tenant from VIM. Returns the old tenant identifier"""
115 try:
116 client = oca.Client(self.user + ':' + self.passwd, self.url)
117 group_list = oca.GroupPool(client)
118 user_list = oca.UserPool(client)
119 group_list.info()
120 user_list.info()
121 for group in group_list:
122 if str(group.id) == str(tenant_id):
123 for user in user_list:
124 if str(user.name) == str(self.user):
125 self._delete_secondarygroup(user.id, group.id)
126 group.delete(client)
127 return None
128 raise vimconn.vimconnNotFoundException("Group {} not found".format(tenant_id))
129 except Exception as e:
130 self.logger.error("Delete tenant " + str(tenant_id) + " error: " + str(e))
131 raise vimconn.vimconnException(e)
132
133 # to be used in future commits
134 def _delete_secondarygroup(self, id_user, id_group):
135 params = '<?xml version="1.0"?> \
136 <methodCall>\
137 <methodName>one.user.delgroup</methodName>\
138 <params>\
139 <param>\
140 <value><string>{}:{}</string></value>\
141 </param>\
142 <param>\
143 <value><int>{}</int></value>\
144 </param>\
145 <param>\
146 <value><int>{}</int></value>\
147 </param>\
148 </params>\
149 </methodCall>'.format(self.user, self.passwd, (str(id_user)), (str(id_group)))
150 requests.post(self.url, params)
151
152 # to be used in future commits
153 # def get_tenant_list(self, filter_dict={}):
154 # return ["tenant"]
155
156 # to be used in future commits
157 # def _check_tenant(self):
158 # try:
159 # client = oca.Client(self.user + ':' + self.passwd, self.url)
160 # group_list = oca.GroupPool(client)
161 # user_list = oca.UserPool(client)
162 # group_list.info()
163 # user_list.info()
164 # for group in group_list:
165 # if str(group.name) == str(self.tenant_name):
166 # for user in user_list:
167 # if str(user.name) == str(self.user):
168 # self._add_secondarygroup(user.id, group.id)
169 # user.chgrp(group.id)
170 # except vimconn.vimconnException as e:
171 # self.logger.error(e)
172
173 # to be used in future commits, needs refactor to manage networks
174 # def _create_bridge_host(self, vlan):
175 # file = open('manage_bridge_OSM', 'w')
176 # # password_path = self.config["password"]["path"]
177 # a = "#! /bin/bash\nsudo brctl addbr br_osm_{vlanused}\n" \
178 # "sudo ip link add link veth1 name veth1.{vlanused} type vlan id {vlanused}\n" \
179 # "sudo brctl addif br_osm_{vlanused} veth1.{vlanused}\n" \
180 # "sudo ip link set dev br_osm_{vlanused} up\n" \
181 # "sudo ip link set dev veth1.{vlanused} up\n".format(vlanused=vlan)
182 # # a = "#! /bin/bash\nsudo brctl addbr br_osm\nsudo ip link set dev br_osm up\n"
183 # file.write(a)
184 # file.close()
185 # for host in self.config["cluster"]["ip"]:
186 # file_scp = "/usr/bin/scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {} manage_bridge_OSM {}@{}:/home/{}".format(
187 # self.config["cluster"]["password_path"][host], self.config["cluster"]["login"][host],
188 # self.config["cluster"]["ip"][host], self.config["cluster"]["login"][host])
189 # os.system(file_scp)
190 # file_permissions = "/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {} {}@{} sudo chmod 700 manage_bridge_OSM".format(
191 # self.config["cluster"]["password_path"][host], self.config["cluster"]["login"][host],
192 # self.config["cluster"]["ip"][host])
193 # os.system(file_permissions)
194 # exec_script = "/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i {} {}@{} sudo ./manage_bridge_OSM".format(
195 # self.config["cluster"]["password_path"][host], self.config["cluster"]["login"][host],
196 # self.config["cluster"]["ip"][host])
197 # os.system(exec_script)
198 # os.remove("manage_bridge_OSM")
199
200 # to be used to manage networks with vlan
201 # def delete_bridge_host(self, vlan):
202 # file = open('manage_bridge_OSM', 'w')
203 # a = "#! /bin/bash\nsudo ip link set dev veth1.3142 down\nsudo ip link set dev br_3142 down\nsudo brctl delbr br_3142\n"
204 # file.write(a)
205 # file.close()
206 # os.system("/usr/bin/scp -i onlife manage_bridge_OSM sysadmin@10.95.84.12:/home/sysadmin")
207 # os.system("/usr/bin/ssh -i onlife sysadmin@10.95.84.12 sudo chmod 700 manage_bridge_OSM")
208 # os.system("/usr/bin/ssh -i onlife sysadmin@10.95.84.12 sudo ./manage_bridge_OSM")
209 # os.remove("manage_bridge_OSM")
210
211 def new_network(self, net_name, net_type, ip_profile=None, shared=False, vlan=None): # , **vim_specific):
212 """Returns the network identifier"""
213 # oca library method cannot be used in this case (problem with cluster parameters)
214 try:
215 # vlan = str(random.randint(self.config["vlan"]["start-range"], self.config["vlan"]["finish-range"]))
216 # self.create_bridge_host(vlan)
217 bridge_config = self.config["bridge_service"]
218 ip_version = "IP4"
219 size = "256"
220 if ip_profile is None:
221 random_number_ipv4 = random.randint(1, 255)
222 ip_start = "192.168." + str(random_number_ipv4) + ".1" # random value
223 else:
224 index = ip_profile["subnet_address"].find("/")
225 ip_start = ip_profile["subnet_address"][:index]
226 if "dhcp_count" in ip_profile.keys() and ip_profile["dhcp_count"] is not None:
227 size = str(ip_profile["dhcp_count"])
228 elif not ("dhcp_count" in ip_profile.keys()) and ip_profile["ip_version"] == "IPv4":
229 prefix = ip_profile["subnet_address"][index + 1:]
230 size = int(math.pow(2, 32 - prefix))
231 if "dhcp_start_address" in ip_profile.keys() and ip_profile["dhcp_start_address"] is not None:
232 ip_start = str(ip_profile["dhcp_start_address"])
233 if ip_profile["ip_version"] == "IPv6":
234 ip_version = "IP6"
235 if ip_version == "IP6":
236 config = "NAME = {}\
237 BRIDGE = {}\
238 VN_MAD = dummy\
239 AR = [TYPE = {}, GLOBAL_PREFIX = {}, SIZE = {}]".format(net_name, bridge_config, ip_version,
240 ip_start, size)
241 else:
242 config = 'NAME = "{}"\
243 BRIDGE = {}\
244 VN_MAD = dummy\
245 AR = [TYPE = {}, IP = {}, SIZE = {}]'.format(net_name, bridge_config, ip_version, ip_start,
246 size)
247
248 params = '<?xml version="1.0"?> \
249 <methodCall>\
250 <methodName>one.vn.allocate</methodName>\
251 <params>\
252 <param>\
253 <value><string>{}:{}</string></value>\
254 </param>\
255 <param>\
256 <value><string>{}</string></value>\
257 </param>\
258 <param>\
259 <value><int>{}</int></value>\
260 </param>\
261 </params>\
262 </methodCall>'.format(self.user, self.passwd, config, self.config["cluster"]["id"])
263 r = requests.post(self.url, params)
264 obj = untangle.parse(str(r.content))
265 return obj.methodResponse.params.param.value.array.data.value[1].i4.cdata.encode('utf-8')
266 except Exception as e:
267 self.logger.error("Create new network error: " + str(e))
268 raise vimconn.vimconnException(e)
269
270 def get_network_list(self, filter_dict={}):
271 """Obtain tenant networks of VIM
272 Filter_dict can be:
273 name: network name
274 id: network uuid
275 public: boolean
276 tenant_id: tenant
277 admin_state_up: boolean
278 status: 'ACTIVE'
279 Returns the network list of dictionaries
280 """
281 try:
282 client = oca.Client(self.user + ':' + self.passwd, self.url)
283 networkList = oca.VirtualNetworkPool(client)
284 networkList.info()
285 response = []
286 if "name" in filter_dict.keys():
287 network_name_filter = filter_dict["name"]
288 else:
289 network_name_filter = None
290 if "id" in filter_dict.keys():
291 network_id_filter = filter_dict["id"]
292 else:
293 network_id_filter = None
294 for network in networkList:
295 match = False
296 if network.name == network_name_filter and str(network.id) == str(network_id_filter):
297 match = True
298 if network_name_filter is None and str(network.id) == str(network_id_filter):
299 match = True
300 if network_id_filter is None and network.name == network_name_filter:
301 match = True
302 if match:
303 net_dict = {"name": network.name, "id": str(network.id)}
304 response.append(net_dict)
305 return response
306 except Exception as e:
307 self.logger.error("Get network list error: " + str(e))
308 raise vimconn.vimconnException(e)
309
310 def get_network(self, net_id):
311 """Obtain network details of network id"""
312 try:
313 client = oca.Client(self.user + ':' + self.passwd, self.url)
314 networkList = oca.VirtualNetworkPool(client)
315 networkList.info()
316 net = {}
317 for network in networkList:
318 if str(network.id) == str(net_id):
319 net['id'] = net_id
320 net['name'] = network.name
321 net['status'] = "ACTIVE"
322 break
323 if net:
324 return net
325 else:
326 raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
327 except Exception as e:
328 self.logger.error("Get network " + str(net_id) + " error): " + str(e))
329 raise vimconn.vimconnException(e)
330
331 def delete_network(self, net_id):
332 """Deletes a tenant network from VIM
333 Returns the network identifier
334 """
335 try:
336 # self.delete_bridge_host()
337 client = oca.Client(self.user + ':' + self.passwd, self.url)
338 networkList = oca.VirtualNetworkPool(client)
339 networkList.info()
340 network_deleted = False
341 for network in networkList:
342 if str(network.id) == str(net_id):
343 oca.VirtualNetwork.delete(network)
344 network_deleted = True
345 if network_deleted:
346 return net_id
347 else:
348 raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
349 except Exception as e:
350 self.logger.error("Delete network " + str(net_id) + "error: " + str(e))
351 raise vimconn.vimconnException(e)
352
353 def get_flavor(self, flavor_id): # Esta correcto
354 """Obtain flavor details from the VIM"""
355 try:
356 client = oca.Client(self.user + ':' + self.passwd, self.url)
357 listaTemplate = oca.VmTemplatePool(client)
358 listaTemplate.info()
359 for template in listaTemplate:
360 if str(template.id) == str(flavor_id):
361 return {'id': template.id, 'name': template.name}
362 raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id))
363 except Exception as e:
364 self.logger.error("get flavor " + str(flavor_id) + " error: " + str(e))
365 raise vimconn.vimconnException(e)
366
367 def new_flavor(self, flavor_data):
368 """Adds a tenant flavor to VIM
369 Returns the flavor identifier"""
370 try:
371 client = oca.Client(self.user + ':' + self.passwd, self.url)
372 template_name = flavor_data["name"][:-4]
373 name = 'NAME = "{}" '.format(template_name)
374 cpu = 'CPU = "{}" '.format(flavor_data["vcpus"])
375 vcpu = 'VCPU = "{}" '.format(flavor_data["vcpus"])
376 memory = 'MEMORY = "{}" '.format(flavor_data["ram"])
377 context = 'CONTEXT = [NETWORK = "YES",SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ] '
378 graphics = 'GRAPHICS = [ LISTEN = "0.0.0.0", TYPE = "VNC" ] '
379 sched_requeriments = 'CLUSTER_ID={}'.format(self.config["cluster"]["id"])
380 template = name + cpu + vcpu + memory + context + graphics + sched_requeriments
381 template_id = oca.VmTemplate.allocate(client, template)
382 return template_id
383 except Exception as e:
384 self.logger.error("Create new flavor error: " + str(e))
385 raise vimconn.vimconnException(e)
386
387 def delete_flavor(self, flavor_id):
388 """ Deletes a tenant flavor from VIM
389 Returns the old flavor_id
390 """
391 try:
392 client = oca.Client(self.user + ':' + self.passwd, self.url)
393 listaTemplate = oca.VmTemplatePool(client)
394 listaTemplate.info()
395 self.logger.info("Deleting VIM flavor DELETE {}".format(self.url))
396 for template in listaTemplate:
397 if str(template.id) == str(flavor_id):
398 template.delete()
399 return template.id
400 raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id))
401 except Exception as e:
402 self.logger.error("Delete flavor " + str(flavor_id) + " error: " + str(e))
403 raise vimconn.vimconnException(e)
404
405 def get_image_list(self, filter_dict={}):
406 """Obtain tenant images from VIM
407 Filter_dict can be:
408 name: image name
409 id: image uuid
410 checksum: image checksum
411 location: image path
412 Returns the image list of dictionaries:
413 [{<the fields at Filter_dict plus some VIM specific>}, ...]
414 List can be empty
415 """
416 # IMPORTANT!!!!! Modify python oca library path pool.py line 102
417
418 try:
419 client = oca.Client(self.user + ':' + self.passwd, self.url)
420 image_pool = oca.ImagePool(client)
421 image_pool.info()
422 images = []
423 if "name" in filter_dict.keys():
424 image_name_filter = filter_dict["name"]
425 else:
426 image_name_filter = None
427 if "id" in filter_dict.keys():
428 image_id_filter = filter_dict["id"]
429 else:
430 image_id_filter = None
431 for image in image_pool:
432 match = False
433 if str(image_name_filter) == str(image.name) and str(image.id) == str(image_id_filter):
434 match = True
435 if image_name_filter is None and str(image.id) == str(image_id_filter):
436 match = True
437 if image_id_filter is None and str(image_name_filter) == str(image.name):
438 match = True
439 if match:
440 images_dict = {"name": image.name, "id": str(image.id)}
441 images.append(images_dict)
442 return images
443 except Exception as e:
444 self.logger.error("Get image list error: " + str(e))
445 raise vimconn.vimconnException(e)
446
447 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
448 availability_zone_index=None, availability_zone_list=None):
449 """Adds a VM instance to VIM
450 Params:
451 start: indicates if VM must start or boot in pause mode. Ignored
452 image_id,flavor_id: image and flavor uuid
453 net_list: list of interfaces, each one is a dictionary with:
454 name:
455 net_id: network uuid to connect
456 vpci: virtual vcpi to assign
457 model: interface model, virtio, e1000, ...
458 mac_address:
459 use: 'data', 'bridge', 'mgmt'
460 type: 'virtual', 'PF', 'VF', 'VFnotShared'
461 vim_id: filled/added by this function
462 #TODO ip, security groups
463 Returns the instance identifier
464 """
465 self.logger.debug(
466 "new_vminstance input: image='{}' flavor='{}' nics='{}'".format(image_id, flavor_id, str(net_list)))
467 try:
468 client = oca.Client(self.user + ':' + self.passwd, self.url)
469 listaTemplate = oca.VmTemplatePool(client)
470 listaTemplate.info()
471 for template in listaTemplate:
472 if str(template.id) == str(flavor_id):
473 cpu = ' CPU = "{}"'.format(template.template.cpu)
474 vcpu = ' VCPU = "{}"'.format(template.template.cpu)
475 memory = ' MEMORY = "{}"'.format(template.template.memory)
476 context = ' CONTEXT = [NETWORK = "YES",SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ]'
477 graphics = ' GRAPHICS = [ LISTEN = "0.0.0.0", TYPE = "VNC" ]'
478 disk = ' DISK = [ IMAGE_ID = {}]'.format(image_id)
479 template_updated = cpu + vcpu + memory + context + graphics + disk
480 networkListVim = oca.VirtualNetworkPool(client)
481 networkListVim.info()
482 network = ""
483 for net in net_list:
484 network_found = False
485 for network_existingInVim in networkListVim:
486 if str(net["net_id"]) == str(network_existingInVim.id):
487 net["vim_id"] = network_existingInVim["id"]
488 network = 'NIC = [NETWORK = "{}",NETWORK_UNAME = "{}" ]'.format(
489 network_existingInVim.name, network_existingInVim.uname)
490 network_found = True
491 break
492 if not network_found:
493 raise vimconn.vimconnNotFoundException("Network {} not found".format(net["net_id"]))
494 template_updated += network
495 if isinstance(cloud_config, dict):
496 if cloud_config.get("user-data"):
497 if isinstance(cloud_config["user-data"], str):
498 template_updated += cloud_config["user-data"]
499 else:
500 for u in cloud_config["user-data"]:
501 template_updated += u
502 oca.VmTemplate.update(template, template_updated)
503 self.logger.info(
504 "Instanciating in OpenNebula a new VM name:{} id:{}".format(template.name, template.id))
505 vminstance_id = template.instantiate(name=name)
506 return str(vminstance_id), None
507 raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id))
508 except Exception as e:
509 self.logger.error("Create new vm instance error: " + str(e))
510 raise vimconn.vimconnException(e)
511
512 def delete_vminstance(self, vm_id, created_items=None):
513 """Removes a VM instance from VIM, returns the deleted vm_id"""
514 try:
515 client = oca.Client(self.user + ':' + self.passwd, self.url)
516 vm_pool = oca.VirtualMachinePool(client)
517 vm_pool.info()
518 vm_exist = False
519 for i in vm_pool:
520 if str(i.id) == str(vm_id):
521 vm_exist = True
522 break
523 if not vm_exist:
524 self.logger.info("The vm " + str(vm_id) + " does not exist or is already deleted")
525 raise vimconn.vimconnNotFoundException("The vm {} does not exist or is already deleted".format(vm_id))
526 params = '<?xml version="1.0"?> \
527 <methodCall>\
528 <methodName>one.vm.recover</methodName>\
529 <params>\
530 <param>\
531 <value><string>{}:{}</string></value>\
532 </param>\
533 <param>\
534 <value><int>{}</int></value>\
535 </param>\
536 <param>\
537 <value><int>{}</int></value>\
538 </param>\
539 </params>\
540 </methodCall>'.format(self.user, self.passwd, str(vm_id), str(3))
541 r = requests.post(self.url, params)
542 obj = untangle.parse(str(r.content))
543 response_success = obj.methodResponse.params.param.value.array.data.value[0].boolean.cdata.encode('utf-8')
544 response = obj.methodResponse.params.param.value.array.data.value[1].i4.cdata.encode('utf-8')
545 # response can be the resource ID on success or the error string on failure.
546 response_error_code = obj.methodResponse.params.param.value.array.data.value[2].i4.cdata.encode('utf-8')
547 if response_success.lower() == "true":
548 return response
549 else:
550 raise vimconn.vimconnException("vm {} cannot be deleted with error_code {}: {}".format(vm_id, response_error_code, response))
551 except Exception as e:
552 self.logger.error("Delete vm instance " + str(vm_id) + " error: " + str(e))
553 raise vimconn.vimconnException(e)
554
555 def refresh_vms_status(self, vm_list):
556 """Refreshes the status of the virtual machines"""
557 vm_dict = {}
558 try:
559 client = oca.Client(self.user + ':' + self.passwd, self.url)
560 vm_pool = oca.VirtualMachinePool(client)
561 vm_pool.info()
562 for vm_id in vm_list:
563 vm = {"interfaces": []}
564 vm_exist = False
565 vm_element = None
566 for i in vm_pool:
567 if str(i.id) == str(vm_id):
568 vm_exist = True
569 vm_element = i
570 break
571 if not vm_exist:
572 self.logger.info("The vm " + str(vm_id) + " does not exist.")
573 vm['status'] = "DELETED"
574 vm['error_msg'] = ("The vm " + str(vm_id) + " does not exist.")
575 continue
576 vm_element.info()
577 vm["vim_info"] = None
578 VMstatus = vm_element.str_lcm_state
579 if VMstatus == "RUNNING":
580 vm['status'] = "ACTIVE"
581 elif "FAILURE" in VMstatus:
582 vm['status'] = "ERROR"
583 vm['error_msg'] = "VM failure"
584 else:
585 vm['status'] = "BUILD"
586 try:
587 for red in vm_element.template.nics:
588 interface = {'vim_info': None, "mac_address": str(red.mac), "vim_net_id": str(red.network_id),
589 "vim_interface_id": str(red.network_id)}
590 # maybe it should be 2 different keys for ip_address if an interface has ipv4 and ipv6
591 if hasattr(red, 'ip'):
592 interface["ip_address"] = str(red.ip)
593 if hasattr(red, 'ip6_global'):
594 interface["ip_address"] = str(red.ip6_global)
595 vm["interfaces"].append(interface)
596 except Exception as e:
597 self.logger.error("Error getting vm interface_information " + type(e).__name__ + ":" + str(e))
598 vm["status"] = "VIM_ERROR"
599 vm["error_msg"] = "Error getting vm interface_information " + type(e).__name__ + ":" + str(e)
600 vm_dict[vm_id] = vm
601 return vm_dict
602 except Exception as e:
603 self.logger.error(e)
604 for k in vm_dict:
605 vm_dict[k]["status"] = "VIM_ERROR"
606 vm_dict[k]["error_msg"] = str(e)
607 return vm_dict
608
609 def refresh_nets_status(self, net_list):
610 """Get the status of the networks
611 Params: the list of network identifiers
612 Returns a dictionary with:
613 net_id: #VIM id of this network
614 status: #Mandatory. Text with one of:
615 # DELETED (not found at vim)
616 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
617 # OTHER (Vim reported other status not understood)
618 # ERROR (VIM indicates an ERROR status)
619 # ACTIVE, INACTIVE, DOWN (admin down),
620 # BUILD (on building process)
621 #
622 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
623 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
624 """
625 net_dict = {}
626 try:
627 for net_id in net_list:
628 net = {}
629 try:
630 net_vim = self.get_network(net_id)
631 net["status"] = net_vim["status"]
632 net["vim_info"] = None
633 except vimconn.vimconnNotFoundException as e:
634 self.logger.error("Exception getting net status: {}".format(str(e)))
635 net['status'] = "DELETED"
636 net['error_msg'] = str(e)
637 except vimconn.vimconnException as e:
638 self.logger.error(e)
639 net["status"] = "VIM_ERROR"
640 net["error_msg"] = str(e)
641 net_dict[net_id] = net
642 return net_dict
643 except vimconn.vimconnException as e:
644 self.logger.error(e)
645 for k in net_dict:
646 net_dict[k]["status"] = "VIM_ERROR"
647 net_dict[k]["error_msg"] = str(e)
648 return net_dict
649
650 # to be used and fixed in future commits... not working properly
651 # def action_vminstance(self, vm_id, action_dict):
652 # """Send and action over a VM instance from VIM
653 # Returns the status"""
654 # try:
655 # if "console" in action_dict:
656 # console_dict = {"protocol": "http",
657 # "server": "10.95.84.42",
658 # "port": "29876",
659 # "suffix": "?token=4hsb9cu9utruakon4p3z"
660 # }
661 # return console_dict
662 # except vimconn.vimconnException as e:
663 # self.logger.error(e)
664