| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| 3 | ## |
| tierno | 9202102 | 2018-09-12 16:29:23 +0200 | [diff] [blame] | 4 | # Copyright 2017 Telefonica Digital Spain S.L.U. |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 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 " \ |
| tierno | 9202102 | 2018-09-12 16:29:23 +0200 | [diff] [blame] | 29 | "Pages, Andres Pozo Munoz, Santiago Perez Marin, Onlife Networks Telefonica I+D Product Innovation " |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 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 |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 296 | if network.name == network_name_filter and str(network.id) == str(network_id_filter): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 297 | match = True |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 298 | if network_name_filter is None and str(network.id) == str(network_id_filter): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 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 | memory = 'MEMORY = "{}" '.format(flavor_data["ram"]) |
| 376 | context = 'CONTEXT = [NETWORK = "YES",SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ] ' |
| 377 | graphics = 'GRAPHICS = [ LISTEN = "0.0.0.0", TYPE = "VNC" ] ' |
| 378 | sched_requeriments = 'CLUSTER_ID={}'.format(self.config["cluster"]["id"]) |
| 379 | template = name + cpu + memory + context + graphics + sched_requeriments |
| 380 | template_id = oca.VmTemplate.allocate(client, template) |
| 381 | return template_id |
| 382 | except Exception as e: |
| 383 | self.logger.error("Create new flavor error: " + str(e)) |
| 384 | raise vimconn.vimconnException(e) |
| 385 | |
| 386 | def delete_flavor(self, flavor_id): |
| 387 | """ Deletes a tenant flavor from VIM |
| 388 | Returns the old flavor_id |
| 389 | """ |
| 390 | try: |
| 391 | client = oca.Client(self.user + ':' + self.passwd, self.url) |
| 392 | listaTemplate = oca.VmTemplatePool(client) |
| 393 | listaTemplate.info() |
| 394 | self.logger.info("Deleting VIM flavor DELETE {}".format(self.url)) |
| 395 | for template in listaTemplate: |
| 396 | if str(template.id) == str(flavor_id): |
| 397 | template.delete() |
| 398 | return template.id |
| 399 | raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id)) |
| 400 | except Exception as e: |
| 401 | self.logger.error("Delete flavor " + str(flavor_id) + " error: " + str(e)) |
| 402 | raise vimconn.vimconnException(e) |
| 403 | |
| 404 | def get_image_list(self, filter_dict={}): |
| 405 | """Obtain tenant images from VIM |
| 406 | Filter_dict can be: |
| 407 | name: image name |
| 408 | id: image uuid |
| 409 | checksum: image checksum |
| 410 | location: image path |
| 411 | Returns the image list of dictionaries: |
| 412 | [{<the fields at Filter_dict plus some VIM specific>}, ...] |
| 413 | List can be empty |
| 414 | """ |
| 415 | # IMPORTANT!!!!! Modify python oca library path pool.py line 102 |
| 416 | |
| 417 | try: |
| 418 | client = oca.Client(self.user + ':' + self.passwd, self.url) |
| 419 | image_pool = oca.ImagePool(client) |
| 420 | image_pool.info() |
| 421 | images = [] |
| 422 | if "name" in filter_dict.keys(): |
| 423 | image_name_filter = filter_dict["name"] |
| 424 | else: |
| 425 | image_name_filter = None |
| 426 | if "id" in filter_dict.keys(): |
| 427 | image_id_filter = filter_dict["id"] |
| 428 | else: |
| 429 | image_id_filter = None |
| 430 | for image in image_pool: |
| 431 | match = False |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 432 | if str(image_name_filter) == str(image.name) and str(image.id) == str(image_id_filter): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 433 | match = True |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 434 | if image_name_filter is None and str(image.id) == str(image_id_filter): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 435 | match = True |
| 436 | if image_id_filter is None and str(image_name_filter) == str(image.name): |
| 437 | match = True |
| 438 | if match: |
| 439 | images_dict = {"name": image.name, "id": str(image.id)} |
| 440 | images.append(images_dict) |
| 441 | return images |
| 442 | except Exception as e: |
| 443 | self.logger.error("Get image list error: " + str(e)) |
| 444 | raise vimconn.vimconnException(e) |
| 445 | |
| 446 | def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None, |
| 447 | availability_zone_index=None, availability_zone_list=None): |
| 448 | """Adds a VM instance to VIM |
| 449 | Params: |
| 450 | start: indicates if VM must start or boot in pause mode. Ignored |
| 451 | image_id,flavor_id: image and flavor uuid |
| 452 | net_list: list of interfaces, each one is a dictionary with: |
| 453 | name: |
| 454 | net_id: network uuid to connect |
| 455 | vpci: virtual vcpi to assign |
| garciadeblas | c4f4d73 | 2018-10-25 18:17:24 +0200 | [diff] [blame] | 456 | model: interface model, virtio, e1000, ... |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 457 | mac_address: |
| 458 | use: 'data', 'bridge', 'mgmt' |
| 459 | type: 'virtual', 'PF', 'VF', 'VFnotShared' |
| 460 | vim_id: filled/added by this function |
| 461 | #TODO ip, security groups |
| 462 | Returns the instance identifier |
| 463 | """ |
| 464 | self.logger.debug( |
| 465 | "new_vminstance input: image='{}' flavor='{}' nics='{}'".format(image_id, flavor_id, str(net_list))) |
| 466 | try: |
| 467 | client = oca.Client(self.user + ':' + self.passwd, self.url) |
| 468 | listaTemplate = oca.VmTemplatePool(client) |
| 469 | listaTemplate.info() |
| 470 | for template in listaTemplate: |
| 471 | if str(template.id) == str(flavor_id): |
| 472 | cpu = ' CPU = "{}"'.format(template.template.cpu) |
| 473 | memory = ' MEMORY = "{}"'.format(template.template.memory) |
| 474 | context = ' CONTEXT = [NETWORK = "YES",SSH_PUBLIC_KEY = "$USER[SSH_PUBLIC_KEY]" ]' |
| 475 | graphics = ' GRAPHICS = [ LISTEN = "0.0.0.0", TYPE = "VNC" ]' |
| 476 | disk = ' DISK = [ IMAGE_ID = {}]'.format(image_id) |
| 477 | sched_requeriments = ' SCHED_REQUIREMENTS = "CLUSTER_ID={}"'.format(self.config["cluster"]["id"]) |
| 478 | template_updated = cpu + memory + context + graphics + disk + sched_requeriments |
| 479 | networkListVim = oca.VirtualNetworkPool(client) |
| 480 | networkListVim.info() |
| 481 | network = "" |
| 482 | for net in net_list: |
| 483 | network_found = False |
| 484 | for network_existingInVim in networkListVim: |
| 485 | if str(net["net_id"]) == str(network_existingInVim.id): |
| 486 | net["vim_id"] = network_existingInVim["id"] |
| 487 | network = 'NIC = [NETWORK = "{}",NETWORK_UNAME = "{}" ]'.format( |
| 488 | network_existingInVim.name, network_existingInVim.uname) |
| 489 | network_found = True |
| 490 | break |
| 491 | if not network_found: |
| 492 | raise vimconn.vimconnNotFoundException("Network {} not found".format(net["net_id"])) |
| 493 | template_updated += network |
| 494 | oca.VmTemplate.update(template, template_updated) |
| 495 | self.logger.info( |
| 496 | "Instanciating in OpenNebula a new VM name:{} id:{}".format(template.name, template.id)) |
| 497 | vminstance_id = template.instantiate(name=name) |
| 498 | return str(vminstance_id), None |
| 499 | raise vimconn.vimconnNotFoundException("Flavor {} not found".format(flavor_id)) |
| 500 | except Exception as e: |
| 501 | self.logger.error("Create new vm instance error: " + str(e)) |
| 502 | raise vimconn.vimconnException(e) |
| 503 | |
| 504 | def delete_vminstance(self, vm_id, created_items=None): |
| 505 | """Removes a VM instance from VIM, returns the deleted vm_id""" |
| 506 | try: |
| 507 | client = oca.Client(self.user + ':' + self.passwd, self.url) |
| 508 | vm_pool = oca.VirtualMachinePool(client) |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 509 | vm_pool.info() |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 510 | vm_exist = False |
| 511 | for i in vm_pool: |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 512 | if str(i.id) == str(vm_id): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 513 | vm_exist = True |
| 514 | break |
| 515 | if not vm_exist: |
| 516 | self.logger.info("The vm " + str(vm_id) + " does not exist or is already deleted") |
| 517 | raise vimconn.vimconnNotFoundException("The vm {} does not exist or is already deleted".format(vm_id)) |
| 518 | params = '<?xml version="1.0"?> \ |
| 519 | <methodCall>\ |
| 520 | <methodName>one.vm.recover</methodName>\ |
| 521 | <params>\ |
| 522 | <param>\ |
| 523 | <value><string>{}:{}</string></value>\ |
| 524 | </param>\ |
| 525 | <param>\ |
| 526 | <value><int>{}</int></value>\ |
| 527 | </param>\ |
| 528 | <param>\ |
| 529 | <value><int>{}</int></value>\ |
| 530 | </param>\ |
| 531 | </params>\ |
| 532 | </methodCall>'.format(self.user, self.passwd, str(vm_id), str(3)) |
| 533 | r = requests.post(self.url, params) |
| 534 | obj = untangle.parse(str(r.content)) |
| 535 | response_success = obj.methodResponse.params.param.value.array.data.value[0].boolean.cdata.encode('utf-8') |
| 536 | response = obj.methodResponse.params.param.value.array.data.value[1].i4.cdata.encode('utf-8') |
| 537 | # response can be the resource ID on success or the error string on failure. |
| 538 | response_error_code = obj.methodResponse.params.param.value.array.data.value[2].i4.cdata.encode('utf-8') |
| 539 | if response_success.lower() == "true": |
| 540 | return response |
| 541 | else: |
| 542 | raise vimconn.vimconnException("vm {} cannot be deleted with error_code {}: {}".format(vm_id, response_error_code, response)) |
| 543 | except Exception as e: |
| 544 | self.logger.error("Delete vm instance " + str(vm_id) + " error: " + str(e)) |
| 545 | raise vimconn.vimconnException(e) |
| 546 | |
| 547 | def refresh_vms_status(self, vm_list): |
| 548 | """Refreshes the status of the virtual machines""" |
| 549 | vm_dict = {} |
| 550 | try: |
| 551 | client = oca.Client(self.user + ':' + self.passwd, self.url) |
| 552 | vm_pool = oca.VirtualMachinePool(client) |
| 553 | vm_pool.info() |
| 554 | for vm_id in vm_list: |
| 555 | vm = {"interfaces": []} |
| 556 | vm_exist = False |
| 557 | vm_element = None |
| 558 | for i in vm_pool: |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 559 | if str(i.id) == str(vm_id): |
| jomacarpe | ea2a73e | 2018-02-27 13:48:22 +0100 | [diff] [blame] | 560 | vm_exist = True |
| 561 | vm_element = i |
| 562 | break |
| 563 | if not vm_exist: |
| 564 | self.logger.info("The vm " + str(vm_id) + " does not exist.") |
| 565 | vm['status'] = "DELETED" |
| 566 | vm['error_msg'] = ("The vm " + str(vm_id) + " does not exist.") |
| 567 | continue |
| 568 | vm_element.info() |
| 569 | vm["vim_info"] = None |
| 570 | VMstatus = vm_element.str_lcm_state |
| 571 | if VMstatus == "RUNNING": |
| 572 | vm['status'] = "ACTIVE" |
| 573 | elif "FAILURE" in VMstatus: |
| 574 | vm['status'] = "ERROR" |
| 575 | vm['error_msg'] = "VM failure" |
| 576 | else: |
| 577 | vm['status'] = "BUILD" |
| 578 | try: |
| 579 | for red in vm_element.template.nics: |
| 580 | interface = {'vim_info': None, "mac_address": str(red.mac), "vim_net_id": str(red.network_id), |
| 581 | "vim_interface_id": str(red.network_id)} |
| 582 | # maybe it should be 2 different keys for ip_address if an interface has ipv4 and ipv6 |
| 583 | if hasattr(red, 'ip'): |
| 584 | interface["ip_address"] = str(red.ip) |
| 585 | if hasattr(red, 'ip6_global'): |
| 586 | interface["ip_address"] = str(red.ip6_global) |
| 587 | vm["interfaces"].append(interface) |
| 588 | except Exception as e: |
| 589 | self.logger.error("Error getting vm interface_information " + type(e).__name__ + ":" + str(e)) |
| 590 | vm["status"] = "VIM_ERROR" |
| 591 | vm["error_msg"] = "Error getting vm interface_information " + type(e).__name__ + ":" + str(e) |
| 592 | vm_dict[vm_id] = vm |
| 593 | return vm_dict |
| 594 | except Exception as e: |
| 595 | self.logger.error(e) |
| 596 | for k in vm_dict: |
| 597 | vm_dict[k]["status"] = "VIM_ERROR" |
| 598 | vm_dict[k]["error_msg"] = str(e) |
| 599 | return vm_dict |
| 600 | |
| 601 | def refresh_nets_status(self, net_list): |
| 602 | """Get the status of the networks |
| 603 | Params: the list of network identifiers |
| 604 | Returns a dictionary with: |
| 605 | net_id: #VIM id of this network |
| 606 | status: #Mandatory. Text with one of: |
| 607 | # DELETED (not found at vim) |
| 608 | # VIM_ERROR (Cannot connect to VIM, VIM response error, ...) |
| 609 | # OTHER (Vim reported other status not understood) |
| 610 | # ERROR (VIM indicates an ERROR status) |
| 611 | # ACTIVE, INACTIVE, DOWN (admin down), |
| 612 | # BUILD (on building process) |
| 613 | # |
| 614 | error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR |
| 615 | vim_info: #Text with plain information obtained from vim (yaml.safe_dump) |
| 616 | """ |
| 617 | net_dict = {} |
| 618 | try: |
| 619 | for net_id in net_list: |
| 620 | net = {} |
| 621 | try: |
| 622 | net_vim = self.get_network(net_id) |
| 623 | net["status"] = net_vim["status"] |
| 624 | net["vim_info"] = None |
| 625 | except vimconn.vimconnNotFoundException as e: |
| 626 | self.logger.error("Exception getting net status: {}".format(str(e))) |
| 627 | net['status'] = "DELETED" |
| 628 | net['error_msg'] = str(e) |
| 629 | except vimconn.vimconnException as e: |
| 630 | self.logger.error(e) |
| 631 | net["status"] = "VIM_ERROR" |
| 632 | net["error_msg"] = str(e) |
| 633 | net_dict[net_id] = net |
| 634 | return net_dict |
| 635 | except vimconn.vimconnException as e: |
| 636 | self.logger.error(e) |
| 637 | for k in net_dict: |
| 638 | net_dict[k]["status"] = "VIM_ERROR" |
| 639 | net_dict[k]["error_msg"] = str(e) |
| 640 | return net_dict |
| 641 | |
| 642 | # to be used and fixed in future commits... not working properly |
| 643 | # def action_vminstance(self, vm_id, action_dict): |
| 644 | # """Send and action over a VM instance from VIM |
| 645 | # Returns the status""" |
| 646 | # try: |
| 647 | # if "console" in action_dict: |
| 648 | # console_dict = {"protocol": "http", |
| 649 | # "server": "10.95.84.42", |
| 650 | # "port": "29876", |
| 651 | # "suffix": "?token=4hsb9cu9utruakon4p3z" |
| 652 | # } |
| 653 | # return console_dict |
| 654 | # except vimconn.vimconnException as e: |
| 655 | # self.logger.error(e) |
| albertoflorez | edf492d | 2018-04-20 00:40:25 +0200 | [diff] [blame] | 656 | |