blob: e06b2f91b4ea0adbc1d041ce93571c8e08d48f57 [file] [log] [blame]
bayramov325fa1c2016-09-08 01:42:46 -07001# -*- coding: utf-8 -*-
2
beierlb22ce2d2019-12-12 12:09:51 -05003# #
kbsuba85c54d2019-10-17 16:30:32 +00004# Copyright 2016-2019 VMware Inc.
bhangare1a0b97c2017-06-21 02:20:15 -07005# This file is part of ETSI OSM
bayramov325fa1c2016-09-08 01:42:46 -07006# 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# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
bhangare1a0b97c2017-06-21 02:20:15 -070021# contact: osslegalrouting@vmware.com
beierlb22ce2d2019-12-12 12:09:51 -050022# #
bayramov325fa1c2016-09-08 01:42:46 -070023
bayramov5761ad12016-10-04 09:00:30 +040024"""
bayramov325fa1c2016-09-08 01:42:46 -070025vimconn_vmware implementation an Abstract class in order to interact with VMware vCloud Director.
bayramov5761ad12016-10-04 09:00:30 +040026"""
bayramovbd6160f2016-09-28 04:12:05 +040027
beierlb22ce2d2019-12-12 12:09:51 -050028import atexit
29import hashlib
30import json
31import logging
bayramov325fa1c2016-09-08 01:42:46 -070032import os
beierlb22ce2d2019-12-12 12:09:51 -050033import random
34import re
Ananda Baitharu319c26f2019-03-05 17:34:31 +000035import shutil
beierlb22ce2d2019-12-12 12:09:51 -050036import socket
37import ssl
38import struct
Ananda Baitharu319c26f2019-03-05 17:34:31 +000039import subprocess
40import tempfile
bayramov325fa1c2016-09-08 01:42:46 -070041import time
beierlb22ce2d2019-12-12 12:09:51 -050042import traceback
bayramov325fa1c2016-09-08 01:42:46 -070043import uuid
sousaedu049cbb12022-01-05 11:39:35 +000044from xml.etree import ElementTree as XmlElementTree
45from xml.sax.saxutils import escape
46
47from lxml import etree as lxmlElementTree
48import netaddr
49from osm_ro_plugin import vimconn
50from progressbar import Bar, ETA, FileTransferSpeed, Percentage, ProgressBar
51from pyvcloud.vcd.client import BasicLoginCredentials, Client
52from pyvcloud.vcd.org import Org
53from pyvcloud.vcd.vapp import VApp
54from pyvcloud.vcd.vdc import VDC
55from pyVim.connect import Disconnect, SmartConnect
56from pyVmomi import vim, vmodl # @UnresolvedImport
57import requests
beierlb22ce2d2019-12-12 12:09:51 -050058import yaml
bayramov325fa1c2016-09-08 01:42:46 -070059
bayramovbd6160f2016-09-28 04:12:05 +040060# global variable for vcd connector type
sousaedu80135b92021-02-17 15:05:18 +010061STANDALONE = "standalone"
bayramovbd6160f2016-09-28 04:12:05 +040062
kate15f1c382016-12-15 01:12:40 -080063# key for flavor dicts
sousaedu80135b92021-02-17 15:05:18 +010064FLAVOR_RAM_KEY = "ram"
65FLAVOR_VCPUS_KEY = "vcpus"
66FLAVOR_DISK_KEY = "disk"
67DEFAULT_IP_PROFILE = {"dhcp_count": 50, "dhcp_enabled": True, "ip_version": "IPv4"}
bhangare0e571a92017-01-12 04:02:23 -080068# global variable for wait time
kate13ab2c42016-12-23 01:34:24 -080069INTERVAL_TIME = 5
70MAX_WAIT_TIME = 1800
bayramov325fa1c2016-09-08 01:42:46 -070071
sousaedu80135b92021-02-17 15:05:18 +010072API_VERSION = "27.0"
bayramovbd6160f2016-09-28 04:12:05 +040073
bayramovef390722016-09-27 03:34:46 -070074# -1: "Could not be created",
75# 0: "Unresolved",
76# 1: "Resolved",
77# 2: "Deployed",
78# 3: "Suspended",
79# 4: "Powered on",
80# 5: "Waiting for user input",
81# 6: "Unknown state",
82# 7: "Unrecognized state",
83# 8: "Powered off",
84# 9: "Inconsistent state",
85# 10: "Children do not all have the same status",
86# 11: "Upload initiated, OVF descriptor pending",
87# 12: "Upload initiated, copying contents",
88# 13: "Upload initiated , disk contents pending",
89# 14: "Upload has been quarantined",
90# 15: "Upload quarantine period has expired"
91
92# mapping vCD status to MANO
sousaedu80135b92021-02-17 15:05:18 +010093vcdStatusCode2manoFormat = {
94 4: "ACTIVE",
95 7: "PAUSED",
96 3: "SUSPENDED",
97 8: "INACTIVE",
98 12: "BUILD",
99 -1: "ERROR",
100 14: "DELETED",
101}
bayramovef390722016-09-27 03:34:46 -0700102
103#
sousaedu80135b92021-02-17 15:05:18 +0100104netStatus2manoFormat = {
105 "ACTIVE": "ACTIVE",
106 "PAUSED": "PAUSED",
107 "INACTIVE": "INACTIVE",
108 "BUILD": "BUILD",
109 "ERROR": "ERROR",
110 "DELETED": "DELETED",
111}
bayramovef390722016-09-27 03:34:46 -0700112
beierl26fec002019-12-06 17:06:40 -0500113
tierno72774862020-05-04 11:44:15 +0000114class vimconnector(vimconn.VimConnector):
kateeb044522017-03-06 23:54:39 -0800115 # dict used to store flavor in memory
116 flavorlist = {}
117
sousaedu80135b92021-02-17 15:05:18 +0100118 def __init__(
119 self,
120 uuid=None,
121 name=None,
122 tenant_id=None,
123 tenant_name=None,
124 url=None,
125 url_admin=None,
126 user=None,
127 passwd=None,
128 log_level=None,
129 config={},
130 persistent_info={},
131 ):
bayramovb6ffe792016-09-28 11:50:56 +0400132 """
133 Constructor create vmware connector to vCloud director.
134
135 By default construct doesn't validate connection state. So client can create object with None arguments.
136 If client specified username , password and host and VDC name. Connector initialize other missing attributes.
137
138 a) It initialize organization UUID
139 b) Initialize tenant_id/vdc ID. (This information derived from tenant name)
140
141 Args:
142 uuid - is organization uuid.
143 name - is organization name that must be presented in vCloud director.
144 tenant_id - is VDC uuid it must be presented in vCloud director
145 tenant_name - is VDC name.
146 url - is hostname or ip address of vCloud director
147 url_admin - same as above.
148 user - is user that administrator for organization. Caller must make sure that
149 username has right privileges.
150
151 password - is password for a user.
152
153 VMware connector also requires PVDC administrative privileges and separate account.
154 This variables must be passed via config argument dict contains keys
155
156 dict['admin_username']
157 dict['admin_password']
kateeb044522017-03-06 23:54:39 -0800158 config - Provide NSX and vCenter information
bayramovb6ffe792016-09-28 11:50:56 +0400159
160 Returns:
161 Nothing.
162 """
163
sousaedu80135b92021-02-17 15:05:18 +0100164 vimconn.VimConnector.__init__(
165 self,
166 uuid,
167 name,
168 tenant_id,
169 tenant_name,
170 url,
171 url_admin,
172 user,
173 passwd,
174 log_level,
175 config,
176 )
kate15f1c382016-12-15 01:12:40 -0800177
sousaedu80135b92021-02-17 15:05:18 +0100178 self.logger = logging.getLogger("ro.vim.vmware")
kate15f1c382016-12-15 01:12:40 -0800179 self.logger.setLevel(10)
tiernob3d36742017-03-03 23:51:05 +0100180 self.persistent_info = persistent_info
kate15f1c382016-12-15 01:12:40 -0800181
bayramovef390722016-09-27 03:34:46 -0700182 self.name = name
kate15f1c382016-12-15 01:12:40 -0800183 self.id = uuid
bayramovef390722016-09-27 03:34:46 -0700184 self.url = url
bayramov325fa1c2016-09-08 01:42:46 -0700185 self.url_admin = url_admin
186 self.tenant_id = tenant_id
187 self.tenant_name = tenant_name
bayramovef390722016-09-27 03:34:46 -0700188 self.user = user
189 self.passwd = passwd
190 self.config = config
191 self.admin_password = None
192 self.admin_user = None
kate15f1c382016-12-15 01:12:40 -0800193 self.org_name = ""
bhangare985a1fd2017-01-31 01:53:21 -0800194 self.nsx_manager = None
195 self.nsx_user = None
196 self.nsx_password = None
sbhangarea8e5b782018-06-21 02:10:03 -0700197 self.availability_zone = None
bayramovef390722016-09-27 03:34:46 -0700198
kasarc5bf2932018-03-09 04:15:22 -0800199 # Disable warnings from self-signed certificates.
200 requests.packages.urllib3.disable_warnings()
201
kate15f1c382016-12-15 01:12:40 -0800202 if tenant_name is not None:
203 orgnameandtenant = tenant_name.split(":")
sousaedu80135b92021-02-17 15:05:18 +0100204
kate15f1c382016-12-15 01:12:40 -0800205 if len(orgnameandtenant) == 2:
katec324e002016-12-23 00:54:47 -0800206 self.tenant_name = orgnameandtenant[1]
207 self.org_name = orgnameandtenant[0]
kate15f1c382016-12-15 01:12:40 -0800208 else:
209 self.tenant_name = tenant_name
sousaedu80135b92021-02-17 15:05:18 +0100210
bhangarea92ae392017-01-12 22:30:29 -0800211 if "orgname" in config:
sousaedu80135b92021-02-17 15:05:18 +0100212 self.org_name = config["orgname"]
katec324e002016-12-23 00:54:47 -0800213
tiernofe789902016-09-29 14:20:44 +0000214 if log_level:
bayramov5761ad12016-10-04 09:00:30 +0400215 self.logger.setLevel(getattr(logging, log_level))
bayramov325fa1c2016-09-08 01:42:46 -0700216
bayramovef390722016-09-27 03:34:46 -0700217 try:
sousaedu80135b92021-02-17 15:05:18 +0100218 self.admin_user = config["admin_username"]
219 self.admin_password = config["admin_password"]
bayramovef390722016-09-27 03:34:46 -0700220 except KeyError:
sousaedu80135b92021-02-17 15:05:18 +0100221 raise vimconn.VimConnException(
222 message="Error admin username or admin password is empty."
223 )
bayramov325fa1c2016-09-08 01:42:46 -0700224
bhangare985a1fd2017-01-31 01:53:21 -0800225 try:
sousaedu80135b92021-02-17 15:05:18 +0100226 self.nsx_manager = config["nsx_manager"]
227 self.nsx_user = config["nsx_user"]
228 self.nsx_password = config["nsx_password"]
bhangare985a1fd2017-01-31 01:53:21 -0800229 except KeyError:
sousaedu80135b92021-02-17 15:05:18 +0100230 raise vimconn.VimConnException(
231 message="Error: nsx manager or nsx user or nsx password is empty in Config"
232 )
bhangare985a1fd2017-01-31 01:53:21 -0800233
kateeb044522017-03-06 23:54:39 -0800234 self.vcenter_ip = config.get("vcenter_ip", None)
235 self.vcenter_port = config.get("vcenter_port", None)
236 self.vcenter_user = config.get("vcenter_user", None)
237 self.vcenter_password = config.get("vcenter_password", None)
238
beierlb22ce2d2019-12-12 12:09:51 -0500239 # Set availability zone for Affinity rules
sbhangarea8e5b782018-06-21 02:10:03 -0700240 self.availability_zone = self.set_availability_zones()
241
sousaedu80135b92021-02-17 15:05:18 +0100242 # ############# Stub code for SRIOV #################
243 # try:
244 # self.dvs_name = config['dv_switch_name']
245 # except KeyError:
246 # raise vimconn.VimConnException(message="Error:
247 # distributed virtaul switch name is empty in Config")
248 #
249 # self.vlanID_range = config.get("vlanID_range", None)
kateac1e3792017-04-01 02:16:39 -0700250
bayramovef390722016-09-27 03:34:46 -0700251 self.org_uuid = None
kasarc5bf2932018-03-09 04:15:22 -0800252 self.client = None
bayramov325fa1c2016-09-08 01:42:46 -0700253
254 if not url:
sousaedu80135b92021-02-17 15:05:18 +0100255 raise vimconn.VimConnException("url param can not be NoneType")
bayramov325fa1c2016-09-08 01:42:46 -0700256
bayramovef390722016-09-27 03:34:46 -0700257 if not self.url_admin: # try to use normal url
bayramov325fa1c2016-09-08 01:42:46 -0700258 self.url_admin = self.url
259
sousaedu80135b92021-02-17 15:05:18 +0100260 logging.debug(
261 "UUID: {} name: {} tenant_id: {} tenant name {}".format(
262 self.id, self.org_name, self.tenant_id, self.tenant_name
263 )
264 )
265 logging.debug(
266 "vcd url {} vcd username: {} vcd password: {}".format(
267 self.url, self.user, self.passwd
268 )
269 )
270 logging.debug(
271 "vcd admin username {} vcd admin passowrd {}".format(
272 self.admin_user, self.admin_password
273 )
274 )
bayramov325fa1c2016-09-08 01:42:46 -0700275
bayramovef390722016-09-27 03:34:46 -0700276 # initialize organization
bayramovbd6160f2016-09-28 04:12:05 +0400277 if self.user is not None and self.passwd is not None and self.url:
278 self.init_organization()
bayramovef390722016-09-27 03:34:46 -0700279
280 def __getitem__(self, index):
sousaedu80135b92021-02-17 15:05:18 +0100281 if index == "name":
kate15f1c382016-12-15 01:12:40 -0800282 return self.name
sousaedu80135b92021-02-17 15:05:18 +0100283
284 if index == "tenant_id":
bayramov325fa1c2016-09-08 01:42:46 -0700285 return self.tenant_id
sousaedu80135b92021-02-17 15:05:18 +0100286
287 if index == "tenant_name":
bayramov325fa1c2016-09-08 01:42:46 -0700288 return self.tenant_name
sousaedu80135b92021-02-17 15:05:18 +0100289 elif index == "id":
bayramov325fa1c2016-09-08 01:42:46 -0700290 return self.id
sousaedu80135b92021-02-17 15:05:18 +0100291 elif index == "org_name":
bayramovef390722016-09-27 03:34:46 -0700292 return self.org_name
sousaedu80135b92021-02-17 15:05:18 +0100293 elif index == "org_uuid":
bayramovef390722016-09-27 03:34:46 -0700294 return self.org_uuid
sousaedu80135b92021-02-17 15:05:18 +0100295 elif index == "user":
bayramov325fa1c2016-09-08 01:42:46 -0700296 return self.user
sousaedu80135b92021-02-17 15:05:18 +0100297 elif index == "passwd":
bayramov325fa1c2016-09-08 01:42:46 -0700298 return self.passwd
sousaedu80135b92021-02-17 15:05:18 +0100299 elif index == "url":
bayramov325fa1c2016-09-08 01:42:46 -0700300 return self.url
sousaedu80135b92021-02-17 15:05:18 +0100301 elif index == "url_admin":
bayramov325fa1c2016-09-08 01:42:46 -0700302 return self.url_admin
bayramovef390722016-09-27 03:34:46 -0700303 elif index == "config":
bayramov325fa1c2016-09-08 01:42:46 -0700304 return self.config
305 else:
tierno7d782ef2019-10-04 12:56:31 +0000306 raise KeyError("Invalid key '{}'".format(index))
bayramov325fa1c2016-09-08 01:42:46 -0700307
bayramovef390722016-09-27 03:34:46 -0700308 def __setitem__(self, index, value):
sousaedu80135b92021-02-17 15:05:18 +0100309 if index == "name":
kate15f1c382016-12-15 01:12:40 -0800310 self.name = value
sousaedu80135b92021-02-17 15:05:18 +0100311
312 if index == "tenant_id":
bayramov325fa1c2016-09-08 01:42:46 -0700313 self.tenant_id = value
sousaedu80135b92021-02-17 15:05:18 +0100314
315 if index == "tenant_name":
bayramov325fa1c2016-09-08 01:42:46 -0700316 self.tenant_name = value
sousaedu80135b92021-02-17 15:05:18 +0100317 elif index == "id":
bayramov325fa1c2016-09-08 01:42:46 -0700318 self.id = value
sousaedu80135b92021-02-17 15:05:18 +0100319 elif index == "org_name":
bayramovef390722016-09-27 03:34:46 -0700320 self.org_name = value
sousaedu80135b92021-02-17 15:05:18 +0100321 elif index == "org_uuid":
kate15f1c382016-12-15 01:12:40 -0800322 self.org_uuid = value
sousaedu80135b92021-02-17 15:05:18 +0100323 elif index == "user":
bayramov325fa1c2016-09-08 01:42:46 -0700324 self.user = value
sousaedu80135b92021-02-17 15:05:18 +0100325 elif index == "passwd":
bayramov325fa1c2016-09-08 01:42:46 -0700326 self.passwd = value
sousaedu80135b92021-02-17 15:05:18 +0100327 elif index == "url":
bayramov325fa1c2016-09-08 01:42:46 -0700328 self.url = value
sousaedu80135b92021-02-17 15:05:18 +0100329 elif index == "url_admin":
bayramov325fa1c2016-09-08 01:42:46 -0700330 self.url_admin = value
331 else:
tierno7d782ef2019-10-04 12:56:31 +0000332 raise KeyError("Invalid key '{}'".format(index))
bayramov325fa1c2016-09-08 01:42:46 -0700333
bayramovef390722016-09-27 03:34:46 -0700334 def connect_as_admin(self):
sousaedu80135b92021-02-17 15:05:18 +0100335 """Method connect as pvdc admin user to vCloud director.
336 There are certain action that can be done only by provider vdc admin user.
337 Organization creation / provider network creation etc.
bayramovef390722016-09-27 03:34:46 -0700338
sousaedu80135b92021-02-17 15:05:18 +0100339 Returns:
340 The return client object that latter can be used to connect to vcloud director as admin for provider vdc
bayramovef390722016-09-27 03:34:46 -0700341 """
kasarc5bf2932018-03-09 04:15:22 -0800342 self.logger.debug("Logging into vCD {} as admin.".format(self.org_name))
bayramov325fa1c2016-09-08 01:42:46 -0700343
kasarc5bf2932018-03-09 04:15:22 -0800344 try:
345 host = self.url
sousaedu80135b92021-02-17 15:05:18 +0100346 org = "System"
347 client_as_admin = Client(
348 host, verify_ssl_certs=False, api_version=API_VERSION
349 )
350 client_as_admin.set_credentials(
351 BasicLoginCredentials(self.admin_user, org, self.admin_password)
352 )
kasarc5bf2932018-03-09 04:15:22 -0800353 except Exception as e:
tierno72774862020-05-04 11:44:15 +0000354 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +0100355 "Can't connect to vCloud director as: {} with exception {}".format(
356 self.admin_user, e
357 )
358 )
bayramov325fa1c2016-09-08 01:42:46 -0700359
kasarc5bf2932018-03-09 04:15:22 -0800360 return client_as_admin
bayramov325fa1c2016-09-08 01:42:46 -0700361
bayramovef390722016-09-27 03:34:46 -0700362 def connect(self):
sousaedu80135b92021-02-17 15:05:18 +0100363 """Method connect as normal user to vCloud director.
bayramovef390722016-09-27 03:34:46 -0700364
sousaedu80135b92021-02-17 15:05:18 +0100365 Returns:
366 The return client object that latter can be used to connect to vCloud director as admin for VDC
bayramovef390722016-09-27 03:34:46 -0700367 """
bayramovb6ffe792016-09-28 11:50:56 +0400368 try:
sousaedu80135b92021-02-17 15:05:18 +0100369 self.logger.debug(
370 "Logging into vCD {} as {} to datacenter {}.".format(
371 self.org_name, self.user, self.org_name
372 )
373 )
kasarc5bf2932018-03-09 04:15:22 -0800374 host = self.url
beierl26fec002019-12-06 17:06:40 -0500375 client = Client(host, verify_ssl_certs=False, api_version=API_VERSION)
sousaedu80135b92021-02-17 15:05:18 +0100376 client.set_credentials(
377 BasicLoginCredentials(self.user, self.org_name, self.passwd)
378 )
beierl26fec002019-12-06 17:06:40 -0500379 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +0100380 raise vimconn.VimConnConnectionException(
381 "Can't connect to vCloud director org: "
382 "{} as user {} with exception: {}".format(self.org_name, self.user, e)
383 )
bayramov325fa1c2016-09-08 01:42:46 -0700384
kasarc5bf2932018-03-09 04:15:22 -0800385 return client
bayramov325fa1c2016-09-08 01:42:46 -0700386
bayramovbd6160f2016-09-28 04:12:05 +0400387 def init_organization(self):
sousaedu80135b92021-02-17 15:05:18 +0100388 """Method initialize organization UUID and VDC parameters.
bayramovbd6160f2016-09-28 04:12:05 +0400389
sousaedu80135b92021-02-17 15:05:18 +0100390 At bare minimum client must provide organization name that present in vCloud director and VDC.
bayramovbd6160f2016-09-28 04:12:05 +0400391
sousaedu80135b92021-02-17 15:05:18 +0100392 The VDC - UUID ( tenant_id) will be initialized at the run time if client didn't call constructor.
393 The Org - UUID will be initialized at the run time if data center present in vCloud director.
bayramov325fa1c2016-09-08 01:42:46 -0700394
sousaedu80135b92021-02-17 15:05:18 +0100395 Returns:
396 The return vca object that letter can be used to connect to vcloud direct as admin
bayramovef390722016-09-27 03:34:46 -0700397 """
kasarc5bf2932018-03-09 04:15:22 -0800398 client = self.connect()
sousaedu80135b92021-02-17 15:05:18 +0100399
kasarc5bf2932018-03-09 04:15:22 -0800400 if not client:
tierno72774862020-05-04 11:44:15 +0000401 raise vimconn.VimConnConnectionException("Failed to connect vCD.")
bhangare1a0b97c2017-06-21 02:20:15 -0700402
kasarc5bf2932018-03-09 04:15:22 -0800403 self.client = client
bayramovef390722016-09-27 03:34:46 -0700404 try:
405 if self.org_uuid is None:
kasarc5bf2932018-03-09 04:15:22 -0800406 org_list = client.get_org_list()
407 for org in org_list.Org:
bayramovbd6160f2016-09-28 04:12:05 +0400408 # we set org UUID at the init phase but we can do it only when we have valid credential.
sousaedu80135b92021-02-17 15:05:18 +0100409 if org.get("name") == self.org_name:
410 self.org_uuid = org.get("href").split("/")[-1]
411 self.logger.debug(
412 "Setting organization UUID {}".format(self.org_uuid)
413 )
bayramovbd6160f2016-09-28 04:12:05 +0400414 break
bayramovbd6160f2016-09-28 04:12:05 +0400415 else:
sousaedu80135b92021-02-17 15:05:18 +0100416 raise vimconn.VimConnException(
417 "Vcloud director organization {} not found".format(
418 self.org_name
419 )
420 )
bayramovbd6160f2016-09-28 04:12:05 +0400421
422 # if well good we require for org details
423 org_details_dict = self.get_org(org_uuid=self.org_uuid)
424
425 # we have two case if we want to initialize VDC ID or VDC name at run time
426 # tenant_name provided but no tenant id
sousaedu80135b92021-02-17 15:05:18 +0100427 if (
428 self.tenant_id is None
429 and self.tenant_name is not None
430 and "vdcs" in org_details_dict
431 ):
432 vdcs_dict = org_details_dict["vdcs"]
bayramovbd6160f2016-09-28 04:12:05 +0400433 for vdc in vdcs_dict:
434 if vdcs_dict[vdc] == self.tenant_name:
435 self.tenant_id = vdc
sousaedu80135b92021-02-17 15:05:18 +0100436 self.logger.debug(
437 "Setting vdc uuid {} for organization UUID {}".format(
438 self.tenant_id, self.org_name
439 )
440 )
bayramovbd6160f2016-09-28 04:12:05 +0400441 break
442 else:
sousaedu80135b92021-02-17 15:05:18 +0100443 raise vimconn.VimConnException(
444 "Tenant name indicated but not present in vcloud director."
445 )
446
bayramovbd6160f2016-09-28 04:12:05 +0400447 # case two we have tenant_id but we don't have tenant name so we find and set it.
sousaedu80135b92021-02-17 15:05:18 +0100448 if (
449 self.tenant_id is not None
450 and self.tenant_name is None
451 and "vdcs" in org_details_dict
452 ):
453 vdcs_dict = org_details_dict["vdcs"]
bayramovbd6160f2016-09-28 04:12:05 +0400454 for vdc in vdcs_dict:
455 if vdc == self.tenant_id:
456 self.tenant_name = vdcs_dict[vdc]
sousaedu80135b92021-02-17 15:05:18 +0100457 self.logger.debug(
458 "Setting vdc uuid {} for organization UUID {}".format(
459 self.tenant_id, self.org_name
460 )
461 )
bayramovbd6160f2016-09-28 04:12:05 +0400462 break
463 else:
sousaedu80135b92021-02-17 15:05:18 +0100464 raise vimconn.VimConnException(
465 "Tenant id indicated but not present in vcloud director"
466 )
467
bayramovef390722016-09-27 03:34:46 -0700468 self.logger.debug("Setting organization uuid {}".format(self.org_uuid))
beierl26fec002019-12-06 17:06:40 -0500469 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +0100470 self.logger.debug(
471 "Failed initialize organization UUID for org {}: {}".format(
472 self.org_name, e
473 ),
474 )
bayramovef390722016-09-27 03:34:46 -0700475 self.logger.debug(traceback.format_exc())
476 self.org_uuid = None
bayramov325fa1c2016-09-08 01:42:46 -0700477
bayramovef390722016-09-27 03:34:46 -0700478 def new_tenant(self, tenant_name=None, tenant_description=None):
sousaedu80135b92021-02-17 15:05:18 +0100479 """Method adds a new tenant to VIM with this name.
480 This action requires access to create VDC action in vCloud director.
bayramovef390722016-09-27 03:34:46 -0700481
sousaedu80135b92021-02-17 15:05:18 +0100482 Args:
483 tenant_name is tenant_name to be created.
484 tenant_description not used for this call
bayramovb6ffe792016-09-28 11:50:56 +0400485
sousaedu80135b92021-02-17 15:05:18 +0100486 Return:
487 returns the tenant identifier in UUID format.
488 If action is failed method will throw vimconn.VimConnException method
489 """
bayramovef390722016-09-27 03:34:46 -0700490 vdc_task = self.create_vdc(vdc_name=tenant_name)
491 if vdc_task is not None:
beierlb22ce2d2019-12-12 12:09:51 -0500492 vdc_uuid, _ = vdc_task.popitem()
sousaedu80135b92021-02-17 15:05:18 +0100493 self.logger.info(
494 "Created new vdc {} and uuid: {}".format(tenant_name, vdc_uuid)
495 )
496
bayramovef390722016-09-27 03:34:46 -0700497 return vdc_uuid
498 else:
sousaedu80135b92021-02-17 15:05:18 +0100499 raise vimconn.VimConnException(
500 "Failed create tenant {}".format(tenant_name)
501 )
bayramovef390722016-09-27 03:34:46 -0700502
bayramov163f1ae2016-09-28 17:16:55 +0400503 def delete_tenant(self, tenant_id=None):
sousaedu80135b92021-02-17 15:05:18 +0100504 """Delete a tenant from VIM
505 Args:
506 tenant_id is tenant_id to be deleted.
kated47ad5f2017-08-03 02:16:13 -0700507
sousaedu80135b92021-02-17 15:05:18 +0100508 Return:
509 returns the tenant identifier in UUID format.
510 If action is failed method will throw exception
kated47ad5f2017-08-03 02:16:13 -0700511 """
512 vca = self.connect_as_admin()
513 if not vca:
tierno72774862020-05-04 11:44:15 +0000514 raise vimconn.VimConnConnectionException("Failed to connect vCD")
kated47ad5f2017-08-03 02:16:13 -0700515
516 if tenant_id is not None:
kasarc5bf2932018-03-09 04:15:22 -0800517 if vca._session:
beierlb22ce2d2019-12-12 12:09:51 -0500518 # Get OrgVDC
sousaedu80135b92021-02-17 15:05:18 +0100519 url_list = [self.url, "/api/vdc/", tenant_id]
520 orgvdc_herf = "".join(url_list)
kasarc5bf2932018-03-09 04:15:22 -0800521
sousaedu80135b92021-02-17 15:05:18 +0100522 headers = {
523 "Accept": "application/*+xml;version=" + API_VERSION,
524 "x-vcloud-authorization": vca._session.headers[
525 "x-vcloud-authorization"
526 ],
527 }
528 response = self.perform_request(
529 req_type="GET", url=orgvdc_herf, headers=headers
530 )
kated47ad5f2017-08-03 02:16:13 -0700531
532 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +0100533 self.logger.debug(
534 "delete_tenant():GET REST API call {} failed. "
535 "Return status code {}".format(
536 orgvdc_herf, response.status_code
537 )
538 )
539
540 raise vimconn.VimConnNotFoundException(
541 "Fail to get tenant {}".format(tenant_id)
542 )
kated47ad5f2017-08-03 02:16:13 -0700543
beierl01bd6692019-12-09 17:06:20 -0500544 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
sousaedu80135b92021-02-17 15:05:18 +0100545 namespaces = {
546 prefix: uri
547 for prefix, uri in lxmlroot_respond.nsmap.items()
548 if prefix
549 }
beierlb22ce2d2019-12-12 12:09:51 -0500550 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
sousaedu80135b92021-02-17 15:05:18 +0100551 vdc_remove_href = lxmlroot_respond.find(
552 "xmlns:Link[@rel='remove']", namespaces
553 ).attrib["href"]
554 vdc_remove_href = vdc_remove_href + "?recursive=true&force=true"
kated47ad5f2017-08-03 02:16:13 -0700555
sousaedu80135b92021-02-17 15:05:18 +0100556 response = self.perform_request(
557 req_type="DELETE", url=vdc_remove_href, headers=headers
558 )
kated47ad5f2017-08-03 02:16:13 -0700559
560 if response.status_code == 202:
kasarc5bf2932018-03-09 04:15:22 -0800561 time.sleep(5)
sousaedu80135b92021-02-17 15:05:18 +0100562
kasarc5bf2932018-03-09 04:15:22 -0800563 return tenant_id
kated47ad5f2017-08-03 02:16:13 -0700564 else:
sousaedu80135b92021-02-17 15:05:18 +0100565 self.logger.debug(
566 "delete_tenant(): DELETE REST API call {} failed. "
567 "Return status code {}".format(
568 vdc_remove_href, response.status_code
569 )
570 )
571
572 raise vimconn.VimConnException(
573 "Fail to delete tenant with ID {}".format(tenant_id)
574 )
kated47ad5f2017-08-03 02:16:13 -0700575 else:
sousaedu80135b92021-02-17 15:05:18 +0100576 self.logger.debug(
577 "delete_tenant():Incorrect tenant ID {}".format(tenant_id)
578 )
579
580 raise vimconn.VimConnNotFoundException(
581 "Fail to get tenant {}".format(tenant_id)
582 )
kated47ad5f2017-08-03 02:16:13 -0700583
bayramov325fa1c2016-09-08 01:42:46 -0700584 def get_tenant_list(self, filter_dict={}):
bayramovb6ffe792016-09-28 11:50:56 +0400585 """Obtain tenants of VIM
bayramov325fa1c2016-09-08 01:42:46 -0700586 filter_dict can contain the following keys:
587 name: filter by tenant name
588 id: filter by tenant uuid/id
589 <other VIM specific>
bayramovb6ffe792016-09-28 11:50:56 +0400590 Returns the tenant list of dictionaries:
bayramov325fa1c2016-09-08 01:42:46 -0700591 [{'name':'<name>, 'id':'<id>, ...}, ...]
bayramov325fa1c2016-09-08 01:42:46 -0700592
bayramovb6ffe792016-09-28 11:50:56 +0400593 """
bayramovef390722016-09-27 03:34:46 -0700594 org_dict = self.get_org(self.org_uuid)
sousaedu80135b92021-02-17 15:05:18 +0100595 vdcs_dict = org_dict["vdcs"]
bayramovef390722016-09-27 03:34:46 -0700596
597 vdclist = []
598 try:
599 for k in vdcs_dict:
sousaedu80135b92021-02-17 15:05:18 +0100600 entry = {"name": vdcs_dict[k], "id": k}
bayramovb6ffe792016-09-28 11:50:56 +0400601 # if caller didn't specify dictionary we return all tenants.
sousaedu80135b92021-02-17 15:05:18 +0100602
bayramovb6ffe792016-09-28 11:50:56 +0400603 if filter_dict is not None and filter_dict:
604 filtered_entry = entry.copy()
605 filtered_dict = set(entry.keys()) - set(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +0100606
beierlb22ce2d2019-12-12 12:09:51 -0500607 for unwanted_key in filtered_dict:
608 del entry[unwanted_key]
sousaedu80135b92021-02-17 15:05:18 +0100609
bayramovb6ffe792016-09-28 11:50:56 +0400610 if filter_dict == entry:
611 vdclist.append(filtered_entry)
612 else:
613 vdclist.append(entry)
beierlb22ce2d2019-12-12 12:09:51 -0500614 except Exception:
bayramovef390722016-09-27 03:34:46 -0700615 self.logger.debug("Error in get_tenant_list()")
616 self.logger.debug(traceback.format_exc())
sousaedu80135b92021-02-17 15:05:18 +0100617
tierno72774862020-05-04 11:44:15 +0000618 raise vimconn.VimConnException("Incorrect state. {}")
bayramovef390722016-09-27 03:34:46 -0700619
620 return vdclist
621
sousaedu80135b92021-02-17 15:05:18 +0100622 def new_network(
623 self,
624 net_name,
625 net_type,
626 ip_profile=None,
627 shared=False,
628 provider_network_profile=None,
629 ):
bayramovb6ffe792016-09-28 11:50:56 +0400630 """Adds a tenant network to VIM
garciadeblasebd66722019-01-31 16:01:31 +0000631 Params:
632 'net_name': name of the network
633 'net_type': one of:
634 'bridge': overlay isolated network
635 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
636 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
637 'ip_profile': is a dict containing the IP parameters of the network
638 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
639 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
640 'gateway_address': (Optional) ip_schema, that is X.X.X.X
641 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
642 'dhcp_enabled': True or False
643 'dhcp_start_address': ip_schema, first IP to grant
644 'dhcp_count': number of IPs to grant.
645 'shared': if this network can be seen/use by other tenants/organization
kbsuba85c54d2019-10-17 16:30:32 +0000646 'provider_network_profile': (optional) contains {segmentation-id: vlan, provider-network: vim_netowrk}
garciadeblasebd66722019-01-31 16:01:31 +0000647 Returns a tuple with the network identifier and created_items, or raises an exception on error
648 created_items can be None or a dictionary where this method can include key-values that will be passed to
649 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
650 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
651 as not present.
652 """
bayramov325fa1c2016-09-08 01:42:46 -0700653
sousaedu80135b92021-02-17 15:05:18 +0100654 self.logger.debug(
655 "new_network tenant {} net_type {} ip_profile {} shared {} provider_network_profile {}".format(
656 net_name, net_type, ip_profile, shared, provider_network_profile
657 )
658 )
659 # vlan = None
660 # if provider_network_profile:
661 # vlan = provider_network_profile.get("segmentation-id")
bayramov325fa1c2016-09-08 01:42:46 -0700662
garciadeblasebd66722019-01-31 16:01:31 +0000663 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +0100664 isshared = "false"
bayramovef390722016-09-27 03:34:46 -0700665
sousaedu80135b92021-02-17 15:05:18 +0100666 if shared:
667 isshared = "true"
668
669 # ############# Stub code for SRIOV #################
670 # if net_type == "data" or net_type == "ptp":
671 # if self.config.get('dv_switch_name') == None:
672 # raise vimconn.VimConnConflictException("You must provide 'dv_switch_name' at config value")
673 # network_uuid = self.create_dvPort_group(net_name)
kbsuba85c54d2019-10-17 16:30:32 +0000674 parent_network_uuid = None
675
kbsuba85c54d2019-10-17 16:30:32 +0000676 if provider_network_profile is not None:
677 for k, v in provider_network_profile.items():
sousaedu80135b92021-02-17 15:05:18 +0100678 if k == "physical_network":
kbsuba85c54d2019-10-17 16:30:32 +0000679 parent_network_uuid = self.get_physical_network_by_name(v)
kateac1e3792017-04-01 02:16:39 -0700680
sousaedu80135b92021-02-17 15:05:18 +0100681 network_uuid = self.create_network(
682 network_name=net_name,
683 net_type=net_type,
684 ip_profile=ip_profile,
685 isshared=isshared,
686 parent_network_uuid=parent_network_uuid,
687 )
688
bayramovef390722016-09-27 03:34:46 -0700689 if network_uuid is not None:
garciadeblasebd66722019-01-31 16:01:31 +0000690 return network_uuid, created_items
bayramovef390722016-09-27 03:34:46 -0700691 else:
sousaedu80135b92021-02-17 15:05:18 +0100692 raise vimconn.VimConnUnexpectedResponse(
693 "Failed create a new network {}".format(net_name)
694 )
bayramovef390722016-09-27 03:34:46 -0700695
696 def get_vcd_network_list(self):
sousaedu80135b92021-02-17 15:05:18 +0100697 """Method available organization for a logged in tenant
bayramovef390722016-09-27 03:34:46 -0700698
sousaedu80135b92021-02-17 15:05:18 +0100699 Returns:
700 The return vca object that letter can be used to connect to vcloud direct as admin
bayramovef390722016-09-27 03:34:46 -0700701 """
702
sousaedu80135b92021-02-17 15:05:18 +0100703 self.logger.debug(
704 "get_vcd_network_list(): retrieving network list for vcd {}".format(
705 self.tenant_name
706 )
707 )
bayramovef390722016-09-27 03:34:46 -0700708
kate15f1c382016-12-15 01:12:40 -0800709 if not self.tenant_name:
tierno72774862020-05-04 11:44:15 +0000710 raise vimconn.VimConnConnectionException("Tenant name is empty.")
kate15f1c382016-12-15 01:12:40 -0800711
beierlb22ce2d2019-12-12 12:09:51 -0500712 _, vdc = self.get_vdc_details()
kate15f1c382016-12-15 01:12:40 -0800713 if vdc is None:
sousaedu80135b92021-02-17 15:05:18 +0100714 raise vimconn.VimConnConnectionException(
715 "Can't retrieve information for a VDC {}".format(self.tenant_name)
716 )
kate15f1c382016-12-15 01:12:40 -0800717
sousaedu80135b92021-02-17 15:05:18 +0100718 vdc_uuid = vdc.get("id").split(":")[3]
kasarc5bf2932018-03-09 04:15:22 -0800719 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +0100720 headers = {
721 "Accept": "application/*+xml;version=" + API_VERSION,
722 "x-vcloud-authorization": self.client._session.headers[
723 "x-vcloud-authorization"
724 ],
725 }
726 response = self.perform_request(
727 req_type="GET", url=vdc.get("href"), headers=headers
728 )
729
kasarc5bf2932018-03-09 04:15:22 -0800730 if response.status_code != 200:
731 self.logger.error("Failed to get vdc content")
tierno72774862020-05-04 11:44:15 +0000732 raise vimconn.VimConnNotFoundException("Failed to get vdc content")
kasarc5bf2932018-03-09 04:15:22 -0800733 else:
beierl26fec002019-12-06 17:06:40 -0500734 content = XmlElementTree.fromstring(response.text)
sbhangarea8e5b782018-06-21 02:10:03 -0700735
bayramovef390722016-09-27 03:34:46 -0700736 network_list = []
737 try:
kasarc5bf2932018-03-09 04:15:22 -0800738 for item in content:
sousaedu80135b92021-02-17 15:05:18 +0100739 if item.tag.split("}")[-1] == "AvailableNetworks":
kasarc5bf2932018-03-09 04:15:22 -0800740 for net in item:
sousaedu80135b92021-02-17 15:05:18 +0100741 response = self.perform_request(
742 req_type="GET", url=net.get("href"), headers=headers
743 )
bayramovef390722016-09-27 03:34:46 -0700744
kasarc5bf2932018-03-09 04:15:22 -0800745 if response.status_code != 200:
746 self.logger.error("Failed to get network content")
sousaedu80135b92021-02-17 15:05:18 +0100747 raise vimconn.VimConnNotFoundException(
748 "Failed to get network content"
749 )
kasarc5bf2932018-03-09 04:15:22 -0800750 else:
beierl26fec002019-12-06 17:06:40 -0500751 net_details = XmlElementTree.fromstring(response.text)
kasarc5bf2932018-03-09 04:15:22 -0800752
753 filter_dict = {}
sousaedu80135b92021-02-17 15:05:18 +0100754 net_uuid = net_details.get("id").split(":")
755
kasarc5bf2932018-03-09 04:15:22 -0800756 if len(net_uuid) != 4:
757 continue
758 else:
759 net_uuid = net_uuid[3]
760 # create dict entry
sousaedu80135b92021-02-17 15:05:18 +0100761 self.logger.debug(
762 "get_vcd_network_list(): Adding network {} "
763 "to a list vcd id {} network {}".format(
764 net_uuid, vdc_uuid, net_details.get("name")
765 )
766 )
767 filter_dict["name"] = net_details.get("name")
kasarc5bf2932018-03-09 04:15:22 -0800768 filter_dict["id"] = net_uuid
sousaedu80135b92021-02-17 15:05:18 +0100769
770 if [
771 i.text
772 for i in net_details
773 if i.tag.split("}")[-1] == "IsShared"
774 ][0] == "true":
kasarc5bf2932018-03-09 04:15:22 -0800775 shared = True
776 else:
777 shared = False
sousaedu80135b92021-02-17 15:05:18 +0100778
kasarc5bf2932018-03-09 04:15:22 -0800779 filter_dict["shared"] = shared
780 filter_dict["tenant_id"] = vdc_uuid
sousaedu80135b92021-02-17 15:05:18 +0100781
782 if int(net_details.get("status")) == 1:
kasarc5bf2932018-03-09 04:15:22 -0800783 filter_dict["admin_state_up"] = True
784 else:
785 filter_dict["admin_state_up"] = False
sousaedu80135b92021-02-17 15:05:18 +0100786
kasarc5bf2932018-03-09 04:15:22 -0800787 filter_dict["status"] = "ACTIVE"
788 filter_dict["type"] = "bridge"
789 network_list.append(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +0100790 self.logger.debug(
791 "get_vcd_network_list adding entry {}".format(
792 filter_dict
793 )
794 )
beierlb22ce2d2019-12-12 12:09:51 -0500795 except Exception:
kasarc5bf2932018-03-09 04:15:22 -0800796 self.logger.debug("Error in get_vcd_network_list", exc_info=True)
bayramovef390722016-09-27 03:34:46 -0700797 pass
798
799 self.logger.debug("get_vcd_network_list returning {}".format(network_list))
sousaedu80135b92021-02-17 15:05:18 +0100800
bayramovef390722016-09-27 03:34:46 -0700801 return network_list
bayramov325fa1c2016-09-08 01:42:46 -0700802
803 def get_network_list(self, filter_dict={}):
bayramovb6ffe792016-09-28 11:50:56 +0400804 """Obtain tenant networks of VIM
bayramov325fa1c2016-09-08 01:42:46 -0700805 Filter_dict can be:
bayramovef390722016-09-27 03:34:46 -0700806 name: network name OR/AND
807 id: network uuid OR/AND
808 shared: boolean OR/AND
809 tenant_id: tenant OR/AND
bayramov325fa1c2016-09-08 01:42:46 -0700810 admin_state_up: boolean
811 status: 'ACTIVE'
bayramovef390722016-09-27 03:34:46 -0700812
813 [{key : value , key : value}]
814
bayramov325fa1c2016-09-08 01:42:46 -0700815 Returns the network list of dictionaries:
816 [{<the fields at Filter_dict plus some VIM specific>}, ...]
817 List can be empty
bayramovb6ffe792016-09-28 11:50:56 +0400818 """
bayramov325fa1c2016-09-08 01:42:46 -0700819
sousaedu80135b92021-02-17 15:05:18 +0100820 self.logger.debug(
821 "get_network_list(): retrieving network list for vcd {}".format(
822 self.tenant_name
823 )
824 )
kate15f1c382016-12-15 01:12:40 -0800825
826 if not self.tenant_name:
tierno72774862020-05-04 11:44:15 +0000827 raise vimconn.VimConnConnectionException("Tenant name is empty.")
bayramov325fa1c2016-09-08 01:42:46 -0700828
beierlb22ce2d2019-12-12 12:09:51 -0500829 _, vdc = self.get_vdc_details()
kate15f1c382016-12-15 01:12:40 -0800830 if vdc is None:
tierno72774862020-05-04 11:44:15 +0000831 raise vimconn.VimConnConnectionException(
sousaedu80135b92021-02-17 15:05:18 +0100832 "Can't retrieve information for a VDC {}.".format(self.tenant_name)
833 )
bayramov325fa1c2016-09-08 01:42:46 -0700834
bayramovef390722016-09-27 03:34:46 -0700835 try:
sousaedu80135b92021-02-17 15:05:18 +0100836 vdcid = vdc.get("id").split(":")[3]
kasarc5bf2932018-03-09 04:15:22 -0800837
838 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +0100839 headers = {
840 "Accept": "application/*+xml;version=" + API_VERSION,
841 "x-vcloud-authorization": self.client._session.headers[
842 "x-vcloud-authorization"
843 ],
844 }
845 response = self.perform_request(
846 req_type="GET", url=vdc.get("href"), headers=headers
847 )
848
kasarc5bf2932018-03-09 04:15:22 -0800849 if response.status_code != 200:
850 self.logger.error("Failed to get vdc content")
tierno72774862020-05-04 11:44:15 +0000851 raise vimconn.VimConnNotFoundException("Failed to get vdc content")
kasarc5bf2932018-03-09 04:15:22 -0800852 else:
beierl26fec002019-12-06 17:06:40 -0500853 content = XmlElementTree.fromstring(response.text)
kasarc5bf2932018-03-09 04:15:22 -0800854
bhangarebfdca492017-03-11 01:32:46 -0800855 network_list = []
kasarc5bf2932018-03-09 04:15:22 -0800856 for item in content:
sousaedu80135b92021-02-17 15:05:18 +0100857 if item.tag.split("}")[-1] == "AvailableNetworks":
kasarc5bf2932018-03-09 04:15:22 -0800858 for net in item:
sousaedu80135b92021-02-17 15:05:18 +0100859 response = self.perform_request(
860 req_type="GET", url=net.get("href"), headers=headers
861 )
bhangarebfdca492017-03-11 01:32:46 -0800862
kasarc5bf2932018-03-09 04:15:22 -0800863 if response.status_code != 200:
864 self.logger.error("Failed to get network content")
sousaedu80135b92021-02-17 15:05:18 +0100865 raise vimconn.VimConnNotFoundException(
866 "Failed to get network content"
867 )
kasarc5bf2932018-03-09 04:15:22 -0800868 else:
beierl26fec002019-12-06 17:06:40 -0500869 net_details = XmlElementTree.fromstring(response.text)
bayramovef390722016-09-27 03:34:46 -0700870
kasarc5bf2932018-03-09 04:15:22 -0800871 filter_entry = {}
sousaedu80135b92021-02-17 15:05:18 +0100872 net_uuid = net_details.get("id").split(":")
873
kasarc5bf2932018-03-09 04:15:22 -0800874 if len(net_uuid) != 4:
875 continue
876 else:
sbhangarea8e5b782018-06-21 02:10:03 -0700877 net_uuid = net_uuid[3]
kasarc5bf2932018-03-09 04:15:22 -0800878 # create dict entry
sousaedu80135b92021-02-17 15:05:18 +0100879 self.logger.debug(
880 "get_network_list(): Adding net {}"
881 " to a list vcd id {} network {}".format(
882 net_uuid, vdcid, net_details.get("name")
883 )
884 )
885 filter_entry["name"] = net_details.get("name")
kasarc5bf2932018-03-09 04:15:22 -0800886 filter_entry["id"] = net_uuid
sousaedu80135b92021-02-17 15:05:18 +0100887
888 if [
889 i.text
890 for i in net_details
891 if i.tag.split("}")[-1] == "IsShared"
892 ][0] == "true":
kasarc5bf2932018-03-09 04:15:22 -0800893 shared = True
894 else:
895 shared = False
sousaedu80135b92021-02-17 15:05:18 +0100896
kasarc5bf2932018-03-09 04:15:22 -0800897 filter_entry["shared"] = shared
898 filter_entry["tenant_id"] = vdcid
sousaedu80135b92021-02-17 15:05:18 +0100899
900 if int(net_details.get("status")) == 1:
kasarc5bf2932018-03-09 04:15:22 -0800901 filter_entry["admin_state_up"] = True
902 else:
903 filter_entry["admin_state_up"] = False
sousaedu80135b92021-02-17 15:05:18 +0100904
kasarc5bf2932018-03-09 04:15:22 -0800905 filter_entry["status"] = "ACTIVE"
906 filter_entry["type"] = "bridge"
907 filtered_entry = filter_entry.copy()
908
909 if filter_dict is not None and filter_dict:
910 # we remove all the key : value we don't care and match only
911 # respected field
sousaedu80135b92021-02-17 15:05:18 +0100912 filtered_dict = set(filter_entry.keys()) - set(
913 filter_dict
914 )
915
beierlb22ce2d2019-12-12 12:09:51 -0500916 for unwanted_key in filtered_dict:
917 del filter_entry[unwanted_key]
sousaedu80135b92021-02-17 15:05:18 +0100918
kasarc5bf2932018-03-09 04:15:22 -0800919 if filter_dict == filter_entry:
920 network_list.append(filtered_entry)
921 else:
922 network_list.append(filtered_entry)
923 except Exception as e:
beierlb22ce2d2019-12-12 12:09:51 -0500924 self.logger.debug("Error in get_network_list", exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100925
tierno72774862020-05-04 11:44:15 +0000926 if isinstance(e, vimconn.VimConnException):
kasarc5bf2932018-03-09 04:15:22 -0800927 raise
928 else:
sousaedu80135b92021-02-17 15:05:18 +0100929 raise vimconn.VimConnNotFoundException(
930 "Failed : Networks list not found {} ".format(e)
931 )
bayramov325fa1c2016-09-08 01:42:46 -0700932
933 self.logger.debug("Returning {}".format(network_list))
sousaedu80135b92021-02-17 15:05:18 +0100934
bayramov325fa1c2016-09-08 01:42:46 -0700935 return network_list
936
937 def get_network(self, net_id):
bayramovfe3f3c92016-10-04 07:53:41 +0400938 """Method obtains network details of net_id VIM network
sousaedu80135b92021-02-17 15:05:18 +0100939 Return a dict with the fields at filter_dict (see get_network_list) plus some VIM specific>}, ...]"""
bayramovef390722016-09-27 03:34:46 -0700940 try:
beierlb22ce2d2019-12-12 12:09:51 -0500941 _, vdc = self.get_vdc_details()
sousaedu80135b92021-02-17 15:05:18 +0100942 vdc_id = vdc.get("id").split(":")[3]
943
kasarc5bf2932018-03-09 04:15:22 -0800944 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +0100945 headers = {
946 "Accept": "application/*+xml;version=" + API_VERSION,
947 "x-vcloud-authorization": self.client._session.headers[
948 "x-vcloud-authorization"
949 ],
950 }
951 response = self.perform_request(
952 req_type="GET", url=vdc.get("href"), headers=headers
953 )
954
kasarc5bf2932018-03-09 04:15:22 -0800955 if response.status_code != 200:
956 self.logger.error("Failed to get vdc content")
tierno72774862020-05-04 11:44:15 +0000957 raise vimconn.VimConnNotFoundException("Failed to get vdc content")
kasarc5bf2932018-03-09 04:15:22 -0800958 else:
beierl26fec002019-12-06 17:06:40 -0500959 content = XmlElementTree.fromstring(response.text)
bhangarebfdca492017-03-11 01:32:46 -0800960
bhangarebfdca492017-03-11 01:32:46 -0800961 filter_dict = {}
962
kasarc5bf2932018-03-09 04:15:22 -0800963 for item in content:
sousaedu80135b92021-02-17 15:05:18 +0100964 if item.tag.split("}")[-1] == "AvailableNetworks":
kasarc5bf2932018-03-09 04:15:22 -0800965 for net in item:
sousaedu80135b92021-02-17 15:05:18 +0100966 response = self.perform_request(
967 req_type="GET", url=net.get("href"), headers=headers
968 )
kasarc30a04e2017-08-24 05:58:18 -0700969
kasarc5bf2932018-03-09 04:15:22 -0800970 if response.status_code != 200:
971 self.logger.error("Failed to get network content")
sousaedu80135b92021-02-17 15:05:18 +0100972 raise vimconn.VimConnNotFoundException(
973 "Failed to get network content"
974 )
kasarc5bf2932018-03-09 04:15:22 -0800975 else:
beierl26fec002019-12-06 17:06:40 -0500976 net_details = XmlElementTree.fromstring(response.text)
kasarc5bf2932018-03-09 04:15:22 -0800977
sousaedu80135b92021-02-17 15:05:18 +0100978 vdc_network_id = net_details.get("id").split(":")
kasarc5bf2932018-03-09 04:15:22 -0800979 if len(vdc_network_id) == 4 and vdc_network_id[3] == net_id:
sousaedu80135b92021-02-17 15:05:18 +0100980 filter_dict["name"] = net_details.get("name")
kasarc5bf2932018-03-09 04:15:22 -0800981 filter_dict["id"] = vdc_network_id[3]
sousaedu80135b92021-02-17 15:05:18 +0100982
983 if [
984 i.text
985 for i in net_details
986 if i.tag.split("}")[-1] == "IsShared"
987 ][0] == "true":
kasarc5bf2932018-03-09 04:15:22 -0800988 shared = True
989 else:
990 shared = False
sousaedu80135b92021-02-17 15:05:18 +0100991
kasarc5bf2932018-03-09 04:15:22 -0800992 filter_dict["shared"] = shared
993 filter_dict["tenant_id"] = vdc_id
sousaedu80135b92021-02-17 15:05:18 +0100994
995 if int(net_details.get("status")) == 1:
kasarc5bf2932018-03-09 04:15:22 -0800996 filter_dict["admin_state_up"] = True
997 else:
998 filter_dict["admin_state_up"] = False
sousaedu80135b92021-02-17 15:05:18 +0100999
kasarc5bf2932018-03-09 04:15:22 -08001000 filter_dict["status"] = "ACTIVE"
1001 filter_dict["type"] = "bridge"
1002 self.logger.debug("Returning {}".format(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +01001003
kasarc5bf2932018-03-09 04:15:22 -08001004 return filter_dict
bayramovef390722016-09-27 03:34:46 -07001005 else:
sousaedu80135b92021-02-17 15:05:18 +01001006 raise vimconn.VimConnNotFoundException(
1007 "Network {} not found".format(net_id)
1008 )
kasarc30a04e2017-08-24 05:58:18 -07001009 except Exception as e:
bayramovef390722016-09-27 03:34:46 -07001010 self.logger.debug("Error in get_network")
1011 self.logger.debug(traceback.format_exc())
sousaedu80135b92021-02-17 15:05:18 +01001012
tierno72774862020-05-04 11:44:15 +00001013 if isinstance(e, vimconn.VimConnException):
kasarc30a04e2017-08-24 05:58:18 -07001014 raise
1015 else:
sousaedu80135b92021-02-17 15:05:18 +01001016 raise vimconn.VimConnNotFoundException(
1017 "Failed : Network not found {} ".format(e)
1018 )
bayramovef390722016-09-27 03:34:46 -07001019
1020 return filter_dict
bayramov325fa1c2016-09-08 01:42:46 -07001021
garciadeblasebd66722019-01-31 16:01:31 +00001022 def delete_network(self, net_id, created_items=None):
bayramovef390722016-09-27 03:34:46 -07001023 """
garciadeblasebd66722019-01-31 16:01:31 +00001024 Removes a tenant network from VIM and its associated elements
1025 :param net_id: VIM identifier of the network, provided by method new_network
1026 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1027 Returns the network identifier or raises an exception upon error or when network is not found
bayramovef390722016-09-27 03:34:46 -07001028 """
1029
kateac1e3792017-04-01 02:16:39 -07001030 # ############# Stub code for SRIOV #################
sousaedu80135b92021-02-17 15:05:18 +01001031 # dvport_group = self.get_dvport_group(net_id)
1032 # if dvport_group:
1033 # #delete portgroup
1034 # status = self.destroy_dvport_group(net_id)
1035 # if status:
1036 # # Remove vlanID from persistent info
1037 # if net_id in self.persistent_info["used_vlanIDs"]:
1038 # del self.persistent_info["used_vlanIDs"][net_id]
1039 #
1040 # return net_id
kateac1e3792017-04-01 02:16:39 -07001041
bayramovfe3f3c92016-10-04 07:53:41 +04001042 vcd_network = self.get_vcd_network(network_uuid=net_id)
1043 if vcd_network is not None and vcd_network:
1044 if self.delete_network_action(network_uuid=net_id):
1045 return net_id
bayramovef390722016-09-27 03:34:46 -07001046 else:
sousaedu80135b92021-02-17 15:05:18 +01001047 raise vimconn.VimConnNotFoundException(
1048 "Network {} not found".format(net_id)
1049 )
bayramov325fa1c2016-09-08 01:42:46 -07001050
1051 def refresh_nets_status(self, net_list):
bayramovbd6160f2016-09-28 04:12:05 +04001052 """Get the status of the networks
sousaedu80135b92021-02-17 15:05:18 +01001053 Params: the list of network identifiers
1054 Returns a dictionary with:
1055 net_id: #VIM id of this network
1056 status: #Mandatory. Text with one of:
1057 # DELETED (not found at vim)
1058 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1059 # OTHER (Vim reported other status not understood)
1060 # ERROR (VIM indicates an ERROR status)
1061 # ACTIVE, INACTIVE, DOWN (admin down),
1062 # BUILD (on building process)
1063 #
1064 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1065 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
bayramov325fa1c2016-09-08 01:42:46 -07001066
bayramovbd6160f2016-09-28 04:12:05 +04001067 """
bayramovef390722016-09-27 03:34:46 -07001068 dict_entry = {}
1069 try:
1070 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +01001071 errormsg = ""
bayramovef390722016-09-27 03:34:46 -07001072 vcd_network = self.get_vcd_network(network_uuid=net)
bayramovfe3f3c92016-10-04 07:53:41 +04001073 if vcd_network is not None and vcd_network:
sousaedu80135b92021-02-17 15:05:18 +01001074 if vcd_network["status"] == "1":
1075 status = "ACTIVE"
bayramovef390722016-09-27 03:34:46 -07001076 else:
sousaedu80135b92021-02-17 15:05:18 +01001077 status = "DOWN"
bayramovef390722016-09-27 03:34:46 -07001078 else:
sousaedu80135b92021-02-17 15:05:18 +01001079 status = "DELETED"
1080 errormsg = "Network not found."
bayramovfe3f3c92016-10-04 07:53:41 +04001081
sousaedu80135b92021-02-17 15:05:18 +01001082 dict_entry[net] = {
1083 "status": status,
1084 "error_msg": errormsg,
1085 "vim_info": yaml.safe_dump(vcd_network),
1086 }
beierlb22ce2d2019-12-12 12:09:51 -05001087 except Exception:
bayramovef390722016-09-27 03:34:46 -07001088 self.logger.debug("Error in refresh_nets_status")
1089 self.logger.debug(traceback.format_exc())
1090
1091 return dict_entry
1092
bayramovbd6160f2016-09-28 04:12:05 +04001093 def get_flavor(self, flavor_id):
bayramovef390722016-09-27 03:34:46 -07001094 """Obtain flavor details from the VIM
sousaedu80135b92021-02-17 15:05:18 +01001095 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific } #TODO to concrete
bayramovef390722016-09-27 03:34:46 -07001096 """
kateeb044522017-03-06 23:54:39 -08001097 if flavor_id not in vimconnector.flavorlist:
tierno72774862020-05-04 11:44:15 +00001098 raise vimconn.VimConnNotFoundException("Flavor not found.")
sousaedu80135b92021-02-17 15:05:18 +01001099
kateeb044522017-03-06 23:54:39 -08001100 return vimconnector.flavorlist[flavor_id]
bayramov325fa1c2016-09-08 01:42:46 -07001101
1102 def new_flavor(self, flavor_data):
bayramovef390722016-09-27 03:34:46 -07001103 """Adds a tenant flavor to VIM
bayramov325fa1c2016-09-08 01:42:46 -07001104 flavor_data contains a dictionary with information, keys:
1105 name: flavor name
1106 ram: memory (cloud type) in MBytes
1107 vpcus: cpus (cloud type)
1108 extended: EPA parameters
1109 - numas: #items requested in same NUMA
1110 memory: number of 1G huge pages memory
beierlb22ce2d2019-12-12 12:09:51 -05001111 paired-threads|cores|threads: number of paired hyperthreads, complete cores OR individual
1112 threads
bayramov325fa1c2016-09-08 01:42:46 -07001113 interfaces: # passthrough(PT) or SRIOV interfaces attached to this numa
1114 - name: interface name
1115 dedicated: yes|no|yes:sriov; for PT, SRIOV or only one SRIOV for the physical NIC
1116 bandwidth: X Gbps; requested guarantee bandwidth
bayramovef390722016-09-27 03:34:46 -07001117 vpci: requested virtual PCI address
bayramov325fa1c2016-09-08 01:42:46 -07001118 disk: disk size
1119 is_public:
bayramov325fa1c2016-09-08 01:42:46 -07001120 #TODO to concrete
bayramovef390722016-09-27 03:34:46 -07001121 Returns the flavor identifier"""
bayramov325fa1c2016-09-08 01:42:46 -07001122
bayramovef390722016-09-27 03:34:46 -07001123 # generate a new uuid put to internal dict and return it.
bhangarea92ae392017-01-12 22:30:29 -08001124 self.logger.debug("Creating new flavor - flavor_data: {}".format(flavor_data))
beierlb22ce2d2019-12-12 12:09:51 -05001125 new_flavor = flavor_data
bhangarea92ae392017-01-12 22:30:29 -08001126 ram = flavor_data.get(FLAVOR_RAM_KEY, 1024)
1127 cpu = flavor_data.get(FLAVOR_VCPUS_KEY, 1)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001128 disk = flavor_data.get(FLAVOR_DISK_KEY, 0)
bhangarea92ae392017-01-12 22:30:29 -08001129
kasarfeaaa052017-06-08 03:46:18 -07001130 if not isinstance(ram, int):
tierno72774862020-05-04 11:44:15 +00001131 raise vimconn.VimConnException("Non-integer value for ram")
kasarfeaaa052017-06-08 03:46:18 -07001132 elif not isinstance(cpu, int):
tierno72774862020-05-04 11:44:15 +00001133 raise vimconn.VimConnException("Non-integer value for cpu")
kasarfeaaa052017-06-08 03:46:18 -07001134 elif not isinstance(disk, int):
tierno72774862020-05-04 11:44:15 +00001135 raise vimconn.VimConnException("Non-integer value for disk")
kasarfeaaa052017-06-08 03:46:18 -07001136
bhangarea92ae392017-01-12 22:30:29 -08001137 extended_flv = flavor_data.get("extended")
1138 if extended_flv:
beierlb22ce2d2019-12-12 12:09:51 -05001139 numas = extended_flv.get("numas")
bhangarea92ae392017-01-12 22:30:29 -08001140 if numas:
1141 for numa in numas:
beierlb22ce2d2019-12-12 12:09:51 -05001142 # overwrite ram and vcpus
sousaedu80135b92021-02-17 15:05:18 +01001143 if "memory" in numa:
1144 ram = numa["memory"] * 1024
1145
1146 if "paired-threads" in numa:
1147 cpu = numa["paired-threads"] * 2
1148 elif "cores" in numa:
1149 cpu = numa["cores"]
1150 elif "threads" in numa:
1151 cpu = numa["threads"]
bhangarea92ae392017-01-12 22:30:29 -08001152
1153 new_flavor[FLAVOR_RAM_KEY] = ram
1154 new_flavor[FLAVOR_VCPUS_KEY] = cpu
1155 new_flavor[FLAVOR_DISK_KEY] = disk
1156 # generate a new uuid put to internal dict and return it.
bayramovef390722016-09-27 03:34:46 -07001157 flavor_id = uuid.uuid4()
kateeb044522017-03-06 23:54:39 -08001158 vimconnector.flavorlist[str(flavor_id)] = new_flavor
bhangarea92ae392017-01-12 22:30:29 -08001159 self.logger.debug("Created flavor - {} : {}".format(flavor_id, new_flavor))
bayramov325fa1c2016-09-08 01:42:46 -07001160
bayramovef390722016-09-27 03:34:46 -07001161 return str(flavor_id)
bayramov325fa1c2016-09-08 01:42:46 -07001162
1163 def delete_flavor(self, flavor_id):
bayramovef390722016-09-27 03:34:46 -07001164 """Deletes a tenant flavor from VIM identify by its id
bayramov325fa1c2016-09-08 01:42:46 -07001165
sousaedu80135b92021-02-17 15:05:18 +01001166 Returns the used id or raise an exception
bayramovef390722016-09-27 03:34:46 -07001167 """
kateeb044522017-03-06 23:54:39 -08001168 if flavor_id not in vimconnector.flavorlist:
tierno72774862020-05-04 11:44:15 +00001169 raise vimconn.VimConnNotFoundException("Flavor not found.")
bayramovef390722016-09-27 03:34:46 -07001170
kateeb044522017-03-06 23:54:39 -08001171 vimconnector.flavorlist.pop(flavor_id, None)
sousaedu80135b92021-02-17 15:05:18 +01001172
bayramovef390722016-09-27 03:34:46 -07001173 return flavor_id
1174
1175 def new_image(self, image_dict):
bayramov5761ad12016-10-04 09:00:30 +04001176 """
bayramov325fa1c2016-09-08 01:42:46 -07001177 Adds a tenant image to VIM
1178 Returns:
1179 200, image-id if the image is created
1180 <0, message if there is an error
bayramov5761ad12016-10-04 09:00:30 +04001181 """
sousaedu80135b92021-02-17 15:05:18 +01001182 return self.get_image_id_from_path(image_dict["location"])
bayramov325fa1c2016-09-08 01:42:46 -07001183
1184 def delete_image(self, image_id):
bayramovfe3f3c92016-10-04 07:53:41 +04001185 """
sousaedu80135b92021-02-17 15:05:18 +01001186 Deletes a tenant image from VIM
1187 Args:
1188 image_id is ID of Image to be deleted
1189 Return:
1190 returns the image identifier in UUID format or raises an exception on error
bayramovfe3f3c92016-10-04 07:53:41 +04001191 """
kasarc5bf2932018-03-09 04:15:22 -08001192 conn = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01001193
kasarc5bf2932018-03-09 04:15:22 -08001194 if not conn:
tierno72774862020-05-04 11:44:15 +00001195 raise vimconn.VimConnConnectionException("Failed to connect vCD")
sousaedu80135b92021-02-17 15:05:18 +01001196
kated47ad5f2017-08-03 02:16:13 -07001197 # Get Catalog details
sousaedu80135b92021-02-17 15:05:18 +01001198 url_list = [self.url, "/api/catalog/", image_id]
1199 catalog_herf = "".join(url_list)
kasarc5bf2932018-03-09 04:15:22 -08001200
sousaedu80135b92021-02-17 15:05:18 +01001201 headers = {
1202 "Accept": "application/*+xml;version=" + API_VERSION,
1203 "x-vcloud-authorization": conn._session.headers["x-vcloud-authorization"],
1204 }
kasarc5bf2932018-03-09 04:15:22 -08001205
sousaedu80135b92021-02-17 15:05:18 +01001206 response = self.perform_request(
1207 req_type="GET", url=catalog_herf, headers=headers
1208 )
bayramovfe3f3c92016-10-04 07:53:41 +04001209
kated47ad5f2017-08-03 02:16:13 -07001210 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01001211 self.logger.debug(
1212 "delete_image():GET REST API call {} failed. "
1213 "Return status code {}".format(catalog_herf, response.status_code)
1214 )
1215
1216 raise vimconn.VimConnNotFoundException(
1217 "Fail to get image {}".format(image_id)
1218 )
kated47ad5f2017-08-03 02:16:13 -07001219
beierl01bd6692019-12-09 17:06:20 -05001220 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
sousaedu80135b92021-02-17 15:05:18 +01001221 namespaces = {
1222 prefix: uri for prefix, uri in lxmlroot_respond.nsmap.items() if prefix
1223 }
beierl01bd6692019-12-09 17:06:20 -05001224 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
kated47ad5f2017-08-03 02:16:13 -07001225
beierl01bd6692019-12-09 17:06:20 -05001226 catalogItems_section = lxmlroot_respond.find("xmlns:CatalogItems", namespaces)
1227 catalogItems = catalogItems_section.iterfind("xmlns:CatalogItem", namespaces)
kated47ad5f2017-08-03 02:16:13 -07001228
sousaedu80135b92021-02-17 15:05:18 +01001229 for catalogItem in catalogItems:
1230 catalogItem_href = catalogItem.attrib["href"]
1231
1232 response = self.perform_request(
1233 req_type="GET", url=catalogItem_href, headers=headers
1234 )
kated47ad5f2017-08-03 02:16:13 -07001235
1236 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01001237 self.logger.debug(
1238 "delete_image():GET REST API call {} failed. "
1239 "Return status code {}".format(catalog_herf, response.status_code)
1240 )
1241 raise vimconn.VimConnNotFoundException(
1242 "Fail to get catalogItem {} for catalog {}".format(
1243 catalogItem, image_id
1244 )
1245 )
kated47ad5f2017-08-03 02:16:13 -07001246
beierl01bd6692019-12-09 17:06:20 -05001247 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
sousaedu80135b92021-02-17 15:05:18 +01001248 namespaces = {
1249 prefix: uri for prefix, uri in lxmlroot_respond.nsmap.items() if prefix
1250 }
beierl01bd6692019-12-09 17:06:20 -05001251 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
sousaedu80135b92021-02-17 15:05:18 +01001252 catalogitem_remove_href = lxmlroot_respond.find(
1253 "xmlns:Link[@rel='remove']", namespaces
1254 ).attrib["href"]
kated47ad5f2017-08-03 02:16:13 -07001255
beierl01bd6692019-12-09 17:06:20 -05001256 # Remove catalogItem
sousaedu80135b92021-02-17 15:05:18 +01001257 response = self.perform_request(
1258 req_type="DELETE", url=catalogitem_remove_href, headers=headers
1259 )
1260
kated47ad5f2017-08-03 02:16:13 -07001261 if response.status_code == requests.codes.no_content:
1262 self.logger.debug("Deleted Catalog item {}".format(catalogItem))
1263 else:
sousaedu80135b92021-02-17 15:05:18 +01001264 raise vimconn.VimConnException(
1265 "Fail to delete Catalog Item {}".format(catalogItem)
1266 )
kated47ad5f2017-08-03 02:16:13 -07001267
beierl01bd6692019-12-09 17:06:20 -05001268 # Remove catalog
sousaedu80135b92021-02-17 15:05:18 +01001269 url_list = [self.url, "/api/admin/catalog/", image_id]
1270 catalog_remove_herf = "".join(url_list)
1271 response = self.perform_request(
1272 req_type="DELETE", url=catalog_remove_herf, headers=headers
1273 )
kated47ad5f2017-08-03 02:16:13 -07001274
1275 if response.status_code == requests.codes.no_content:
1276 self.logger.debug("Deleted Catalog {}".format(image_id))
sousaedu80135b92021-02-17 15:05:18 +01001277
kated47ad5f2017-08-03 02:16:13 -07001278 return image_id
1279 else:
tierno72774862020-05-04 11:44:15 +00001280 raise vimconn.VimConnException("Fail to delete Catalog {}".format(image_id))
kated47ad5f2017-08-03 02:16:13 -07001281
bayramov325fa1c2016-09-08 01:42:46 -07001282 def catalog_exists(self, catalog_name, catalogs):
bayramovfe3f3c92016-10-04 07:53:41 +04001283 """
1284
1285 :param catalog_name:
1286 :param catalogs:
1287 :return:
1288 """
bayramov325fa1c2016-09-08 01:42:46 -07001289 for catalog in catalogs:
sousaedu80135b92021-02-17 15:05:18 +01001290 if catalog["name"] == catalog_name:
1291 return catalog["id"]
bayramov325fa1c2016-09-08 01:42:46 -07001292
bayramovb6ffe792016-09-28 11:50:56 +04001293 def create_vimcatalog(self, vca=None, catalog_name=None):
sousaedu80135b92021-02-17 15:05:18 +01001294 """Create new catalog entry in vCloud director.
bayramovb6ffe792016-09-28 11:50:56 +04001295
sousaedu80135b92021-02-17 15:05:18 +01001296 Args
1297 vca: vCloud director.
1298 catalog_name catalog that client wish to create. Note no validation done for a name.
1299 Client must make sure that provide valid string representation.
bayramovb6ffe792016-09-28 11:50:56 +04001300
sousaedu80135b92021-02-17 15:05:18 +01001301 Returns catalog id if catalog created else None.
bayramovb6ffe792016-09-28 11:50:56 +04001302
1303 """
1304 try:
Ananda Baitharu319c26f2019-03-05 17:34:31 +00001305 lxml_catalog_element = vca.create_catalog(catalog_name, catalog_name)
sousaedu80135b92021-02-17 15:05:18 +01001306
Ananda Baitharu319c26f2019-03-05 17:34:31 +00001307 if lxml_catalog_element:
sousaedu80135b92021-02-17 15:05:18 +01001308 id_attr_value = lxml_catalog_element.get("id")
1309 return id_attr_value.split(":")[-1]
1310
kasarc5bf2932018-03-09 04:15:22 -08001311 catalogs = vca.list_catalogs()
Ananda Baitharu319c26f2019-03-05 17:34:31 +00001312 except Exception as ex:
1313 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01001314 'create_vimcatalog(): Creation of catalog "{}" failed with error: {}'.format(
1315 catalog_name, ex
1316 )
1317 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00001318 raise
bayramov325fa1c2016-09-08 01:42:46 -07001319 return self.catalog_exists(catalog_name, catalogs)
1320
bayramov5761ad12016-10-04 09:00:30 +04001321 # noinspection PyIncorrectDocstring
sousaedu80135b92021-02-17 15:05:18 +01001322 def upload_ovf(
1323 self,
1324 vca=None,
1325 catalog_name=None,
1326 image_name=None,
1327 media_file_name=None,
1328 description="",
1329 progress=False,
1330 chunk_bytes=128 * 1024,
1331 ):
bayramov325fa1c2016-09-08 01:42:46 -07001332 """
1333 Uploads a OVF file to a vCloud catalog
1334
bayramov5761ad12016-10-04 09:00:30 +04001335 :param chunk_bytes:
1336 :param progress:
1337 :param description:
1338 :param image_name:
1339 :param vca:
bayramov325fa1c2016-09-08 01:42:46 -07001340 :param catalog_name: (str): The name of the catalog to upload the media.
bayramov325fa1c2016-09-08 01:42:46 -07001341 :param media_file_name: (str): The name of the local media file to upload.
1342 :return: (bool) True if the media file was successfully uploaded, false otherwise.
1343 """
1344 os.path.isfile(media_file_name)
1345 statinfo = os.stat(media_file_name)
bayramov325fa1c2016-09-08 01:42:46 -07001346
1347 # find a catalog entry where we upload OVF.
1348 # create vApp Template and check the status if vCD able to read OVF it will respond with appropirate
1349 # status change.
1350 # if VCD can parse OVF we upload VMDK file
bhangarebfdca492017-03-11 01:32:46 -08001351 try:
kasarc5bf2932018-03-09 04:15:22 -08001352 for catalog in vca.list_catalogs():
sousaedu80135b92021-02-17 15:05:18 +01001353 if catalog_name != catalog["name"]:
bhangarebfdca492017-03-11 01:32:46 -08001354 continue
sousaedu80135b92021-02-17 15:05:18 +01001355 catalog_href = "{}/api/catalog/{}/action/upload".format(
1356 self.url, catalog["id"]
1357 )
bhangarebfdca492017-03-11 01:32:46 -08001358 data = """
beierlb22ce2d2019-12-12 12:09:51 -05001359 <UploadVAppTemplateParams name="{}"
1360 xmlns="http://www.vmware.com/vcloud/v1.5"
1361 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1">
1362 <Description>{} vApp Template</Description>
1363 </UploadVAppTemplateParams>
sousaedu80135b92021-02-17 15:05:18 +01001364 """.format(
1365 catalog_name, description
1366 )
kasarc5bf2932018-03-09 04:15:22 -08001367
1368 if self.client:
sousaedu80135b92021-02-17 15:05:18 +01001369 headers = {
1370 "Accept": "application/*+xml;version=" + API_VERSION,
1371 "x-vcloud-authorization": self.client._session.headers[
1372 "x-vcloud-authorization"
1373 ],
1374 }
1375 headers[
1376 "Content-Type"
1377 ] = "application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml"
kasarc5bf2932018-03-09 04:15:22 -08001378
sousaedu80135b92021-02-17 15:05:18 +01001379 response = self.perform_request(
1380 req_type="POST", url=catalog_href, headers=headers, data=data
1381 )
kasarc5bf2932018-03-09 04:15:22 -08001382
bhangarebfdca492017-03-11 01:32:46 -08001383 if response.status_code == requests.codes.created:
beierl26fec002019-12-06 17:06:40 -05001384 catalogItem = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01001385 entity = [
1386 child
1387 for child in catalogItem
1388 if child.get("type")
1389 == "application/vnd.vmware.vcloud.vAppTemplate+xml"
1390 ][0]
1391 href = entity.get("href")
bhangarebfdca492017-03-11 01:32:46 -08001392 template = href
kasarc5bf2932018-03-09 04:15:22 -08001393
sousaedu80135b92021-02-17 15:05:18 +01001394 response = self.perform_request(
1395 req_type="GET", url=href, headers=headers
1396 )
bhangarebfdca492017-03-11 01:32:46 -08001397
1398 if response.status_code == requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01001399 headers["Content-Type"] = "Content-Type text/xml"
1400 result = re.search(
1401 'rel="upload:default"\shref="(.*?\/descriptor.ovf)"',
1402 response.text,
1403 )
1404
kasarc5bf2932018-03-09 04:15:22 -08001405 if result:
1406 transfer_href = result.group(1)
1407
sousaedu80135b92021-02-17 15:05:18 +01001408 response = self.perform_request(
1409 req_type="PUT",
1410 url=transfer_href,
1411 headers=headers,
1412 data=open(media_file_name, "rb"),
1413 )
1414
bhangarebfdca492017-03-11 01:32:46 -08001415 if response.status_code != requests.codes.ok:
1416 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01001417 "Failed create vApp template for catalog name {} and image {}".format(
1418 catalog_name, media_file_name
1419 )
1420 )
bhangarebfdca492017-03-11 01:32:46 -08001421 return False
1422
1423 # TODO fix this with aync block
1424 time.sleep(5)
1425
sousaedu80135b92021-02-17 15:05:18 +01001426 self.logger.debug(
1427 "vApp template for catalog name {} and image {}".format(
1428 catalog_name, media_file_name
1429 )
1430 )
bhangarebfdca492017-03-11 01:32:46 -08001431
1432 # uploading VMDK file
1433 # check status of OVF upload and upload remaining files.
sousaedu80135b92021-02-17 15:05:18 +01001434 response = self.perform_request(
1435 req_type="GET", url=template, headers=headers
1436 )
bhangarebfdca492017-03-11 01:32:46 -08001437
1438 if response.status_code == requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01001439 result = re.search(
1440 'rel="upload:default"\s*href="(.*?vmdk)"', response.text
1441 )
1442
kasarc5bf2932018-03-09 04:15:22 -08001443 if result:
1444 link_href = result.group(1)
sousaedu80135b92021-02-17 15:05:18 +01001445
kasarc5bf2932018-03-09 04:15:22 -08001446 # we skip ovf since it already uploaded.
sousaedu80135b92021-02-17 15:05:18 +01001447 if "ovf" in link_href:
kasarc5bf2932018-03-09 04:15:22 -08001448 continue
sousaedu80135b92021-02-17 15:05:18 +01001449
kasarc5bf2932018-03-09 04:15:22 -08001450 # The OVF file and VMDK must be in a same directory
beierlb22ce2d2019-12-12 12:09:51 -05001451 head, _ = os.path.split(media_file_name)
sousaedu80135b92021-02-17 15:05:18 +01001452 file_vmdk = head + "/" + link_href.split("/")[-1]
1453
kasarc5bf2932018-03-09 04:15:22 -08001454 if not os.path.isfile(file_vmdk):
1455 return False
sousaedu80135b92021-02-17 15:05:18 +01001456
kasarc5bf2932018-03-09 04:15:22 -08001457 statinfo = os.stat(file_vmdk)
1458 if statinfo.st_size == 0:
1459 return False
sousaedu80135b92021-02-17 15:05:18 +01001460
kasarc5bf2932018-03-09 04:15:22 -08001461 hrefvmdk = link_href
1462
1463 if progress:
sousaedu80135b92021-02-17 15:05:18 +01001464 widgets = [
1465 "Uploading file: ",
1466 Percentage(),
1467 " ",
1468 Bar(),
1469 " ",
1470 ETA(),
1471 " ",
1472 FileTransferSpeed(),
1473 ]
1474 progress_bar = ProgressBar(
1475 widgets=widgets, maxval=statinfo.st_size
1476 ).start()
kasarc5bf2932018-03-09 04:15:22 -08001477
1478 bytes_transferred = 0
sousaedu80135b92021-02-17 15:05:18 +01001479 f = open(file_vmdk, "rb")
1480
kasarc5bf2932018-03-09 04:15:22 -08001481 while bytes_transferred < statinfo.st_size:
1482 my_bytes = f.read(chunk_bytes)
1483 if len(my_bytes) <= chunk_bytes:
sousaedu80135b92021-02-17 15:05:18 +01001484 headers["Content-Range"] = "bytes {}-{}/{}".format(
1485 bytes_transferred,
1486 len(my_bytes) - 1,
1487 statinfo.st_size,
1488 )
1489 headers["Content-Length"] = str(len(my_bytes))
1490 response = requests.put(
1491 url=hrefvmdk,
1492 headers=headers,
1493 data=my_bytes,
1494 verify=False,
1495 )
1496
kasarc5bf2932018-03-09 04:15:22 -08001497 if response.status_code == requests.codes.ok:
1498 bytes_transferred += len(my_bytes)
1499 if progress:
1500 progress_bar.update(bytes_transferred)
1501 else:
1502 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01001503 "file upload failed with error: [{}] {}".format(
1504 response.status_code, response.text
1505 )
1506 )
kasarc5bf2932018-03-09 04:15:22 -08001507
1508 f.close()
sousaedu80135b92021-02-17 15:05:18 +01001509
bhangarebfdca492017-03-11 01:32:46 -08001510 return False
sousaedu80135b92021-02-17 15:05:18 +01001511
kasarc5bf2932018-03-09 04:15:22 -08001512 f.close()
1513 if progress:
1514 progress_bar.finish()
1515 time.sleep(10)
sousaedu80135b92021-02-17 15:05:18 +01001516
kasarc5bf2932018-03-09 04:15:22 -08001517 return True
1518 else:
sousaedu80135b92021-02-17 15:05:18 +01001519 self.logger.debug(
1520 "Failed retrieve vApp template for catalog name {} for OVF {}".format(
1521 catalog_name, media_file_name
1522 )
1523 )
kasarc5bf2932018-03-09 04:15:22 -08001524 return False
bhangarebfdca492017-03-11 01:32:46 -08001525 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01001526 self.logger.debug(
1527 "Failed while uploading OVF to catalog {} for OVF file {} with Exception {}".format(
1528 catalog_name, media_file_name, exp
1529 )
1530 )
bayramov325fa1c2016-09-08 01:42:46 -07001531
sousaedu80135b92021-02-17 15:05:18 +01001532 raise vimconn.VimConnException(
1533 "Failed while uploading OVF to catalog {} for OVF file {} with Exception {}".format(
1534 catalog_name, media_file_name, exp
1535 )
1536 )
1537
1538 self.logger.debug(
1539 "Failed retrieve catalog name {} for OVF file {}".format(
1540 catalog_name, media_file_name
1541 )
1542 )
1543
bayramov325fa1c2016-09-08 01:42:46 -07001544 return False
1545
sousaedu80135b92021-02-17 15:05:18 +01001546 def upload_vimimage(
1547 self,
1548 vca=None,
1549 catalog_name=None,
1550 media_name=None,
1551 medial_file_name=None,
1552 progress=False,
1553 ):
bayramov325fa1c2016-09-08 01:42:46 -07001554 """Upload media file"""
bayramovfe3f3c92016-10-04 07:53:41 +04001555 # TODO add named parameters for readability
sousaedu80135b92021-02-17 15:05:18 +01001556 return self.upload_ovf(
1557 vca=vca,
1558 catalog_name=catalog_name,
1559 image_name=media_name.split(".")[0],
1560 media_file_name=medial_file_name,
1561 description="medial_file_name",
1562 progress=progress,
1563 )
bayramov325fa1c2016-09-08 01:42:46 -07001564
bayramovb6ffe792016-09-28 11:50:56 +04001565 def validate_uuid4(self, uuid_string=None):
sousaedu80135b92021-02-17 15:05:18 +01001566 """Method validate correct format of UUID.
bayramovb6ffe792016-09-28 11:50:56 +04001567
1568 Return: true if string represent valid uuid
1569 """
1570 try:
beierlb22ce2d2019-12-12 12:09:51 -05001571 uuid.UUID(uuid_string, version=4)
bayramovb6ffe792016-09-28 11:50:56 +04001572 except ValueError:
1573 return False
sousaedu80135b92021-02-17 15:05:18 +01001574
bayramovb6ffe792016-09-28 11:50:56 +04001575 return True
1576
1577 def get_catalogid(self, catalog_name=None, catalogs=None):
sousaedu80135b92021-02-17 15:05:18 +01001578 """Method check catalog and return catalog ID in UUID format.
bayramovb6ffe792016-09-28 11:50:56 +04001579
1580 Args
1581 catalog_name: catalog name as string
1582 catalogs: list of catalogs.
1583
1584 Return: catalogs uuid
1585 """
bayramov325fa1c2016-09-08 01:42:46 -07001586 for catalog in catalogs:
sousaedu80135b92021-02-17 15:05:18 +01001587 if catalog["name"] == catalog_name:
1588 catalog_id = catalog["id"]
kasarc5bf2932018-03-09 04:15:22 -08001589 return catalog_id
sousaedu80135b92021-02-17 15:05:18 +01001590
bayramov325fa1c2016-09-08 01:42:46 -07001591 return None
1592
bayramovb6ffe792016-09-28 11:50:56 +04001593 def get_catalogbyid(self, catalog_uuid=None, catalogs=None):
sousaedu80135b92021-02-17 15:05:18 +01001594 """Method check catalog and return catalog name lookup done by catalog UUID.
bayramovb6ffe792016-09-28 11:50:56 +04001595
1596 Args
1597 catalog_name: catalog name as string
1598 catalogs: list of catalogs.
1599
1600 Return: catalogs name or None
1601 """
bayramovb6ffe792016-09-28 11:50:56 +04001602 if not self.validate_uuid4(uuid_string=catalog_uuid):
1603 return None
1604
bayramov325fa1c2016-09-08 01:42:46 -07001605 for catalog in catalogs:
sousaedu80135b92021-02-17 15:05:18 +01001606 catalog_id = catalog.get("id")
1607
bayramovb6ffe792016-09-28 11:50:56 +04001608 if catalog_id == catalog_uuid:
sousaedu80135b92021-02-17 15:05:18 +01001609 return catalog.get("name")
1610
bayramov325fa1c2016-09-08 01:42:46 -07001611 return None
1612
bhangare06312472017-03-30 05:49:07 -07001613 def get_catalog_obj(self, catalog_uuid=None, catalogs=None):
sousaedu80135b92021-02-17 15:05:18 +01001614 """Method check catalog and return catalog name lookup done by catalog UUID.
bhangare06312472017-03-30 05:49:07 -07001615
1616 Args
1617 catalog_name: catalog name as string
1618 catalogs: list of catalogs.
1619
1620 Return: catalogs name or None
1621 """
bhangare06312472017-03-30 05:49:07 -07001622 if not self.validate_uuid4(uuid_string=catalog_uuid):
1623 return None
1624
1625 for catalog in catalogs:
sousaedu80135b92021-02-17 15:05:18 +01001626 catalog_id = catalog.get("id")
1627
bhangare06312472017-03-30 05:49:07 -07001628 if catalog_id == catalog_uuid:
1629 return catalog
sousaedu80135b92021-02-17 15:05:18 +01001630
bhangare06312472017-03-30 05:49:07 -07001631 return None
1632
bayramovfe3f3c92016-10-04 07:53:41 +04001633 def get_image_id_from_path(self, path=None, progress=False):
sousaedu80135b92021-02-17 15:05:18 +01001634 """Method upload OVF image to vCloud director.
bayramov325fa1c2016-09-08 01:42:46 -07001635
bayramovb6ffe792016-09-28 11:50:56 +04001636 Each OVF image represented as single catalog entry in vcloud director.
1637 The method check for existing catalog entry. The check done by file name without file extension.
1638
1639 if given catalog name already present method will respond with existing catalog uuid otherwise
1640 it will create new catalog entry and upload OVF file to newly created catalog.
1641
1642 If method can't create catalog entry or upload a file it will throw exception.
1643
bayramovfe3f3c92016-10-04 07:53:41 +04001644 Method accept boolean flag progress that will output progress bar. It useful method
1645 for standalone upload use case. In case to test large file upload.
1646
bayramovb6ffe792016-09-28 11:50:56 +04001647 Args
bayramovfe3f3c92016-10-04 07:53:41 +04001648 path: - valid path to OVF file.
1649 progress - boolean progress bar show progress bar.
bayramovb6ffe792016-09-28 11:50:56 +04001650
1651 Return: if image uploaded correct method will provide image catalog UUID.
1652 """
kate15f1c382016-12-15 01:12:40 -08001653 if not path:
tierno72774862020-05-04 11:44:15 +00001654 raise vimconn.VimConnException("Image path can't be None.")
bayramovfe3f3c92016-10-04 07:53:41 +04001655
1656 if not os.path.isfile(path):
tierno72774862020-05-04 11:44:15 +00001657 raise vimconn.VimConnException("Can't read file. File not found.")
bayramovfe3f3c92016-10-04 07:53:41 +04001658
1659 if not os.access(path, os.R_OK):
sousaedu80135b92021-02-17 15:05:18 +01001660 raise vimconn.VimConnException(
1661 "Can't read file. Check file permission to read."
1662 )
bayramovfe3f3c92016-10-04 07:53:41 +04001663
1664 self.logger.debug("get_image_id_from_path() client requesting {} ".format(path))
bayramov325fa1c2016-09-08 01:42:46 -07001665
beierlb22ce2d2019-12-12 12:09:51 -05001666 _, filename = os.path.split(path)
1667 _, file_extension = os.path.splitext(path)
sousaedu80135b92021-02-17 15:05:18 +01001668 if file_extension != ".ovf":
1669 self.logger.debug(
1670 "Wrong file extension {} connector support only OVF container.".format(
1671 file_extension
1672 )
1673 )
1674
1675 raise vimconn.VimConnException(
1676 "Wrong container. vCloud director supports only OVF."
1677 )
kate15f1c382016-12-15 01:12:40 -08001678
bayramov325fa1c2016-09-08 01:42:46 -07001679 catalog_name = os.path.splitext(filename)[0]
sousaedu80135b92021-02-17 15:05:18 +01001680 catalog_md5_name = hashlib.md5(path.encode("utf-8")).hexdigest()
1681 self.logger.debug(
1682 "File name {} Catalog Name {} file path {} "
1683 "vdc catalog name {}".format(filename, catalog_name, path, catalog_md5_name)
1684 )
bayramov325fa1c2016-09-08 01:42:46 -07001685
bhangarebfdca492017-03-11 01:32:46 -08001686 try:
beierlb22ce2d2019-12-12 12:09:51 -05001687 org, _ = self.get_vdc_details()
kasarc5bf2932018-03-09 04:15:22 -08001688 catalogs = org.list_catalogs()
bhangarebfdca492017-03-11 01:32:46 -08001689 except Exception as exp:
1690 self.logger.debug("Failed get catalogs() with Exception {} ".format(exp))
sousaedu80135b92021-02-17 15:05:18 +01001691
1692 raise vimconn.VimConnException(
1693 "Failed get catalogs() with Exception {} ".format(exp)
1694 )
bhangarebfdca492017-03-11 01:32:46 -08001695
bayramov325fa1c2016-09-08 01:42:46 -07001696 if len(catalogs) == 0:
sousaedu80135b92021-02-17 15:05:18 +01001697 self.logger.info(
1698 "Creating a new catalog entry {} in vcloud director".format(
1699 catalog_name
1700 )
1701 )
kasarc5bf2932018-03-09 04:15:22 -08001702
sousaedu80135b92021-02-17 15:05:18 +01001703 if self.create_vimcatalog(org, catalog_md5_name) is None:
1704 raise vimconn.VimConnException(
1705 "Failed create new catalog {} ".format(catalog_md5_name)
1706 )
1707
1708 result = self.upload_vimimage(
1709 vca=org,
1710 catalog_name=catalog_md5_name,
1711 media_name=filename,
1712 medial_file_name=path,
1713 progress=progress,
1714 )
1715
bayramov325fa1c2016-09-08 01:42:46 -07001716 if not result:
sousaedu80135b92021-02-17 15:05:18 +01001717 raise vimconn.VimConnException(
1718 "Failed create vApp template for catalog {} ".format(catalog_name)
1719 )
1720
kasarc5bf2932018-03-09 04:15:22 -08001721 return self.get_catalogid(catalog_name, catalogs)
bayramov325fa1c2016-09-08 01:42:46 -07001722 else:
1723 for catalog in catalogs:
1724 # search for existing catalog if we find same name we return ID
1725 # TODO optimize this
sousaedu80135b92021-02-17 15:05:18 +01001726 if catalog["name"] == catalog_md5_name:
1727 self.logger.debug(
1728 "Found existing catalog entry for {} "
1729 "catalog id {}".format(
1730 catalog_name, self.get_catalogid(catalog_md5_name, catalogs)
1731 )
1732 )
1733
kasarc5bf2932018-03-09 04:15:22 -08001734 return self.get_catalogid(catalog_md5_name, catalogs)
bayramov325fa1c2016-09-08 01:42:46 -07001735
bayramovfe3f3c92016-10-04 07:53:41 +04001736 # if we didn't find existing catalog we create a new one and upload image.
sousaedu80135b92021-02-17 15:05:18 +01001737 self.logger.debug(
1738 "Creating new catalog entry {} - {}".format(catalog_name, catalog_md5_name)
1739 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00001740 if self.create_vimcatalog(org, catalog_md5_name) is None:
sousaedu80135b92021-02-17 15:05:18 +01001741 raise vimconn.VimConnException(
1742 "Failed create new catalog {} ".format(catalog_md5_name)
1743 )
bayramovfe3f3c92016-10-04 07:53:41 +04001744
sousaedu80135b92021-02-17 15:05:18 +01001745 result = self.upload_vimimage(
1746 vca=org,
1747 catalog_name=catalog_md5_name,
1748 media_name=filename,
1749 medial_file_name=path,
1750 progress=progress,
1751 )
bayramov325fa1c2016-09-08 01:42:46 -07001752 if not result:
sousaedu80135b92021-02-17 15:05:18 +01001753 raise vimconn.VimConnException(
1754 "Failed create vApp template for catalog {} ".format(catalog_md5_name)
1755 )
bayramov325fa1c2016-09-08 01:42:46 -07001756
kasarc5bf2932018-03-09 04:15:22 -08001757 return self.get_catalogid(catalog_md5_name, org.list_catalogs())
bayramov325fa1c2016-09-08 01:42:46 -07001758
kate8fc61fc2017-01-23 19:57:06 -08001759 def get_image_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01001760 """Obtain tenant images from VIM
kate8fc61fc2017-01-23 19:57:06 -08001761 Filter_dict can be:
1762 name: image name
1763 id: image uuid
1764 checksum: image checksum
1765 location: image path
1766 Returns the image list of dictionaries:
1767 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1768 List can be empty
sousaedu80135b92021-02-17 15:05:18 +01001769 """
kate8fc61fc2017-01-23 19:57:06 -08001770 try:
beierlb22ce2d2019-12-12 12:09:51 -05001771 org, _ = self.get_vdc_details()
kate8fc61fc2017-01-23 19:57:06 -08001772 image_list = []
kasarc5bf2932018-03-09 04:15:22 -08001773 catalogs = org.list_catalogs()
sousaedu80135b92021-02-17 15:05:18 +01001774
kate8fc61fc2017-01-23 19:57:06 -08001775 if len(catalogs) == 0:
1776 return image_list
1777 else:
1778 for catalog in catalogs:
sousaedu80135b92021-02-17 15:05:18 +01001779 catalog_uuid = catalog.get("id")
1780 name = catalog.get("name")
kate8fc61fc2017-01-23 19:57:06 -08001781 filtered_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01001782
kate34718682017-01-24 03:20:43 -08001783 if filter_dict.get("name") and filter_dict["name"] != name:
1784 continue
sousaedu80135b92021-02-17 15:05:18 +01001785
kate34718682017-01-24 03:20:43 -08001786 if filter_dict.get("id") and filter_dict["id"] != catalog_uuid:
1787 continue
sousaedu80135b92021-02-17 15:05:18 +01001788
beierlb22ce2d2019-12-12 12:09:51 -05001789 filtered_dict["name"] = name
1790 filtered_dict["id"] = catalog_uuid
kate34718682017-01-24 03:20:43 -08001791 image_list.append(filtered_dict)
kate8fc61fc2017-01-23 19:57:06 -08001792
sousaedu80135b92021-02-17 15:05:18 +01001793 self.logger.debug(
1794 "List of already created catalog items: {}".format(image_list)
1795 )
1796
kate8fc61fc2017-01-23 19:57:06 -08001797 return image_list
1798 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01001799 raise vimconn.VimConnException(
1800 "Exception occured while retriving catalog items {}".format(exp)
1801 )
kate8fc61fc2017-01-23 19:57:06 -08001802
bayramovef390722016-09-27 03:34:46 -07001803 def get_vappid(self, vdc=None, vapp_name=None):
sousaedu80135b92021-02-17 15:05:18 +01001804 """Method takes vdc object and vApp name and returns vapp uuid or None
bayramovef390722016-09-27 03:34:46 -07001805
1806 Args:
bayramovef390722016-09-27 03:34:46 -07001807 vdc: The VDC object.
1808 vapp_name: is application vappp name identifier
1809
bayramovb6ffe792016-09-28 11:50:56 +04001810 Returns:
bayramovef390722016-09-27 03:34:46 -07001811 The return vApp name otherwise None
1812 """
bayramovef390722016-09-27 03:34:46 -07001813 if vdc is None or vapp_name is None:
1814 return None
sousaedu80135b92021-02-17 15:05:18 +01001815
bayramovef390722016-09-27 03:34:46 -07001816 # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
bayramov325fa1c2016-09-08 01:42:46 -07001817 try:
sousaedu80135b92021-02-17 15:05:18 +01001818 refs = [
1819 ref
1820 for ref in vdc.ResourceEntities.ResourceEntity
1821 if ref.name == vapp_name
1822 and ref.type_ == "application/vnd.vmware.vcloud.vApp+xml"
1823 ]
1824
bayramov325fa1c2016-09-08 01:42:46 -07001825 if len(refs) == 1:
1826 return refs[0].href.split("vapp")[1][1:]
bayramovef390722016-09-27 03:34:46 -07001827 except Exception as e:
1828 self.logger.exception(e)
1829 return False
sousaedu80135b92021-02-17 15:05:18 +01001830
bayramovef390722016-09-27 03:34:46 -07001831 return None
1832
bayramovfe3f3c92016-10-04 07:53:41 +04001833 def check_vapp(self, vdc=None, vapp_uuid=None):
sousaedu80135b92021-02-17 15:05:18 +01001834 """Method Method returns True or False if vapp deployed in vCloud director
bayramovef390722016-09-27 03:34:46 -07001835
sousaedu80135b92021-02-17 15:05:18 +01001836 Args:
1837 vca: Connector to VCA
1838 vdc: The VDC object.
1839 vappid: vappid is application identifier
bayramovef390722016-09-27 03:34:46 -07001840
sousaedu80135b92021-02-17 15:05:18 +01001841 Returns:
1842 The return True if vApp deployed
1843 :param vdc:
1844 :param vapp_uuid:
bayramovef390722016-09-27 03:34:46 -07001845 """
1846 try:
sousaedu80135b92021-02-17 15:05:18 +01001847 refs = [
1848 ref
1849 for ref in vdc.ResourceEntities.ResourceEntity
1850 if ref.type_ == "application/vnd.vmware.vcloud.vApp+xml"
1851 ]
1852
bayramovef390722016-09-27 03:34:46 -07001853 for ref in refs:
1854 vappid = ref.href.split("vapp")[1][1:]
1855 # find vapp with respected vapp uuid
sousaedu80135b92021-02-17 15:05:18 +01001856
bayramovfe3f3c92016-10-04 07:53:41 +04001857 if vappid == vapp_uuid:
bayramovef390722016-09-27 03:34:46 -07001858 return True
1859 except Exception as e:
1860 self.logger.exception(e)
sousaedu80135b92021-02-17 15:05:18 +01001861
bayramovef390722016-09-27 03:34:46 -07001862 return False
sousaedu80135b92021-02-17 15:05:18 +01001863
bayramovef390722016-09-27 03:34:46 -07001864 return False
1865
kasarc5bf2932018-03-09 04:15:22 -08001866 def get_namebyvappid(self, vapp_uuid=None):
bayramovef390722016-09-27 03:34:46 -07001867 """Method returns vApp name from vCD and lookup done by vapp_id.
1868
1869 Args:
bayramovfe3f3c92016-10-04 07:53:41 +04001870 vapp_uuid: vappid is application identifier
bayramovef390722016-09-27 03:34:46 -07001871
1872 Returns:
1873 The return vApp name otherwise None
1874 """
bayramovef390722016-09-27 03:34:46 -07001875 try:
kasarc5bf2932018-03-09 04:15:22 -08001876 if self.client and vapp_uuid:
1877 vapp_call = "{}/api/vApp/vapp-{}".format(self.url, vapp_uuid)
sousaedu80135b92021-02-17 15:05:18 +01001878 headers = {
1879 "Accept": "application/*+xml;version=" + API_VERSION,
1880 "x-vcloud-authorization": self.client._session.headers[
1881 "x-vcloud-authorization"
1882 ],
1883 }
bhangare1a0b97c2017-06-21 02:20:15 -07001884
sousaedu80135b92021-02-17 15:05:18 +01001885 response = self.perform_request(
1886 req_type="GET", url=vapp_call, headers=headers
1887 )
1888
beierlb22ce2d2019-12-12 12:09:51 -05001889 # Retry login if session expired & retry sending request
kasarc5bf2932018-03-09 04:15:22 -08001890 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01001891 response = self.retry_rest("GET", vapp_call)
bhangare1a0b97c2017-06-21 02:20:15 -07001892
beierl26fec002019-12-06 17:06:40 -05001893 tree = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01001894
1895 return tree.attrib["name"] if "name" in tree.attrib else None
bayramovef390722016-09-27 03:34:46 -07001896 except Exception as e:
1897 self.logger.exception(e)
sousaedu80135b92021-02-17 15:05:18 +01001898
bayramov325fa1c2016-09-08 01:42:46 -07001899 return None
sousaedu80135b92021-02-17 15:05:18 +01001900
bayramov325fa1c2016-09-08 01:42:46 -07001901 return None
1902
sousaedu80135b92021-02-17 15:05:18 +01001903 def new_vminstance(
1904 self,
1905 name=None,
1906 description="",
1907 start=False,
1908 image_id=None,
1909 flavor_id=None,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001910 affinity_group_list=[],
sousaedu80135b92021-02-17 15:05:18 +01001911 net_list=[],
1912 cloud_config=None,
1913 disk_list=None,
1914 availability_zone_index=None,
1915 availability_zone_list=None,
1916 ):
bayramov325fa1c2016-09-08 01:42:46 -07001917 """Adds a VM instance to VIM
1918 Params:
tierno19860412017-10-03 10:46:46 +02001919 'start': (boolean) indicates if VM must start or created in pause mode.
1920 'image_id','flavor_id': image and flavor VIM id to use for the VM
1921 'net_list': list of interfaces, each one is a dictionary with:
1922 'name': (optional) name for the interface.
1923 'net_id': VIM network id where this interface must be connect to. Mandatory for type==virtual
beierlb22ce2d2019-12-12 12:09:51 -05001924 'vpci': (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM
1925 capabilities
garciadeblasc4f4d732018-10-25 18:17:24 +02001926 'model': (optional and only have sense for type==virtual) interface model: virtio, e1000, ...
tierno19860412017-10-03 10:46:46 +02001927 'mac_address': (optional) mac address to assign to this interface
beierlb22ce2d2019-12-12 12:09:51 -05001928 #TODO: CHECK if an optional 'vlan' parameter is needed for VIMs when type if VF and net_id is not
1929 provided, the VLAN tag to be used. In case net_id is provided, the internal network vlan is used
1930 for tagging VF
tierno19860412017-10-03 10:46:46 +02001931 'type': (mandatory) can be one of:
1932 'virtual', in this case always connected to a network of type 'net_type=bridge'
beierlb22ce2d2019-12-12 12:09:51 -05001933 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a
1934 data/ptp network or it can created unconnected
tierno66eba6e2017-11-10 17:09:18 +01001935 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
tierno19860412017-10-03 10:46:46 +02001936 'VFnotShared'(SRIOV without VLAN tag) same as PF for network connectivity. VF where no other VFs
1937 are allocated on the same physical NIC
1938 'bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
1939 'port_security': (optional) If False it must avoid any traffic filtering at this interface. If missing
1940 or True, it must apply the default VIM behaviour
1941 After execution the method will add the key:
1942 'vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
1943 interface. 'net_list' is modified
1944 'cloud_config': (optional) dictionary with:
1945 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1946 'users': (optional) list of users to be inserted, each item is a dict with:
1947 'name': (mandatory) user name,
1948 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1949 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
1950 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
1951 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1952 'dest': (mandatory) string with the destination absolute path
1953 'encoding': (optional, by default text). Can be one of:
1954 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1955 'content' (mandatory): string with the content of the file
1956 'permissions': (optional) string with file permissions, typically octal notation '0644'
1957 'owner': (optional) file owner, string with the format 'owner:group'
1958 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1959 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1960 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1961 'size': (mandatory) string with the size of the disk in GB
1962 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1963 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1964 availability_zone_index is None
tierno98e909c2017-10-14 13:27:03 +02001965 Returns a tuple with the instance identifier and created_items or raises an exception on error
1966 created_items can be None or a dictionary where this method can include key-values that will be passed to
1967 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1968 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1969 as not present.
bayramov325fa1c2016-09-08 01:42:46 -07001970 """
kate15f1c382016-12-15 01:12:40 -08001971 self.logger.info("Creating new instance for entry {}".format(name))
sousaedu80135b92021-02-17 15:05:18 +01001972 self.logger.debug(
1973 "desc {} boot {} image_id: {} flavor_id: {} net_list: {} cloud_config {} disk_list {} "
1974 "availability_zone_index {} availability_zone_list {}".format(
1975 description,
1976 start,
1977 image_id,
1978 flavor_id,
1979 net_list,
1980 cloud_config,
1981 disk_list,
1982 availability_zone_index,
1983 availability_zone_list,
1984 )
1985 )
bayramov325fa1c2016-09-08 01:42:46 -07001986
beierlb22ce2d2019-12-12 12:09:51 -05001987 # new vm name = vmname + tenant_id + uuid
sousaedu80135b92021-02-17 15:05:18 +01001988 new_vm_name = [name, "-", str(uuid.uuid4())]
1989 vmname_andid = "".join(new_vm_name)
bayramov5761ad12016-10-04 09:00:30 +04001990
kasarc5bf2932018-03-09 04:15:22 -08001991 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +01001992 if net["type"] == "PCI-PASSTHROUGH":
tierno72774862020-05-04 11:44:15 +00001993 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01001994 "Current vCD version does not support type : {}".format(net["type"])
1995 )
bayramov325fa1c2016-09-08 01:42:46 -07001996
kasarc5bf2932018-03-09 04:15:22 -08001997 if len(net_list) > 10:
tierno72774862020-05-04 11:44:15 +00001998 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01001999 "The VM hardware versions 7 and above support upto 10 NICs only"
2000 )
kasarc5bf2932018-03-09 04:15:22 -08002001
2002 # if vm already deployed we return existing uuid
bayramovef390722016-09-27 03:34:46 -07002003 # we check for presence of VDC, Catalog entry and Flavor.
kasarc5bf2932018-03-09 04:15:22 -08002004 org, vdc = self.get_vdc_details()
bayramovef390722016-09-27 03:34:46 -07002005 if vdc is None:
tierno72774862020-05-04 11:44:15 +00002006 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01002007 "new_vminstance(): Failed create vApp {}: (Failed retrieve VDC information)".format(
2008 name
2009 )
2010 )
2011
kasarc5bf2932018-03-09 04:15:22 -08002012 catalogs = org.list_catalogs()
bhangare1a0b97c2017-06-21 02:20:15 -07002013 if catalogs is None:
beierlb22ce2d2019-12-12 12:09:51 -05002014 # Retry once, if failed by refreshing token
bhangare1a0b97c2017-06-21 02:20:15 -07002015 self.get_token()
kasarc5bf2932018-03-09 04:15:22 -08002016 org = Org(self.client, resource=self.client.get_org())
2017 catalogs = org.list_catalogs()
sousaedu80135b92021-02-17 15:05:18 +01002018
bayramovef390722016-09-27 03:34:46 -07002019 if catalogs is None:
tierno72774862020-05-04 11:44:15 +00002020 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01002021 "new_vminstance(): Failed create vApp {}: (Failed retrieve catalogs list)".format(
2022 name
2023 )
2024 )
bayramovbd6160f2016-09-28 04:12:05 +04002025
sousaedu80135b92021-02-17 15:05:18 +01002026 catalog_hash_name = self.get_catalogbyid(
2027 catalog_uuid=image_id, catalogs=catalogs
2028 )
kate15f1c382016-12-15 01:12:40 -08002029 if catalog_hash_name:
sousaedu80135b92021-02-17 15:05:18 +01002030 self.logger.info(
2031 "Found catalog entry {} for image id {}".format(
2032 catalog_hash_name, image_id
2033 )
2034 )
kate15f1c382016-12-15 01:12:40 -08002035 else:
sousaedu80135b92021-02-17 15:05:18 +01002036 raise vimconn.VimConnNotFoundException(
2037 "new_vminstance(): Failed create vApp {}: "
2038 "(Failed retrieve catalog information {})".format(name, image_id)
2039 )
kate15f1c382016-12-15 01:12:40 -08002040
kate15f1c382016-12-15 01:12:40 -08002041 # Set vCPU and Memory based on flavor.
bayramovb6ffe792016-09-28 11:50:56 +04002042 vm_cpus = None
2043 vm_memory = None
bhangarea92ae392017-01-12 22:30:29 -08002044 vm_disk = None
bhangare68e73e62017-07-04 22:44:01 -07002045 numas = None
kateac1e3792017-04-01 02:16:39 -07002046
bayramovb6ffe792016-09-28 11:50:56 +04002047 if flavor_id is not None:
kateeb044522017-03-06 23:54:39 -08002048 if flavor_id not in vimconnector.flavorlist:
sousaedu80135b92021-02-17 15:05:18 +01002049 raise vimconn.VimConnNotFoundException(
2050 "new_vminstance(): Failed create vApp {}: "
2051 "Failed retrieve flavor information "
2052 "flavor id {}".format(name, flavor_id)
2053 )
bayramovb6ffe792016-09-28 11:50:56 +04002054 else:
2055 try:
kateeb044522017-03-06 23:54:39 -08002056 flavor = vimconnector.flavorlist[flavor_id]
kate15f1c382016-12-15 01:12:40 -08002057 vm_cpus = flavor[FLAVOR_VCPUS_KEY]
2058 vm_memory = flavor[FLAVOR_RAM_KEY]
bhangarea92ae392017-01-12 22:30:29 -08002059 vm_disk = flavor[FLAVOR_DISK_KEY]
bhangarefda5f7c2017-01-12 23:50:34 -08002060 extended = flavor.get("extended", None)
sousaedu80135b92021-02-17 15:05:18 +01002061
bhangarefda5f7c2017-01-12 23:50:34 -08002062 if extended:
beierlb22ce2d2019-12-12 12:09:51 -05002063 numas = extended.get("numas", None)
kateeb044522017-03-06 23:54:39 -08002064 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01002065 raise vimconn.VimConnException(
2066 "Corrupted flavor. {}.Exception: {}".format(flavor_id, exp)
2067 )
bayramov325fa1c2016-09-08 01:42:46 -07002068
bayramovef390722016-09-27 03:34:46 -07002069 # image upload creates template name as catalog name space Template.
kate15f1c382016-12-15 01:12:40 -08002070 templateName = self.get_catalogbyid(catalog_uuid=image_id, catalogs=catalogs)
beierlb22ce2d2019-12-12 12:09:51 -05002071 # power_on = 'false'
2072 # if start:
2073 # power_on = 'true'
bayramovef390722016-09-27 03:34:46 -07002074
2075 # client must provide at least one entry in net_list if not we report error
beierlb22ce2d2019-12-12 12:09:51 -05002076 # If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
beierl26fec002019-12-06 17:06:40 -05002077 # If no mgmt, then the 1st NN in netlist is considered as primary net.
bhangare0e571a92017-01-12 04:02:23 -08002078 primary_net = None
kate15f1c382016-12-15 01:12:40 -08002079 primary_netname = None
Ravi Chamarty1fdf9992018-10-07 15:45:44 +00002080 primary_net_href = None
beierlb22ce2d2019-12-12 12:09:51 -05002081 # network_mode = 'bridged'
bayramovb6ffe792016-09-28 11:50:56 +04002082 if net_list is not None and len(net_list) > 0:
bhangare0e571a92017-01-12 04:02:23 -08002083 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +01002084 if "use" in net and net["use"] == "mgmt" and not primary_net:
bhangare0e571a92017-01-12 04:02:23 -08002085 primary_net = net
sousaedu80135b92021-02-17 15:05:18 +01002086
bayramovb6ffe792016-09-28 11:50:56 +04002087 if primary_net is None:
bhangare0e571a92017-01-12 04:02:23 -08002088 primary_net = net_list[0]
2089
2090 try:
sousaedu80135b92021-02-17 15:05:18 +01002091 primary_net_id = primary_net["net_id"]
2092 url_list = [self.url, "/api/network/", primary_net_id]
2093 primary_net_href = "".join(url_list)
bhangare0e571a92017-01-12 04:02:23 -08002094 network_dict = self.get_vcd_network(network_uuid=primary_net_id)
bhangare0e571a92017-01-12 04:02:23 -08002095
sousaedu80135b92021-02-17 15:05:18 +01002096 if "name" in network_dict:
2097 primary_netname = network_dict["name"]
bhangare0e571a92017-01-12 04:02:23 -08002098 except KeyError:
sousaedu80135b92021-02-17 15:05:18 +01002099 raise vimconn.VimConnException(
2100 "Corrupted flavor. {}".format(primary_net)
2101 )
bhangare0e571a92017-01-12 04:02:23 -08002102 else:
sousaedu80135b92021-02-17 15:05:18 +01002103 raise vimconn.VimConnUnexpectedResponse(
2104 "new_vminstance(): Failed network list is empty."
2105 )
bayramovef390722016-09-27 03:34:46 -07002106
2107 # use: 'data', 'bridge', 'mgmt'
2108 # create vApp. Set vcpu and ram based on flavor id.
bhangarebfdca492017-03-11 01:32:46 -08002109 try:
kasarc5bf2932018-03-09 04:15:22 -08002110 vdc_obj = VDC(self.client, resource=org.get_vdc(self.tenant_name))
2111 if not vdc_obj:
sousaedu80135b92021-02-17 15:05:18 +01002112 raise vimconn.VimConnNotFoundException(
2113 "new_vminstance(): Failed to get VDC object"
2114 )
bhangare1a0b97c2017-06-21 02:20:15 -07002115
beierl26fec002019-12-06 17:06:40 -05002116 for retry in (1, 2):
kasarc5bf2932018-03-09 04:15:22 -08002117 items = org.get_catalog_item(catalog_hash_name, catalog_hash_name)
2118 catalog_items = [items.attrib]
2119
2120 if len(catalog_items) == 1:
2121 if self.client:
sousaedu80135b92021-02-17 15:05:18 +01002122 headers = {
2123 "Accept": "application/*+xml;version=" + API_VERSION,
2124 "x-vcloud-authorization": self.client._session.headers[
2125 "x-vcloud-authorization"
2126 ],
2127 }
kasarc5bf2932018-03-09 04:15:22 -08002128
sousaedu80135b92021-02-17 15:05:18 +01002129 response = self.perform_request(
2130 req_type="GET",
2131 url=catalog_items[0].get("href"),
2132 headers=headers,
2133 )
beierl26fec002019-12-06 17:06:40 -05002134 catalogItem = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01002135 entity = [
2136 child
2137 for child in catalogItem
2138 if child.get("type")
2139 == "application/vnd.vmware.vcloud.vAppTemplate+xml"
2140 ][0]
kasarc5bf2932018-03-09 04:15:22 -08002141 vapp_tempalte_href = entity.get("href")
sbhangarea8e5b782018-06-21 02:10:03 -07002142
sousaedu80135b92021-02-17 15:05:18 +01002143 response = self.perform_request(
2144 req_type="GET", url=vapp_tempalte_href, headers=headers
2145 )
2146
kasarc5bf2932018-03-09 04:15:22 -08002147 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01002148 self.logger.debug(
2149 "REST API call {} failed. Return status code {}".format(
2150 vapp_tempalte_href, response.status_code
2151 )
2152 )
kasarc5bf2932018-03-09 04:15:22 -08002153 else:
beierl26fec002019-12-06 17:06:40 -05002154 result = (response.text).replace("\n", " ")
kasarc5bf2932018-03-09 04:15:22 -08002155
beierl26fec002019-12-06 17:06:40 -05002156 vapp_template_tree = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01002157 children_element = [
2158 child for child in vapp_template_tree if "Children" in child.tag
2159 ][0]
2160 vm_element = [child for child in children_element if "Vm" in child.tag][
2161 0
2162 ]
2163 vm_name = vm_element.get("name")
2164 vm_id = vm_element.get("id")
2165 vm_href = vm_element.get("href")
kasarc5bf2932018-03-09 04:15:22 -08002166
beierlb22ce2d2019-12-12 12:09:51 -05002167 # cpus = re.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',
2168 # result).group(1)
sousaedu80135b92021-02-17 15:05:18 +01002169 memory_mb = re.search(
2170 "<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>",
2171 result,
2172 ).group(1)
beierlb22ce2d2019-12-12 12:09:51 -05002173 # cores = re.search('<vmw:CoresPerSocket ovf:required.*?>(\d+)</vmw:CoresPerSocket>', result).group(1)
kasarc5bf2932018-03-09 04:15:22 -08002174
sousaedu80135b92021-02-17 15:05:18 +01002175 headers[
2176 "Content-Type"
2177 ] = "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml"
2178 vdc_id = vdc.get("id").split(":")[-1]
2179 instantiate_vapp_href = (
2180 "{}/api/vdc/{}/action/instantiateVAppTemplate".format(
2181 self.url, vdc_id
2182 )
2183 )
2184
2185 with open(
2186 os.path.join(
2187 os.path.dirname(__file__), "InstantiateVAppTemplateParams.xml"
2188 ),
2189 "r",
2190 ) as f:
beierl26fec002019-12-06 17:06:40 -05002191 template = f.read()
2192
sousaedu80135b92021-02-17 15:05:18 +01002193 data = template.format(
2194 vmname_andid,
2195 primary_netname,
2196 primary_net_href,
2197 vapp_tempalte_href,
2198 vm_href,
2199 vm_id,
2200 vm_name,
2201 primary_netname,
2202 cpu=vm_cpus,
2203 core=1,
2204 memory=vm_memory,
2205 )
kasarc5bf2932018-03-09 04:15:22 -08002206
sousaedu80135b92021-02-17 15:05:18 +01002207 response = self.perform_request(
2208 req_type="POST",
2209 url=instantiate_vapp_href,
2210 headers=headers,
2211 data=data,
2212 )
kasarc5bf2932018-03-09 04:15:22 -08002213
2214 if response.status_code != 201:
sousaedu80135b92021-02-17 15:05:18 +01002215 self.logger.error(
2216 "REST call {} failed reason : {}"
2217 "status code : {}".format(
2218 instantiate_vapp_href, response.text, response.status_code
2219 )
2220 )
2221 raise vimconn.VimConnException(
2222 "new_vminstance(): Failed to create"
2223 "vAapp {}".format(vmname_andid)
2224 )
kasarc5bf2932018-03-09 04:15:22 -08002225 else:
beierl26fec002019-12-06 17:06:40 -05002226 vapptask = self.get_task_from_response(response.text)
kasarc5bf2932018-03-09 04:15:22 -08002227
beierlb22ce2d2019-12-12 12:09:51 -05002228 if vapptask is None and retry == 1:
2229 self.get_token() # Retry getting token
bhangare68e73e62017-07-04 22:44:01 -07002230 continue
2231 else:
2232 break
2233
bhangare1a0b97c2017-06-21 02:20:15 -07002234 if vapptask is None or vapptask is False:
tierno72774862020-05-04 11:44:15 +00002235 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002236 "new_vminstance(): failed to create vApp {}".format(vmname_andid)
2237 )
kasarc5bf2932018-03-09 04:15:22 -08002238
sbhangarea8e5b782018-06-21 02:10:03 -07002239 # wait for task to complete
kasarc5bf2932018-03-09 04:15:22 -08002240 result = self.client.get_task_monitor().wait_for_success(task=vapptask)
2241
sousaedu80135b92021-02-17 15:05:18 +01002242 if result.get("status") == "success":
2243 self.logger.debug(
2244 "new_vminstance(): Sucessfully created Vapp {}".format(vmname_andid)
2245 )
kasarc5bf2932018-03-09 04:15:22 -08002246 else:
tierno72774862020-05-04 11:44:15 +00002247 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002248 "new_vminstance(): failed to create vApp {}".format(vmname_andid)
2249 )
bhangarebfdca492017-03-11 01:32:46 -08002250 except Exception as exp:
tierno72774862020-05-04 11:44:15 +00002251 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002252 "new_vminstance(): failed to create vApp {} with Exception:{}".format(
2253 vmname_andid, exp
2254 )
2255 )
bayramovef390722016-09-27 03:34:46 -07002256
2257 # we should have now vapp in undeployed state.
bhangarebfdca492017-03-11 01:32:46 -08002258 try:
sousaedu80135b92021-02-17 15:05:18 +01002259 vdc_obj = VDC(self.client, href=vdc.get("href"))
kasarc5bf2932018-03-09 04:15:22 -08002260 vapp_resource = vdc_obj.get_vapp(vmname_andid)
sousaedu80135b92021-02-17 15:05:18 +01002261 vapp_uuid = vapp_resource.get("id").split(":")[-1]
kasarc5bf2932018-03-09 04:15:22 -08002262 vapp = VApp(self.client, resource=vapp_resource)
bhangarebfdca492017-03-11 01:32:46 -08002263 except Exception as exp:
tierno72774862020-05-04 11:44:15 +00002264 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002265 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}".format(
2266 vmname_andid, exp
2267 )
2268 )
bhangarebfdca492017-03-11 01:32:46 -08002269
bhangare1a0b97c2017-06-21 02:20:15 -07002270 if vapp_uuid is None:
tierno72774862020-05-04 11:44:15 +00002271 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002272 "new_vminstance(): Failed to retrieve vApp {} after creation".format(
2273 vmname_andid
2274 )
2275 )
bhangarea92ae392017-01-12 22:30:29 -08002276
beierl26fec002019-12-06 17:06:40 -05002277 # Add PCI passthrough/SRIOV configrations
kateac1e3792017-04-01 02:16:39 -07002278 pci_devices_info = []
kateac1e3792017-04-01 02:16:39 -07002279 reserve_memory = False
2280
2281 for net in net_list:
tierno66eba6e2017-11-10 17:09:18 +01002282 if net["type"] == "PF" or net["type"] == "PCI-PASSTHROUGH":
kateac1e3792017-04-01 02:16:39 -07002283 pci_devices_info.append(net)
sousaedu80135b92021-02-17 15:05:18 +01002284 elif (
2285 net["type"] == "VF"
2286 or net["type"] == "SR-IOV"
2287 or net["type"] == "VFnotShared"
2288 ) and "net_id" in net:
Ravi Chamartye21c9cc2018-10-24 02:14:53 +00002289 reserve_memory = True
kateac1e3792017-04-01 02:16:39 -07002290
beierl26fec002019-12-06 17:06:40 -05002291 # Add PCI
bhangarefda5f7c2017-01-12 23:50:34 -08002292 if len(pci_devices_info) > 0:
sousaedu80135b92021-02-17 15:05:18 +01002293 self.logger.info(
2294 "Need to add PCI devices {} into VM {}".format(
2295 pci_devices_info, vmname_andid
2296 )
2297 )
2298 PCI_devices_status, _, _ = self.add_pci_devices(
2299 vapp_uuid, pci_devices_info, vmname_andid
2300 )
2301
beierl26fec002019-12-06 17:06:40 -05002302 if PCI_devices_status:
sousaedu80135b92021-02-17 15:05:18 +01002303 self.logger.info(
2304 "Added PCI devives {} to VM {}".format(
2305 pci_devices_info, vmname_andid
2306 )
2307 )
kateac1e3792017-04-01 02:16:39 -07002308 reserve_memory = True
bhangarefda5f7c2017-01-12 23:50:34 -08002309 else:
sousaedu80135b92021-02-17 15:05:18 +01002310 self.logger.info(
2311 "Fail to add PCI devives {} to VM {}".format(
2312 pci_devices_info, vmname_andid
2313 )
2314 )
bhangare1a0b97c2017-06-21 02:20:15 -07002315
beierl26fec002019-12-06 17:06:40 -05002316 # Add serial console - this allows cloud images to boot as if we are running under OpenStack
2317 self.add_serial_device(vapp_uuid)
2318
bhangarea92ae392017-01-12 22:30:29 -08002319 if vm_disk:
beierl26fec002019-12-06 17:06:40 -05002320 # Assuming there is only one disk in ovf and fast provisioning in organization vDC is disabled
bhangarea92ae392017-01-12 22:30:29 -08002321 result = self.modify_vm_disk(vapp_uuid, vm_disk)
beierl26fec002019-12-06 17:06:40 -05002322 if result:
bhangarea92ae392017-01-12 22:30:29 -08002323 self.logger.debug("Modified Disk size of VM {} ".format(vmname_andid))
bayramovef390722016-09-27 03:34:46 -07002324
beierlb22ce2d2019-12-12 12:09:51 -05002325 # Add new or existing disks to vApp
bhangare06312472017-03-30 05:49:07 -07002326 if disk_list:
2327 added_existing_disk = False
2328 for disk in disk_list:
sousaedu80135b92021-02-17 15:05:18 +01002329 if "device_type" in disk and disk["device_type"] == "cdrom":
2330 image_id = disk["image_id"]
kasar0c007d62017-05-19 03:13:57 -07002331 # Adding CD-ROM to VM
2332 # will revisit code once specification ready to support this feature
2333 self.insert_media_to_vm(vapp, image_id)
2334 elif "image_id" in disk and disk["image_id"] is not None:
sousaedu80135b92021-02-17 15:05:18 +01002335 self.logger.debug(
2336 "Adding existing disk from image {} to vm {} ".format(
2337 disk["image_id"], vapp_uuid
2338 )
2339 )
2340 self.add_existing_disk(
2341 catalogs=catalogs,
2342 image_id=disk["image_id"],
2343 size=disk["size"],
2344 template_name=templateName,
2345 vapp_uuid=vapp_uuid,
2346 )
bhangare06312472017-03-30 05:49:07 -07002347 added_existing_disk = True
2348 else:
beierlb22ce2d2019-12-12 12:09:51 -05002349 # Wait till added existing disk gets reflected into vCD database/API
bhangare06312472017-03-30 05:49:07 -07002350 if added_existing_disk:
2351 time.sleep(5)
2352 added_existing_disk = False
sousaedu80135b92021-02-17 15:05:18 +01002353 self.add_new_disk(vapp_uuid, disk["size"])
bhangare06312472017-03-30 05:49:07 -07002354
kasarde691232017-03-25 03:37:31 -07002355 if numas:
2356 # Assigning numa affinity setting
2357 for numa in numas:
sousaedu80135b92021-02-17 15:05:18 +01002358 if "paired-threads-id" in numa:
2359 paired_threads_id = numa["paired-threads-id"]
kasarde691232017-03-25 03:37:31 -07002360 self.set_numa_affinity(vapp_uuid, paired_threads_id)
2361
bhangare0e571a92017-01-12 04:02:23 -08002362 # add NICs & connect to networks in netlist
bayramovef390722016-09-27 03:34:46 -07002363 try:
sousaedu80135b92021-02-17 15:05:18 +01002364 vdc_obj = VDC(self.client, href=vdc.get("href"))
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00002365 vapp_resource = vdc_obj.get_vapp(vmname_andid)
2366 vapp = VApp(self.client, resource=vapp_resource)
sousaedu80135b92021-02-17 15:05:18 +01002367 vapp_id = vapp_resource.get("id").split(":")[-1]
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00002368
2369 self.logger.info("Removing primary NIC: ")
2370 # First remove all NICs so that NIC properties can be adjusted as needed
2371 self.remove_primary_network_adapter_from_all_vms(vapp)
2372
kate15f1c382016-12-15 01:12:40 -08002373 self.logger.info("Request to connect VM to a network: {}".format(net_list))
bhangare0e571a92017-01-12 04:02:23 -08002374 primary_nic_index = 0
Ravi Chamarty1fdf9992018-10-07 15:45:44 +00002375 nicIndex = 0
bayramovef390722016-09-27 03:34:46 -07002376 for net in net_list:
2377 # openmano uses network id in UUID format.
2378 # vCloud Director need a name so we do reverse operation from provided UUID we lookup a name
kate15f1c382016-12-15 01:12:40 -08002379 # [{'use': 'bridge', 'net_id': '527d4bf7-566a-41e7-a9e7-ca3cdd9cef4f', 'type': 'virtual',
2380 # 'vpci': '0000:00:11.0', 'name': 'eth0'}]
2381
sousaedu80135b92021-02-17 15:05:18 +01002382 if "net_id" not in net:
kate15f1c382016-12-15 01:12:40 -08002383 continue
2384
beierlb22ce2d2019-12-12 12:09:51 -05002385 # Using net_id as a vim_id i.e. vim interface id, as do not have saperate vim interface id
2386 # Same will be returned in refresh_vms_status() as vim_interface_id
sousaedu80135b92021-02-17 15:05:18 +01002387 net["vim_id"] = net[
2388 "net_id"
2389 ] # Provide the same VIM identifier as the VIM network
tierno19860412017-10-03 10:46:46 +02002390
sousaedu80135b92021-02-17 15:05:18 +01002391 interface_net_id = net["net_id"]
2392 interface_net_name = self.get_network_name_by_id(
2393 network_uuid=interface_net_id
2394 )
2395 interface_network_mode = net["use"]
bayramovef390722016-09-27 03:34:46 -07002396
sousaedu80135b92021-02-17 15:05:18 +01002397 if interface_network_mode == "mgmt":
bhangare0e571a92017-01-12 04:02:23 -08002398 primary_nic_index = nicIndex
2399
kate15f1c382016-12-15 01:12:40 -08002400 """- POOL (A static IP address is allocated automatically from a pool of addresses.)
2401 - DHCP (The IP address is obtained from a DHCP service.)
2402 - MANUAL (The IP address is assigned manually in the IpAddress element.)
2403 - NONE (No IP addressing mode specified.)"""
2404
2405 if primary_netname is not None:
sousaedu80135b92021-02-17 15:05:18 +01002406 self.logger.debug(
2407 "new_vminstance(): Filtering by net name {}".format(
2408 interface_net_name
2409 )
2410 )
2411 nets = [
2412 n
2413 for n in self.get_network_list()
2414 if n.get("name") == interface_net_name
2415 ]
2416
bayramovef390722016-09-27 03:34:46 -07002417 if len(nets) == 1:
sousaedu80135b92021-02-17 15:05:18 +01002418 self.logger.info(
2419 "new_vminstance(): Found requested network: {}".format(
2420 nets[0].get("name")
2421 )
2422 )
bhangare1a0b97c2017-06-21 02:20:15 -07002423
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00002424 if interface_net_name != primary_netname:
2425 # connect network to VM - with all DHCP by default
sousaedu80135b92021-02-17 15:05:18 +01002426 self.logger.info(
2427 "new_vminstance(): Attaching net {} to vapp".format(
2428 interface_net_name
2429 )
2430 )
2431 self.connect_vapp_to_org_vdc_network(
2432 vapp_id, nets[0].get("name")
2433 )
kasar3ac5dc42017-03-15 06:28:22 -07002434
sousaedu80135b92021-02-17 15:05:18 +01002435 type_list = ("PF", "PCI-PASSTHROUGH", "VFnotShared")
2436 nic_type = "VMXNET3"
2437 if "type" in net and net["type"] not in type_list:
kasar3ac5dc42017-03-15 06:28:22 -07002438 # fetching nic type from vnf
sousaedu80135b92021-02-17 15:05:18 +01002439 if "model" in net:
2440 if net["model"] is not None:
2441 if (
2442 net["model"].lower() == "paravirt"
2443 or net["model"].lower() == "virtio"
2444 ):
2445 nic_type = "VMXNET3"
kasar204e39e2018-01-25 00:57:02 -08002446 else:
sousaedu80135b92021-02-17 15:05:18 +01002447 nic_type = net["model"]
kasar204e39e2018-01-25 00:57:02 -08002448
sousaedu80135b92021-02-17 15:05:18 +01002449 self.logger.info(
2450 "new_vminstance(): adding network adapter "
2451 "to a network {}".format(nets[0].get("name"))
2452 )
2453 self.add_network_adapter_to_vms(
2454 vapp,
2455 nets[0].get("name"),
2456 primary_nic_index,
2457 nicIndex,
2458 net,
2459 nic_type=nic_type,
2460 )
kasar3ac5dc42017-03-15 06:28:22 -07002461 else:
sousaedu80135b92021-02-17 15:05:18 +01002462 self.logger.info(
2463 "new_vminstance(): adding network adapter "
2464 "to a network {}".format(nets[0].get("name"))
2465 )
2466
2467 if net["type"] in ["SR-IOV", "VF"]:
2468 nic_type = net["type"]
2469 self.add_network_adapter_to_vms(
2470 vapp,
2471 nets[0].get("name"),
2472 primary_nic_index,
2473 nicIndex,
2474 net,
2475 nic_type=nic_type,
2476 )
bhangare0e571a92017-01-12 04:02:23 -08002477 nicIndex += 1
bayramovef390722016-09-27 03:34:46 -07002478
kasardc1f02e2017-03-25 07:20:30 -07002479 # cloud-init for ssh-key injection
2480 if cloud_config:
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002481 # Create a catalog which will be carrying the config drive ISO
2482 # This catalog is deleted during vApp deletion. The catalog name carries
2483 # vApp UUID and thats how it gets identified during its deletion.
sousaedu80135b92021-02-17 15:05:18 +01002484 config_drive_catalog_name = "cfg_drv-" + vapp_uuid
2485 self.logger.info(
2486 'new_vminstance(): Creating catalog "{}" to carry config drive ISO'.format(
2487 config_drive_catalog_name
2488 )
2489 )
2490 config_drive_catalog_id = self.create_vimcatalog(
2491 org, config_drive_catalog_name
2492 )
2493
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002494 if config_drive_catalog_id is None:
sousaedu80135b92021-02-17 15:05:18 +01002495 error_msg = (
2496 "new_vminstance(): Failed to create new catalog '{}' to carry the config drive "
2497 "ISO".format(config_drive_catalog_name)
2498 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002499 raise Exception(error_msg)
2500
2501 # Create config-drive ISO
2502 _, userdata = self._create_user_data(cloud_config)
2503 # self.logger.debug('new_vminstance(): The userdata for cloud-init: {}'.format(userdata))
2504 iso_path = self.create_config_drive_iso(userdata)
sousaedu80135b92021-02-17 15:05:18 +01002505 self.logger.debug(
2506 "new_vminstance(): The ISO is successfully created. Path: {}".format(
2507 iso_path
2508 )
2509 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002510
sousaedu80135b92021-02-17 15:05:18 +01002511 self.logger.info(
2512 "new_vminstance(): uploading iso to catalog {}".format(
2513 config_drive_catalog_name
2514 )
2515 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002516 self.upload_iso_to_catalog(config_drive_catalog_id, iso_path)
2517 # Attach the config-drive ISO to the VM
sousaedu80135b92021-02-17 15:05:18 +01002518 self.logger.info(
2519 "new_vminstance(): Attaching the config-drive ISO to the VM"
2520 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002521 self.insert_media_to_vm(vapp, config_drive_catalog_id)
2522 shutil.rmtree(os.path.dirname(iso_path), ignore_errors=True)
kasardc1f02e2017-03-25 07:20:30 -07002523
kateac1e3792017-04-01 02:16:39 -07002524 # If VM has PCI devices or SRIOV reserve memory for VM
2525 if reserve_memory:
Ravi Chamartye21c9cc2018-10-24 02:14:53 +00002526 self.reserve_memory_for_all_vms(vapp, memory_mb)
bhangarefda5f7c2017-01-12 23:50:34 -08002527
sousaedu80135b92021-02-17 15:05:18 +01002528 self.logger.debug(
2529 "new_vminstance(): starting power on vApp {} ".format(vmname_andid)
2530 )
bhangare1a0b97c2017-06-21 02:20:15 -07002531
kasarc5bf2932018-03-09 04:15:22 -08002532 poweron_task = self.power_on_vapp(vapp_id, vmname_andid)
2533 result = self.client.get_task_monitor().wait_for_success(task=poweron_task)
sousaedu80135b92021-02-17 15:05:18 +01002534 if result.get("status") == "success":
2535 self.logger.info(
2536 "new_vminstance(): Successfully power on "
2537 "vApp {}".format(vmname_andid)
2538 )
kasarc5bf2932018-03-09 04:15:22 -08002539 else:
sousaedu80135b92021-02-17 15:05:18 +01002540 self.logger.error(
2541 "new_vminstance(): failed to power on vApp "
2542 "{}".format(vmname_andid)
2543 )
bhangarebfdca492017-03-11 01:32:46 -08002544
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002545 except Exception as exp:
2546 try:
2547 self.delete_vminstance(vapp_uuid)
2548 except Exception as exp2:
2549 self.logger.error("new_vminstance rollback fail {}".format(exp2))
bhangarebfdca492017-03-11 01:32:46 -08002550 # it might be a case if specific mandatory entry in dict is empty or some other pyVcloud exception
sousaedu80135b92021-02-17 15:05:18 +01002551 self.logger.error(
2552 "new_vminstance(): Failed create new vm instance {} with exception {}".format(
2553 name, exp
2554 )
2555 )
2556 raise vimconn.VimConnException(
2557 "new_vminstance(): Failed create new vm instance {} with exception {}".format(
2558 name, exp
2559 )
2560 )
bayramovef390722016-09-27 03:34:46 -07002561 # check if vApp deployed and if that the case return vApp UUID otherwise -1
kate13ab2c42016-12-23 01:34:24 -08002562 wait_time = 0
2563 vapp_uuid = None
2564 while wait_time <= MAX_WAIT_TIME:
bhangarebfdca492017-03-11 01:32:46 -08002565 try:
kasarc5bf2932018-03-09 04:15:22 -08002566 vapp_resource = vdc_obj.get_vapp(vmname_andid)
sbhangarea8e5b782018-06-21 02:10:03 -07002567 vapp = VApp(self.client, resource=vapp_resource)
bhangarebfdca492017-03-11 01:32:46 -08002568 except Exception as exp:
tierno72774862020-05-04 11:44:15 +00002569 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01002570 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}".format(
2571 vmname_andid, exp
2572 )
2573 )
bhangarebfdca492017-03-11 01:32:46 -08002574
beierlb22ce2d2019-12-12 12:09:51 -05002575 # if vapp and vapp.me.deployed:
sousaedu80135b92021-02-17 15:05:18 +01002576 if vapp and vapp_resource.get("deployed") == "true":
2577 vapp_uuid = vapp_resource.get("id").split(":")[-1]
kate13ab2c42016-12-23 01:34:24 -08002578 break
2579 else:
sousaedu80135b92021-02-17 15:05:18 +01002580 self.logger.debug(
2581 "new_vminstance(): Wait for vApp {} to deploy".format(name)
2582 )
kate13ab2c42016-12-23 01:34:24 -08002583 time.sleep(INTERVAL_TIME)
2584
beierlb22ce2d2019-12-12 12:09:51 -05002585 wait_time += INTERVAL_TIME
kate13ab2c42016-12-23 01:34:24 -08002586
beierlb22ce2d2019-12-12 12:09:51 -05002587 # SET Affinity Rule for VM
2588 # Pre-requisites: User has created Hosh Groups in vCenter with respective Hosts to be used
2589 # While creating VIM account user has to pass the Host Group names in availability_zone list
2590 # "availability_zone" is a part of VIM "config" parameters
2591 # For example, in VIM config: "availability_zone":["HG_170","HG_174","HG_175"]
2592 # Host groups are referred as availability zones
2593 # With following procedure, deployed VM will be added into a VM group.
2594 # Then A VM to Host Affinity rule will be created using the VM group & Host group.
sousaedu80135b92021-02-17 15:05:18 +01002595 if availability_zone_list:
2596 self.logger.debug(
2597 "Existing Host Groups in VIM {}".format(
2598 self.config.get("availability_zone")
2599 )
2600 )
beierlb22ce2d2019-12-12 12:09:51 -05002601 # Admin access required for creating Affinity rules
sbhangarea8e5b782018-06-21 02:10:03 -07002602 client = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01002603
sbhangarea8e5b782018-06-21 02:10:03 -07002604 if not client:
sousaedu80135b92021-02-17 15:05:18 +01002605 raise vimconn.VimConnConnectionException(
2606 "Failed to connect vCD as admin"
2607 )
sbhangarea8e5b782018-06-21 02:10:03 -07002608 else:
2609 self.client = client
sousaedu80135b92021-02-17 15:05:18 +01002610
sbhangarea8e5b782018-06-21 02:10:03 -07002611 if self.client:
sousaedu80135b92021-02-17 15:05:18 +01002612 headers = {
2613 "Accept": "application/*+xml;version=27.0",
2614 "x-vcloud-authorization": self.client._session.headers[
2615 "x-vcloud-authorization"
2616 ],
2617 }
2618
beierlb22ce2d2019-12-12 12:09:51 -05002619 # Step1: Get provider vdc details from organization
sbhangarea8e5b782018-06-21 02:10:03 -07002620 pvdc_href = self.get_pvdc_for_org(self.tenant_name, headers)
2621 if pvdc_href is not None:
beierlb22ce2d2019-12-12 12:09:51 -05002622 # Step2: Found required pvdc, now get resource pool information
sbhangarea8e5b782018-06-21 02:10:03 -07002623 respool_href = self.get_resource_pool_details(pvdc_href, headers)
2624 if respool_href is None:
beierlb22ce2d2019-12-12 12:09:51 -05002625 # Raise error if respool_href not found
sousaedu80135b92021-02-17 15:05:18 +01002626 msg = "new_vminstance():Error in finding resource pool details in pvdc {}".format(
2627 pvdc_href
2628 )
sbhangarea8e5b782018-06-21 02:10:03 -07002629 self.log_message(msg)
2630
beierlb22ce2d2019-12-12 12:09:51 -05002631 # Step3: Verify requested availability zone(hostGroup) is present in vCD
sbhangarea8e5b782018-06-21 02:10:03 -07002632 # get availability Zone
sousaedu80135b92021-02-17 15:05:18 +01002633 vm_az = self.get_vm_availability_zone(
2634 availability_zone_index, availability_zone_list
2635 )
2636
sbhangarea8e5b782018-06-21 02:10:03 -07002637 # check if provided av zone(hostGroup) is present in vCD VIM
2638 status = self.check_availibility_zone(vm_az, respool_href, headers)
2639 if status is False:
sousaedu80135b92021-02-17 15:05:18 +01002640 msg = (
2641 "new_vminstance(): Error in finding availability zone(Host Group): {} in "
2642 "resource pool {} status: {}"
2643 ).format(vm_az, respool_href, status)
sbhangarea8e5b782018-06-21 02:10:03 -07002644 self.log_message(msg)
2645 else:
sousaedu80135b92021-02-17 15:05:18 +01002646 self.logger.debug(
2647 "new_vminstance(): Availability zone {} found in VIM".format(vm_az)
2648 )
sbhangarea8e5b782018-06-21 02:10:03 -07002649
beierlb22ce2d2019-12-12 12:09:51 -05002650 # Step4: Find VM group references to create vm group
sbhangarea8e5b782018-06-21 02:10:03 -07002651 vmgrp_href = self.find_vmgroup_reference(respool_href, headers)
beierlb22ce2d2019-12-12 12:09:51 -05002652 if vmgrp_href is None:
sbhangarea8e5b782018-06-21 02:10:03 -07002653 msg = "new_vminstance(): No reference to VmGroup found in resource pool"
2654 self.log_message(msg)
2655
beierlb22ce2d2019-12-12 12:09:51 -05002656 # Step5: Create a VmGroup with name az_VmGroup
sousaedu80135b92021-02-17 15:05:18 +01002657 vmgrp_name = (
2658 vm_az + "_" + name
2659 ) # Formed VM Group name = Host Group name + VM name
sbhangarea8e5b782018-06-21 02:10:03 -07002660 status = self.create_vmgroup(vmgrp_name, vmgrp_href, headers)
2661 if status is not True:
sousaedu80135b92021-02-17 15:05:18 +01002662 msg = "new_vminstance(): Error in creating VM group {}".format(
2663 vmgrp_name
2664 )
sbhangarea8e5b782018-06-21 02:10:03 -07002665 self.log_message(msg)
2666
beierlb22ce2d2019-12-12 12:09:51 -05002667 # VM Group url to add vms to vm group
2668 vmgrpname_url = self.url + "/api/admin/extension/vmGroup/name/" + vmgrp_name
sbhangarea8e5b782018-06-21 02:10:03 -07002669
beierlb22ce2d2019-12-12 12:09:51 -05002670 # Step6: Add VM to VM Group
2671 # Find VM uuid from vapp_uuid
sbhangarea8e5b782018-06-21 02:10:03 -07002672 vm_details = self.get_vapp_details_rest(vapp_uuid)
sousaedu80135b92021-02-17 15:05:18 +01002673 vm_uuid = vm_details["vmuuid"]
sbhangarea8e5b782018-06-21 02:10:03 -07002674
2675 status = self.add_vm_to_vmgroup(vm_uuid, vmgrpname_url, vmgrp_name, headers)
2676 if status is not True:
sousaedu80135b92021-02-17 15:05:18 +01002677 msg = "new_vminstance(): Error in adding VM to VM group {}".format(
2678 vmgrp_name
2679 )
sbhangarea8e5b782018-06-21 02:10:03 -07002680 self.log_message(msg)
2681
beierlb22ce2d2019-12-12 12:09:51 -05002682 # Step7: Create VM to Host affinity rule
2683 addrule_href = self.get_add_rule_reference(respool_href, headers)
sbhangarea8e5b782018-06-21 02:10:03 -07002684 if addrule_href is None:
sousaedu80135b92021-02-17 15:05:18 +01002685 msg = "new_vminstance(): Error in finding href to add rule in resource pool: {}".format(
2686 respool_href
2687 )
sbhangarea8e5b782018-06-21 02:10:03 -07002688 self.log_message(msg)
2689
sousaedu80135b92021-02-17 15:05:18 +01002690 status = self.create_vm_to_host_affinity_rule(
2691 addrule_href, vmgrp_name, vm_az, "Affinity", headers
2692 )
sbhangarea8e5b782018-06-21 02:10:03 -07002693 if status is False:
sousaedu80135b92021-02-17 15:05:18 +01002694 msg = "new_vminstance(): Error in creating affinity rule for VM {} in Host group {}".format(
2695 name, vm_az
2696 )
sbhangarea8e5b782018-06-21 02:10:03 -07002697 self.log_message(msg)
2698 else:
sousaedu80135b92021-02-17 15:05:18 +01002699 self.logger.debug(
2700 "new_vminstance(): Affinity rule created successfully. Added {} in Host group {}".format(
2701 name, vm_az
2702 )
2703 )
beierlb22ce2d2019-12-12 12:09:51 -05002704 # Reset token to a normal user to perform other operations
sbhangarea8e5b782018-06-21 02:10:03 -07002705 self.get_token()
2706
bayramovef390722016-09-27 03:34:46 -07002707 if vapp_uuid is not None:
tierno98e909c2017-10-14 13:27:03 +02002708 return vapp_uuid, None
bayramovbd6160f2016-09-28 04:12:05 +04002709 else:
sousaedu80135b92021-02-17 15:05:18 +01002710 raise vimconn.VimConnUnexpectedResponse(
2711 "new_vminstance(): Failed create new vm instance {}".format(name)
2712 )
bayramov325fa1c2016-09-08 01:42:46 -07002713
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002714 def create_config_drive_iso(self, user_data):
2715 tmpdir = tempfile.mkdtemp()
sousaedu80135b92021-02-17 15:05:18 +01002716 iso_path = os.path.join(tmpdir, "ConfigDrive.iso")
2717 latest_dir = os.path.join(tmpdir, "openstack", "latest")
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002718 os.makedirs(latest_dir)
sousaedu80135b92021-02-17 15:05:18 +01002719 with open(
2720 os.path.join(latest_dir, "meta_data.json"), "w"
2721 ) as meta_file_obj, open(
2722 os.path.join(latest_dir, "user_data"), "w"
2723 ) as userdata_file_obj:
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002724 userdata_file_obj.write(user_data)
sousaedu80135b92021-02-17 15:05:18 +01002725 meta_file_obj.write(
2726 json.dumps(
2727 {
2728 "availability_zone": "nova",
2729 "launch_index": 0,
2730 "name": "ConfigDrive",
2731 "uuid": str(uuid.uuid4()),
2732 }
2733 )
2734 )
2735 genisoimage_cmd = (
2736 "genisoimage -J -r -V config-2 -o {iso_path} {source_dir_path}".format(
2737 iso_path=iso_path, source_dir_path=tmpdir
2738 )
2739 )
2740 self.logger.info(
2741 'create_config_drive_iso(): Creating ISO by running command "{}"'.format(
2742 genisoimage_cmd
2743 )
2744 )
2745
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002746 try:
sousaedu80135b92021-02-17 15:05:18 +01002747 FNULL = open(os.devnull, "w")
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002748 subprocess.check_call(genisoimage_cmd, shell=True, stdout=FNULL)
2749 except subprocess.CalledProcessError as e:
2750 shutil.rmtree(tmpdir, ignore_errors=True)
sousaedu80135b92021-02-17 15:05:18 +01002751 error_msg = "create_config_drive_iso(): Exception while running genisoimage command: {}".format(
2752 e
2753 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002754 self.logger.error(error_msg)
2755 raise Exception(error_msg)
sousaedu80135b92021-02-17 15:05:18 +01002756
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002757 return iso_path
2758
2759 def upload_iso_to_catalog(self, catalog_id, iso_file_path):
2760 if not os.path.isfile(iso_file_path):
sousaedu80135b92021-02-17 15:05:18 +01002761 error_msg = "upload_iso_to_catalog(): Given iso file is not present. Given path: {}".format(
2762 iso_file_path
2763 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002764 self.logger.error(error_msg)
2765 raise Exception(error_msg)
sousaedu80135b92021-02-17 15:05:18 +01002766
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002767 iso_file_stat = os.stat(iso_file_path)
sousaedu80135b92021-02-17 15:05:18 +01002768 xml_media_elem = """<?xml version="1.0" encoding="UTF-8"?>
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002769 <Media
2770 xmlns="http://www.vmware.com/vcloud/v1.5"
2771 name="{iso_name}"
2772 size="{iso_size}"
2773 imageType="iso">
2774 <Description>ISO image for config-drive</Description>
sousaedu80135b92021-02-17 15:05:18 +01002775 </Media>""".format(
2776 iso_name=os.path.basename(iso_file_path), iso_size=iso_file_stat.st_size
2777 )
2778 headers = {
2779 "Accept": "application/*+xml;version=" + API_VERSION,
2780 "x-vcloud-authorization": self.client._session.headers[
2781 "x-vcloud-authorization"
2782 ],
2783 }
2784 headers["Content-Type"] = "application/vnd.vmware.vcloud.media+xml"
2785 catalog_href = self.url + "/api/catalog/" + catalog_id + "/action/upload"
2786 response = self.perform_request(
2787 req_type="POST", url=catalog_href, headers=headers, data=xml_media_elem
2788 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002789
2790 if response.status_code != 201:
sousaedu80135b92021-02-17 15:05:18 +01002791 error_msg = "upload_iso_to_catalog(): Failed to POST an action/upload request to {}".format(
2792 catalog_href
2793 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002794 self.logger.error(error_msg)
2795 raise Exception(error_msg)
2796
beierl26fec002019-12-06 17:06:40 -05002797 catalogItem = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01002798 entity = [
2799 child
2800 for child in catalogItem
2801 if child.get("type") == "application/vnd.vmware.vcloud.media+xml"
2802 ][0]
2803 entity_href = entity.get("href")
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002804
sousaedu80135b92021-02-17 15:05:18 +01002805 response = self.perform_request(
2806 req_type="GET", url=entity_href, headers=headers
2807 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002808 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01002809 raise Exception(
2810 "upload_iso_to_catalog(): Failed to GET entity href {}".format(
2811 entity_href
2812 )
2813 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002814
sousaedu80135b92021-02-17 15:05:18 +01002815 match = re.search(
2816 r'<Files>\s+?<File.+?href="(.+?)"/>\s+?</File>\s+?</Files>',
2817 response.text,
2818 re.DOTALL,
2819 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002820 if match:
2821 media_upload_href = match.group(1)
2822 else:
sousaedu80135b92021-02-17 15:05:18 +01002823 raise Exception(
2824 "Could not parse the upload URL for the media file from the last response"
2825 )
beierl26fec002019-12-06 17:06:40 -05002826 upload_iso_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01002827 headers["Content-Type"] = "application/octet-stream"
2828 response = self.perform_request(
2829 req_type="PUT",
2830 url=media_upload_href,
2831 headers=headers,
2832 data=open(iso_file_path, "rb"),
2833 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00002834
2835 if response.status_code != 200:
2836 raise Exception('PUT request to "{}" failed'.format(media_upload_href))
sousaedu80135b92021-02-17 15:05:18 +01002837
Ananda Baitharub23558c2019-06-18 13:53:37 +00002838 result = self.client.get_task_monitor().wait_for_success(task=upload_iso_task)
sousaedu80135b92021-02-17 15:05:18 +01002839 if result.get("status") != "success":
2840 raise Exception(
2841 "The upload iso task failed with status {}".format(result.get("status"))
2842 )
sbhangarea8e5b782018-06-21 02:10:03 -07002843
beierlb22ce2d2019-12-12 12:09:51 -05002844 def get_vcd_availibility_zones(self, respool_href, headers):
sousaedu80135b92021-02-17 15:05:18 +01002845 """Method to find presence of av zone is VIM resource pool
sbhangarea8e5b782018-06-21 02:10:03 -07002846
sousaedu80135b92021-02-17 15:05:18 +01002847 Args:
2848 respool_href - resource pool href
2849 headers - header information
sbhangarea8e5b782018-06-21 02:10:03 -07002850
sousaedu80135b92021-02-17 15:05:18 +01002851 Returns:
2852 vcd_az - list of azone present in vCD
sbhangarea8e5b782018-06-21 02:10:03 -07002853 """
2854 vcd_az = []
beierlb22ce2d2019-12-12 12:09:51 -05002855 url = respool_href
sousaedu80135b92021-02-17 15:05:18 +01002856 resp = self.perform_request(req_type="GET", url=respool_href, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07002857
2858 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01002859 self.logger.debug(
2860 "REST API call {} failed. Return status code {}".format(
2861 url, resp.status_code
2862 )
2863 )
sbhangarea8e5b782018-06-21 02:10:03 -07002864 else:
beierlb22ce2d2019-12-12 12:09:51 -05002865 # Get the href to hostGroups and find provided hostGroup is present in it
sbhangarea8e5b782018-06-21 02:10:03 -07002866 resp_xml = XmlElementTree.fromstring(resp.content)
2867 for child in resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01002868 if "VMWProviderVdcResourcePool" in child.tag:
sbhangarea8e5b782018-06-21 02:10:03 -07002869 for schild in child:
sousaedu80135b92021-02-17 15:05:18 +01002870 if "Link" in schild.tag:
2871 if (
2872 schild.attrib.get("type")
2873 == "application/vnd.vmware.admin.vmwHostGroupsType+xml"
2874 ):
2875 hostGroup = schild.attrib.get("href")
2876 hg_resp = self.perform_request(
2877 req_type="GET", url=hostGroup, headers=headers
2878 )
2879
sbhangarea8e5b782018-06-21 02:10:03 -07002880 if hg_resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01002881 self.logger.debug(
2882 "REST API call {} failed. Return status code {}".format(
2883 hostGroup, hg_resp.status_code
2884 )
2885 )
sbhangarea8e5b782018-06-21 02:10:03 -07002886 else:
sousaedu80135b92021-02-17 15:05:18 +01002887 hg_resp_xml = XmlElementTree.fromstring(
2888 hg_resp.content
2889 )
sbhangarea8e5b782018-06-21 02:10:03 -07002890 for hostGroup in hg_resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01002891 if "HostGroup" in hostGroup.tag:
beierlb22ce2d2019-12-12 12:09:51 -05002892 # append host group name to the list
sbhangarea8e5b782018-06-21 02:10:03 -07002893 vcd_az.append(hostGroup.attrib.get("name"))
sousaedu80135b92021-02-17 15:05:18 +01002894
sbhangarea8e5b782018-06-21 02:10:03 -07002895 return vcd_az
2896
sbhangarea8e5b782018-06-21 02:10:03 -07002897 def set_availability_zones(self):
2898 """
2899 Set vim availability zone
2900 """
sbhangarea8e5b782018-06-21 02:10:03 -07002901 vim_availability_zones = None
2902 availability_zone = None
sousaedu80135b92021-02-17 15:05:18 +01002903
2904 if "availability_zone" in self.config:
2905 vim_availability_zones = self.config.get("availability_zone")
2906
sbhangarea8e5b782018-06-21 02:10:03 -07002907 if isinstance(vim_availability_zones, str):
2908 availability_zone = [vim_availability_zones]
2909 elif isinstance(vim_availability_zones, list):
2910 availability_zone = vim_availability_zones
2911 else:
2912 return availability_zone
2913
2914 return availability_zone
2915
sbhangarea8e5b782018-06-21 02:10:03 -07002916 def get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
2917 """
2918 Return the availability zone to be used by the created VM.
2919 returns: The VIM availability zone to be used or None
2920 """
2921 if availability_zone_index is None:
sousaedu80135b92021-02-17 15:05:18 +01002922 if not self.config.get("availability_zone"):
sbhangarea8e5b782018-06-21 02:10:03 -07002923 return None
sousaedu80135b92021-02-17 15:05:18 +01002924 elif isinstance(self.config.get("availability_zone"), str):
2925 return self.config["availability_zone"]
sbhangarea8e5b782018-06-21 02:10:03 -07002926 else:
sousaedu80135b92021-02-17 15:05:18 +01002927 return self.config["availability_zone"][0]
sbhangarea8e5b782018-06-21 02:10:03 -07002928
2929 vim_availability_zones = self.availability_zone
2930
2931 # check if VIM offer enough availability zones describe in the VNFD
sousaedu80135b92021-02-17 15:05:18 +01002932 if vim_availability_zones and len(availability_zone_list) <= len(
2933 vim_availability_zones
2934 ):
sbhangarea8e5b782018-06-21 02:10:03 -07002935 # check if all the names of NFV AV match VIM AV names
2936 match_by_index = False
2937 for av in availability_zone_list:
2938 if av not in vim_availability_zones:
2939 match_by_index = True
2940 break
sousaedu80135b92021-02-17 15:05:18 +01002941
sbhangarea8e5b782018-06-21 02:10:03 -07002942 if match_by_index:
sousaedu80135b92021-02-17 15:05:18 +01002943 self.logger.debug(
2944 "Required Availability zone or Host Group not found in VIM config"
2945 )
2946 self.logger.debug(
2947 "Input Availability zone list: {}".format(availability_zone_list)
2948 )
2949 self.logger.debug(
2950 "VIM configured Availability zones: {}".format(
2951 vim_availability_zones
2952 )
2953 )
sbhangarea8e5b782018-06-21 02:10:03 -07002954 self.logger.debug("VIM Availability zones will be used by index")
2955 return vim_availability_zones[availability_zone_index]
2956 else:
2957 return availability_zone_list[availability_zone_index]
2958 else:
sousaedu80135b92021-02-17 15:05:18 +01002959 raise vimconn.VimConnConflictException(
2960 "No enough availability zones at VIM for this deployment"
2961 )
sbhangarea8e5b782018-06-21 02:10:03 -07002962
sousaedu80135b92021-02-17 15:05:18 +01002963 def create_vm_to_host_affinity_rule(
2964 self, addrule_href, vmgrpname, hostgrpname, polarity, headers
2965 ):
2966 """Method to create VM to Host Affinity rule in vCD
sbhangarea8e5b782018-06-21 02:10:03 -07002967
2968 Args:
2969 addrule_href - href to make a POST request
2970 vmgrpname - name of the VM group created
2971 hostgrpnmae - name of the host group created earlier
2972 polarity - Affinity or Anti-affinity (default: Affinity)
2973 headers - headers to make REST call
2974
2975 Returns:
2976 True- if rule is created
2977 False- Failed to create rule due to some error
2978
2979 """
2980 task_status = False
2981 rule_name = polarity + "_" + vmgrpname
2982 payload = """<?xml version="1.0" encoding="UTF-8"?>
2983 <vmext:VMWVmHostAffinityRule
2984 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
2985 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
2986 type="application/vnd.vmware.admin.vmwVmHostAffinityRule+xml">
2987 <vcloud:Name>{}</vcloud:Name>
2988 <vcloud:IsEnabled>true</vcloud:IsEnabled>
2989 <vcloud:IsMandatory>true</vcloud:IsMandatory>
2990 <vcloud:Polarity>{}</vcloud:Polarity>
2991 <vmext:HostGroupName>{}</vmext:HostGroupName>
2992 <vmext:VmGroupName>{}</vmext:VmGroupName>
sousaedu80135b92021-02-17 15:05:18 +01002993 </vmext:VMWVmHostAffinityRule>""".format(
2994 rule_name, polarity, hostgrpname, vmgrpname
2995 )
sbhangarea8e5b782018-06-21 02:10:03 -07002996
sousaedu80135b92021-02-17 15:05:18 +01002997 resp = self.perform_request(
2998 req_type="POST", url=addrule_href, headers=headers, data=payload
2999 )
sbhangarea8e5b782018-06-21 02:10:03 -07003000
3001 if resp.status_code != requests.codes.accepted:
sousaedu80135b92021-02-17 15:05:18 +01003002 self.logger.debug(
3003 "REST API call {} failed. Return status code {}".format(
3004 addrule_href, resp.status_code
3005 )
3006 )
sbhangarea8e5b782018-06-21 02:10:03 -07003007 task_status = False
sousaedu80135b92021-02-17 15:05:18 +01003008
sbhangarea8e5b782018-06-21 02:10:03 -07003009 return task_status
3010 else:
3011 affinity_task = self.get_task_from_response(resp.content)
beierlb22ce2d2019-12-12 12:09:51 -05003012 self.logger.debug("affinity_task: {}".format(affinity_task))
sousaedu80135b92021-02-17 15:05:18 +01003013
sbhangarea8e5b782018-06-21 02:10:03 -07003014 if affinity_task is None or affinity_task is False:
tierno72774862020-05-04 11:44:15 +00003015 raise vimconn.VimConnUnexpectedResponse("failed to find affinity task")
sbhangarea8e5b782018-06-21 02:10:03 -07003016 # wait for task to complete
3017 result = self.client.get_task_monitor().wait_for_success(task=affinity_task)
sousaedu80135b92021-02-17 15:05:18 +01003018
3019 if result.get("status") == "success":
3020 self.logger.debug(
3021 "Successfully created affinity rule {}".format(rule_name)
3022 )
sbhangarea8e5b782018-06-21 02:10:03 -07003023 return True
3024 else:
tierno72774862020-05-04 11:44:15 +00003025 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01003026 "failed to create affinity rule {}".format(rule_name)
3027 )
sbhangarea8e5b782018-06-21 02:10:03 -07003028
beierlb22ce2d2019-12-12 12:09:51 -05003029 def get_add_rule_reference(self, respool_href, headers):
sousaedu80135b92021-02-17 15:05:18 +01003030 """This method finds href to add vm to host affinity rule to vCD
sbhangarea8e5b782018-06-21 02:10:03 -07003031
3032 Args:
3033 respool_href- href to resource pool
3034 headers- header information to make REST call
3035
3036 Returns:
3037 None - if no valid href to add rule found or
3038 addrule_href - href to add vm to host affinity rule of resource pool
3039 """
3040 addrule_href = None
sousaedu80135b92021-02-17 15:05:18 +01003041 resp = self.perform_request(req_type="GET", url=respool_href, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003042
3043 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003044 self.logger.debug(
3045 "REST API call {} failed. Return status code {}".format(
3046 respool_href, resp.status_code
3047 )
3048 )
sbhangarea8e5b782018-06-21 02:10:03 -07003049 else:
sbhangarea8e5b782018-06-21 02:10:03 -07003050 resp_xml = XmlElementTree.fromstring(resp.content)
3051 for child in resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003052 if "VMWProviderVdcResourcePool" in child.tag:
sbhangarea8e5b782018-06-21 02:10:03 -07003053 for schild in child:
sousaedu80135b92021-02-17 15:05:18 +01003054 if "Link" in schild.tag:
3055 if (
3056 schild.attrib.get("type")
3057 == "application/vnd.vmware.admin.vmwVmHostAffinityRule+xml"
3058 and schild.attrib.get("rel") == "add"
3059 ):
3060 addrule_href = schild.attrib.get("href")
sbhangarea8e5b782018-06-21 02:10:03 -07003061 break
3062
3063 return addrule_href
3064
sbhangarea8e5b782018-06-21 02:10:03 -07003065 def add_vm_to_vmgroup(self, vm_uuid, vmGroupNameURL, vmGroup_name, headers):
sousaedu80135b92021-02-17 15:05:18 +01003066 """Method to add deployed VM to newly created VM Group.
sbhangarea8e5b782018-06-21 02:10:03 -07003067 This is required to create VM to Host affinity in vCD
3068
3069 Args:
3070 vm_uuid- newly created vm uuid
3071 vmGroupNameURL- URL to VM Group name
3072 vmGroup_name- Name of VM group created
3073 headers- Headers for REST request
3074
3075 Returns:
3076 True- if VM added to VM group successfully
3077 False- if any error encounter
3078 """
sousaedu80135b92021-02-17 15:05:18 +01003079 addvm_resp = self.perform_request(
3080 req_type="GET", url=vmGroupNameURL, headers=headers
3081 ) # , data=payload)
sbhangarea8e5b782018-06-21 02:10:03 -07003082
3083 if addvm_resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003084 self.logger.debug(
3085 "REST API call to get VM Group Name url {} failed. Return status code {}".format(
3086 vmGroupNameURL, addvm_resp.status_code
3087 )
3088 )
sbhangarea8e5b782018-06-21 02:10:03 -07003089 return False
3090 else:
3091 resp_xml = XmlElementTree.fromstring(addvm_resp.content)
3092 for child in resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003093 if child.tag.split("}")[1] == "Link":
sbhangarea8e5b782018-06-21 02:10:03 -07003094 if child.attrib.get("rel") == "addVms":
beierlb22ce2d2019-12-12 12:09:51 -05003095 addvmtogrpURL = child.attrib.get("href")
sbhangarea8e5b782018-06-21 02:10:03 -07003096
beierlb22ce2d2019-12-12 12:09:51 -05003097 # Get vm details
sousaedu80135b92021-02-17 15:05:18 +01003098 url_list = [self.url, "/api/vApp/vm-", vm_uuid]
3099 vmdetailsURL = "".join(url_list)
sbhangarea8e5b782018-06-21 02:10:03 -07003100
sousaedu80135b92021-02-17 15:05:18 +01003101 resp = self.perform_request(req_type="GET", url=vmdetailsURL, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003102
3103 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003104 self.logger.debug(
3105 "REST API call {} failed. Return status code {}".format(
3106 vmdetailsURL, resp.status_code
3107 )
3108 )
sbhangarea8e5b782018-06-21 02:10:03 -07003109 return False
3110
beierlb22ce2d2019-12-12 12:09:51 -05003111 # Parse VM details
sbhangarea8e5b782018-06-21 02:10:03 -07003112 resp_xml = XmlElementTree.fromstring(resp.content)
sousaedu80135b92021-02-17 15:05:18 +01003113 if resp_xml.tag.split("}")[1] == "Vm":
sbhangarea8e5b782018-06-21 02:10:03 -07003114 vm_id = resp_xml.attrib.get("id")
3115 vm_name = resp_xml.attrib.get("name")
3116 vm_href = resp_xml.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05003117 # print vm_id, vm_name, vm_href
sousaedu80135b92021-02-17 15:05:18 +01003118
beierlb22ce2d2019-12-12 12:09:51 -05003119 # Add VM into VMgroup
sbhangarea8e5b782018-06-21 02:10:03 -07003120 payload = """<?xml version="1.0" encoding="UTF-8"?>\
3121 <ns2:Vms xmlns:ns2="http://www.vmware.com/vcloud/v1.5" \
3122 xmlns="http://www.vmware.com/vcloud/versions" \
3123 xmlns:ns3="http://schemas.dmtf.org/ovf/envelope/1" \
3124 xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" \
3125 xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/common" \
3126 xmlns:ns6="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" \
3127 xmlns:ns7="http://www.vmware.com/schema/ovf" \
3128 xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1" \
3129 xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">\
3130 <ns2:VmReference href="{}" id="{}" name="{}" \
3131 type="application/vnd.vmware.vcloud.vm+xml" />\
sousaedu80135b92021-02-17 15:05:18 +01003132 </ns2:Vms>""".format(
3133 vm_href, vm_id, vm_name
3134 )
sbhangarea8e5b782018-06-21 02:10:03 -07003135
sousaedu80135b92021-02-17 15:05:18 +01003136 addvmtogrp_resp = self.perform_request(
3137 req_type="POST", url=addvmtogrpURL, headers=headers, data=payload
3138 )
sbhangarea8e5b782018-06-21 02:10:03 -07003139
3140 if addvmtogrp_resp.status_code != requests.codes.accepted:
sousaedu80135b92021-02-17 15:05:18 +01003141 self.logger.debug(
3142 "REST API call {} failed. Return status code {}".format(
3143 addvmtogrpURL, addvmtogrp_resp.status_code
3144 )
3145 )
3146
sbhangarea8e5b782018-06-21 02:10:03 -07003147 return False
3148 else:
sousaedu80135b92021-02-17 15:05:18 +01003149 self.logger.debug(
3150 "Done adding VM {} to VMgroup {}".format(vm_name, vmGroup_name)
3151 )
3152
sbhangarea8e5b782018-06-21 02:10:03 -07003153 return True
3154
sbhangarea8e5b782018-06-21 02:10:03 -07003155 def create_vmgroup(self, vmgroup_name, vmgroup_href, headers):
3156 """Method to create a VM group in vCD
3157
sousaedu80135b92021-02-17 15:05:18 +01003158 Args:
3159 vmgroup_name : Name of VM group to be created
3160 vmgroup_href : href for vmgroup
3161 headers- Headers for REST request
sbhangarea8e5b782018-06-21 02:10:03 -07003162 """
beierlb22ce2d2019-12-12 12:09:51 -05003163 # POST to add URL with required data
sbhangarea8e5b782018-06-21 02:10:03 -07003164 vmgroup_status = False
3165 payload = """<VMWVmGroup xmlns="http://www.vmware.com/vcloud/extension/v1.5" \
3166 xmlns:vcloud_v1.5="http://www.vmware.com/vcloud/v1.5" name="{}">\
3167 <vmCount>1</vmCount>\
sousaedu80135b92021-02-17 15:05:18 +01003168 </VMWVmGroup>""".format(
3169 vmgroup_name
3170 )
3171 resp = self.perform_request(
3172 req_type="POST", url=vmgroup_href, headers=headers, data=payload
3173 )
sbhangarea8e5b782018-06-21 02:10:03 -07003174
3175 if resp.status_code != requests.codes.accepted:
sousaedu80135b92021-02-17 15:05:18 +01003176 self.logger.debug(
3177 "REST API call {} failed. Return status code {}".format(
3178 vmgroup_href, resp.status_code
3179 )
3180 )
3181
sbhangarea8e5b782018-06-21 02:10:03 -07003182 return vmgroup_status
3183 else:
3184 vmgroup_task = self.get_task_from_response(resp.content)
3185 if vmgroup_task is None or vmgroup_task is False:
tierno72774862020-05-04 11:44:15 +00003186 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01003187 "create_vmgroup(): failed to create VM group {}".format(
3188 vmgroup_name
3189 )
3190 )
sbhangarea8e5b782018-06-21 02:10:03 -07003191
3192 # wait for task to complete
3193 result = self.client.get_task_monitor().wait_for_success(task=vmgroup_task)
3194
sousaedu80135b92021-02-17 15:05:18 +01003195 if result.get("status") == "success":
3196 self.logger.debug(
3197 "create_vmgroup(): Successfully created VM group {}".format(
3198 vmgroup_name
3199 )
3200 )
beierlb22ce2d2019-12-12 12:09:51 -05003201 # time.sleep(10)
sbhangarea8e5b782018-06-21 02:10:03 -07003202 vmgroup_status = True
sousaedu80135b92021-02-17 15:05:18 +01003203
sbhangarea8e5b782018-06-21 02:10:03 -07003204 return vmgroup_status
3205 else:
tierno72774862020-05-04 11:44:15 +00003206 raise vimconn.VimConnUnexpectedResponse(
sousaedu80135b92021-02-17 15:05:18 +01003207 "create_vmgroup(): failed to create VM group {}".format(
3208 vmgroup_name
3209 )
3210 )
sbhangarea8e5b782018-06-21 02:10:03 -07003211
3212 def find_vmgroup_reference(self, url, headers):
sousaedu80135b92021-02-17 15:05:18 +01003213 """Method to create a new VMGroup which is required to add created VM
3214 Args:
3215 url- resource pool href
3216 headers- header information
sbhangarea8e5b782018-06-21 02:10:03 -07003217
sousaedu80135b92021-02-17 15:05:18 +01003218 Returns:
3219 returns href to VM group to create VM group
sbhangarea8e5b782018-06-21 02:10:03 -07003220 """
beierlb22ce2d2019-12-12 12:09:51 -05003221 # Perform GET on resource pool to find 'add' link to create VMGroup
3222 # https://vcd-ip/api/admin/extension/providervdc/<providervdc id>/resourcePools
sbhangarea8e5b782018-06-21 02:10:03 -07003223 vmgrp_href = None
sousaedu80135b92021-02-17 15:05:18 +01003224 resp = self.perform_request(req_type="GET", url=url, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003225
3226 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003227 self.logger.debug(
3228 "REST API call {} failed. Return status code {}".format(
3229 url, resp.status_code
3230 )
3231 )
sbhangarea8e5b782018-06-21 02:10:03 -07003232 else:
beierlb22ce2d2019-12-12 12:09:51 -05003233 # Get the href to add vmGroup to vCD
sbhangarea8e5b782018-06-21 02:10:03 -07003234 resp_xml = XmlElementTree.fromstring(resp.content)
3235 for child in resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003236 if "VMWProviderVdcResourcePool" in child.tag:
sbhangarea8e5b782018-06-21 02:10:03 -07003237 for schild in child:
sousaedu80135b92021-02-17 15:05:18 +01003238 if "Link" in schild.tag:
beierlb22ce2d2019-12-12 12:09:51 -05003239 # Find href with type VMGroup and rel with add
sousaedu80135b92021-02-17 15:05:18 +01003240 if (
3241 schild.attrib.get("type")
3242 == "application/vnd.vmware.admin.vmwVmGroupType+xml"
3243 and schild.attrib.get("rel") == "add"
3244 ):
3245 vmgrp_href = schild.attrib.get("href")
3246
sbhangarea8e5b782018-06-21 02:10:03 -07003247 return vmgrp_href
3248
sbhangarea8e5b782018-06-21 02:10:03 -07003249 def check_availibility_zone(self, az, respool_href, headers):
sousaedu80135b92021-02-17 15:05:18 +01003250 """Method to verify requested av zone is present or not in provided
3251 resource pool
sbhangarea8e5b782018-06-21 02:10:03 -07003252
sousaedu80135b92021-02-17 15:05:18 +01003253 Args:
3254 az - name of hostgroup (availibility_zone)
3255 respool_href - Resource Pool href
3256 headers - Headers to make REST call
3257 Returns:
3258 az_found - True if availibility_zone is found else False
sbhangarea8e5b782018-06-21 02:10:03 -07003259 """
3260 az_found = False
sousaedu80135b92021-02-17 15:05:18 +01003261 headers["Accept"] = "application/*+xml;version=27.0"
3262 resp = self.perform_request(req_type="GET", url=respool_href, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003263
3264 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003265 self.logger.debug(
3266 "REST API call {} failed. Return status code {}".format(
3267 respool_href, resp.status_code
3268 )
3269 )
sbhangarea8e5b782018-06-21 02:10:03 -07003270 else:
beierlb22ce2d2019-12-12 12:09:51 -05003271 # Get the href to hostGroups and find provided hostGroup is present in it
sbhangarea8e5b782018-06-21 02:10:03 -07003272 resp_xml = XmlElementTree.fromstring(resp.content)
3273
3274 for child in resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003275 if "VMWProviderVdcResourcePool" in child.tag:
sbhangarea8e5b782018-06-21 02:10:03 -07003276 for schild in child:
sousaedu80135b92021-02-17 15:05:18 +01003277 if "Link" in schild.tag:
3278 if (
3279 schild.attrib.get("type")
3280 == "application/vnd.vmware.admin.vmwHostGroupsType+xml"
3281 ):
3282 hostGroup_href = schild.attrib.get("href")
3283 hg_resp = self.perform_request(
3284 req_type="GET", url=hostGroup_href, headers=headers
3285 )
3286
sbhangarea8e5b782018-06-21 02:10:03 -07003287 if hg_resp.status_code != requests.codes.ok:
beierlb22ce2d2019-12-12 12:09:51 -05003288 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01003289 "REST API call {} failed. Return status code {}".format(
3290 hostGroup_href, hg_resp.status_code
3291 )
3292 )
sbhangarea8e5b782018-06-21 02:10:03 -07003293 else:
sousaedu80135b92021-02-17 15:05:18 +01003294 hg_resp_xml = XmlElementTree.fromstring(
3295 hg_resp.content
3296 )
sbhangarea8e5b782018-06-21 02:10:03 -07003297 for hostGroup in hg_resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003298 if "HostGroup" in hostGroup.tag:
sbhangarea8e5b782018-06-21 02:10:03 -07003299 if hostGroup.attrib.get("name") == az:
3300 az_found = True
3301 break
sousaedu80135b92021-02-17 15:05:18 +01003302
sbhangarea8e5b782018-06-21 02:10:03 -07003303 return az_found
3304
sbhangarea8e5b782018-06-21 02:10:03 -07003305 def get_pvdc_for_org(self, org_vdc, headers):
sousaedu80135b92021-02-17 15:05:18 +01003306 """This method gets provider vdc references from organisation
sbhangarea8e5b782018-06-21 02:10:03 -07003307
sousaedu80135b92021-02-17 15:05:18 +01003308 Args:
3309 org_vdc - name of the organisation VDC to find pvdc
3310 headers - headers to make REST call
sbhangarea8e5b782018-06-21 02:10:03 -07003311
sousaedu80135b92021-02-17 15:05:18 +01003312 Returns:
3313 None - if no pvdc href found else
3314 pvdc_href - href to pvdc
sbhangarea8e5b782018-06-21 02:10:03 -07003315 """
beierlb22ce2d2019-12-12 12:09:51 -05003316 # Get provider VDC references from vCD
sbhangarea8e5b782018-06-21 02:10:03 -07003317 pvdc_href = None
beierlb22ce2d2019-12-12 12:09:51 -05003318 # url = '<vcd url>/api/admin/extension/providerVdcReferences'
sousaedu80135b92021-02-17 15:05:18 +01003319 url_list = [self.url, "/api/admin/extension/providerVdcReferences"]
3320 url = "".join(url_list)
sbhangarea8e5b782018-06-21 02:10:03 -07003321
sousaedu80135b92021-02-17 15:05:18 +01003322 response = self.perform_request(req_type="GET", url=url, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003323 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003324 self.logger.debug(
3325 "REST API call {} failed. Return status code {}".format(
3326 url, response.status_code
3327 )
3328 )
sbhangarea8e5b782018-06-21 02:10:03 -07003329 else:
beierl26fec002019-12-06 17:06:40 -05003330 xmlroot_response = XmlElementTree.fromstring(response.text)
sbhangarea8e5b782018-06-21 02:10:03 -07003331 for child in xmlroot_response:
sousaedu80135b92021-02-17 15:05:18 +01003332 if "ProviderVdcReference" in child.tag:
3333 pvdc_href = child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05003334 # Get vdcReferences to find org
sousaedu80135b92021-02-17 15:05:18 +01003335 pvdc_resp = self.perform_request(
3336 req_type="GET", url=pvdc_href, headers=headers
3337 )
3338
sbhangarea8e5b782018-06-21 02:10:03 -07003339 if pvdc_resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003340 raise vimconn.VimConnException(
3341 "REST API call {} failed. "
3342 "Return status code {}".format(url, pvdc_resp.status_code)
3343 )
sbhangarea8e5b782018-06-21 02:10:03 -07003344
3345 pvdc_resp_xml = XmlElementTree.fromstring(pvdc_resp.content)
3346 for child in pvdc_resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003347 if "Link" in child.tag:
3348 if (
3349 child.attrib.get("type")
3350 == "application/vnd.vmware.admin.vdcReferences+xml"
3351 ):
3352 vdc_href = child.attrib.get("href")
sbhangarea8e5b782018-06-21 02:10:03 -07003353
beierlb22ce2d2019-12-12 12:09:51 -05003354 # Check if provided org is present in vdc
sousaedu80135b92021-02-17 15:05:18 +01003355 vdc_resp = self.perform_request(
3356 req_type="GET", url=vdc_href, headers=headers
3357 )
3358
sbhangarea8e5b782018-06-21 02:10:03 -07003359 if vdc_resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003360 raise vimconn.VimConnException(
3361 "REST API call {} failed. "
3362 "Return status code {}".format(
3363 url, vdc_resp.status_code
3364 )
3365 )
3366 vdc_resp_xml = XmlElementTree.fromstring(
3367 vdc_resp.content
3368 )
3369
sbhangarea8e5b782018-06-21 02:10:03 -07003370 for child in vdc_resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003371 if "VdcReference" in child.tag:
3372 if child.attrib.get("name") == org_vdc:
sbhangarea8e5b782018-06-21 02:10:03 -07003373 return pvdc_href
3374
sbhangarea8e5b782018-06-21 02:10:03 -07003375 def get_resource_pool_details(self, pvdc_href, headers):
sousaedu80135b92021-02-17 15:05:18 +01003376 """Method to get resource pool information.
3377 Host groups are property of resource group.
3378 To get host groups, we need to GET details of resource pool.
sbhangarea8e5b782018-06-21 02:10:03 -07003379
sousaedu80135b92021-02-17 15:05:18 +01003380 Args:
3381 pvdc_href: href to pvdc details
3382 headers: headers
sbhangarea8e5b782018-06-21 02:10:03 -07003383
sousaedu80135b92021-02-17 15:05:18 +01003384 Returns:
3385 respool_href - Returns href link reference to resource pool
sbhangarea8e5b782018-06-21 02:10:03 -07003386 """
3387 respool_href = None
sousaedu80135b92021-02-17 15:05:18 +01003388 resp = self.perform_request(req_type="GET", url=pvdc_href, headers=headers)
sbhangarea8e5b782018-06-21 02:10:03 -07003389
3390 if resp.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01003391 self.logger.debug(
3392 "REST API call {} failed. Return status code {}".format(
3393 pvdc_href, resp.status_code
3394 )
3395 )
sbhangarea8e5b782018-06-21 02:10:03 -07003396 else:
3397 respool_resp_xml = XmlElementTree.fromstring(resp.content)
3398 for child in respool_resp_xml:
sousaedu80135b92021-02-17 15:05:18 +01003399 if "Link" in child.tag:
3400 if (
3401 child.attrib.get("type")
3402 == "application/vnd.vmware.admin.vmwProviderVdcResourcePoolSet+xml"
3403 ):
sbhangarea8e5b782018-06-21 02:10:03 -07003404 respool_href = child.attrib.get("href")
3405 break
sousaedu80135b92021-02-17 15:05:18 +01003406
sbhangarea8e5b782018-06-21 02:10:03 -07003407 return respool_href
3408
sbhangarea8e5b782018-06-21 02:10:03 -07003409 def log_message(self, msg):
3410 """
sousaedu80135b92021-02-17 15:05:18 +01003411 Method to log error messages related to Affinity rule creation
3412 in new_vminstance & raise Exception
3413 Args :
3414 msg - Error message to be logged
sbhangarea8e5b782018-06-21 02:10:03 -07003415
3416 """
beierlb22ce2d2019-12-12 12:09:51 -05003417 # get token to connect vCD as a normal user
sbhangarea8e5b782018-06-21 02:10:03 -07003418 self.get_token()
3419 self.logger.debug(msg)
sousaedu80135b92021-02-17 15:05:18 +01003420
tierno72774862020-05-04 11:44:15 +00003421 raise vimconn.VimConnException(msg)
sbhangarea8e5b782018-06-21 02:10:03 -07003422
beierlb22ce2d2019-12-12 12:09:51 -05003423 # #
3424 # #
3425 # # based on current discussion
3426 # #
3427 # #
3428 # # server:
bayramovef390722016-09-27 03:34:46 -07003429 # created: '2016-09-08T11:51:58'
3430 # description: simple-instance.linux1.1
3431 # flavor: ddc6776e-75a9-11e6-ad5f-0800273e724c
3432 # hostId: e836c036-74e7-11e6-b249-0800273e724c
3433 # image: dde30fe6-75a9-11e6-ad5f-0800273e724c
3434 # status: ACTIVE
3435 # error_msg:
3436 # interfaces: …
3437 #
bayramovfe3f3c92016-10-04 07:53:41 +04003438 def get_vminstance(self, vim_vm_uuid=None):
bayramov5761ad12016-10-04 09:00:30 +04003439 """Returns the VM instance information from VIM"""
bayramovef390722016-09-27 03:34:46 -07003440 self.logger.debug("Client requesting vm instance {} ".format(vim_vm_uuid))
bayramov325fa1c2016-09-08 01:42:46 -07003441
beierlb22ce2d2019-12-12 12:09:51 -05003442 _, vdc = self.get_vdc_details()
bayramovef390722016-09-27 03:34:46 -07003443 if vdc is None:
tierno72774862020-05-04 11:44:15 +00003444 raise vimconn.VimConnConnectionException(
sousaedu80135b92021-02-17 15:05:18 +01003445 "Failed to get a reference of VDC for a tenant {}".format(
3446 self.tenant_name
3447 )
3448 )
bayramov325fa1c2016-09-08 01:42:46 -07003449
bayramovfe3f3c92016-10-04 07:53:41 +04003450 vm_info_dict = self.get_vapp_details_rest(vapp_uuid=vim_vm_uuid)
3451 if not vm_info_dict:
sousaedu80135b92021-02-17 15:05:18 +01003452 self.logger.debug(
3453 "get_vminstance(): Failed to get vApp name by UUID {}".format(
3454 vim_vm_uuid
3455 )
3456 )
3457 raise vimconn.VimConnNotFoundException(
3458 "Failed to get vApp name by UUID {}".format(vim_vm_uuid)
3459 )
bayramov325fa1c2016-09-08 01:42:46 -07003460
sousaedu80135b92021-02-17 15:05:18 +01003461 status_key = vm_info_dict["status"]
3462 error = ""
bayramovef390722016-09-27 03:34:46 -07003463 try:
sousaedu80135b92021-02-17 15:05:18 +01003464 vm_dict = {
3465 "created": vm_info_dict["created"],
3466 "description": vm_info_dict["name"],
3467 "status": vcdStatusCode2manoFormat[int(status_key)],
3468 "hostId": vm_info_dict["vmuuid"],
3469 "error_msg": error,
3470 "vim_info": yaml.safe_dump(vm_info_dict),
3471 "interfaces": [],
3472 }
bayramovef390722016-09-27 03:34:46 -07003473
sousaedu80135b92021-02-17 15:05:18 +01003474 if "interfaces" in vm_info_dict:
3475 vm_dict["interfaces"] = vm_info_dict["interfaces"]
bayramovfe3f3c92016-10-04 07:53:41 +04003476 else:
sousaedu80135b92021-02-17 15:05:18 +01003477 vm_dict["interfaces"] = []
bayramovfe3f3c92016-10-04 07:53:41 +04003478 except KeyError:
sousaedu80135b92021-02-17 15:05:18 +01003479 vm_dict = {
3480 "created": "",
3481 "description": "",
3482 "status": vcdStatusCode2manoFormat[int(-1)],
3483 "hostId": vm_info_dict["vmuuid"],
3484 "error_msg": "Inconsistency state",
3485 "vim_info": yaml.safe_dump(vm_info_dict),
3486 "interfaces": [],
3487 }
bayramovef390722016-09-27 03:34:46 -07003488
3489 return vm_dict
3490
garciadeblas89598d42022-06-30 13:57:43 +02003491 def delete_vminstance(self, vm_id, created_items=None, volumes_to_hold=None):
bayramovef390722016-09-27 03:34:46 -07003492 """Method poweroff and remove VM instance from vcloud director network.
3493
3494 Args:
garciadeblas89598d42022-06-30 13:57:43 +02003495 vm_id: VM UUID
bayramovef390722016-09-27 03:34:46 -07003496
3497 Returns:
3498 Returns the instance identifier
3499 """
garciadeblas89598d42022-06-30 13:57:43 +02003500 self.logger.debug("Client requesting delete vm instance {} ".format(vm_id))
bayramov325fa1c2016-09-08 01:42:46 -07003501
beierl01bd6692019-12-09 17:06:20 -05003502 _, vdc = self.get_vdc_details()
sousaedu80135b92021-02-17 15:05:18 +01003503 vdc_obj = VDC(self.client, href=vdc.get("href"))
kasarc5bf2932018-03-09 04:15:22 -08003504 if vdc_obj is None:
sousaedu80135b92021-02-17 15:05:18 +01003505 self.logger.debug(
3506 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
3507 self.tenant_name
3508 )
3509 )
tierno72774862020-05-04 11:44:15 +00003510 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01003511 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
3512 self.tenant_name
3513 )
3514 )
bayramov325fa1c2016-09-08 01:42:46 -07003515
bayramovef390722016-09-27 03:34:46 -07003516 try:
garciadeblas89598d42022-06-30 13:57:43 +02003517 vapp_name = self.get_namebyvappid(vm_id)
bayramovef390722016-09-27 03:34:46 -07003518 if vapp_name is None:
sousaedu80135b92021-02-17 15:05:18 +01003519 self.logger.debug(
3520 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003521 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003522 )
3523 )
3524
3525 return (
3526 -1,
3527 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003528 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003529 ),
3530 )
3531
garciadeblas89598d42022-06-30 13:57:43 +02003532 self.logger.info("Deleting vApp {} and UUID {}".format(vapp_name, vm_id))
Ravi Chamarty41840092018-10-31 16:12:38 +00003533 vapp_resource = vdc_obj.get_vapp(vapp_name)
3534 vapp = VApp(self.client, resource=vapp_resource)
bayramov325fa1c2016-09-08 01:42:46 -07003535
bayramovef390722016-09-27 03:34:46 -07003536 # Delete vApp and wait for status change if task executed and vApp is None.
kate13ab2c42016-12-23 01:34:24 -08003537 if vapp:
sousaedu80135b92021-02-17 15:05:18 +01003538 if vapp_resource.get("deployed") == "true":
kate13ab2c42016-12-23 01:34:24 -08003539 self.logger.info("Powering off vApp {}".format(vapp_name))
beierl01bd6692019-12-09 17:06:20 -05003540 # Power off vApp
kate13ab2c42016-12-23 01:34:24 -08003541 powered_off = False
3542 wait_time = 0
sousaedu80135b92021-02-17 15:05:18 +01003543
kate13ab2c42016-12-23 01:34:24 -08003544 while wait_time <= MAX_WAIT_TIME:
kasarc5bf2932018-03-09 04:15:22 -08003545 power_off_task = vapp.power_off()
sousaedu80135b92021-02-17 15:05:18 +01003546 result = self.client.get_task_monitor().wait_for_success(
3547 task=power_off_task
3548 )
bayramovef390722016-09-27 03:34:46 -07003549
sousaedu80135b92021-02-17 15:05:18 +01003550 if result.get("status") == "success":
kasarc5bf2932018-03-09 04:15:22 -08003551 powered_off = True
3552 break
kate13ab2c42016-12-23 01:34:24 -08003553 else:
sousaedu80135b92021-02-17 15:05:18 +01003554 self.logger.info(
3555 "Wait for vApp {} to power off".format(vapp_name)
3556 )
kate13ab2c42016-12-23 01:34:24 -08003557 time.sleep(INTERVAL_TIME)
3558
beierl01bd6692019-12-09 17:06:20 -05003559 wait_time += INTERVAL_TIME
sousaedu80135b92021-02-17 15:05:18 +01003560
kate13ab2c42016-12-23 01:34:24 -08003561 if not powered_off:
beierl01bd6692019-12-09 17:06:20 -05003562 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01003563 "delete_vminstance(): Failed to power off VM instance {} ".format(
garciadeblas89598d42022-06-30 13:57:43 +02003564 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003565 )
3566 )
kate13ab2c42016-12-23 01:34:24 -08003567 else:
sousaedu80135b92021-02-17 15:05:18 +01003568 self.logger.info(
3569 "delete_vminstance(): Powered off VM instance {} ".format(
garciadeblas89598d42022-06-30 13:57:43 +02003570 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003571 )
3572 )
kate13ab2c42016-12-23 01:34:24 -08003573
beierl01bd6692019-12-09 17:06:20 -05003574 # Undeploy vApp
kate13ab2c42016-12-23 01:34:24 -08003575 self.logger.info("Undeploy vApp {}".format(vapp_name))
3576 wait_time = 0
3577 undeployed = False
3578 while wait_time <= MAX_WAIT_TIME:
sbhangarea8e5b782018-06-21 02:10:03 -07003579 vapp = VApp(self.client, resource=vapp_resource)
kate13ab2c42016-12-23 01:34:24 -08003580 if not vapp:
beierl01bd6692019-12-09 17:06:20 -05003581 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01003582 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003583 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003584 )
3585 )
kate13ab2c42016-12-23 01:34:24 -08003586
sousaedu80135b92021-02-17 15:05:18 +01003587 return (
3588 -1,
3589 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003590 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003591 ),
3592 )
3593
3594 undeploy_task = vapp.undeploy()
3595 result = self.client.get_task_monitor().wait_for_success(
3596 task=undeploy_task
3597 )
3598
3599 if result.get("status") == "success":
kasarc5bf2932018-03-09 04:15:22 -08003600 undeployed = True
3601 break
kate13ab2c42016-12-23 01:34:24 -08003602 else:
sousaedu80135b92021-02-17 15:05:18 +01003603 self.logger.debug(
3604 "Wait for vApp {} to undeploy".format(vapp_name)
3605 )
kate13ab2c42016-12-23 01:34:24 -08003606 time.sleep(INTERVAL_TIME)
3607
beierl01bd6692019-12-09 17:06:20 -05003608 wait_time += INTERVAL_TIME
kate13ab2c42016-12-23 01:34:24 -08003609
3610 if not undeployed:
sousaedu80135b92021-02-17 15:05:18 +01003611 self.logger.debug(
3612 "delete_vminstance(): Failed to undeploy vApp {} ".format(
garciadeblas89598d42022-06-30 13:57:43 +02003613 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003614 )
3615 )
kate13ab2c42016-12-23 01:34:24 -08003616
3617 # delete vapp
3618 self.logger.info("Start deletion of vApp {} ".format(vapp_name))
kate13ab2c42016-12-23 01:34:24 -08003619 if vapp is not None:
3620 wait_time = 0
3621 result = False
3622
3623 while wait_time <= MAX_WAIT_TIME:
kasarc5bf2932018-03-09 04:15:22 -08003624 vapp = VApp(self.client, resource=vapp_resource)
kate13ab2c42016-12-23 01:34:24 -08003625 if not vapp:
beierl01bd6692019-12-09 17:06:20 -05003626 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +01003627 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003628 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003629 )
3630 )
3631
3632 return (
3633 -1,
3634 "delete_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02003635 vm_id
sousaedu80135b92021-02-17 15:05:18 +01003636 ),
3637 )
kate13ab2c42016-12-23 01:34:24 -08003638
kasarc5bf2932018-03-09 04:15:22 -08003639 delete_task = vdc_obj.delete_vapp(vapp.name, force=True)
sousaedu80135b92021-02-17 15:05:18 +01003640 result = self.client.get_task_monitor().wait_for_success(
3641 task=delete_task
3642 )
3643 if result.get("status") == "success":
kasarc5bf2932018-03-09 04:15:22 -08003644 break
kate13ab2c42016-12-23 01:34:24 -08003645 else:
sousaedu80135b92021-02-17 15:05:18 +01003646 self.logger.debug(
3647 "Wait for vApp {} to delete".format(vapp_name)
3648 )
kate13ab2c42016-12-23 01:34:24 -08003649 time.sleep(INTERVAL_TIME)
3650
beierl01bd6692019-12-09 17:06:20 -05003651 wait_time += INTERVAL_TIME
kate13ab2c42016-12-23 01:34:24 -08003652
kasarc5bf2932018-03-09 04:15:22 -08003653 if result is None:
sousaedu80135b92021-02-17 15:05:18 +01003654 self.logger.debug(
garciadeblas89598d42022-06-30 13:57:43 +02003655 "delete_vminstance(): Failed delete uuid {} ".format(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003656 )
kasarc5bf2932018-03-09 04:15:22 -08003657 else:
sousaedu80135b92021-02-17 15:05:18 +01003658 self.logger.info(
garciadeblas89598d42022-06-30 13:57:43 +02003659 "Deleted vm instance {} successfully".format(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003660 )
3661 config_drive_catalog_name, config_drive_catalog_id = (
garciadeblas89598d42022-06-30 13:57:43 +02003662 "cfg_drv-" + vm_id,
sousaedu80135b92021-02-17 15:05:18 +01003663 None,
3664 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00003665 catalog_list = self.get_image_list()
sousaedu80135b92021-02-17 15:05:18 +01003666
Ananda Baitharu319c26f2019-03-05 17:34:31 +00003667 try:
sousaedu80135b92021-02-17 15:05:18 +01003668 config_drive_catalog_id = [
3669 catalog_["id"]
3670 for catalog_ in catalog_list
3671 if catalog_["name"] == config_drive_catalog_name
3672 ][0]
Ananda Baitharu319c26f2019-03-05 17:34:31 +00003673 except IndexError:
3674 pass
sousaedu80135b92021-02-17 15:05:18 +01003675
Ananda Baitharu319c26f2019-03-05 17:34:31 +00003676 if config_drive_catalog_id:
sousaedu80135b92021-02-17 15:05:18 +01003677 self.logger.debug(
3678 "delete_vminstance(): Found a config drive catalog {} matching "
3679 'vapp_name"{}". Deleting it.'.format(
3680 config_drive_catalog_id, vapp_name
3681 )
3682 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00003683 self.delete_image(config_drive_catalog_id)
sousaedu80135b92021-02-17 15:05:18 +01003684
garciadeblas89598d42022-06-30 13:57:43 +02003685 return vm_id
beierl01bd6692019-12-09 17:06:20 -05003686 except Exception:
bayramovef390722016-09-27 03:34:46 -07003687 self.logger.debug(traceback.format_exc())
sousaedu80135b92021-02-17 15:05:18 +01003688
3689 raise vimconn.VimConnException(
garciadeblas89598d42022-06-30 13:57:43 +02003690 "delete_vminstance(): Failed delete vm instance {}".format(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003691 )
bayramovef390722016-09-27 03:34:46 -07003692
bayramov325fa1c2016-09-08 01:42:46 -07003693 def refresh_vms_status(self, vm_list):
bayramovef390722016-09-27 03:34:46 -07003694 """Get the status of the virtual machines and their interfaces/ports
sousaedu80135b92021-02-17 15:05:18 +01003695 Params: the list of VM identifiers
3696 Returns a dictionary with:
3697 vm_id: #VIM id of this Virtual Machine
3698 status: #Mandatory. Text with one of:
3699 # DELETED (not found at vim)
3700 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3701 # OTHER (Vim reported other status not understood)
3702 # ERROR (VIM indicates an ERROR status)
3703 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
3704 # CREATING (on building process), ERROR
3705 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
3706 #
3707 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3708 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3709 interfaces:
3710 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3711 mac_address: #Text format XX:XX:XX:XX:XX:XX
3712 vim_net_id: #network id where this interface is connected
3713 vim_interface_id: #interface/port VIM id
3714 ip_address: #null, or text with IPv4, IPv6 address
bayramovef390722016-09-27 03:34:46 -07003715 """
bayramovef390722016-09-27 03:34:46 -07003716 self.logger.debug("Client requesting refresh vm status for {} ".format(vm_list))
bhangare985a1fd2017-01-31 01:53:21 -08003717
beierlb22ce2d2019-12-12 12:09:51 -05003718 _, vdc = self.get_vdc_details()
bayramovef390722016-09-27 03:34:46 -07003719 if vdc is None:
sousaedu80135b92021-02-17 15:05:18 +01003720 raise vimconn.VimConnException(
3721 "Failed to get a reference of VDC for a tenant {}".format(
3722 self.tenant_name
3723 )
3724 )
bayramovef390722016-09-27 03:34:46 -07003725
3726 vms_dict = {}
kasarde691232017-03-25 03:37:31 -07003727 nsx_edge_list = []
bayramovef390722016-09-27 03:34:46 -07003728 for vmuuid in vm_list:
kasarc5bf2932018-03-09 04:15:22 -08003729 vapp_name = self.get_namebyvappid(vmuuid)
3730 if vapp_name is not None:
bayramovef390722016-09-27 03:34:46 -07003731 try:
bhangare1a0b97c2017-06-21 02:20:15 -07003732 vm_pci_details = self.get_vm_pci_details(vmuuid)
sousaedu80135b92021-02-17 15:05:18 +01003733 vdc_obj = VDC(self.client, href=vdc.get("href"))
kasarc5bf2932018-03-09 04:15:22 -08003734 vapp_resource = vdc_obj.get_vapp(vapp_name)
3735 the_vapp = VApp(self.client, resource=vapp_resource)
bhangarebfdca492017-03-11 01:32:46 -08003736
kasarc5bf2932018-03-09 04:15:22 -08003737 vm_details = {}
3738 for vm in the_vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01003739 headers = {
3740 "Accept": "application/*+xml;version=" + API_VERSION,
3741 "x-vcloud-authorization": self.client._session.headers[
3742 "x-vcloud-authorization"
3743 ],
3744 }
3745 response = self.perform_request(
3746 req_type="GET", url=vm.get("href"), headers=headers
3747 )
bhangarebfdca492017-03-11 01:32:46 -08003748
kasarc5bf2932018-03-09 04:15:22 -08003749 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01003750 self.logger.error(
3751 "refresh_vms_status : REST call {} failed reason : {}"
3752 "status code : {}".format(
3753 vm.get("href"), response.text, response.status_code
3754 )
3755 )
3756 raise vimconn.VimConnException(
3757 "refresh_vms_status : Failed to get VM details"
3758 )
kasarde691232017-03-25 03:37:31 -07003759
sousaedu80135b92021-02-17 15:05:18 +01003760 xmlroot = XmlElementTree.fromstring(response.text)
beierl26fec002019-12-06 17:06:40 -05003761 result = response.text.replace("\n", " ")
beierlb22ce2d2019-12-12 12:09:51 -05003762 hdd_match = re.search(
sousaedu80135b92021-02-17 15:05:18 +01003763 'vcloud:capacity="(\d+)"\svcloud:storageProfileOverrideVmDefault=',
3764 result,
3765 )
3766
Ravi Chamarty1fdf9992018-10-07 15:45:44 +00003767 if hdd_match:
3768 hdd_mb = hdd_match.group(1)
sousaedu80135b92021-02-17 15:05:18 +01003769 vm_details["hdd_mb"] = int(hdd_mb) if hdd_mb else None
3770
beierlb22ce2d2019-12-12 12:09:51 -05003771 cpus_match = re.search(
sousaedu80135b92021-02-17 15:05:18 +01003772 "<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>",
3773 result,
3774 )
3775
Ravi Chamarty1fdf9992018-10-07 15:45:44 +00003776 if cpus_match:
3777 cpus = cpus_match.group(1)
sousaedu80135b92021-02-17 15:05:18 +01003778 vm_details["cpus"] = int(cpus) if cpus else None
3779
beierlb22ce2d2019-12-12 12:09:51 -05003780 memory_mb = re.search(
sousaedu80135b92021-02-17 15:05:18 +01003781 "<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>",
3782 result,
3783 ).group(1)
3784 vm_details["memory_mb"] = int(memory_mb) if memory_mb else None
3785 vm_details["status"] = vcdStatusCode2manoFormat[
3786 int(xmlroot.get("status"))
3787 ]
3788 vm_details["id"] = xmlroot.get("id")
3789 vm_details["name"] = xmlroot.get("name")
kasarc5bf2932018-03-09 04:15:22 -08003790 vm_info = [vm_details]
sousaedu80135b92021-02-17 15:05:18 +01003791
kasarc5bf2932018-03-09 04:15:22 -08003792 if vm_pci_details:
sbhangarea8e5b782018-06-21 02:10:03 -07003793 vm_info[0].update(vm_pci_details)
kasarc5bf2932018-03-09 04:15:22 -08003794
sousaedu80135b92021-02-17 15:05:18 +01003795 vm_dict = {
3796 "status": vcdStatusCode2manoFormat[
3797 int(vapp_resource.get("status"))
3798 ],
3799 "error_msg": vcdStatusCode2manoFormat[
3800 int(vapp_resource.get("status"))
3801 ],
3802 "vim_info": yaml.safe_dump(vm_info),
3803 "interfaces": [],
3804 }
kasarc5bf2932018-03-09 04:15:22 -08003805
3806 # get networks
sbhangarea8e5b782018-06-21 02:10:03 -07003807 vm_ip = None
kasar1b7b9522018-05-15 06:15:07 -07003808 vm_mac = None
sousaedu80135b92021-02-17 15:05:18 +01003809 networks = re.findall(
3810 "<NetworkConnection needsCustomization=.*?</NetworkConnection>",
3811 result,
3812 )
3813
kasar1b7b9522018-05-15 06:15:07 -07003814 for network in networks:
sousaedu80135b92021-02-17 15:05:18 +01003815 mac_s = re.search("<MACAddress>(.*?)</MACAddress>", network)
kasar1b7b9522018-05-15 06:15:07 -07003816 vm_mac = mac_s.group(1) if mac_s else None
sousaedu80135b92021-02-17 15:05:18 +01003817 ip_s = re.search("<IpAddress>(.*?)</IpAddress>", network)
kasar1b7b9522018-05-15 06:15:07 -07003818 vm_ip = ip_s.group(1) if ip_s else None
kasarc5bf2932018-03-09 04:15:22 -08003819
kasar1b7b9522018-05-15 06:15:07 -07003820 if vm_ip is None:
3821 if not nsx_edge_list:
3822 nsx_edge_list = self.get_edge_details()
3823 if nsx_edge_list is None:
sousaedu80135b92021-02-17 15:05:18 +01003824 raise vimconn.VimConnException(
3825 "refresh_vms_status:"
3826 "Failed to get edge details from NSX Manager"
3827 )
3828
kasar1b7b9522018-05-15 06:15:07 -07003829 if vm_mac is not None:
sousaedu80135b92021-02-17 15:05:18 +01003830 vm_ip = self.get_ipaddr_from_NSXedge(
3831 nsx_edge_list, vm_mac
3832 )
kasarc5bf2932018-03-09 04:15:22 -08003833
beierlb22ce2d2019-12-12 12:09:51 -05003834 net_s = re.search('network="(.*?)"', network)
kasarabac1e22018-05-17 02:44:39 -07003835 network_name = net_s.group(1) if net_s else None
kasar1b7b9522018-05-15 06:15:07 -07003836 vm_net_id = self.get_network_id_by_name(network_name)
sousaedu80135b92021-02-17 15:05:18 +01003837 interface = {
3838 "mac_address": vm_mac,
3839 "vim_net_id": vm_net_id,
3840 "vim_interface_id": vm_net_id,
3841 "ip_address": vm_ip,
3842 }
kasar1b7b9522018-05-15 06:15:07 -07003843 vm_dict["interfaces"].append(interface)
kasarc5bf2932018-03-09 04:15:22 -08003844
bayramovef390722016-09-27 03:34:46 -07003845 # add a vm to vm dict
3846 vms_dict.setdefault(vmuuid, vm_dict)
kasarc5bf2932018-03-09 04:15:22 -08003847 self.logger.debug("refresh_vms_status : vm info {}".format(vm_dict))
bhangarebfdca492017-03-11 01:32:46 -08003848 except Exception as exp:
3849 self.logger.debug("Error in response {}".format(exp))
bayramovef390722016-09-27 03:34:46 -07003850 self.logger.debug(traceback.format_exc())
3851
3852 return vms_dict
3853
kasarde691232017-03-25 03:37:31 -07003854 def get_edge_details(self):
3855 """Get the NSX edge list from NSX Manager
sousaedu80135b92021-02-17 15:05:18 +01003856 Returns list of NSX edges
kasarde691232017-03-25 03:37:31 -07003857 """
3858 edge_list = []
sousaedu80135b92021-02-17 15:05:18 +01003859 rheaders = {"Content-Type": "application/xml"}
3860 nsx_api_url = "/api/4.0/edges"
kasarde691232017-03-25 03:37:31 -07003861
sousaedu80135b92021-02-17 15:05:18 +01003862 self.logger.debug(
3863 "Get edge details from NSX Manager {} {}".format(
3864 self.nsx_manager, nsx_api_url
3865 )
3866 )
kasarde691232017-03-25 03:37:31 -07003867
3868 try:
sousaedu80135b92021-02-17 15:05:18 +01003869 resp = requests.get(
3870 self.nsx_manager + nsx_api_url,
3871 auth=(self.nsx_user, self.nsx_password),
3872 verify=False,
3873 headers=rheaders,
3874 )
kasarde691232017-03-25 03:37:31 -07003875 if resp.status_code == requests.codes.ok:
3876 paged_Edge_List = XmlElementTree.fromstring(resp.text)
3877 for edge_pages in paged_Edge_List:
sousaedu80135b92021-02-17 15:05:18 +01003878 if edge_pages.tag == "edgePage":
kasarde691232017-03-25 03:37:31 -07003879 for edge_summary in edge_pages:
sousaedu80135b92021-02-17 15:05:18 +01003880 if edge_summary.tag == "pagingInfo":
kasarde691232017-03-25 03:37:31 -07003881 for element in edge_summary:
sousaedu80135b92021-02-17 15:05:18 +01003882 if (
3883 element.tag == "totalCount"
3884 and element.text == "0"
3885 ):
tierno72774862020-05-04 11:44:15 +00003886 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01003887 "get_edge_details: No NSX edges details found: {}".format(
3888 self.nsx_manager
3889 )
3890 )
kasarde691232017-03-25 03:37:31 -07003891
sousaedu80135b92021-02-17 15:05:18 +01003892 if edge_summary.tag == "edgeSummary":
kasarde691232017-03-25 03:37:31 -07003893 for element in edge_summary:
sousaedu80135b92021-02-17 15:05:18 +01003894 if element.tag == "id":
kasarde691232017-03-25 03:37:31 -07003895 edge_list.append(element.text)
3896 else:
sousaedu80135b92021-02-17 15:05:18 +01003897 raise vimconn.VimConnException(
3898 "get_edge_details: No NSX edge details found: {}".format(
3899 self.nsx_manager
3900 )
3901 )
kasarde691232017-03-25 03:37:31 -07003902
3903 if not edge_list:
sousaedu80135b92021-02-17 15:05:18 +01003904 raise vimconn.VimConnException(
3905 "get_edge_details: "
3906 "No NSX edge details found: {}".format(self.nsx_manager)
3907 )
kasarde691232017-03-25 03:37:31 -07003908 else:
sousaedu80135b92021-02-17 15:05:18 +01003909 self.logger.debug(
3910 "get_edge_details: Found NSX edges {}".format(edge_list)
3911 )
3912
kasarde691232017-03-25 03:37:31 -07003913 return edge_list
3914 else:
sousaedu80135b92021-02-17 15:05:18 +01003915 self.logger.debug(
3916 "get_edge_details: "
3917 "Failed to get NSX edge details from NSX Manager: {}".format(
3918 resp.content
3919 )
3920 )
3921
kasarde691232017-03-25 03:37:31 -07003922 return None
3923
3924 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01003925 self.logger.debug(
3926 "get_edge_details: "
3927 "Failed to get NSX edge details from NSX Manager: {}".format(exp)
3928 )
3929 raise vimconn.VimConnException(
3930 "get_edge_details: "
3931 "Failed to get NSX edge details from NSX Manager: {}".format(exp)
3932 )
kasarde691232017-03-25 03:37:31 -07003933
kasarde691232017-03-25 03:37:31 -07003934 def get_ipaddr_from_NSXedge(self, nsx_edges, mac_address):
3935 """Get IP address details from NSX edges, using the MAC address
sousaedu80135b92021-02-17 15:05:18 +01003936 PARAMS: nsx_edges : List of NSX edges
3937 mac_address : Find IP address corresponding to this MAC address
3938 Returns: IP address corrresponding to the provided MAC address
kasarde691232017-03-25 03:37:31 -07003939 """
kasarde691232017-03-25 03:37:31 -07003940 ip_addr = None
sousaedu80135b92021-02-17 15:05:18 +01003941 rheaders = {"Content-Type": "application/xml"}
kasarde691232017-03-25 03:37:31 -07003942
3943 self.logger.debug("get_ipaddr_from_NSXedge: Finding IP addr from NSX edge")
3944
3945 try:
3946 for edge in nsx_edges:
sousaedu80135b92021-02-17 15:05:18 +01003947 nsx_api_url = "/api/4.0/edges/" + edge + "/dhcp/leaseInfo"
kasarde691232017-03-25 03:37:31 -07003948
sousaedu80135b92021-02-17 15:05:18 +01003949 resp = requests.get(
3950 self.nsx_manager + nsx_api_url,
3951 auth=(self.nsx_user, self.nsx_password),
3952 verify=False,
3953 headers=rheaders,
3954 )
kasarde691232017-03-25 03:37:31 -07003955
3956 if resp.status_code == requests.codes.ok:
3957 dhcp_leases = XmlElementTree.fromstring(resp.text)
3958 for child in dhcp_leases:
sousaedu80135b92021-02-17 15:05:18 +01003959 if child.tag == "dhcpLeaseInfo":
kasarde691232017-03-25 03:37:31 -07003960 dhcpLeaseInfo = child
3961 for leaseInfo in dhcpLeaseInfo:
3962 for elem in leaseInfo:
sousaedu80135b92021-02-17 15:05:18 +01003963 if (elem.tag) == "macAddress":
kasarde691232017-03-25 03:37:31 -07003964 edge_mac_addr = elem.text
sousaedu80135b92021-02-17 15:05:18 +01003965
3966 if (elem.tag) == "ipAddress":
kasarde691232017-03-25 03:37:31 -07003967 ip_addr = elem.text
sousaedu80135b92021-02-17 15:05:18 +01003968
kasarde691232017-03-25 03:37:31 -07003969 if edge_mac_addr is not None:
3970 if edge_mac_addr == mac_address:
sousaedu80135b92021-02-17 15:05:18 +01003971 self.logger.debug(
3972 "Found ip addr {} for mac {} at NSX edge {}".format(
3973 ip_addr, mac_address, edge
3974 )
3975 )
3976
kasarde691232017-03-25 03:37:31 -07003977 return ip_addr
3978 else:
sousaedu80135b92021-02-17 15:05:18 +01003979 self.logger.debug(
3980 "get_ipaddr_from_NSXedge: "
3981 "Error occurred while getting DHCP lease info from NSX Manager: {}".format(
3982 resp.content
3983 )
3984 )
kasarde691232017-03-25 03:37:31 -07003985
sousaedu80135b92021-02-17 15:05:18 +01003986 self.logger.debug(
3987 "get_ipaddr_from_NSXedge: No IP addr found in any NSX edge"
3988 )
3989
kasarde691232017-03-25 03:37:31 -07003990 return None
3991
3992 except XmlElementTree.ParseError as Err:
sousaedu80135b92021-02-17 15:05:18 +01003993 self.logger.debug(
3994 "ParseError in response from NSX Manager {}".format(Err.message),
3995 exc_info=True,
3996 )
kasarde691232017-03-25 03:37:31 -07003997
garciadeblas89598d42022-06-30 13:57:43 +02003998 def action_vminstance(self, vm_id=None, action_dict=None, created_items={}):
bayramovef390722016-09-27 03:34:46 -07003999 """Send and action over a VM instance from VIM
4000 Returns the vm_id if the action was successfully sent to the VIM"""
4001
sousaedu80135b92021-02-17 15:05:18 +01004002 self.logger.debug(
garciadeblas89598d42022-06-30 13:57:43 +02004003 "Received action for vm {} and action dict {}".format(vm_id, action_dict)
sousaedu80135b92021-02-17 15:05:18 +01004004 )
4005
garciadeblas89598d42022-06-30 13:57:43 +02004006 if vm_id is None or action_dict is None:
tierno72774862020-05-04 11:44:15 +00004007 raise vimconn.VimConnException("Invalid request. VM id or action is None.")
bayramovef390722016-09-27 03:34:46 -07004008
beierlb22ce2d2019-12-12 12:09:51 -05004009 _, vdc = self.get_vdc_details()
bayramovef390722016-09-27 03:34:46 -07004010 if vdc is None:
sousaedu80135b92021-02-17 15:05:18 +01004011 raise vimconn.VimConnException(
4012 "Failed to get a reference of VDC for a tenant {}".format(
4013 self.tenant_name
4014 )
4015 )
bayramovef390722016-09-27 03:34:46 -07004016
garciadeblas89598d42022-06-30 13:57:43 +02004017 vapp_name = self.get_namebyvappid(vm_id)
bayramovef390722016-09-27 03:34:46 -07004018 if vapp_name is None:
sousaedu80135b92021-02-17 15:05:18 +01004019 self.logger.debug(
4020 "action_vminstance(): Failed to get vm by given {} vm uuid".format(
garciadeblas89598d42022-06-30 13:57:43 +02004021 vm_id
sousaedu80135b92021-02-17 15:05:18 +01004022 )
4023 )
4024
4025 raise vimconn.VimConnException(
garciadeblas89598d42022-06-30 13:57:43 +02004026 "Failed to get vm by given {} vm uuid".format(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01004027 )
bayramovef390722016-09-27 03:34:46 -07004028 else:
sousaedu80135b92021-02-17 15:05:18 +01004029 self.logger.info(
garciadeblas89598d42022-06-30 13:57:43 +02004030 "Action_vminstance vApp {} and UUID {}".format(vapp_name, vm_id)
sousaedu80135b92021-02-17 15:05:18 +01004031 )
bayramovef390722016-09-27 03:34:46 -07004032
4033 try:
sousaedu80135b92021-02-17 15:05:18 +01004034 vdc_obj = VDC(self.client, href=vdc.get("href"))
kasarc5bf2932018-03-09 04:15:22 -08004035 vapp_resource = vdc_obj.get_vapp(vapp_name)
sbhangarea8e5b782018-06-21 02:10:03 -07004036 vapp = VApp(self.client, resource=vapp_resource)
sousaedu80135b92021-02-17 15:05:18 +01004037
bayramovef390722016-09-27 03:34:46 -07004038 if "start" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01004039 self.logger.info(
4040 "action_vminstance: Power on vApp: {}".format(vapp_name)
4041 )
garciadeblas89598d42022-06-30 13:57:43 +02004042 poweron_task = self.power_on_vapp(vm_id, vapp_name)
sousaedu80135b92021-02-17 15:05:18 +01004043 result = self.client.get_task_monitor().wait_for_success(
4044 task=poweron_task
4045 )
kasarc5bf2932018-03-09 04:15:22 -08004046 self.instance_actions_result("start", result, vapp_name)
kasar3ac5dc42017-03-15 06:28:22 -07004047 elif "rebuild" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01004048 self.logger.info(
4049 "action_vminstance: Rebuild vApp: {}".format(vapp_name)
4050 )
kasarc5bf2932018-03-09 04:15:22 -08004051 rebuild_task = vapp.deploy(power_on=True)
sousaedu80135b92021-02-17 15:05:18 +01004052 result = self.client.get_task_monitor().wait_for_success(
4053 task=rebuild_task
4054 )
kasar3ac5dc42017-03-15 06:28:22 -07004055 self.instance_actions_result("rebuild", result, vapp_name)
bayramovef390722016-09-27 03:34:46 -07004056 elif "pause" in action_dict:
kasar3ac5dc42017-03-15 06:28:22 -07004057 self.logger.info("action_vminstance: pause vApp: {}".format(vapp_name))
sousaedu80135b92021-02-17 15:05:18 +01004058 pause_task = vapp.undeploy(action="suspend")
4059 result = self.client.get_task_monitor().wait_for_success(
4060 task=pause_task
4061 )
kasar3ac5dc42017-03-15 06:28:22 -07004062 self.instance_actions_result("pause", result, vapp_name)
bayramovef390722016-09-27 03:34:46 -07004063 elif "resume" in action_dict:
kasar3ac5dc42017-03-15 06:28:22 -07004064 self.logger.info("action_vminstance: resume vApp: {}".format(vapp_name))
garciadeblas89598d42022-06-30 13:57:43 +02004065 poweron_task = self.power_on_vapp(vm_id, vapp_name)
sousaedu80135b92021-02-17 15:05:18 +01004066 result = self.client.get_task_monitor().wait_for_success(
4067 task=poweron_task
4068 )
kasar3ac5dc42017-03-15 06:28:22 -07004069 self.instance_actions_result("resume", result, vapp_name)
bayramovef390722016-09-27 03:34:46 -07004070 elif "shutoff" in action_dict or "shutdown" in action_dict:
beierlb22ce2d2019-12-12 12:09:51 -05004071 action_name, _ = list(action_dict.items())[0]
sousaedu80135b92021-02-17 15:05:18 +01004072 self.logger.info(
4073 "action_vminstance: {} vApp: {}".format(action_name, vapp_name)
4074 )
kasarc5bf2932018-03-09 04:15:22 -08004075 shutdown_task = vapp.shutdown()
sousaedu80135b92021-02-17 15:05:18 +01004076 result = self.client.get_task_monitor().wait_for_success(
4077 task=shutdown_task
4078 )
kasar3ac5dc42017-03-15 06:28:22 -07004079 if action_name == "shutdown":
4080 self.instance_actions_result("shutdown", result, vapp_name)
bhangare985a1fd2017-01-31 01:53:21 -08004081 else:
kasar3ac5dc42017-03-15 06:28:22 -07004082 self.instance_actions_result("shutoff", result, vapp_name)
bayramovef390722016-09-27 03:34:46 -07004083 elif "forceOff" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01004084 result = vapp.undeploy(action="powerOff")
kasar3ac5dc42017-03-15 06:28:22 -07004085 self.instance_actions_result("forceOff", result, vapp_name)
4086 elif "reboot" in action_dict:
4087 self.logger.info("action_vminstance: reboot vApp: {}".format(vapp_name))
kasarc5bf2932018-03-09 04:15:22 -08004088 reboot_task = vapp.reboot()
sbhangarea8e5b782018-06-21 02:10:03 -07004089 self.client.get_task_monitor().wait_for_success(task=reboot_task)
bayramovef390722016-09-27 03:34:46 -07004090 else:
tierno72774862020-05-04 11:44:15 +00004091 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01004092 "action_vminstance: Invalid action {} or action is None.".format(
4093 action_dict
4094 )
4095 )
4096
garciadeblas89598d42022-06-30 13:57:43 +02004097 return vm_id
beierlb22ce2d2019-12-12 12:09:51 -05004098 except Exception as exp:
bhangarebfdca492017-03-11 01:32:46 -08004099 self.logger.debug("action_vminstance: Failed with Exception {}".format(exp))
sousaedu80135b92021-02-17 15:05:18 +01004100
4101 raise vimconn.VimConnException(
4102 "action_vminstance: Failed with Exception {}".format(exp)
4103 )
bayramovef390722016-09-27 03:34:46 -07004104
kasar3ac5dc42017-03-15 06:28:22 -07004105 def instance_actions_result(self, action, result, vapp_name):
sousaedu80135b92021-02-17 15:05:18 +01004106 if result.get("status") == "success":
4107 self.logger.info(
4108 "action_vminstance: Sucessfully {} the vApp: {}".format(
4109 action, vapp_name
4110 )
4111 )
kasar3ac5dc42017-03-15 06:28:22 -07004112 else:
sousaedu80135b92021-02-17 15:05:18 +01004113 self.logger.error(
4114 "action_vminstance: Failed to {} vApp: {}".format(action, vapp_name)
4115 )
kasar3ac5dc42017-03-15 06:28:22 -07004116
kasarcf655072019-03-20 01:40:05 -07004117 def get_vminstance_console(self, vm_id, console_type="novnc"):
bayramovef390722016-09-27 03:34:46 -07004118 """
bayramov325fa1c2016-09-08 01:42:46 -07004119 Get a console for the virtual machine
4120 Params:
4121 vm_id: uuid of the VM
4122 console_type, can be:
bayramovef390722016-09-27 03:34:46 -07004123 "novnc" (by default), "xvpvnc" for VNC types,
bayramov325fa1c2016-09-08 01:42:46 -07004124 "rdp-html5" for RDP types, "spice-html5" for SPICE types
4125 Returns dict with the console parameters:
4126 protocol: ssh, ftp, http, https, ...
bayramovef390722016-09-27 03:34:46 -07004127 server: usually ip address
4128 port: the http, ssh, ... port
4129 suffix: extra text, e.g. the http path and query string
4130 """
kasarcf655072019-03-20 01:40:05 -07004131 console_dict = {}
4132
sousaedu80135b92021-02-17 15:05:18 +01004133 if console_type is None or console_type == "novnc":
4134 url_rest_call = "{}/api/vApp/vm-{}/screen/action/acquireMksTicket".format(
4135 self.url, vm_id
4136 )
4137 headers = {
4138 "Accept": "application/*+xml;version=" + API_VERSION,
4139 "x-vcloud-authorization": self.client._session.headers[
4140 "x-vcloud-authorization"
4141 ],
4142 }
4143 response = self.perform_request(
4144 req_type="POST", url=url_rest_call, headers=headers
4145 )
kasarcf655072019-03-20 01:40:05 -07004146
4147 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01004148 response = self.retry_rest("GET", url_rest_call)
kasarcf655072019-03-20 01:40:05 -07004149
4150 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01004151 self.logger.error(
4152 "REST call {} failed reason : {}"
4153 "status code : {}".format(
4154 url_rest_call, response.text, response.status_code
4155 )
4156 )
4157 raise vimconn.VimConnException(
4158 "get_vminstance_console : Failed to get " "VM Mks ticket details"
4159 )
4160
beierl26fec002019-12-06 17:06:40 -05004161 s = re.search("<Host>(.*?)</Host>", response.text)
sousaedu80135b92021-02-17 15:05:18 +01004162 console_dict["server"] = s.group(1) if s else None
beierl26fec002019-12-06 17:06:40 -05004163 s1 = re.search("<Port>(\d+)</Port>", response.text)
sousaedu80135b92021-02-17 15:05:18 +01004164 console_dict["port"] = s1.group(1) if s1 else None
4165 url_rest_call = "{}/api/vApp/vm-{}/screen/action/acquireTicket".format(
4166 self.url, vm_id
4167 )
4168 headers = {
4169 "Accept": "application/*+xml;version=" + API_VERSION,
4170 "x-vcloud-authorization": self.client._session.headers[
4171 "x-vcloud-authorization"
4172 ],
4173 }
4174 response = self.perform_request(
4175 req_type="POST", url=url_rest_call, headers=headers
4176 )
kasarcf655072019-03-20 01:40:05 -07004177
4178 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01004179 response = self.retry_rest("GET", url_rest_call)
kasarcf655072019-03-20 01:40:05 -07004180
4181 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01004182 self.logger.error(
4183 "REST call {} failed reason : {}"
4184 "status code : {}".format(
4185 url_rest_call, response.text, response.status_code
4186 )
4187 )
4188 raise vimconn.VimConnException(
4189 "get_vminstance_console : Failed to get " "VM console details"
4190 )
4191
beierl26fec002019-12-06 17:06:40 -05004192 s = re.search(">.*?/(vm-\d+.*)</", response.text)
sousaedu80135b92021-02-17 15:05:18 +01004193 console_dict["suffix"] = s.group(1) if s else None
4194 console_dict["protocol"] = "https"
kasarcf655072019-03-20 01:40:05 -07004195
4196 return console_dict
bayramov325fa1c2016-09-08 01:42:46 -07004197
bayramovef390722016-09-27 03:34:46 -07004198 # NOT USED METHODS in current version
bayramov325fa1c2016-09-08 01:42:46 -07004199
4200 def host_vim2gui(self, host, server_dict):
bayramov5761ad12016-10-04 09:00:30 +04004201 """Transform host dictionary from VIM format to GUI format,
bayramov325fa1c2016-09-08 01:42:46 -07004202 and append to the server_dict
bayramov5761ad12016-10-04 09:00:30 +04004203 """
tierno72774862020-05-04 11:44:15 +00004204 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004205
4206 def get_hosts_info(self):
bayramov5761ad12016-10-04 09:00:30 +04004207 """Get the information of deployed hosts
4208 Returns the hosts content"""
tierno72774862020-05-04 11:44:15 +00004209 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004210
4211 def get_hosts(self, vim_tenant):
bayramov5761ad12016-10-04 09:00:30 +04004212 """Get the hosts and deployed instances
4213 Returns the hosts content"""
tierno72774862020-05-04 11:44:15 +00004214 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004215
4216 def get_processor_rankings(self):
bayramov5761ad12016-10-04 09:00:30 +04004217 """Get the processor rankings in the VIM database"""
tierno72774862020-05-04 11:44:15 +00004218 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004219
4220 def new_host(self, host_data):
bayramov5761ad12016-10-04 09:00:30 +04004221 """Adds a new host to VIM"""
sousaedu80135b92021-02-17 15:05:18 +01004222 """Returns status code of the VIM response"""
tierno72774862020-05-04 11:44:15 +00004223 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004224
4225 def new_external_port(self, port_data):
bayramov5761ad12016-10-04 09:00:30 +04004226 """Adds a external port to VIM"""
sousaedu80135b92021-02-17 15:05:18 +01004227 """Returns the port identifier"""
tierno72774862020-05-04 11:44:15 +00004228 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004229
bayramovef390722016-09-27 03:34:46 -07004230 def new_external_network(self, net_name, net_type):
bayramov5761ad12016-10-04 09:00:30 +04004231 """Adds a external network to VIM (shared)"""
sousaedu80135b92021-02-17 15:05:18 +01004232 """Returns the network identifier"""
tierno72774862020-05-04 11:44:15 +00004233 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004234
4235 def connect_port_network(self, port_id, network_id, admin=False):
bayramov5761ad12016-10-04 09:00:30 +04004236 """Connects a external port to a network"""
sousaedu80135b92021-02-17 15:05:18 +01004237 """Returns status code of the VIM response"""
tierno72774862020-05-04 11:44:15 +00004238 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004239
4240 def new_vminstancefromJSON(self, vm_data):
bayramov5761ad12016-10-04 09:00:30 +04004241 """Adds a VM instance to VIM"""
sousaedu80135b92021-02-17 15:05:18 +01004242 """Returns the instance identifier"""
tierno72774862020-05-04 11:44:15 +00004243 raise vimconn.VimConnNotImplemented("Should have implemented this")
bayramov325fa1c2016-09-08 01:42:46 -07004244
kate15f1c382016-12-15 01:12:40 -08004245 def get_network_name_by_id(self, network_uuid=None):
bayramovef390722016-09-27 03:34:46 -07004246 """Method gets vcloud director network named based on supplied uuid.
4247
4248 Args:
kate15f1c382016-12-15 01:12:40 -08004249 network_uuid: network_id
bayramovef390722016-09-27 03:34:46 -07004250
4251 Returns:
4252 The return network name.
4253 """
4254
kate15f1c382016-12-15 01:12:40 -08004255 if not network_uuid:
bayramovef390722016-09-27 03:34:46 -07004256 return None
4257
4258 try:
kate15f1c382016-12-15 01:12:40 -08004259 org_dict = self.get_org(self.org_uuid)
sousaedu80135b92021-02-17 15:05:18 +01004260 if "networks" in org_dict:
4261 org_network_dict = org_dict["networks"]
4262
kate15f1c382016-12-15 01:12:40 -08004263 for net_uuid in org_network_dict:
4264 if net_uuid == network_uuid:
4265 return org_network_dict[net_uuid]
beierlb22ce2d2019-12-12 12:09:51 -05004266 except Exception:
bayramovef390722016-09-27 03:34:46 -07004267 self.logger.debug("Exception in get_network_name_by_id")
4268 self.logger.debug(traceback.format_exc())
4269
4270 return None
4271
bhangare2c855072016-12-27 01:41:28 -08004272 def get_network_id_by_name(self, network_name=None):
4273 """Method gets vcloud director network uuid based on supplied name.
4274
4275 Args:
4276 network_name: network_name
4277 Returns:
4278 The return network uuid.
4279 network_uuid: network_id
4280 """
bhangare2c855072016-12-27 01:41:28 -08004281 if not network_name:
4282 self.logger.debug("get_network_id_by_name() : Network name is empty")
4283 return None
4284
4285 try:
4286 org_dict = self.get_org(self.org_uuid)
sousaedu80135b92021-02-17 15:05:18 +01004287 if org_dict and "networks" in org_dict:
4288 org_network_dict = org_dict["networks"]
4289
tierno1b856002019-11-07 16:28:54 +00004290 for net_uuid, net_name in org_network_dict.items():
bhangare2c855072016-12-27 01:41:28 -08004291 if net_name == network_name:
4292 return net_uuid
4293
4294 except KeyError as exp:
4295 self.logger.debug("get_network_id_by_name() : KeyError- {} ".format(exp))
4296
4297 return None
4298
kbsuba85c54d2019-10-17 16:30:32 +00004299 def get_physical_network_by_name(self, physical_network_name):
sousaedu80135b92021-02-17 15:05:18 +01004300 """
kbsuba85c54d2019-10-17 16:30:32 +00004301 Methos returns uuid of physical network which passed
4302 Args:
4303 physical_network_name: physical network name
4304 Returns:
4305 UUID of physical_network_name
sousaedu80135b92021-02-17 15:05:18 +01004306 """
kbsuba85c54d2019-10-17 16:30:32 +00004307 try:
4308 client_as_admin = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01004309
kbsuba85c54d2019-10-17 16:30:32 +00004310 if not client_as_admin:
tierno72774862020-05-04 11:44:15 +00004311 raise vimconn.VimConnConnectionException("Failed to connect vCD.")
sousaedu80135b92021-02-17 15:05:18 +01004312
4313 url_list = [self.url, "/api/admin/vdc/", self.tenant_id]
4314 vm_list_rest_call = "".join(url_list)
kbsuba85c54d2019-10-17 16:30:32 +00004315
4316 if client_as_admin._session:
sousaedu80135b92021-02-17 15:05:18 +01004317 headers = {
4318 "Accept": "application/*+xml;version=" + API_VERSION,
4319 "x-vcloud-authorization": client_as_admin._session.headers[
4320 "x-vcloud-authorization"
4321 ],
4322 }
4323 response = self.perform_request(
4324 req_type="GET", url=vm_list_rest_call, headers=headers
4325 )
kbsuba85c54d2019-10-17 16:30:32 +00004326 provider_network = None
4327 available_network = None
beierlb22ce2d2019-12-12 12:09:51 -05004328 # add_vdc_rest_url = None
kbsuba85c54d2019-10-17 16:30:32 +00004329
4330 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01004331 self.logger.debug(
4332 "REST API call {} failed. Return status code {}".format(
4333 vm_list_rest_call, response.status_code
4334 )
4335 )
kbsuba85c54d2019-10-17 16:30:32 +00004336 return None
4337 else:
4338 try:
beierl26fec002019-12-06 17:06:40 -05004339 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
kbsuba85c54d2019-10-17 16:30:32 +00004340 for child in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004341 if child.tag.split("}")[1] == "ProviderVdcReference":
4342 provider_network = child.attrib.get("href")
kbsuba85c54d2019-10-17 16:30:32 +00004343 # application/vnd.vmware.admin.providervdc+xml
sousaedu80135b92021-02-17 15:05:18 +01004344
4345 if child.tag.split("}")[1] == "Link":
4346 if (
4347 child.attrib.get("type")
4348 == "application/vnd.vmware.vcloud.orgVdcNetwork+xml"
4349 and child.attrib.get("rel") == "add"
4350 ):
4351 child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05004352 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01004353 self.logger.debug(
4354 "Failed parse respond for rest api call {}".format(
4355 vm_list_rest_call
4356 )
4357 )
beierl26fec002019-12-06 17:06:40 -05004358 self.logger.debug("Respond body {}".format(response.text))
sousaedu80135b92021-02-17 15:05:18 +01004359
kbsuba85c54d2019-10-17 16:30:32 +00004360 return None
4361
4362 # find pvdc provided available network
sousaedu80135b92021-02-17 15:05:18 +01004363 response = self.perform_request(
4364 req_type="GET", url=provider_network, headers=headers
4365 )
kbsuba85c54d2019-10-17 16:30:32 +00004366
4367 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01004368 self.logger.debug(
4369 "REST API call {} failed. Return status code {}".format(
4370 vm_list_rest_call, response.status_code
4371 )
4372 )
4373
kbsuba85c54d2019-10-17 16:30:32 +00004374 return None
4375
4376 try:
beierl26fec002019-12-06 17:06:40 -05004377 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
kbsuba85c54d2019-10-17 16:30:32 +00004378 for child in vm_list_xmlroot.iter():
sousaedu80135b92021-02-17 15:05:18 +01004379 if child.tag.split("}")[1] == "AvailableNetworks":
kbsuba85c54d2019-10-17 16:30:32 +00004380 for networks in child.iter():
sousaedu80135b92021-02-17 15:05:18 +01004381 if (
4382 networks.attrib.get("href") is not None
4383 and networks.attrib.get("name") is not None
4384 ):
4385 if (
4386 networks.attrib.get("name")
4387 == physical_network_name
4388 ):
4389 network_url = networks.attrib.get("href")
4390 available_network = network_url[
4391 network_url.rindex("/") + 1 :
4392 ]
kbsuba85c54d2019-10-17 16:30:32 +00004393 break
sousaedu80135b92021-02-17 15:05:18 +01004394 except Exception:
kbsuba85c54d2019-10-17 16:30:32 +00004395 return None
4396
4397 return available_network
4398 except Exception as e:
4399 self.logger.error("Error while getting physical network: {}".format(e))
4400
bayramovef390722016-09-27 03:34:46 -07004401 def list_org_action(self):
4402 """
4403 Method leverages vCloud director and query for available organization for particular user
4404
4405 Args:
4406 vca - is active VCA connection.
4407 vdc_name - is a vdc name that will be used to query vms action
4408
4409 Returns:
4410 The return XML respond
4411 """
sousaedu80135b92021-02-17 15:05:18 +01004412 url_list = [self.url, "/api/org"]
4413 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07004414
kasarc5bf2932018-03-09 04:15:22 -08004415 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01004416 headers = {
4417 "Accept": "application/*+xml;version=" + API_VERSION,
4418 "x-vcloud-authorization": self.client._session.headers[
4419 "x-vcloud-authorization"
4420 ],
4421 }
kasarc5bf2932018-03-09 04:15:22 -08004422
sousaedu80135b92021-02-17 15:05:18 +01004423 response = self.perform_request(
4424 req_type="GET", url=vm_list_rest_call, headers=headers
4425 )
bhangare1a0b97c2017-06-21 02:20:15 -07004426
4427 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01004428 response = self.retry_rest("GET", vm_list_rest_call)
bhangare1a0b97c2017-06-21 02:20:15 -07004429
bayramovef390722016-09-27 03:34:46 -07004430 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05004431 return response.text
bayramovef390722016-09-27 03:34:46 -07004432
4433 return None
4434
4435 def get_org_action(self, org_uuid=None):
4436 """
kasarc5bf2932018-03-09 04:15:22 -08004437 Method leverages vCloud director and retrieve available object for organization.
bayramovef390722016-09-27 03:34:46 -07004438
4439 Args:
kasarc5bf2932018-03-09 04:15:22 -08004440 org_uuid - vCD organization uuid
4441 self.client - is active connection.
bayramovef390722016-09-27 03:34:46 -07004442
4443 Returns:
4444 The return XML respond
4445 """
4446
bayramovef390722016-09-27 03:34:46 -07004447 if org_uuid is None:
4448 return None
4449
sousaedu80135b92021-02-17 15:05:18 +01004450 url_list = [self.url, "/api/org/", org_uuid]
4451 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07004452
sbhangarea8e5b782018-06-21 02:10:03 -07004453 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01004454 headers = {
4455 "Accept": "application/*+xml;version=" + API_VERSION,
4456 "x-vcloud-authorization": self.client._session.headers[
4457 "x-vcloud-authorization"
4458 ],
4459 }
bhangare1a0b97c2017-06-21 02:20:15 -07004460
beierlb22ce2d2019-12-12 12:09:51 -05004461 # response = requests.get(vm_list_rest_call, headers=headers, verify=False)
sousaedu80135b92021-02-17 15:05:18 +01004462 response = self.perform_request(
4463 req_type="GET", url=vm_list_rest_call, headers=headers
4464 )
4465
bhangare1a0b97c2017-06-21 02:20:15 -07004466 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01004467 response = self.retry_rest("GET", vm_list_rest_call)
bhangare1a0b97c2017-06-21 02:20:15 -07004468
bayramovef390722016-09-27 03:34:46 -07004469 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05004470 return response.text
sousaedu80135b92021-02-17 15:05:18 +01004471
bayramovef390722016-09-27 03:34:46 -07004472 return None
4473
4474 def get_org(self, org_uuid=None):
4475 """
4476 Method retrieves available organization in vCloud Director
4477
4478 Args:
bayramovb6ffe792016-09-28 11:50:56 +04004479 org_uuid - is a organization uuid.
bayramovef390722016-09-27 03:34:46 -07004480
4481 Returns:
bayramovb6ffe792016-09-28 11:50:56 +04004482 The return dictionary with following key
4483 "network" - for network list under the org
4484 "catalogs" - for network list under the org
4485 "vdcs" - for vdc list under org
bayramovef390722016-09-27 03:34:46 -07004486 """
4487
4488 org_dict = {}
bayramovef390722016-09-27 03:34:46 -07004489
4490 if org_uuid is None:
4491 return org_dict
4492
4493 content = self.get_org_action(org_uuid=org_uuid)
4494 try:
4495 vdc_list = {}
4496 network_list = {}
4497 catalog_list = {}
4498 vm_list_xmlroot = XmlElementTree.fromstring(content)
4499 for child in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004500 if child.attrib["type"] == "application/vnd.vmware.vcloud.vdc+xml":
4501 vdc_list[child.attrib["href"].split("/")[-1:][0]] = child.attrib[
4502 "name"
4503 ]
4504 org_dict["vdcs"] = vdc_list
4505
4506 if (
4507 child.attrib["type"]
4508 == "application/vnd.vmware.vcloud.orgNetwork+xml"
4509 ):
4510 network_list[
4511 child.attrib["href"].split("/")[-1:][0]
4512 ] = child.attrib["name"]
4513 org_dict["networks"] = network_list
4514
4515 if child.attrib["type"] == "application/vnd.vmware.vcloud.catalog+xml":
4516 catalog_list[
4517 child.attrib["href"].split("/")[-1:][0]
4518 ] = child.attrib["name"]
4519 org_dict["catalogs"] = catalog_list
beierlb22ce2d2019-12-12 12:09:51 -05004520 except Exception:
bayramovef390722016-09-27 03:34:46 -07004521 pass
4522
4523 return org_dict
4524
4525 def get_org_list(self):
4526 """
4527 Method retrieves available organization in vCloud Director
4528
4529 Args:
4530 vca - is active VCA connection.
4531
4532 Returns:
4533 The return dictionary and key for each entry VDC UUID
4534 """
bayramovef390722016-09-27 03:34:46 -07004535 org_dict = {}
bayramovef390722016-09-27 03:34:46 -07004536
4537 content = self.list_org_action()
4538 try:
4539 vm_list_xmlroot = XmlElementTree.fromstring(content)
sousaedu80135b92021-02-17 15:05:18 +01004540
bayramovef390722016-09-27 03:34:46 -07004541 for vm_xml in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004542 if vm_xml.tag.split("}")[1] == "Org":
4543 org_uuid = vm_xml.attrib["href"].split("/")[-1:]
4544 org_dict[org_uuid[0]] = vm_xml.attrib["name"]
beierlb22ce2d2019-12-12 12:09:51 -05004545 except Exception:
bayramovef390722016-09-27 03:34:46 -07004546 pass
4547
4548 return org_dict
4549
4550 def vms_view_action(self, vdc_name=None):
sousaedu80135b92021-02-17 15:05:18 +01004551 """Method leverages vCloud director vms query call
bayramovef390722016-09-27 03:34:46 -07004552
4553 Args:
4554 vca - is active VCA connection.
4555 vdc_name - is a vdc name that will be used to query vms action
4556
4557 Returns:
4558 The return XML respond
4559 """
4560 vca = self.connect()
4561 if vdc_name is None:
4562 return None
4563
sousaedu80135b92021-02-17 15:05:18 +01004564 url_list = [vca.host, "/api/vms/query"]
4565 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07004566
4567 if not (not vca.vcloud_session or not vca.vcloud_session.organization):
sousaedu80135b92021-02-17 15:05:18 +01004568 refs = [
4569 ref
4570 for ref in vca.vcloud_session.organization.Link
4571 if ref.name == vdc_name
4572 and ref.type_ == "application/vnd.vmware.vcloud.vdc+xml"
4573 ]
4574
bayramovef390722016-09-27 03:34:46 -07004575 if len(refs) == 1:
sousaedu80135b92021-02-17 15:05:18 +01004576 response = self.perform_request(
4577 req_type="GET",
4578 url=vm_list_rest_call,
4579 headers=vca.vcloud_session.get_vcloud_headers(),
4580 verify=vca.verify,
4581 logger=vca.logger,
4582 )
4583
bayramovef390722016-09-27 03:34:46 -07004584 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05004585 return response.text
bayramovef390722016-09-27 03:34:46 -07004586
4587 return None
4588
4589 def get_vapp_list(self, vdc_name=None):
4590 """
4591 Method retrieves vApp list deployed vCloud director and returns a dictionary
4592 contains a list of all vapp deployed for queried VDC.
4593 The key for a dictionary is vApp UUID
4594
4595
4596 Args:
4597 vca - is active VCA connection.
4598 vdc_name - is a vdc name that will be used to query vms action
4599
4600 Returns:
4601 The return dictionary and key for each entry vapp UUID
4602 """
bayramovef390722016-09-27 03:34:46 -07004603 vapp_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01004604
bayramovef390722016-09-27 03:34:46 -07004605 if vdc_name is None:
4606 return vapp_dict
4607
4608 content = self.vms_view_action(vdc_name=vdc_name)
4609 try:
4610 vm_list_xmlroot = XmlElementTree.fromstring(content)
4611 for vm_xml in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004612 if vm_xml.tag.split("}")[1] == "VMRecord":
4613 if vm_xml.attrib["isVAppTemplate"] == "true":
4614 rawuuid = vm_xml.attrib["container"].split("/")[-1:]
4615 if "vappTemplate-" in rawuuid[0]:
bayramovef390722016-09-27 03:34:46 -07004616 # vm in format vappTemplate-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
4617 # vm and use raw UUID as key
4618 vapp_dict[rawuuid[0][13:]] = vm_xml.attrib
beierlb22ce2d2019-12-12 12:09:51 -05004619 except Exception:
bayramovef390722016-09-27 03:34:46 -07004620 pass
4621
4622 return vapp_dict
4623
4624 def get_vm_list(self, vdc_name=None):
4625 """
4626 Method retrieves VM's list deployed vCloud director. It returns a dictionary
4627 contains a list of all VM's deployed for queried VDC.
4628 The key for a dictionary is VM UUID
4629
4630
4631 Args:
4632 vca - is active VCA connection.
4633 vdc_name - is a vdc name that will be used to query vms action
4634
4635 Returns:
4636 The return dictionary and key for each entry vapp UUID
4637 """
4638 vm_dict = {}
4639
4640 if vdc_name is None:
4641 return vm_dict
4642
4643 content = self.vms_view_action(vdc_name=vdc_name)
4644 try:
4645 vm_list_xmlroot = XmlElementTree.fromstring(content)
4646 for vm_xml in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004647 if vm_xml.tag.split("}")[1] == "VMRecord":
4648 if vm_xml.attrib["isVAppTemplate"] == "false":
4649 rawuuid = vm_xml.attrib["href"].split("/")[-1:]
4650 if "vm-" in rawuuid[0]:
bayramovef390722016-09-27 03:34:46 -07004651 # vm in format vm-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
4652 # vm and use raw UUID as key
4653 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
beierlb22ce2d2019-12-12 12:09:51 -05004654 except Exception:
bayramovef390722016-09-27 03:34:46 -07004655 pass
4656
4657 return vm_dict
4658
4659 def get_vapp(self, vdc_name=None, vapp_name=None, isuuid=False):
4660 """
bayramovb6ffe792016-09-28 11:50:56 +04004661 Method retrieves VM deployed vCloud director. It returns VM attribute as dictionary
bayramovef390722016-09-27 03:34:46 -07004662 contains a list of all VM's deployed for queried VDC.
4663 The key for a dictionary is VM UUID
4664
4665
4666 Args:
4667 vca - is active VCA connection.
4668 vdc_name - is a vdc name that will be used to query vms action
4669
4670 Returns:
4671 The return dictionary and key for each entry vapp UUID
4672 """
4673 vm_dict = {}
4674 vca = self.connect()
sousaedu80135b92021-02-17 15:05:18 +01004675
bayramovef390722016-09-27 03:34:46 -07004676 if not vca:
tierno72774862020-05-04 11:44:15 +00004677 raise vimconn.VimConnConnectionException("self.connect() is failed")
bayramovef390722016-09-27 03:34:46 -07004678
4679 if vdc_name is None:
4680 return vm_dict
4681
4682 content = self.vms_view_action(vdc_name=vdc_name)
4683 try:
4684 vm_list_xmlroot = XmlElementTree.fromstring(content)
4685 for vm_xml in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004686 if (
4687 vm_xml.tag.split("}")[1] == "VMRecord"
4688 and vm_xml.attrib["isVAppTemplate"] == "false"
4689 ):
bayramovb6ffe792016-09-28 11:50:56 +04004690 # lookup done by UUID
bayramovef390722016-09-27 03:34:46 -07004691 if isuuid:
sousaedu80135b92021-02-17 15:05:18 +01004692 if vapp_name in vm_xml.attrib["container"]:
4693 rawuuid = vm_xml.attrib["href"].split("/")[-1:]
4694 if "vm-" in rawuuid[0]:
bayramovef390722016-09-27 03:34:46 -07004695 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
bayramovb6ffe792016-09-28 11:50:56 +04004696 break
4697 # lookup done by Name
4698 else:
sousaedu80135b92021-02-17 15:05:18 +01004699 if vapp_name in vm_xml.attrib["name"]:
4700 rawuuid = vm_xml.attrib["href"].split("/")[-1:]
4701 if "vm-" in rawuuid[0]:
bayramovb6ffe792016-09-28 11:50:56 +04004702 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
4703 break
beierlb22ce2d2019-12-12 12:09:51 -05004704 except Exception:
bayramovef390722016-09-27 03:34:46 -07004705 pass
4706
4707 return vm_dict
4708
4709 def get_network_action(self, network_uuid=None):
4710 """
4711 Method leverages vCloud director and query network based on network uuid
4712
4713 Args:
4714 vca - is active VCA connection.
4715 network_uuid - is a network uuid
4716
4717 Returns:
4718 The return XML respond
4719 """
bayramovef390722016-09-27 03:34:46 -07004720 if network_uuid is None:
4721 return None
4722
sousaedu80135b92021-02-17 15:05:18 +01004723 url_list = [self.url, "/api/network/", network_uuid]
4724 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07004725
kasarc5bf2932018-03-09 04:15:22 -08004726 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01004727 headers = {
4728 "Accept": "application/*+xml;version=" + API_VERSION,
4729 "x-vcloud-authorization": self.client._session.headers[
4730 "x-vcloud-authorization"
4731 ],
4732 }
4733 response = self.perform_request(
4734 req_type="GET", url=vm_list_rest_call, headers=headers
4735 )
bhangare1a0b97c2017-06-21 02:20:15 -07004736
beierlb22ce2d2019-12-12 12:09:51 -05004737 # Retry login if session expired & retry sending request
bhangare1a0b97c2017-06-21 02:20:15 -07004738 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01004739 response = self.retry_rest("GET", vm_list_rest_call)
bhangare1a0b97c2017-06-21 02:20:15 -07004740
bayramovef390722016-09-27 03:34:46 -07004741 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05004742 return response.text
bayramovef390722016-09-27 03:34:46 -07004743
4744 return None
4745
4746 def get_vcd_network(self, network_uuid=None):
4747 """
4748 Method retrieves available network from vCloud Director
4749
4750 Args:
4751 network_uuid - is VCD network UUID
4752
4753 Each element serialized as key : value pair
4754
4755 Following keys available for access. network_configuration['Gateway'}
4756 <Configuration>
4757 <IpScopes>
4758 <IpScope>
4759 <IsInherited>true</IsInherited>
4760 <Gateway>172.16.252.100</Gateway>
4761 <Netmask>255.255.255.0</Netmask>
4762 <Dns1>172.16.254.201</Dns1>
4763 <Dns2>172.16.254.202</Dns2>
4764 <DnsSuffix>vmwarelab.edu</DnsSuffix>
4765 <IsEnabled>true</IsEnabled>
4766 <IpRanges>
4767 <IpRange>
4768 <StartAddress>172.16.252.1</StartAddress>
4769 <EndAddress>172.16.252.99</EndAddress>
4770 </IpRange>
4771 </IpRanges>
4772 </IpScope>
4773 </IpScopes>
4774 <FenceMode>bridged</FenceMode>
4775
4776 Returns:
4777 The return dictionary and key for each entry vapp UUID
4778 """
bayramovef390722016-09-27 03:34:46 -07004779 network_configuration = {}
sousaedu80135b92021-02-17 15:05:18 +01004780
bayramovef390722016-09-27 03:34:46 -07004781 if network_uuid is None:
4782 return network_uuid
4783
bayramovef390722016-09-27 03:34:46 -07004784 try:
bhangarebfdca492017-03-11 01:32:46 -08004785 content = self.get_network_action(network_uuid=network_uuid)
kbsub3de27d62019-12-05 17:20:18 +00004786 if content is not None:
4787 vm_list_xmlroot = XmlElementTree.fromstring(content)
sousaedu80135b92021-02-17 15:05:18 +01004788 network_configuration["status"] = vm_list_xmlroot.get("status")
4789 network_configuration["name"] = vm_list_xmlroot.get("name")
4790 network_configuration["uuid"] = vm_list_xmlroot.get("id").split(":")[3]
bayramovef390722016-09-27 03:34:46 -07004791
kbsub3de27d62019-12-05 17:20:18 +00004792 for child in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004793 if child.tag.split("}")[1] == "IsShared":
4794 network_configuration["isShared"] = child.text.strip()
4795
4796 if child.tag.split("}")[1] == "Configuration":
kbsub3de27d62019-12-05 17:20:18 +00004797 for configuration in child.iter():
4798 tagKey = configuration.tag.split("}")[1].strip()
4799 if tagKey != "":
sousaedu80135b92021-02-17 15:05:18 +01004800 network_configuration[
4801 tagKey
4802 ] = configuration.text.strip()
beierlb22ce2d2019-12-12 12:09:51 -05004803 except Exception as exp:
bhangarebfdca492017-03-11 01:32:46 -08004804 self.logger.debug("get_vcd_network: Failed with Exception {}".format(exp))
sousaedu80135b92021-02-17 15:05:18 +01004805
4806 raise vimconn.VimConnException(
4807 "get_vcd_network: Failed with Exception {}".format(exp)
4808 )
bayramovef390722016-09-27 03:34:46 -07004809
4810 return network_configuration
4811
4812 def delete_network_action(self, network_uuid=None):
4813 """
4814 Method delete given network from vCloud director
4815
4816 Args:
4817 network_uuid - is a network uuid that client wish to delete
4818
4819 Returns:
4820 The return None or XML respond or false
4821 """
kasarc5bf2932018-03-09 04:15:22 -08004822 client = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01004823
kasarc5bf2932018-03-09 04:15:22 -08004824 if not client:
tierno72774862020-05-04 11:44:15 +00004825 raise vimconn.VimConnConnectionException("Failed to connect vCD as admin")
sousaedu80135b92021-02-17 15:05:18 +01004826
bayramovef390722016-09-27 03:34:46 -07004827 if network_uuid is None:
4828 return False
4829
sousaedu80135b92021-02-17 15:05:18 +01004830 url_list = [self.url, "/api/admin/network/", network_uuid]
4831 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07004832
kasarc5bf2932018-03-09 04:15:22 -08004833 if client._session:
sousaedu80135b92021-02-17 15:05:18 +01004834 headers = {
4835 "Accept": "application/*+xml;version=" + API_VERSION,
4836 "x-vcloud-authorization": client._session.headers[
4837 "x-vcloud-authorization"
4838 ],
4839 }
4840 response = self.perform_request(
4841 req_type="DELETE", url=vm_list_rest_call, headers=headers
4842 )
4843
bayramovef390722016-09-27 03:34:46 -07004844 if response.status_code == 202:
4845 return True
4846
4847 return False
4848
sousaedu80135b92021-02-17 15:05:18 +01004849 def create_network(
4850 self,
4851 network_name=None,
4852 net_type="bridge",
4853 parent_network_uuid=None,
4854 ip_profile=None,
4855 isshared="true",
4856 ):
bayramovef390722016-09-27 03:34:46 -07004857 """
4858 Method create network in vCloud director
4859
4860 Args:
4861 network_name - is network name to be created.
bhangare0e571a92017-01-12 04:02:23 -08004862 net_type - can be 'bridge','data','ptp','mgmt'.
4863 ip_profile is a dict containing the IP parameters of the network
4864 isshared - is a boolean
bayramovef390722016-09-27 03:34:46 -07004865 parent_network_uuid - is parent provider vdc network that will be used for mapping.
4866 It optional attribute. by default if no parent network indicate the first available will be used.
4867
4868 Returns:
4869 The return network uuid or return None
4870 """
sousaedu80135b92021-02-17 15:05:18 +01004871 new_network_name = [network_name, "-", str(uuid.uuid4())]
4872 content = self.create_network_rest(
4873 network_name="".join(new_network_name),
4874 ip_profile=ip_profile,
4875 net_type=net_type,
4876 parent_network_uuid=parent_network_uuid,
4877 isshared=isshared,
4878 )
bayramovef390722016-09-27 03:34:46 -07004879
bayramovef390722016-09-27 03:34:46 -07004880 if content is None:
4881 self.logger.debug("Failed create network {}.".format(network_name))
sousaedu80135b92021-02-17 15:05:18 +01004882
bayramovef390722016-09-27 03:34:46 -07004883 return None
4884
4885 try:
4886 vm_list_xmlroot = XmlElementTree.fromstring(content)
sousaedu80135b92021-02-17 15:05:18 +01004887 vcd_uuid = vm_list_xmlroot.get("id").split(":")
bayramovef390722016-09-27 03:34:46 -07004888 if len(vcd_uuid) == 4:
sousaedu80135b92021-02-17 15:05:18 +01004889 self.logger.info(
4890 "Created new network name: {} uuid: {}".format(
4891 network_name, vcd_uuid[3]
4892 )
4893 )
4894
bayramovef390722016-09-27 03:34:46 -07004895 return vcd_uuid[3]
beierlb22ce2d2019-12-12 12:09:51 -05004896 except Exception:
bayramovef390722016-09-27 03:34:46 -07004897 self.logger.debug("Failed create network {}".format(network_name))
sousaedu80135b92021-02-17 15:05:18 +01004898
bayramovef390722016-09-27 03:34:46 -07004899 return None
4900
sousaedu80135b92021-02-17 15:05:18 +01004901 def create_network_rest(
4902 self,
4903 network_name=None,
4904 net_type="bridge",
4905 parent_network_uuid=None,
4906 ip_profile=None,
4907 isshared="true",
4908 ):
bayramovef390722016-09-27 03:34:46 -07004909 """
4910 Method create network in vCloud director
4911
4912 Args:
4913 network_name - is network name to be created.
bhangare0e571a92017-01-12 04:02:23 -08004914 net_type - can be 'bridge','data','ptp','mgmt'.
4915 ip_profile is a dict containing the IP parameters of the network
4916 isshared - is a boolean
bayramovef390722016-09-27 03:34:46 -07004917 parent_network_uuid - is parent provider vdc network that will be used for mapping.
4918 It optional attribute. by default if no parent network indicate the first available will be used.
4919
4920 Returns:
4921 The return network uuid or return None
4922 """
kasarc5bf2932018-03-09 04:15:22 -08004923 client_as_admin = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01004924
kasarc5bf2932018-03-09 04:15:22 -08004925 if not client_as_admin:
tierno72774862020-05-04 11:44:15 +00004926 raise vimconn.VimConnConnectionException("Failed to connect vCD.")
sousaedu80135b92021-02-17 15:05:18 +01004927
bayramovef390722016-09-27 03:34:46 -07004928 if network_name is None:
4929 return None
4930
sousaedu80135b92021-02-17 15:05:18 +01004931 url_list = [self.url, "/api/admin/vdc/", self.tenant_id]
4932 vm_list_rest_call = "".join(url_list)
kasarc5bf2932018-03-09 04:15:22 -08004933
4934 if client_as_admin._session:
sousaedu80135b92021-02-17 15:05:18 +01004935 headers = {
4936 "Accept": "application/*+xml;version=" + API_VERSION,
4937 "x-vcloud-authorization": client_as_admin._session.headers[
4938 "x-vcloud-authorization"
4939 ],
4940 }
4941 response = self.perform_request(
4942 req_type="GET", url=vm_list_rest_call, headers=headers
4943 )
bayramovef390722016-09-27 03:34:46 -07004944 provider_network = None
4945 available_networks = None
4946 add_vdc_rest_url = None
4947
4948 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01004949 self.logger.debug(
4950 "REST API call {} failed. Return status code {}".format(
4951 vm_list_rest_call, response.status_code
4952 )
4953 )
4954
bayramovef390722016-09-27 03:34:46 -07004955 return None
4956 else:
4957 try:
beierl26fec002019-12-06 17:06:40 -05004958 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
bayramovef390722016-09-27 03:34:46 -07004959 for child in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01004960 if child.tag.split("}")[1] == "ProviderVdcReference":
4961 provider_network = child.attrib.get("href")
bayramovef390722016-09-27 03:34:46 -07004962 # application/vnd.vmware.admin.providervdc+xml
sousaedu80135b92021-02-17 15:05:18 +01004963
4964 if child.tag.split("}")[1] == "Link":
4965 if (
4966 child.attrib.get("type")
4967 == "application/vnd.vmware.vcloud.orgVdcNetwork+xml"
4968 and child.attrib.get("rel") == "add"
4969 ):
4970 add_vdc_rest_url = child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05004971 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01004972 self.logger.debug(
4973 "Failed parse respond for rest api call {}".format(
4974 vm_list_rest_call
4975 )
4976 )
beierl26fec002019-12-06 17:06:40 -05004977 self.logger.debug("Respond body {}".format(response.text))
sousaedu80135b92021-02-17 15:05:18 +01004978
bayramovef390722016-09-27 03:34:46 -07004979 return None
4980
4981 # find pvdc provided available network
sousaedu80135b92021-02-17 15:05:18 +01004982 response = self.perform_request(
4983 req_type="GET", url=provider_network, headers=headers
4984 )
kbsuba85c54d2019-10-17 16:30:32 +00004985
bayramovef390722016-09-27 03:34:46 -07004986 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01004987 self.logger.debug(
4988 "REST API call {} failed. Return status code {}".format(
4989 vm_list_rest_call, response.status_code
4990 )
4991 )
4992
bayramovef390722016-09-27 03:34:46 -07004993 return None
4994
bayramovef390722016-09-27 03:34:46 -07004995 if parent_network_uuid is None:
4996 try:
beierl26fec002019-12-06 17:06:40 -05004997 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
bayramovef390722016-09-27 03:34:46 -07004998 for child in vm_list_xmlroot.iter():
sousaedu80135b92021-02-17 15:05:18 +01004999 if child.tag.split("}")[1] == "AvailableNetworks":
bayramovef390722016-09-27 03:34:46 -07005000 for networks in child.iter():
5001 # application/vnd.vmware.admin.network+xml
sousaedu80135b92021-02-17 15:05:18 +01005002 if networks.attrib.get("href") is not None:
5003 available_networks = networks.attrib.get("href")
bayramovef390722016-09-27 03:34:46 -07005004 break
beierlb22ce2d2019-12-12 12:09:51 -05005005 except Exception:
bayramovef390722016-09-27 03:34:46 -07005006 return None
5007
bhangarebfdca492017-03-11 01:32:46 -08005008 try:
beierlb22ce2d2019-12-12 12:09:51 -05005009 # Configure IP profile of the network
sousaedu80135b92021-02-17 15:05:18 +01005010 ip_profile = (
5011 ip_profile if ip_profile is not None else DEFAULT_IP_PROFILE
5012 )
bhangare0e571a92017-01-12 04:02:23 -08005013
sousaedu80135b92021-02-17 15:05:18 +01005014 if (
5015 "subnet_address" not in ip_profile
5016 or ip_profile["subnet_address"] is None
5017 ):
kasarde691232017-03-25 03:37:31 -07005018 subnet_rand = random.randint(0, 255)
5019 ip_base = "192.168.{}.".format(subnet_rand)
sousaedu80135b92021-02-17 15:05:18 +01005020 ip_profile["subnet_address"] = ip_base + "0/24"
kasarde691232017-03-25 03:37:31 -07005021 else:
sousaedu80135b92021-02-17 15:05:18 +01005022 ip_base = ip_profile["subnet_address"].rsplit(".", 1)[0] + "."
kasarde691232017-03-25 03:37:31 -07005023
sousaedu80135b92021-02-17 15:05:18 +01005024 if (
5025 "gateway_address" not in ip_profile
5026 or ip_profile["gateway_address"] is None
5027 ):
5028 ip_profile["gateway_address"] = ip_base + "1"
bhangare0e571a92017-01-12 04:02:23 -08005029
sousaedu80135b92021-02-17 15:05:18 +01005030 if "dhcp_count" not in ip_profile or ip_profile["dhcp_count"] is None:
5031 ip_profile["dhcp_count"] = DEFAULT_IP_PROFILE["dhcp_count"]
bhangare0e571a92017-01-12 04:02:23 -08005032
sousaedu80135b92021-02-17 15:05:18 +01005033 if (
5034 "dhcp_enabled" not in ip_profile
5035 or ip_profile["dhcp_enabled"] is None
5036 ):
5037 ip_profile["dhcp_enabled"] = DEFAULT_IP_PROFILE["dhcp_enabled"]
5038
5039 if (
5040 "dhcp_start_address" not in ip_profile
5041 or ip_profile["dhcp_start_address"] is None
5042 ):
5043 ip_profile["dhcp_start_address"] = ip_base + "3"
5044
5045 if "ip_version" not in ip_profile or ip_profile["ip_version"] is None:
5046 ip_profile["ip_version"] = DEFAULT_IP_PROFILE["ip_version"]
5047
5048 if "dns_address" not in ip_profile or ip_profile["dns_address"] is None:
5049 ip_profile["dns_address"] = ip_base + "2"
5050
5051 gateway_address = ip_profile["gateway_address"]
5052 dhcp_count = int(ip_profile["dhcp_count"])
5053 subnet_address = self.convert_cidr_to_netmask(
5054 ip_profile["subnet_address"]
5055 )
5056
5057 if ip_profile["dhcp_enabled"] is True:
5058 dhcp_enabled = "true"
bhangarebfdca492017-03-11 01:32:46 -08005059 else:
sousaedu80135b92021-02-17 15:05:18 +01005060 dhcp_enabled = "false"
5061
5062 dhcp_start_address = ip_profile["dhcp_start_address"]
bhangare0e571a92017-01-12 04:02:23 -08005063
beierlb22ce2d2019-12-12 12:09:51 -05005064 # derive dhcp_end_address from dhcp_start_address & dhcp_count
bhangarebfdca492017-03-11 01:32:46 -08005065 end_ip_int = int(netaddr.IPAddress(dhcp_start_address))
5066 end_ip_int += dhcp_count - 1
5067 dhcp_end_address = str(netaddr.IPAddress(end_ip_int))
5068
beierlb22ce2d2019-12-12 12:09:51 -05005069 # ip_version = ip_profile['ip_version']
sousaedu80135b92021-02-17 15:05:18 +01005070 dns_address = ip_profile["dns_address"]
bhangarebfdca492017-03-11 01:32:46 -08005071 except KeyError as exp:
5072 self.logger.debug("Create Network REST: Key error {}".format(exp))
sousaedu80135b92021-02-17 15:05:18 +01005073
5074 raise vimconn.VimConnException(
5075 "Create Network REST: Key error{}".format(exp)
5076 )
bhangare0e571a92017-01-12 04:02:23 -08005077
bayramovef390722016-09-27 03:34:46 -07005078 # either use client provided UUID or search for a first available
5079 # if both are not defined we return none
5080 if parent_network_uuid is not None:
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00005081 provider_network = None
5082 available_networks = None
5083 add_vdc_rest_url = None
sousaedu80135b92021-02-17 15:05:18 +01005084 url_list = [self.url, "/api/admin/vdc/", self.tenant_id, "/networks"]
5085 add_vdc_rest_url = "".join(url_list)
5086 url_list = [self.url, "/api/admin/network/", parent_network_uuid]
5087 available_networks = "".join(url_list)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00005088
beierlb22ce2d2019-12-12 12:09:51 -05005089 # Creating all networks as Direct Org VDC type networks.
5090 # Unused in case of Underlay (data/ptp) network interface.
5091 fence_mode = "isolated"
sousaedu80135b92021-02-17 15:05:18 +01005092 is_inherited = "false"
tierno455612d2017-05-30 16:40:10 +02005093 dns_list = dns_address.split(";")
5094 dns1 = dns_list[0]
5095 dns2_text = ""
sousaedu80135b92021-02-17 15:05:18 +01005096
tierno455612d2017-05-30 16:40:10 +02005097 if len(dns_list) >= 2:
sousaedu80135b92021-02-17 15:05:18 +01005098 dns2_text = "\n <Dns2>{}</Dns2>\n".format(
5099 dns_list[1]
5100 )
5101
kbsuba85c54d2019-10-17 16:30:32 +00005102 if net_type == "isolated":
beierlb22ce2d2019-12-12 12:09:51 -05005103 fence_mode = "isolated"
kbsuba85c54d2019-10-17 16:30:32 +00005104 data = """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
5105 <Description>Openmano created</Description>
5106 <Configuration>
5107 <IpScopes>
5108 <IpScope>
5109 <IsInherited>{1:s}</IsInherited>
5110 <Gateway>{2:s}</Gateway>
5111 <Netmask>{3:s}</Netmask>
5112 <Dns1>{4:s}</Dns1>{5:s}
5113 <IsEnabled>{6:s}</IsEnabled>
5114 <IpRanges>
5115 <IpRange>
5116 <StartAddress>{7:s}</StartAddress>
5117 <EndAddress>{8:s}</EndAddress>
5118 </IpRange>
5119 </IpRanges>
5120 </IpScope>
5121 </IpScopes>
5122 <FenceMode>{9:s}</FenceMode>
5123 </Configuration>
5124 <IsShared>{10:s}</IsShared>
sousaedu80135b92021-02-17 15:05:18 +01005125 </OrgVdcNetwork> """.format(
5126 escape(network_name),
5127 is_inherited,
5128 gateway_address,
5129 subnet_address,
5130 dns1,
5131 dns2_text,
5132 dhcp_enabled,
5133 dhcp_start_address,
5134 dhcp_end_address,
5135 fence_mode,
5136 isshared,
5137 )
kbsuba85c54d2019-10-17 16:30:32 +00005138 else:
5139 fence_mode = "bridged"
5140 data = """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
5141 <Description>Openmano created</Description>
5142 <Configuration>
5143 <IpScopes>
5144 <IpScope>
5145 <IsInherited>{1:s}</IsInherited>
5146 <Gateway>{2:s}</Gateway>
5147 <Netmask>{3:s}</Netmask>
5148 <Dns1>{4:s}</Dns1>{5:s}
5149 <IsEnabled>{6:s}</IsEnabled>
5150 <IpRanges>
5151 <IpRange>
5152 <StartAddress>{7:s}</StartAddress>
5153 <EndAddress>{8:s}</EndAddress>
5154 </IpRange>
5155 </IpRanges>
5156 </IpScope>
5157 </IpScopes>
5158 <ParentNetwork href="{9:s}"/>
5159 <FenceMode>{10:s}</FenceMode>
5160 </Configuration>
5161 <IsShared>{11:s}</IsShared>
sousaedu80135b92021-02-17 15:05:18 +01005162 </OrgVdcNetwork> """.format(
5163 escape(network_name),
5164 is_inherited,
5165 gateway_address,
5166 subnet_address,
5167 dns1,
5168 dns2_text,
5169 dhcp_enabled,
5170 dhcp_start_address,
5171 dhcp_end_address,
5172 available_networks,
5173 fence_mode,
5174 isshared,
5175 )
bayramovef390722016-09-27 03:34:46 -07005176
sousaedu80135b92021-02-17 15:05:18 +01005177 headers["Content-Type"] = "application/vnd.vmware.vcloud.orgVdcNetwork+xml"
bhangare0e571a92017-01-12 04:02:23 -08005178 try:
sousaedu80135b92021-02-17 15:05:18 +01005179 response = self.perform_request(
5180 req_type="POST", url=add_vdc_rest_url, headers=headers, data=data
5181 )
bayramovef390722016-09-27 03:34:46 -07005182
bhangare0e571a92017-01-12 04:02:23 -08005183 if response.status_code != 201:
sousaedu80135b92021-02-17 15:05:18 +01005184 self.logger.debug(
5185 "Create Network POST REST API call failed. "
5186 "Return status code {}, response.text: {}".format(
5187 response.status_code, response.text
5188 )
5189 )
bhangare0e571a92017-01-12 04:02:23 -08005190 else:
beierl26fec002019-12-06 17:06:40 -05005191 network_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01005192 self.logger.debug(
5193 "Create Network REST : Waiting for Network creation complete"
5194 )
kasarc5bf2932018-03-09 04:15:22 -08005195 time.sleep(5)
sousaedu80135b92021-02-17 15:05:18 +01005196 result = self.client.get_task_monitor().wait_for_success(
5197 task=network_task
5198 )
5199
5200 if result.get("status") == "success":
beierl26fec002019-12-06 17:06:40 -05005201 return response.text
kasarc5bf2932018-03-09 04:15:22 -08005202 else:
sousaedu80135b92021-02-17 15:05:18 +01005203 self.logger.debug(
5204 "create_network_rest task failed. Network Create response : {}".format(
5205 response.text
5206 )
5207 )
bhangare0e571a92017-01-12 04:02:23 -08005208 except Exception as exp:
5209 self.logger.debug("create_network_rest : Exception : {} ".format(exp))
5210
5211 return None
5212
5213 def convert_cidr_to_netmask(self, cidr_ip=None):
5214 """
5215 Method sets convert CIDR netmask address to normal IP format
5216 Args:
5217 cidr_ip : CIDR IP address
5218 Returns:
5219 netmask : Converted netmask
5220 """
5221 if cidr_ip is not None:
sousaedu80135b92021-02-17 15:05:18 +01005222 if "/" in cidr_ip:
5223 _, net_bits = cidr_ip.split("/")
5224 netmask = socket.inet_ntoa(
5225 struct.pack(">I", (0xFFFFFFFF << (32 - int(net_bits))) & 0xFFFFFFFF)
5226 )
bhangare0e571a92017-01-12 04:02:23 -08005227 else:
5228 netmask = cidr_ip
sousaedu80135b92021-02-17 15:05:18 +01005229
bhangare0e571a92017-01-12 04:02:23 -08005230 return netmask
sousaedu80135b92021-02-17 15:05:18 +01005231
bayramovef390722016-09-27 03:34:46 -07005232 return None
5233
5234 def get_provider_rest(self, vca=None):
5235 """
5236 Method gets provider vdc view from vcloud director
5237
5238 Args:
5239 network_name - is network name to be created.
5240 parent_network_uuid - is parent provider vdc network that will be used for mapping.
5241 It optional attribute. by default if no parent network indicate the first available will be used.
5242
5243 Returns:
5244 The return xml content of respond or None
5245 """
sousaedu80135b92021-02-17 15:05:18 +01005246 url_list = [self.url, "/api/admin"]
bayramovef390722016-09-27 03:34:46 -07005247
kasarc5bf2932018-03-09 04:15:22 -08005248 if vca:
sousaedu80135b92021-02-17 15:05:18 +01005249 headers = {
5250 "Accept": "application/*+xml;version=" + API_VERSION,
5251 "x-vcloud-authorization": self.client._session.headers[
5252 "x-vcloud-authorization"
5253 ],
5254 }
5255 response = self.perform_request(
5256 req_type="GET", url="".join(url_list), headers=headers
5257 )
bayramovef390722016-09-27 03:34:46 -07005258
5259 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05005260 return response.text
sousaedu80135b92021-02-17 15:05:18 +01005261
bayramovef390722016-09-27 03:34:46 -07005262 return None
5263
5264 def create_vdc(self, vdc_name=None):
bayramovef390722016-09-27 03:34:46 -07005265 vdc_dict = {}
bayramovef390722016-09-27 03:34:46 -07005266 xml_content = self.create_vdc_from_tmpl_rest(vdc_name=vdc_name)
sousaedu80135b92021-02-17 15:05:18 +01005267
bayramovef390722016-09-27 03:34:46 -07005268 if xml_content is not None:
bayramovef390722016-09-27 03:34:46 -07005269 try:
5270 task_resp_xmlroot = XmlElementTree.fromstring(xml_content)
5271 for child in task_resp_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01005272 if child.tag.split("}")[1] == "Owner":
5273 vdc_id = child.attrib.get("href").split("/")[-1]
5274 vdc_dict[vdc_id] = task_resp_xmlroot.get("href")
5275
bayramovef390722016-09-27 03:34:46 -07005276 return vdc_dict
beierlb22ce2d2019-12-12 12:09:51 -05005277 except Exception:
bayramovef390722016-09-27 03:34:46 -07005278 self.logger.debug("Respond body {}".format(xml_content))
5279
5280 return None
5281
5282 def create_vdc_from_tmpl_rest(self, vdc_name=None):
5283 """
5284 Method create vdc in vCloud director based on VDC template.
kasarc5bf2932018-03-09 04:15:22 -08005285 it uses pre-defined template.
bayramovef390722016-09-27 03:34:46 -07005286
5287 Args:
5288 vdc_name - name of a new vdc.
5289
5290 Returns:
5291 The return xml content of respond or None
5292 """
kasarc5bf2932018-03-09 04:15:22 -08005293 # pre-requesite atleast one vdc template should be available in vCD
bayramovef390722016-09-27 03:34:46 -07005294 self.logger.info("Creating new vdc {}".format(vdc_name))
kasarc5bf2932018-03-09 04:15:22 -08005295 vca = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01005296
bayramovef390722016-09-27 03:34:46 -07005297 if not vca:
tierno72774862020-05-04 11:44:15 +00005298 raise vimconn.VimConnConnectionException("Failed to connect vCD")
sousaedu80135b92021-02-17 15:05:18 +01005299
bayramovef390722016-09-27 03:34:46 -07005300 if vdc_name is None:
5301 return None
5302
sousaedu80135b92021-02-17 15:05:18 +01005303 url_list = [self.url, "/api/vdcTemplates"]
5304 vm_list_rest_call = "".join(url_list)
5305 headers = {
5306 "Accept": "application/*+xml;version=" + API_VERSION,
5307 "x-vcloud-authorization": vca._session.headers["x-vcloud-authorization"],
5308 }
5309 response = self.perform_request(
5310 req_type="GET", url=vm_list_rest_call, headers=headers
5311 )
bayramovef390722016-09-27 03:34:46 -07005312
5313 # container url to a template
5314 vdc_template_ref = None
5315 try:
beierl26fec002019-12-06 17:06:40 -05005316 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
bayramovef390722016-09-27 03:34:46 -07005317 for child in vm_list_xmlroot:
5318 # application/vnd.vmware.admin.providervdc+xml
5319 # we need find a template from witch we instantiate VDC
sousaedu80135b92021-02-17 15:05:18 +01005320 if child.tag.split("}")[1] == "VdcTemplate":
5321 if (
5322 child.attrib.get("type")
5323 == "application/vnd.vmware.admin.vdcTemplate+xml"
5324 ):
5325 vdc_template_ref = child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05005326 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01005327 self.logger.debug(
5328 "Failed parse respond for rest api call {}".format(vm_list_rest_call)
5329 )
beierl26fec002019-12-06 17:06:40 -05005330 self.logger.debug("Respond body {}".format(response.text))
sousaedu80135b92021-02-17 15:05:18 +01005331
bayramovef390722016-09-27 03:34:46 -07005332 return None
5333
5334 # if we didn't found required pre defined template we return None
5335 if vdc_template_ref is None:
5336 return None
5337
5338 try:
5339 # instantiate vdc
sousaedu80135b92021-02-17 15:05:18 +01005340 url_list = [self.url, "/api/org/", self.org_uuid, "/action/instantiate"]
5341 vm_list_rest_call = "".join(url_list)
bayramovef390722016-09-27 03:34:46 -07005342 data = """<InstantiateVdcTemplateParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
5343 <Source href="{1:s}"></Source>
5344 <Description>opnemano</Description>
sousaedu80135b92021-02-17 15:05:18 +01005345 </InstantiateVdcTemplateParams>""".format(
5346 vdc_name, vdc_template_ref
5347 )
5348 headers[
5349 "Content-Type"
5350 ] = "application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml"
5351 response = self.perform_request(
5352 req_type="POST", url=vm_list_rest_call, headers=headers, data=data
5353 )
beierl26fec002019-12-06 17:06:40 -05005354 vdc_task = self.get_task_from_response(response.text)
kasarc5bf2932018-03-09 04:15:22 -08005355 self.client.get_task_monitor().wait_for_success(task=vdc_task)
kated47ad5f2017-08-03 02:16:13 -07005356
bayramovef390722016-09-27 03:34:46 -07005357 # if we all ok we respond with content otherwise by default None
5358 if response.status_code >= 200 and response.status_code < 300:
beierl26fec002019-12-06 17:06:40 -05005359 return response.text
sousaedu80135b92021-02-17 15:05:18 +01005360
bayramovef390722016-09-27 03:34:46 -07005361 return None
beierlb22ce2d2019-12-12 12:09:51 -05005362 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01005363 self.logger.debug(
5364 "Failed parse respond for rest api call {}".format(vm_list_rest_call)
5365 )
beierl26fec002019-12-06 17:06:40 -05005366 self.logger.debug("Respond body {}".format(response.text))
bayramovef390722016-09-27 03:34:46 -07005367
5368 return None
5369
5370 def create_vdc_rest(self, vdc_name=None):
5371 """
5372 Method create network in vCloud director
5373
5374 Args:
kasarc5bf2932018-03-09 04:15:22 -08005375 vdc_name - vdc name to be created
bayramovef390722016-09-27 03:34:46 -07005376 Returns:
kasarc5bf2932018-03-09 04:15:22 -08005377 The return response
bayramovef390722016-09-27 03:34:46 -07005378 """
bayramovef390722016-09-27 03:34:46 -07005379 self.logger.info("Creating new vdc {}".format(vdc_name))
bayramovef390722016-09-27 03:34:46 -07005380 vca = self.connect_as_admin()
sousaedu80135b92021-02-17 15:05:18 +01005381
bayramovef390722016-09-27 03:34:46 -07005382 if not vca:
tierno72774862020-05-04 11:44:15 +00005383 raise vimconn.VimConnConnectionException("Failed to connect vCD")
sousaedu80135b92021-02-17 15:05:18 +01005384
bayramovef390722016-09-27 03:34:46 -07005385 if vdc_name is None:
5386 return None
5387
sousaedu80135b92021-02-17 15:05:18 +01005388 url_list = [self.url, "/api/admin/org/", self.org_uuid]
5389 vm_list_rest_call = "".join(url_list)
kasarc5bf2932018-03-09 04:15:22 -08005390
5391 if vca._session:
sousaedu80135b92021-02-17 15:05:18 +01005392 headers = {
5393 "Accept": "application/*+xml;version=" + API_VERSION,
5394 "x-vcloud-authorization": self.client._session.headers[
5395 "x-vcloud-authorization"
5396 ],
5397 }
5398 response = self.perform_request(
5399 req_type="GET", url=vm_list_rest_call, headers=headers
5400 )
bayramovef390722016-09-27 03:34:46 -07005401 provider_vdc_ref = None
5402 add_vdc_rest_url = None
beierlb22ce2d2019-12-12 12:09:51 -05005403 # available_networks = None
bayramovef390722016-09-27 03:34:46 -07005404
5405 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01005406 self.logger.debug(
5407 "REST API call {} failed. Return status code {}".format(
5408 vm_list_rest_call, response.status_code
5409 )
5410 )
5411
bayramovef390722016-09-27 03:34:46 -07005412 return None
5413 else:
5414 try:
beierl26fec002019-12-06 17:06:40 -05005415 vm_list_xmlroot = XmlElementTree.fromstring(response.text)
bayramovef390722016-09-27 03:34:46 -07005416 for child in vm_list_xmlroot:
5417 # application/vnd.vmware.admin.providervdc+xml
sousaedu80135b92021-02-17 15:05:18 +01005418 if child.tag.split("}")[1] == "Link":
5419 if (
5420 child.attrib.get("type")
5421 == "application/vnd.vmware.admin.createVdcParams+xml"
5422 and child.attrib.get("rel") == "add"
5423 ):
5424 add_vdc_rest_url = child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05005425 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01005426 self.logger.debug(
5427 "Failed parse respond for rest api call {}".format(
5428 vm_list_rest_call
5429 )
5430 )
beierl26fec002019-12-06 17:06:40 -05005431 self.logger.debug("Respond body {}".format(response.text))
sousaedu80135b92021-02-17 15:05:18 +01005432
bayramovef390722016-09-27 03:34:46 -07005433 return None
5434
5435 response = self.get_provider_rest(vca=vca)
bayramovef390722016-09-27 03:34:46 -07005436 try:
5437 vm_list_xmlroot = XmlElementTree.fromstring(response)
5438 for child in vm_list_xmlroot:
sousaedu80135b92021-02-17 15:05:18 +01005439 if child.tag.split("}")[1] == "ProviderVdcReferences":
bayramovef390722016-09-27 03:34:46 -07005440 for sub_child in child:
sousaedu80135b92021-02-17 15:05:18 +01005441 provider_vdc_ref = sub_child.attrib.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05005442 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01005443 self.logger.debug(
5444 "Failed parse respond for rest api call {}".format(
5445 vm_list_rest_call
5446 )
5447 )
bayramovef390722016-09-27 03:34:46 -07005448 self.logger.debug("Respond body {}".format(response))
sousaedu80135b92021-02-17 15:05:18 +01005449
bayramovef390722016-09-27 03:34:46 -07005450 return None
5451
bayramovef390722016-09-27 03:34:46 -07005452 if add_vdc_rest_url is not None and provider_vdc_ref is not None:
5453 data = """ <CreateVdcParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5"><Description>{1:s}</Description>
5454 <AllocationModel>ReservationPool</AllocationModel>
5455 <ComputeCapacity><Cpu><Units>MHz</Units><Allocated>2048</Allocated><Limit>2048</Limit></Cpu>
5456 <Memory><Units>MB</Units><Allocated>2048</Allocated><Limit>2048</Limit></Memory>
5457 </ComputeCapacity><NicQuota>0</NicQuota><NetworkQuota>100</NetworkQuota>
5458 <VdcStorageProfile><Enabled>true</Enabled><Units>MB</Units><Limit>20480</Limit><Default>true</Default></VdcStorageProfile>
5459 <ProviderVdcReference
5460 name="Main Provider"
5461 href="{2:s}" />
sousaedu80135b92021-02-17 15:05:18 +01005462 <UsesFastProvisioning>true</UsesFastProvisioning></CreateVdcParams>""".format(
5463 escape(vdc_name), escape(vdc_name), provider_vdc_ref
5464 )
5465 headers[
5466 "Content-Type"
5467 ] = "application/vnd.vmware.admin.createVdcParams+xml"
5468 response = self.perform_request(
5469 req_type="POST",
5470 url=add_vdc_rest_url,
5471 headers=headers,
5472 data=data,
5473 )
bayramovef390722016-09-27 03:34:46 -07005474
bayramovef390722016-09-27 03:34:46 -07005475 # if we all ok we respond with content otherwise by default None
5476 if response.status_code == 201:
beierl26fec002019-12-06 17:06:40 -05005477 return response.text
sousaedu80135b92021-02-17 15:05:18 +01005478
bayramovef390722016-09-27 03:34:46 -07005479 return None
bayramovfe3f3c92016-10-04 07:53:41 +04005480
bhangarefda5f7c2017-01-12 23:50:34 -08005481 def get_vapp_details_rest(self, vapp_uuid=None, need_admin_access=False):
bayramovfe3f3c92016-10-04 07:53:41 +04005482 """
5483 Method retrieve vapp detail from vCloud director
5484
5485 Args:
5486 vapp_uuid - is vapp identifier.
5487
5488 Returns:
5489 The return network uuid or return None
5490 """
bayramovfe3f3c92016-10-04 07:53:41 +04005491 parsed_respond = {}
bhangarefda5f7c2017-01-12 23:50:34 -08005492 vca = None
bayramovfe3f3c92016-10-04 07:53:41 +04005493
bhangarefda5f7c2017-01-12 23:50:34 -08005494 if need_admin_access:
5495 vca = self.connect_as_admin()
5496 else:
sbhangarea8e5b782018-06-21 02:10:03 -07005497 vca = self.client
bhangarefda5f7c2017-01-12 23:50:34 -08005498
bayramovfe3f3c92016-10-04 07:53:41 +04005499 if not vca:
tierno72774862020-05-04 11:44:15 +00005500 raise vimconn.VimConnConnectionException("Failed to connect vCD")
bayramovfe3f3c92016-10-04 07:53:41 +04005501 if vapp_uuid is None:
5502 return None
5503
sousaedu80135b92021-02-17 15:05:18 +01005504 url_list = [self.url, "/api/vApp/vapp-", vapp_uuid]
5505 get_vapp_restcall = "".join(url_list)
bhangarefda5f7c2017-01-12 23:50:34 -08005506
kasarc5bf2932018-03-09 04:15:22 -08005507 if vca._session:
sousaedu80135b92021-02-17 15:05:18 +01005508 headers = {
5509 "Accept": "application/*+xml;version=" + API_VERSION,
5510 "x-vcloud-authorization": vca._session.headers[
5511 "x-vcloud-authorization"
5512 ],
5513 }
5514 response = self.perform_request(
5515 req_type="GET", url=get_vapp_restcall, headers=headers
5516 )
bayramovfe3f3c92016-10-04 07:53:41 +04005517
bhangare1a0b97c2017-06-21 02:20:15 -07005518 if response.status_code == 403:
beierlb22ce2d2019-12-12 12:09:51 -05005519 if need_admin_access is False:
sousaedu80135b92021-02-17 15:05:18 +01005520 response = self.retry_rest("GET", get_vapp_restcall)
bhangare1a0b97c2017-06-21 02:20:15 -07005521
bayramovfe3f3c92016-10-04 07:53:41 +04005522 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01005523 self.logger.debug(
5524 "REST API call {} failed. Return status code {}".format(
5525 get_vapp_restcall, response.status_code
5526 )
5527 )
5528
bayramovfe3f3c92016-10-04 07:53:41 +04005529 return parsed_respond
5530
5531 try:
beierl26fec002019-12-06 17:06:40 -05005532 xmlroot_respond = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01005533 parsed_respond["ovfDescriptorUploaded"] = xmlroot_respond.attrib[
5534 "ovfDescriptorUploaded"
5535 ]
beierlb22ce2d2019-12-12 12:09:51 -05005536 namespaces = {
5537 "vssd": "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData",
sousaedu80135b92021-02-17 15:05:18 +01005538 "ovf": "http://schemas.dmtf.org/ovf/envelope/1",
5539 "vmw": "http://www.vmware.com/schema/ovf",
5540 "vm": "http://www.vmware.com/vcloud/v1.5",
5541 "rasd": "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
beierlb22ce2d2019-12-12 12:09:51 -05005542 "vmext": "http://www.vmware.com/vcloud/extension/v1.5",
sousaedu80135b92021-02-17 15:05:18 +01005543 "xmlns": "http://www.vmware.com/vcloud/v1.5",
beierlb22ce2d2019-12-12 12:09:51 -05005544 }
bayramovfe3f3c92016-10-04 07:53:41 +04005545
sousaedu80135b92021-02-17 15:05:18 +01005546 created_section = xmlroot_respond.find("vm:DateCreated", namespaces)
bayramovfe3f3c92016-10-04 07:53:41 +04005547 if created_section is not None:
sousaedu80135b92021-02-17 15:05:18 +01005548 parsed_respond["created"] = created_section.text
bayramovfe3f3c92016-10-04 07:53:41 +04005549
sousaedu80135b92021-02-17 15:05:18 +01005550 network_section = xmlroot_respond.find(
5551 "vm:NetworkConfigSection/vm:NetworkConfig", namespaces
5552 )
5553 if (
5554 network_section is not None
5555 and "networkName" in network_section.attrib
5556 ):
5557 parsed_respond["networkname"] = network_section.attrib[
5558 "networkName"
5559 ]
bayramovfe3f3c92016-10-04 07:53:41 +04005560
sousaedu80135b92021-02-17 15:05:18 +01005561 ipscopes_section = xmlroot_respond.find(
5562 "vm:NetworkConfigSection/vm:NetworkConfig/vm:Configuration/vm:IpScopes",
5563 namespaces,
5564 )
bayramovfe3f3c92016-10-04 07:53:41 +04005565 if ipscopes_section is not None:
5566 for ipscope in ipscopes_section:
5567 for scope in ipscope:
5568 tag_key = scope.tag.split("}")[1]
sousaedu80135b92021-02-17 15:05:18 +01005569 if tag_key == "IpRanges":
bayramovfe3f3c92016-10-04 07:53:41 +04005570 ip_ranges = scope.getchildren()
5571 for ipblock in ip_ranges:
5572 for block in ipblock:
sousaedu80135b92021-02-17 15:05:18 +01005573 parsed_respond[
5574 block.tag.split("}")[1]
5575 ] = block.text
bayramovfe3f3c92016-10-04 07:53:41 +04005576 else:
5577 parsed_respond[tag_key] = scope.text
5578
5579 # parse children section for other attrib
sousaedu80135b92021-02-17 15:05:18 +01005580 children_section = xmlroot_respond.find("vm:Children/", namespaces)
bayramovfe3f3c92016-10-04 07:53:41 +04005581 if children_section is not None:
sousaedu80135b92021-02-17 15:05:18 +01005582 parsed_respond["name"] = children_section.attrib["name"]
5583 parsed_respond["nestedHypervisorEnabled"] = (
5584 children_section.attrib["nestedHypervisorEnabled"]
5585 if "nestedHypervisorEnabled" in children_section.attrib
5586 else None
5587 )
5588 parsed_respond["deployed"] = children_section.attrib["deployed"]
5589 parsed_respond["status"] = children_section.attrib["status"]
5590 parsed_respond["vmuuid"] = children_section.attrib["id"].split(":")[
5591 -1
5592 ]
5593 network_adapter = children_section.find(
5594 "vm:NetworkConnectionSection", namespaces
5595 )
bayramovfe3f3c92016-10-04 07:53:41 +04005596 nic_list = []
5597 for adapters in network_adapter:
5598 adapter_key = adapters.tag.split("}")[1]
sousaedu80135b92021-02-17 15:05:18 +01005599 if adapter_key == "PrimaryNetworkConnectionIndex":
5600 parsed_respond["primarynetwork"] = adapters.text
5601
5602 if adapter_key == "NetworkConnection":
bayramovfe3f3c92016-10-04 07:53:41 +04005603 vnic = {}
sousaedu80135b92021-02-17 15:05:18 +01005604 if "network" in adapters.attrib:
5605 vnic["network"] = adapters.attrib["network"]
bayramovfe3f3c92016-10-04 07:53:41 +04005606 for adapter in adapters:
5607 setting_key = adapter.tag.split("}")[1]
5608 vnic[setting_key] = adapter.text
5609 nic_list.append(vnic)
5610
5611 for link in children_section:
sousaedu80135b92021-02-17 15:05:18 +01005612 if link.tag.split("}")[1] == "Link" and "rel" in link.attrib:
5613 if link.attrib["rel"] == "screen:acquireTicket":
5614 parsed_respond["acquireTicket"] = link.attrib
bayramovfe3f3c92016-10-04 07:53:41 +04005615
sousaedu80135b92021-02-17 15:05:18 +01005616 if link.attrib["rel"] == "screen:acquireMksTicket":
5617 parsed_respond["acquireMksTicket"] = link.attrib
5618
5619 parsed_respond["interfaces"] = nic_list
5620 vCloud_extension_section = children_section.find(
5621 "xmlns:VCloudExtension", namespaces
5622 )
bhangarefda5f7c2017-01-12 23:50:34 -08005623 if vCloud_extension_section is not None:
5624 vm_vcenter_info = {}
sousaedu80135b92021-02-17 15:05:18 +01005625 vim_info = vCloud_extension_section.find(
5626 "vmext:VmVimInfo", namespaces
5627 )
5628 vmext = vim_info.find("vmext:VmVimObjectRef", namespaces)
5629
bhangarefda5f7c2017-01-12 23:50:34 -08005630 if vmext is not None:
sousaedu80135b92021-02-17 15:05:18 +01005631 vm_vcenter_info["vm_moref_id"] = vmext.find(
5632 "vmext:MoRef", namespaces
5633 ).text
5634
beierlb22ce2d2019-12-12 12:09:51 -05005635 parsed_respond["vm_vcenter_info"] = vm_vcenter_info
bayramovfe3f3c92016-10-04 07:53:41 +04005636
sousaedu80135b92021-02-17 15:05:18 +01005637 virtual_hardware_section = children_section.find(
5638 "ovf:VirtualHardwareSection", namespaces
5639 )
bhangarea92ae392017-01-12 22:30:29 -08005640 vm_virtual_hardware_info = {}
5641 if virtual_hardware_section is not None:
sousaedu80135b92021-02-17 15:05:18 +01005642 for item in virtual_hardware_section.iterfind(
5643 "ovf:Item", namespaces
5644 ):
5645 if (
5646 item.find("rasd:Description", namespaces).text
5647 == "Hard disk"
5648 ):
beierlb22ce2d2019-12-12 12:09:51 -05005649 disk_size = item.find(
sousaedu80135b92021-02-17 15:05:18 +01005650 "rasd:HostResource", namespaces
5651 ).attrib["{" + namespaces["vm"] + "}capacity"]
beierlb22ce2d2019-12-12 12:09:51 -05005652 vm_virtual_hardware_info["disk_size"] = disk_size
bhangarea92ae392017-01-12 22:30:29 -08005653 break
5654
5655 for link in virtual_hardware_section:
sousaedu80135b92021-02-17 15:05:18 +01005656 if (
5657 link.tag.split("}")[1] == "Link"
5658 and "rel" in link.attrib
5659 ):
5660 if link.attrib["rel"] == "edit" and link.attrib[
5661 "href"
5662 ].endswith("/disks"):
5663 vm_virtual_hardware_info[
5664 "disk_edit_href"
5665 ] = link.attrib["href"]
bhangarea92ae392017-01-12 22:30:29 -08005666 break
5667
beierlb22ce2d2019-12-12 12:09:51 -05005668 parsed_respond["vm_virtual_hardware"] = vm_virtual_hardware_info
5669 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01005670 self.logger.info(
5671 "Error occurred calling rest api for getting vApp details {}".format(
5672 exp
5673 )
5674 )
5675
bayramovfe3f3c92016-10-04 07:53:41 +04005676 return parsed_respond
5677
kasarc5bf2932018-03-09 04:15:22 -08005678 def acquire_console(self, vm_uuid=None):
bayramovfe3f3c92016-10-04 07:53:41 +04005679 if vm_uuid is None:
5680 return None
bayramovfe3f3c92016-10-04 07:53:41 +04005681
sousaedu80135b92021-02-17 15:05:18 +01005682 if self.client._session:
5683 headers = {
5684 "Accept": "application/*+xml;version=" + API_VERSION,
5685 "x-vcloud-authorization": self.client._session.headers[
5686 "x-vcloud-authorization"
5687 ],
5688 }
5689 vm_dict = self.get_vapp_details_rest(vapp_uuid=vm_uuid)
5690 console_dict = vm_dict["acquireTicket"]
5691 console_rest_call = console_dict["href"]
5692
5693 response = self.perform_request(
5694 req_type="POST", url=console_rest_call, headers=headers
5695 )
kasarc5bf2932018-03-09 04:15:22 -08005696
bhangare1a0b97c2017-06-21 02:20:15 -07005697 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01005698 response = self.retry_rest("POST", console_rest_call)
bayramovfe3f3c92016-10-04 07:53:41 +04005699
bayramov5761ad12016-10-04 09:00:30 +04005700 if response.status_code == requests.codes.ok:
beierl26fec002019-12-06 17:06:40 -05005701 return response.text
bayramovfe3f3c92016-10-04 07:53:41 +04005702
kate15f1c382016-12-15 01:12:40 -08005703 return None
kate13ab2c42016-12-23 01:34:24 -08005704
bhangarea92ae392017-01-12 22:30:29 -08005705 def modify_vm_disk(self, vapp_uuid, flavor_disk):
5706 """
5707 Method retrieve vm disk details
5708
5709 Args:
5710 vapp_uuid - is vapp identifier.
5711 flavor_disk - disk size as specified in VNFD (flavor)
5712
5713 Returns:
5714 The return network uuid or return None
5715 """
5716 status = None
5717 try:
beierlb22ce2d2019-12-12 12:09:51 -05005718 # Flavor disk is in GB convert it into MB
bhangarea92ae392017-01-12 22:30:29 -08005719 flavor_disk = int(flavor_disk) * 1024
5720 vm_details = self.get_vapp_details_rest(vapp_uuid)
sousaedu80135b92021-02-17 15:05:18 +01005721
bhangarea92ae392017-01-12 22:30:29 -08005722 if vm_details:
5723 vm_name = vm_details["name"]
beierlb22ce2d2019-12-12 12:09:51 -05005724 self.logger.info("VM: {} flavor_disk :{}".format(vm_name, flavor_disk))
bhangarea92ae392017-01-12 22:30:29 -08005725
5726 if vm_details and "vm_virtual_hardware" in vm_details:
5727 vm_disk = int(vm_details["vm_virtual_hardware"]["disk_size"])
5728 disk_edit_href = vm_details["vm_virtual_hardware"]["disk_edit_href"]
beierlb22ce2d2019-12-12 12:09:51 -05005729 self.logger.info("VM: {} VM_disk :{}".format(vm_name, vm_disk))
bhangarea92ae392017-01-12 22:30:29 -08005730
5731 if flavor_disk > vm_disk:
beierlb22ce2d2019-12-12 12:09:51 -05005732 status = self.modify_vm_disk_rest(disk_edit_href, flavor_disk)
sousaedu80135b92021-02-17 15:05:18 +01005733 self.logger.info(
5734 "Modify disk of VM {} from {} to {} MB".format(
5735 vm_name, vm_disk, flavor_disk
5736 )
5737 )
bhangarea92ae392017-01-12 22:30:29 -08005738 else:
5739 status = True
5740 self.logger.info("No need to modify disk of VM {}".format(vm_name))
5741
5742 return status
5743 except Exception as exp:
5744 self.logger.info("Error occurred while modifing disk size {}".format(exp))
5745
beierlb22ce2d2019-12-12 12:09:51 -05005746 def modify_vm_disk_rest(self, disk_href, disk_size):
bhangarea92ae392017-01-12 22:30:29 -08005747 """
5748 Method retrieve modify vm disk size
5749
5750 Args:
5751 disk_href - vCD API URL to GET and PUT disk data
5752 disk_size - disk size as specified in VNFD (flavor)
5753
5754 Returns:
5755 The return network uuid or return None
5756 """
bhangarea92ae392017-01-12 22:30:29 -08005757 if disk_href is None or disk_size is None:
5758 return None
5759
kasarc5bf2932018-03-09 04:15:22 -08005760 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01005761 headers = {
5762 "Accept": "application/*+xml;version=" + API_VERSION,
5763 "x-vcloud-authorization": self.client._session.headers[
5764 "x-vcloud-authorization"
5765 ],
5766 }
5767 response = self.perform_request(
5768 req_type="GET", url=disk_href, headers=headers
5769 )
bhangare1a0b97c2017-06-21 02:20:15 -07005770
5771 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01005772 response = self.retry_rest("GET", disk_href)
bhangarea92ae392017-01-12 22:30:29 -08005773
5774 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01005775 self.logger.debug(
5776 "GET REST API call {} failed. Return status code {}".format(
5777 disk_href, response.status_code
5778 )
5779 )
5780
bhangarea92ae392017-01-12 22:30:29 -08005781 return None
sousaedu80135b92021-02-17 15:05:18 +01005782
bhangarea92ae392017-01-12 22:30:29 -08005783 try:
beierl01bd6692019-12-09 17:06:20 -05005784 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
sousaedu80135b92021-02-17 15:05:18 +01005785 namespaces = {
5786 prefix: uri for prefix, uri in lxmlroot_respond.nsmap.items() if prefix
5787 }
beierlb22ce2d2019-12-12 12:09:51 -05005788 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
bhangarea92ae392017-01-12 22:30:29 -08005789
sousaedu80135b92021-02-17 15:05:18 +01005790 for item in lxmlroot_respond.iterfind("xmlns:Item", namespaces):
beierlb22ce2d2019-12-12 12:09:51 -05005791 if item.find("rasd:Description", namespaces).text == "Hard disk":
5792 disk_item = item.find("rasd:HostResource", namespaces)
bhangarea92ae392017-01-12 22:30:29 -08005793 if disk_item is not None:
sousaedu80135b92021-02-17 15:05:18 +01005794 disk_item.attrib["{" + namespaces["xmlns"] + "}capacity"] = str(
5795 disk_size
5796 )
bhangarea92ae392017-01-12 22:30:29 -08005797 break
5798
sousaedu80135b92021-02-17 15:05:18 +01005799 data = lxmlElementTree.tostring(
5800 lxmlroot_respond, encoding="utf8", method="xml", xml_declaration=True
5801 )
bhangarea92ae392017-01-12 22:30:29 -08005802
beierlb22ce2d2019-12-12 12:09:51 -05005803 # Send PUT request to modify disk size
sousaedu80135b92021-02-17 15:05:18 +01005804 headers[
5805 "Content-Type"
5806 ] = "application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1"
bhangarea92ae392017-01-12 22:30:29 -08005807
sousaedu80135b92021-02-17 15:05:18 +01005808 response = self.perform_request(
5809 req_type="PUT", url=disk_href, headers=headers, data=data
5810 )
bhangare1a0b97c2017-06-21 02:20:15 -07005811 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01005812 add_headers = {"Content-Type": headers["Content-Type"]}
5813 response = self.retry_rest("PUT", disk_href, add_headers, data)
bhangarea92ae392017-01-12 22:30:29 -08005814
5815 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01005816 self.logger.debug(
5817 "PUT REST API call {} failed. Return status code {}".format(
5818 disk_href, response.status_code
5819 )
5820 )
bhangarea92ae392017-01-12 22:30:29 -08005821 else:
beierl26fec002019-12-06 17:06:40 -05005822 modify_disk_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01005823 result = self.client.get_task_monitor().wait_for_success(
5824 task=modify_disk_task
5825 )
5826 if result.get("status") == "success":
kasarc5bf2932018-03-09 04:15:22 -08005827 return True
5828 else:
sbhangarea8e5b782018-06-21 02:10:03 -07005829 return False
bhangarea92ae392017-01-12 22:30:29 -08005830
sousaedu80135b92021-02-17 15:05:18 +01005831 return None
beierl26fec002019-12-06 17:06:40 -05005832 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01005833 self.logger.info(
5834 "Error occurred calling rest api for modifing disk size {}".format(exp)
5835 )
5836
5837 return None
bhangarea92ae392017-01-12 22:30:29 -08005838
beierl26fec002019-12-06 17:06:40 -05005839 def add_serial_device(self, vapp_uuid):
5840 """
sousaedu80135b92021-02-17 15:05:18 +01005841 Method to attach a serial device to a VM
beierl26fec002019-12-06 17:06:40 -05005842
sousaedu80135b92021-02-17 15:05:18 +01005843 Args:
5844 vapp_uuid - uuid of vApp/VM
beierl26fec002019-12-06 17:06:40 -05005845
sousaedu80135b92021-02-17 15:05:18 +01005846 Returns:
beierl26fec002019-12-06 17:06:40 -05005847 """
5848 self.logger.info("Add serial devices into vApp {}".format(vapp_uuid))
5849 _, content = self.get_vcenter_content()
5850 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
sousaedu80135b92021-02-17 15:05:18 +01005851
beierl26fec002019-12-06 17:06:40 -05005852 if vm_moref_id:
5853 try:
5854 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01005855 self.logger.info(
5856 "VM {} is currently on host {}".format(vm_obj, host_obj)
5857 )
beierl26fec002019-12-06 17:06:40 -05005858 if host_obj and vm_obj:
5859 spec = vim.vm.ConfigSpec()
5860 spec.deviceChange = []
5861 serial_spec = vim.vm.device.VirtualDeviceSpec()
sousaedu80135b92021-02-17 15:05:18 +01005862 serial_spec.operation = "add"
beierl26fec002019-12-06 17:06:40 -05005863 serial_port = vim.vm.device.VirtualSerialPort()
5864 serial_port.yieldOnPoll = True
5865 backing = serial_port.URIBackingInfo()
sousaedu80135b92021-02-17 15:05:18 +01005866 backing.serviceURI = "tcp://:65500"
5867 backing.direction = "server"
beierl26fec002019-12-06 17:06:40 -05005868 serial_port.backing = backing
5869 serial_spec.device = serial_port
5870 spec.deviceChange.append(serial_spec)
5871 vm_obj.ReconfigVM_Task(spec=spec)
beierl26fec002019-12-06 17:06:40 -05005872 self.logger.info("Adding serial device to VM {}".format(vm_obj))
5873 except vmodl.MethodFault as error:
5874 self.logger.error("Error occurred while adding PCI devices {} ", error)
5875
5876 def add_pci_devices(self, vapp_uuid, pci_devices, vmname_andid):
bhangarefda5f7c2017-01-12 23:50:34 -08005877 """
sousaedu80135b92021-02-17 15:05:18 +01005878 Method to attach pci devices to VM
bhangarefda5f7c2017-01-12 23:50:34 -08005879
sousaedu80135b92021-02-17 15:05:18 +01005880 Args:
5881 vapp_uuid - uuid of vApp/VM
5882 pci_devices - pci devices infromation as specified in VNFD (flavor)
bhangarefda5f7c2017-01-12 23:50:34 -08005883
sousaedu80135b92021-02-17 15:05:18 +01005884 Returns:
5885 The status of add pci device task , vm object and
5886 vcenter_conect object
bhangarefda5f7c2017-01-12 23:50:34 -08005887 """
5888 vm_obj = None
sousaedu80135b92021-02-17 15:05:18 +01005889 self.logger.info(
5890 "Add pci devices {} into vApp {}".format(pci_devices, vapp_uuid)
5891 )
bhangare06312472017-03-30 05:49:07 -07005892 vcenter_conect, content = self.get_vcenter_content()
5893 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
kateeb044522017-03-06 23:54:39 -08005894
bhangare06312472017-03-30 05:49:07 -07005895 if vm_moref_id:
bhangarefda5f7c2017-01-12 23:50:34 -08005896 try:
5897 no_of_pci_devices = len(pci_devices)
5898 if no_of_pci_devices > 0:
beierlb22ce2d2019-12-12 12:09:51 -05005899 # Get VM and its host
bhangare06312472017-03-30 05:49:07 -07005900 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01005901 self.logger.info(
5902 "VM {} is currently on host {}".format(vm_obj, host_obj)
5903 )
5904
bhangarefda5f7c2017-01-12 23:50:34 -08005905 if host_obj and vm_obj:
beierlb22ce2d2019-12-12 12:09:51 -05005906 # get PCI devies from host on which vapp is currently installed
sousaedu80135b92021-02-17 15:05:18 +01005907 avilable_pci_devices = self.get_pci_devices(
5908 host_obj, no_of_pci_devices
5909 )
bhangarefda5f7c2017-01-12 23:50:34 -08005910
5911 if avilable_pci_devices is None:
beierlb22ce2d2019-12-12 12:09:51 -05005912 # find other hosts with active pci devices
sousaedu80135b92021-02-17 15:05:18 +01005913 (
5914 new_host_obj,
5915 avilable_pci_devices,
5916 ) = self.get_host_and_PCIdevices(content, no_of_pci_devices)
5917
5918 if (
5919 new_host_obj is not None
5920 and avilable_pci_devices is not None
5921 and len(avilable_pci_devices) > 0
5922 ):
5923 # Migrate vm to the host where PCI devices are availble
5924 self.logger.info(
5925 "Relocate VM {} on new host {}".format(
5926 vm_obj, new_host_obj
5927 )
beierlb22ce2d2019-12-12 12:09:51 -05005928 )
bhangarefda5f7c2017-01-12 23:50:34 -08005929
bhangarefda5f7c2017-01-12 23:50:34 -08005930 task = self.relocate_vm(new_host_obj, vm_obj)
5931 if task is not None:
sousaedu80135b92021-02-17 15:05:18 +01005932 result = self.wait_for_vcenter_task(
5933 task, vcenter_conect
5934 )
5935 self.logger.info(
5936 "Migrate VM status: {}".format(result)
5937 )
bhangarefda5f7c2017-01-12 23:50:34 -08005938 host_obj = new_host_obj
5939 else:
sousaedu80135b92021-02-17 15:05:18 +01005940 self.logger.info(
5941 "Fail to migrate VM : {}".format(result)
5942 )
tierno72774862020-05-04 11:44:15 +00005943 raise vimconn.VimConnNotFoundException(
beierlb22ce2d2019-12-12 12:09:51 -05005944 "Fail to migrate VM : {} to host {}".format(
sousaedu80135b92021-02-17 15:05:18 +01005945 vmname_andid, new_host_obj
bhangarefda5f7c2017-01-12 23:50:34 -08005946 )
sousaedu80135b92021-02-17 15:05:18 +01005947 )
bhangarefda5f7c2017-01-12 23:50:34 -08005948
sousaedu80135b92021-02-17 15:05:18 +01005949 if (
5950 host_obj is not None
5951 and avilable_pci_devices is not None
5952 and len(avilable_pci_devices) > 0
5953 ):
beierlb22ce2d2019-12-12 12:09:51 -05005954 # Add PCI devices one by one
bhangarefda5f7c2017-01-12 23:50:34 -08005955 for pci_device in avilable_pci_devices:
5956 task = self.add_pci_to_vm(host_obj, vm_obj, pci_device)
5957 if task:
sousaedu80135b92021-02-17 15:05:18 +01005958 status = self.wait_for_vcenter_task(
5959 task, vcenter_conect
5960 )
5961
bhangarefda5f7c2017-01-12 23:50:34 -08005962 if status:
sousaedu80135b92021-02-17 15:05:18 +01005963 self.logger.info(
5964 "Added PCI device {} to VM {}".format(
5965 pci_device, str(vm_obj)
5966 )
5967 )
bhangarefda5f7c2017-01-12 23:50:34 -08005968 else:
sousaedu80135b92021-02-17 15:05:18 +01005969 self.logger.error(
5970 "Fail to add PCI device {} to VM {}".format(
5971 pci_device, str(vm_obj)
5972 )
5973 )
5974
bhangarefda5f7c2017-01-12 23:50:34 -08005975 return True, vm_obj, vcenter_conect
5976 else:
sousaedu80135b92021-02-17 15:05:18 +01005977 self.logger.error(
5978 "Currently there is no host with"
5979 " {} number of avaialble PCI devices required for VM {}".format(
5980 no_of_pci_devices, vmname_andid
5981 )
5982 )
5983
tierno72774862020-05-04 11:44:15 +00005984 raise vimconn.VimConnNotFoundException(
beierlb22ce2d2019-12-12 12:09:51 -05005985 "Currently there is no host with {} "
5986 "number of avaialble PCI devices required for VM {}".format(
sousaedu80135b92021-02-17 15:05:18 +01005987 no_of_pci_devices, vmname_andid
5988 )
5989 )
bhangarefda5f7c2017-01-12 23:50:34 -08005990 else:
sousaedu80135b92021-02-17 15:05:18 +01005991 self.logger.debug(
5992 "No infromation about PCI devices {} ", pci_devices
5993 )
bhangarefda5f7c2017-01-12 23:50:34 -08005994 except vmodl.MethodFault as error:
beierlb22ce2d2019-12-12 12:09:51 -05005995 self.logger.error("Error occurred while adding PCI devices {} ", error)
sousaedu80135b92021-02-17 15:05:18 +01005996
bhangarefda5f7c2017-01-12 23:50:34 -08005997 return None, vm_obj, vcenter_conect
5998
5999 def get_vm_obj(self, content, mob_id):
6000 """
sousaedu80135b92021-02-17 15:05:18 +01006001 Method to get the vsphere VM object associated with a given morf ID
6002 Args:
6003 vapp_uuid - uuid of vApp/VM
6004 content - vCenter content object
6005 mob_id - mob_id of VM
bhangarefda5f7c2017-01-12 23:50:34 -08006006
sousaedu80135b92021-02-17 15:05:18 +01006007 Returns:
6008 VM and host object
bhangarefda5f7c2017-01-12 23:50:34 -08006009 """
6010 vm_obj = None
6011 host_obj = None
sousaedu80135b92021-02-17 15:05:18 +01006012
beierlb22ce2d2019-12-12 12:09:51 -05006013 try:
sousaedu80135b92021-02-17 15:05:18 +01006014 container = content.viewManager.CreateContainerView(
6015 content.rootFolder, [vim.VirtualMachine], True
6016 )
bhangarefda5f7c2017-01-12 23:50:34 -08006017 for vm in container.view:
6018 mobID = vm._GetMoId()
sousaedu80135b92021-02-17 15:05:18 +01006019
bhangarefda5f7c2017-01-12 23:50:34 -08006020 if mobID == mob_id:
6021 vm_obj = vm
6022 host_obj = vm_obj.runtime.host
6023 break
6024 except Exception as exp:
6025 self.logger.error("Error occurred while finding VM object : {}".format(exp))
sousaedu80135b92021-02-17 15:05:18 +01006026
bhangarefda5f7c2017-01-12 23:50:34 -08006027 return host_obj, vm_obj
6028
6029 def get_pci_devices(self, host, need_devices):
6030 """
sousaedu80135b92021-02-17 15:05:18 +01006031 Method to get the details of pci devices on given host
6032 Args:
6033 host - vSphere host object
6034 need_devices - number of pci devices needed on host
bhangarefda5f7c2017-01-12 23:50:34 -08006035
sousaedu80135b92021-02-17 15:05:18 +01006036 Returns:
6037 array of pci devices
bhangarefda5f7c2017-01-12 23:50:34 -08006038 """
6039 all_devices = []
6040 all_device_ids = []
6041 used_devices_ids = []
6042
6043 try:
6044 if host:
6045 pciPassthruInfo = host.config.pciPassthruInfo
6046 pciDevies = host.hardware.pciDevice
6047
6048 for pci_status in pciPassthruInfo:
6049 if pci_status.passthruActive:
6050 for device in pciDevies:
6051 if device.id == pci_status.id:
6052 all_device_ids.append(device.id)
6053 all_devices.append(device)
6054
beierlb22ce2d2019-12-12 12:09:51 -05006055 # check if devices are in use
bhangarefda5f7c2017-01-12 23:50:34 -08006056 avalible_devices = all_devices
6057 for vm in host.vm:
6058 if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
6059 vm_devices = vm.config.hardware.device
6060 for device in vm_devices:
6061 if type(device) is vim.vm.device.VirtualPCIPassthrough:
6062 if device.backing.id in all_device_ids:
6063 for use_device in avalible_devices:
6064 if use_device.id == device.backing.id:
6065 avalible_devices.remove(use_device)
sousaedu80135b92021-02-17 15:05:18 +01006066
bhangarefda5f7c2017-01-12 23:50:34 -08006067 used_devices_ids.append(device.backing.id)
sousaedu80135b92021-02-17 15:05:18 +01006068 self.logger.debug(
6069 "Device {} from devices {}"
6070 "is in use".format(device.backing.id, device)
6071 )
bhangarefda5f7c2017-01-12 23:50:34 -08006072 if len(avalible_devices) < need_devices:
sousaedu80135b92021-02-17 15:05:18 +01006073 self.logger.debug(
6074 "Host {} don't have {} number of active devices".format(
6075 host, need_devices
6076 )
6077 )
6078 self.logger.debug(
6079 "found only {} devices {}".format(
6080 len(avalible_devices), avalible_devices
6081 )
6082 )
6083
bhangarefda5f7c2017-01-12 23:50:34 -08006084 return None
6085 else:
6086 required_devices = avalible_devices[:need_devices]
sousaedu80135b92021-02-17 15:05:18 +01006087 self.logger.info(
6088 "Found {} PCI devices on host {} but required only {}".format(
6089 len(avalible_devices), host, need_devices
6090 )
6091 )
6092 self.logger.info(
6093 "Retruning {} devices as {}".format(need_devices, required_devices)
6094 )
bhangarefda5f7c2017-01-12 23:50:34 -08006095
sousaedu80135b92021-02-17 15:05:18 +01006096 return required_devices
bhangarefda5f7c2017-01-12 23:50:34 -08006097 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006098 self.logger.error(
6099 "Error {} occurred while finding pci devices on host: {}".format(
6100 exp, host
6101 )
6102 )
bhangarefda5f7c2017-01-12 23:50:34 -08006103
6104 return None
6105
6106 def get_host_and_PCIdevices(self, content, need_devices):
6107 """
sousaedu80135b92021-02-17 15:05:18 +01006108 Method to get the details of pci devices infromation on all hosts
bhangarefda5f7c2017-01-12 23:50:34 -08006109
sousaedu80135b92021-02-17 15:05:18 +01006110 Args:
6111 content - vSphere host object
6112 need_devices - number of pci devices needed on host
bhangarefda5f7c2017-01-12 23:50:34 -08006113
sousaedu80135b92021-02-17 15:05:18 +01006114 Returns:
6115 array of pci devices and host object
bhangarefda5f7c2017-01-12 23:50:34 -08006116 """
6117 host_obj = None
6118 pci_device_objs = None
sousaedu80135b92021-02-17 15:05:18 +01006119
bhangarefda5f7c2017-01-12 23:50:34 -08006120 try:
6121 if content:
sousaedu80135b92021-02-17 15:05:18 +01006122 container = content.viewManager.CreateContainerView(
6123 content.rootFolder, [vim.HostSystem], True
6124 )
bhangarefda5f7c2017-01-12 23:50:34 -08006125 for host in container.view:
6126 devices = self.get_pci_devices(host, need_devices)
sousaedu80135b92021-02-17 15:05:18 +01006127
bhangarefda5f7c2017-01-12 23:50:34 -08006128 if devices:
6129 host_obj = host
6130 pci_device_objs = devices
6131 break
6132 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006133 self.logger.error(
6134 "Error {} occurred while finding pci devices on host: {}".format(
6135 exp, host_obj
6136 )
6137 )
bhangarefda5f7c2017-01-12 23:50:34 -08006138
beierlb22ce2d2019-12-12 12:09:51 -05006139 return host_obj, pci_device_objs
bhangarefda5f7c2017-01-12 23:50:34 -08006140
beierlb22ce2d2019-12-12 12:09:51 -05006141 def relocate_vm(self, dest_host, vm):
bhangarefda5f7c2017-01-12 23:50:34 -08006142 """
sousaedu80135b92021-02-17 15:05:18 +01006143 Method to get the relocate VM to new host
bhangarefda5f7c2017-01-12 23:50:34 -08006144
sousaedu80135b92021-02-17 15:05:18 +01006145 Args:
6146 dest_host - vSphere host object
6147 vm - vSphere VM object
bhangarefda5f7c2017-01-12 23:50:34 -08006148
sousaedu80135b92021-02-17 15:05:18 +01006149 Returns:
6150 task object
bhangarefda5f7c2017-01-12 23:50:34 -08006151 """
6152 task = None
sousaedu80135b92021-02-17 15:05:18 +01006153
bhangarefda5f7c2017-01-12 23:50:34 -08006154 try:
6155 relocate_spec = vim.vm.RelocateSpec(host=dest_host)
6156 task = vm.Relocate(relocate_spec)
sousaedu80135b92021-02-17 15:05:18 +01006157 self.logger.info(
6158 "Migrating {} to destination host {}".format(vm, dest_host)
6159 )
bhangarefda5f7c2017-01-12 23:50:34 -08006160 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006161 self.logger.error(
6162 "Error occurred while relocate VM {} to new host {}: {}".format(
6163 dest_host, vm, exp
6164 )
6165 )
6166
bhangarefda5f7c2017-01-12 23:50:34 -08006167 return task
6168
sousaedu80135b92021-02-17 15:05:18 +01006169 def wait_for_vcenter_task(self, task, actionName="job", hideResult=False):
bhangarefda5f7c2017-01-12 23:50:34 -08006170 """
6171 Waits and provides updates on a vSphere task
6172 """
6173 while task.info.state == vim.TaskInfo.State.running:
6174 time.sleep(2)
6175
6176 if task.info.state == vim.TaskInfo.State.success:
6177 if task.info.result is not None and not hideResult:
sousaedu80135b92021-02-17 15:05:18 +01006178 self.logger.info(
6179 "{} completed successfully, result: {}".format(
6180 actionName, task.info.result
6181 )
beierlb22ce2d2019-12-12 12:09:51 -05006182 )
sousaedu80135b92021-02-17 15:05:18 +01006183 else:
6184 self.logger.info("Task {} completed successfully.".format(actionName))
6185 else:
6186 self.logger.error(
6187 "{} did not complete successfully: {} ".format(
6188 actionName, task.info.error
6189 )
6190 )
bhangarefda5f7c2017-01-12 23:50:34 -08006191
6192 return task.info.result
6193
beierlb22ce2d2019-12-12 12:09:51 -05006194 def add_pci_to_vm(self, host_object, vm_object, host_pci_dev):
bhangarefda5f7c2017-01-12 23:50:34 -08006195 """
sousaedu80135b92021-02-17 15:05:18 +01006196 Method to add pci device in given VM
bhangarefda5f7c2017-01-12 23:50:34 -08006197
sousaedu80135b92021-02-17 15:05:18 +01006198 Args:
6199 host_object - vSphere host object
6200 vm_object - vSphere VM object
6201 host_pci_dev - host_pci_dev must be one of the devices from the
6202 host_object.hardware.pciDevice list
6203 which is configured as a PCI passthrough device
bhangarefda5f7c2017-01-12 23:50:34 -08006204
sousaedu80135b92021-02-17 15:05:18 +01006205 Returns:
6206 task object
bhangarefda5f7c2017-01-12 23:50:34 -08006207 """
6208 task = None
sousaedu80135b92021-02-17 15:05:18 +01006209
bhangarefda5f7c2017-01-12 23:50:34 -08006210 if vm_object and host_object and host_pci_dev:
beierlb22ce2d2019-12-12 12:09:51 -05006211 try:
6212 # Add PCI device to VM
sousaedu80135b92021-02-17 15:05:18 +01006213 pci_passthroughs = vm_object.environmentBrowser.QueryConfigTarget(
6214 host=None
6215 ).pciPassthrough
6216 systemid_by_pciid = {
6217 item.pciDevice.id: item.systemId for item in pci_passthroughs
6218 }
bhangarefda5f7c2017-01-12 23:50:34 -08006219
6220 if host_pci_dev.id not in systemid_by_pciid:
sousaedu80135b92021-02-17 15:05:18 +01006221 self.logger.error(
6222 "Device {} is not a passthrough device ".format(host_pci_dev)
6223 )
bhangarefda5f7c2017-01-12 23:50:34 -08006224 return None
6225
aticig2b24d622022-03-11 15:03:55 +03006226 deviceId = hex(host_pci_dev.deviceId % 2**16).lstrip("0x")
sousaedu80135b92021-02-17 15:05:18 +01006227 backing = vim.VirtualPCIPassthroughDeviceBackingInfo(
6228 deviceId=deviceId,
6229 id=host_pci_dev.id,
6230 systemId=systemid_by_pciid[host_pci_dev.id],
6231 vendorId=host_pci_dev.vendorId,
6232 deviceName=host_pci_dev.deviceName,
6233 )
bhangarefda5f7c2017-01-12 23:50:34 -08006234
6235 hba_object = vim.VirtualPCIPassthrough(key=-100, backing=backing)
bhangarefda5f7c2017-01-12 23:50:34 -08006236 new_device_config = vim.VirtualDeviceConfigSpec(device=hba_object)
6237 new_device_config.operation = "add"
6238 vmConfigSpec = vim.vm.ConfigSpec()
6239 vmConfigSpec.deviceChange = [new_device_config]
bhangarefda5f7c2017-01-12 23:50:34 -08006240 task = vm_object.ReconfigVM_Task(spec=vmConfigSpec)
sousaedu80135b92021-02-17 15:05:18 +01006241 self.logger.info(
6242 "Adding PCI device {} into VM {} from host {} ".format(
6243 host_pci_dev, vm_object, host_object
beierlb22ce2d2019-12-12 12:09:51 -05006244 )
sousaedu80135b92021-02-17 15:05:18 +01006245 )
bhangarefda5f7c2017-01-12 23:50:34 -08006246 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006247 self.logger.error(
6248 "Error occurred while adding pci devive {} to VM {}: {}".format(
6249 host_pci_dev, vm_object, exp
6250 )
6251 )
6252
bhangarefda5f7c2017-01-12 23:50:34 -08006253 return task
6254
bhangare06312472017-03-30 05:49:07 -07006255 def get_vm_vcenter_info(self):
bhangarefda5f7c2017-01-12 23:50:34 -08006256 """
kateeb044522017-03-06 23:54:39 -08006257 Method to get details of vCenter and vm
bhangarefda5f7c2017-01-12 23:50:34 -08006258
6259 Args:
6260 vapp_uuid - uuid of vApp or VM
6261
6262 Returns:
6263 Moref Id of VM and deails of vCenter
6264 """
kateeb044522017-03-06 23:54:39 -08006265 vm_vcenter_info = {}
bhangarefda5f7c2017-01-12 23:50:34 -08006266
kateeb044522017-03-06 23:54:39 -08006267 if self.vcenter_ip is not None:
6268 vm_vcenter_info["vm_vcenter_ip"] = self.vcenter_ip
6269 else:
sousaedu80135b92021-02-17 15:05:18 +01006270 raise vimconn.VimConnException(
6271 message="vCenter IP is not provided."
6272 " Please provide vCenter IP while attaching datacenter "
6273 "to tenant in --config"
6274 )
6275
kateeb044522017-03-06 23:54:39 -08006276 if self.vcenter_port is not None:
6277 vm_vcenter_info["vm_vcenter_port"] = self.vcenter_port
6278 else:
sousaedu80135b92021-02-17 15:05:18 +01006279 raise vimconn.VimConnException(
6280 message="vCenter port is not provided."
6281 " Please provide vCenter port while attaching datacenter "
6282 "to tenant in --config"
6283 )
6284
kateeb044522017-03-06 23:54:39 -08006285 if self.vcenter_user is not None:
6286 vm_vcenter_info["vm_vcenter_user"] = self.vcenter_user
6287 else:
sousaedu80135b92021-02-17 15:05:18 +01006288 raise vimconn.VimConnException(
6289 message="vCenter user is not provided."
6290 " Please provide vCenter user while attaching datacenter "
6291 "to tenant in --config"
6292 )
bhangarefda5f7c2017-01-12 23:50:34 -08006293
kateeb044522017-03-06 23:54:39 -08006294 if self.vcenter_password is not None:
6295 vm_vcenter_info["vm_vcenter_password"] = self.vcenter_password
6296 else:
sousaedu80135b92021-02-17 15:05:18 +01006297 raise vimconn.VimConnException(
6298 message="vCenter user password is not provided."
6299 " Please provide vCenter user password while attaching datacenter "
6300 "to tenant in --config"
6301 )
bhangarefda5f7c2017-01-12 23:50:34 -08006302
bhangare06312472017-03-30 05:49:07 -07006303 return vm_vcenter_info
bhangarefda5f7c2017-01-12 23:50:34 -08006304
bhangarefda5f7c2017-01-12 23:50:34 -08006305 def get_vm_pci_details(self, vmuuid):
6306 """
sousaedu80135b92021-02-17 15:05:18 +01006307 Method to get VM PCI device details from vCenter
bhangarefda5f7c2017-01-12 23:50:34 -08006308
sousaedu80135b92021-02-17 15:05:18 +01006309 Args:
6310 vm_obj - vSphere VM object
bhangarefda5f7c2017-01-12 23:50:34 -08006311
sousaedu80135b92021-02-17 15:05:18 +01006312 Returns:
6313 dict of PCI devives attached to VM
bhangarefda5f7c2017-01-12 23:50:34 -08006314
6315 """
6316 vm_pci_devices_info = {}
sousaedu80135b92021-02-17 15:05:18 +01006317
bhangarefda5f7c2017-01-12 23:50:34 -08006318 try:
beierlb22ce2d2019-12-12 12:09:51 -05006319 _, content = self.get_vcenter_content()
bhangare06312472017-03-30 05:49:07 -07006320 vm_moref_id = self.get_vm_moref_id(vmuuid)
6321 if vm_moref_id:
beierlb22ce2d2019-12-12 12:09:51 -05006322 # Get VM and its host
kateeb044522017-03-06 23:54:39 -08006323 if content:
bhangare06312472017-03-30 05:49:07 -07006324 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
kateeb044522017-03-06 23:54:39 -08006325 if host_obj and vm_obj:
beierlb22ce2d2019-12-12 12:09:51 -05006326 vm_pci_devices_info["host_name"] = host_obj.name
sousaedu80135b92021-02-17 15:05:18 +01006327 vm_pci_devices_info["host_ip"] = host_obj.config.network.vnic[
6328 0
6329 ].spec.ip.ipAddress
6330
kateeb044522017-03-06 23:54:39 -08006331 for device in vm_obj.config.hardware.device:
6332 if type(device) == vim.vm.device.VirtualPCIPassthrough:
sousaedu80135b92021-02-17 15:05:18 +01006333 device_details = {
6334 "devide_id": device.backing.id,
6335 "pciSlotNumber": device.slotInfo.pciSlotNumber,
6336 }
6337 vm_pci_devices_info[
6338 device.deviceInfo.label
6339 ] = device_details
kateeb044522017-03-06 23:54:39 -08006340 else:
sousaedu80135b92021-02-17 15:05:18 +01006341 self.logger.error(
6342 "Can not connect to vCenter while getting "
6343 "PCI devices infromationn"
6344 )
6345
kateeb044522017-03-06 23:54:39 -08006346 return vm_pci_devices_info
bhangarefda5f7c2017-01-12 23:50:34 -08006347 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006348 self.logger.error(
6349 "Error occurred while getting VM information" " for VM : {}".format(exp)
6350 )
6351
tierno72774862020-05-04 11:44:15 +00006352 raise vimconn.VimConnException(message=exp)
bhangare0e571a92017-01-12 04:02:23 -08006353
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006354 def reserve_memory_for_all_vms(self, vapp, memory_mb):
6355 """
sousaedu80135b92021-02-17 15:05:18 +01006356 Method to reserve memory for all VMs
6357 Args :
6358 vapp - VApp
6359 memory_mb - Memory in MB
6360 Returns:
6361 None
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006362 """
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006363 self.logger.info("Reserve memory for all VMs")
sousaedu80135b92021-02-17 15:05:18 +01006364
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006365 for vms in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01006366 vm_id = vms.get("id").split(":")[-1]
6367 url_rest_call = "{}/api/vApp/vm-{}/virtualHardwareSection/memory".format(
6368 self.url, vm_id
6369 )
6370 headers = {
6371 "Accept": "application/*+xml;version=" + API_VERSION,
6372 "x-vcloud-authorization": self.client._session.headers[
6373 "x-vcloud-authorization"
6374 ],
6375 }
6376 headers["Content-Type"] = "application/vnd.vmware.vcloud.rasdItem+xml"
6377 response = self.perform_request(
6378 req_type="GET", url=url_rest_call, headers=headers
6379 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006380
6381 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006382 response = self.retry_rest("GET", url_rest_call)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006383
6384 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01006385 self.logger.error(
6386 "REST call {} failed reason : {}"
6387 "status code : {}".format(
6388 url_rest_call, response.text, response.status_code
6389 )
6390 )
6391 raise vimconn.VimConnException(
6392 "reserve_memory_for_all_vms : Failed to get " "memory"
6393 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006394
sousaedu80135b92021-02-17 15:05:18 +01006395 bytexml = bytes(bytearray(response.text, encoding="utf-8"))
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006396 contentelem = lxmlElementTree.XML(bytexml)
sousaedu80135b92021-02-17 15:05:18 +01006397 namespaces = {
6398 prefix: uri for prefix, uri in contentelem.nsmap.items() if prefix
6399 }
beierlb22ce2d2019-12-12 12:09:51 -05006400 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006401
6402 # Find the reservation element in the response
6403 memelem_list = contentelem.findall(".//rasd:Reservation", namespaces)
6404 for memelem in memelem_list:
6405 memelem.text = str(memory_mb)
6406
6407 newdata = lxmlElementTree.tostring(contentelem, pretty_print=True)
6408
sousaedu80135b92021-02-17 15:05:18 +01006409 response = self.perform_request(
6410 req_type="PUT", url=url_rest_call, headers=headers, data=newdata
6411 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006412
6413 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006414 add_headers = {"Content-Type": headers["Content-Type"]}
6415 response = self.retry_rest("PUT", url_rest_call, add_headers, newdata)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006416
6417 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01006418 self.logger.error(
6419 "REST call {} failed reason : {}"
6420 "status code : {} ".format(
6421 url_rest_call, response.text, response.status_code
6422 )
6423 )
6424 raise vimconn.VimConnException(
6425 "reserve_memory_for_all_vms : Failed to update "
6426 "virtual hardware memory section"
6427 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006428 else:
beierl26fec002019-12-06 17:06:40 -05006429 mem_task = self.get_task_from_response(response.text)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006430 result = self.client.get_task_monitor().wait_for_success(task=mem_task)
sousaedu80135b92021-02-17 15:05:18 +01006431
6432 if result.get("status") == "success":
6433 self.logger.info(
6434 "reserve_memory_for_all_vms(): VM {} succeeded ".format(vm_id)
6435 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006436 else:
sousaedu80135b92021-02-17 15:05:18 +01006437 self.logger.error(
6438 "reserve_memory_for_all_vms(): VM {} failed ".format(vm_id)
6439 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006440
6441 def connect_vapp_to_org_vdc_network(self, vapp_id, net_name):
6442 """
sousaedu80135b92021-02-17 15:05:18 +01006443 Configure VApp network config with org vdc network
6444 Args :
6445 vapp - VApp
6446 Returns:
6447 None
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006448 """
6449
sousaedu80135b92021-02-17 15:05:18 +01006450 self.logger.info(
6451 "Connecting vapp {} to org vdc network {}".format(vapp_id, net_name)
6452 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006453
sousaedu80135b92021-02-17 15:05:18 +01006454 url_rest_call = "{}/api/vApp/vapp-{}/networkConfigSection/".format(
6455 self.url, vapp_id
6456 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006457
sousaedu80135b92021-02-17 15:05:18 +01006458 headers = {
6459 "Accept": "application/*+xml;version=" + API_VERSION,
6460 "x-vcloud-authorization": self.client._session.headers[
6461 "x-vcloud-authorization"
6462 ],
6463 }
6464 response = self.perform_request(
6465 req_type="GET", url=url_rest_call, headers=headers
6466 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006467
6468 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006469 response = self.retry_rest("GET", url_rest_call)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006470
6471 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01006472 self.logger.error(
6473 "REST call {} failed reason : {}"
6474 "status code : {}".format(
6475 url_rest_call, response.text, response.status_code
6476 )
6477 )
6478 raise vimconn.VimConnException(
6479 "connect_vapp_to_org_vdc_network : Failed to get "
6480 "network config section"
6481 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006482
beierl26fec002019-12-06 17:06:40 -05006483 data = response.text
sousaedu80135b92021-02-17 15:05:18 +01006484 headers[
6485 "Content-Type"
6486 ] = "application/vnd.vmware.vcloud.networkConfigSection+xml"
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006487 net_id = self.get_network_id_by_name(net_name)
6488 if not net_id:
sousaedu80135b92021-02-17 15:05:18 +01006489 raise vimconn.VimConnException(
6490 "connect_vapp_to_org_vdc_network : Failed to find " "existing network"
6491 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006492
sousaedu80135b92021-02-17 15:05:18 +01006493 bytexml = bytes(bytearray(data, encoding="utf-8"))
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006494 newelem = lxmlElementTree.XML(bytexml)
tierno7d782ef2019-10-04 12:56:31 +00006495 namespaces = {prefix: uri for prefix, uri in newelem.nsmap.items() if prefix}
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006496 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
6497 nwcfglist = newelem.findall(".//xmlns:NetworkConfig", namespaces)
6498
Ravi Chamarty259aebc2019-06-05 17:06:39 +00006499 # VCD 9.7 returns an incorrect parentnetwork element. Fix it before PUT operation
6500 parentnetworklist = newelem.findall(".//xmlns:ParentNetwork", namespaces)
6501 if parentnetworklist:
6502 for pn in parentnetworklist:
6503 if "href" not in pn.keys():
6504 id_val = pn.get("id")
6505 href_val = "{}/api/network/{}".format(self.url, id_val)
6506 pn.set("href", href_val)
6507
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006508 newstr = """<NetworkConfig networkName="{}">
6509 <Configuration>
6510 <ParentNetwork href="{}/api/network/{}"/>
6511 <FenceMode>bridged</FenceMode>
6512 </Configuration>
6513 </NetworkConfig>
sousaedu80135b92021-02-17 15:05:18 +01006514 """.format(
6515 net_name, self.url, net_id
6516 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006517 newcfgelem = lxmlElementTree.fromstring(newstr)
6518 if nwcfglist:
6519 nwcfglist[0].addnext(newcfgelem)
6520
6521 newdata = lxmlElementTree.tostring(newelem, pretty_print=True)
6522
sousaedu80135b92021-02-17 15:05:18 +01006523 response = self.perform_request(
6524 req_type="PUT", url=url_rest_call, headers=headers, data=newdata
6525 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006526
6527 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006528 add_headers = {"Content-Type": headers["Content-Type"]}
6529 response = self.retry_rest("PUT", url_rest_call, add_headers, newdata)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006530
6531 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01006532 self.logger.error(
6533 "REST call {} failed reason : {}"
6534 "status code : {} ".format(
6535 url_rest_call, response.text, response.status_code
6536 )
6537 )
6538 raise vimconn.VimConnException(
6539 "connect_vapp_to_org_vdc_network : Failed to update "
6540 "network config section"
6541 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006542 else:
beierl26fec002019-12-06 17:06:40 -05006543 vapp_task = self.get_task_from_response(response.text)
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006544 result = self.client.get_task_monitor().wait_for_success(task=vapp_task)
sousaedu80135b92021-02-17 15:05:18 +01006545 if result.get("status") == "success":
6546 self.logger.info(
6547 "connect_vapp_to_org_vdc_network(): Vapp {} connected to "
6548 "network {}".format(vapp_id, net_name)
6549 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006550 else:
sousaedu80135b92021-02-17 15:05:18 +01006551 self.logger.error(
6552 "connect_vapp_to_org_vdc_network(): Vapp {} failed to "
6553 "connect to network {}".format(vapp_id, net_name)
6554 )
Ravi Chamartyb0ab2c02018-10-26 01:40:50 +00006555
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006556 def remove_primary_network_adapter_from_all_vms(self, vapp):
6557 """
sousaedu80135b92021-02-17 15:05:18 +01006558 Method to remove network adapter type to vm
6559 Args :
6560 vapp - VApp
6561 Returns:
6562 None
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006563 """
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006564 self.logger.info("Removing network adapter from all VMs")
sousaedu80135b92021-02-17 15:05:18 +01006565
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006566 for vms in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01006567 vm_id = vms.get("id").split(":")[-1]
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006568
sousaedu80135b92021-02-17 15:05:18 +01006569 url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(
6570 self.url, vm_id
6571 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006572
sousaedu80135b92021-02-17 15:05:18 +01006573 headers = {
6574 "Accept": "application/*+xml;version=" + API_VERSION,
6575 "x-vcloud-authorization": self.client._session.headers[
6576 "x-vcloud-authorization"
6577 ],
6578 }
6579 response = self.perform_request(
6580 req_type="GET", url=url_rest_call, headers=headers
6581 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006582
6583 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006584 response = self.retry_rest("GET", url_rest_call)
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006585
6586 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01006587 self.logger.error(
6588 "REST call {} failed reason : {}"
6589 "status code : {}".format(
6590 url_rest_call, response.text, response.status_code
6591 )
6592 )
6593 raise vimconn.VimConnException(
6594 "remove_primary_network_adapter : Failed to get "
6595 "network connection section"
6596 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006597
beierl26fec002019-12-06 17:06:40 -05006598 data = response.text
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006599 data = data.split('<Link rel="edit"')[0]
6600
sousaedu80135b92021-02-17 15:05:18 +01006601 headers[
6602 "Content-Type"
6603 ] = "application/vnd.vmware.vcloud.networkConnectionSection+xml"
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006604
6605 newdata = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6606 <NetworkConnectionSection xmlns="http://www.vmware.com/vcloud/v1.5"
6607 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
6608 xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
6609 xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common"
6610 xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
6611 xmlns:vmw="http://www.vmware.com/schema/ovf"
6612 xmlns:ovfenv="http://schemas.dmtf.org/ovf/environment/1"
6613 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
6614 xmlns:ns9="http://www.vmware.com/vcloud/versions"
beierlb22ce2d2019-12-12 12:09:51 -05006615 href="{url}" type="application/vnd.vmware.vcloud.networkConnectionSection+xml"
6616 ovf:required="false">
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006617 <ovf:Info>Specifies the available VM network connections</ovf:Info>
6618 <PrimaryNetworkConnectionIndex>0</PrimaryNetworkConnectionIndex>
beierlb22ce2d2019-12-12 12:09:51 -05006619 <Link rel="edit" href="{url}"
6620 type="application/vnd.vmware.vcloud.networkConnectionSection+xml"/>
sousaedu80135b92021-02-17 15:05:18 +01006621 </NetworkConnectionSection>""".format(
6622 url=url_rest_call
6623 )
6624 response = self.perform_request(
6625 req_type="PUT", url=url_rest_call, headers=headers, data=newdata
6626 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006627
6628 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006629 add_headers = {"Content-Type": headers["Content-Type"]}
6630 response = self.retry_rest("PUT", url_rest_call, add_headers, newdata)
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006631
6632 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01006633 self.logger.error(
6634 "REST call {} failed reason : {}"
6635 "status code : {} ".format(
6636 url_rest_call, response.text, response.status_code
6637 )
6638 )
6639 raise vimconn.VimConnException(
6640 "remove_primary_network_adapter : Failed to update "
6641 "network connection section"
6642 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006643 else:
beierl26fec002019-12-06 17:06:40 -05006644 nic_task = self.get_task_from_response(response.text)
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006645 result = self.client.get_task_monitor().wait_for_success(task=nic_task)
sousaedu80135b92021-02-17 15:05:18 +01006646 if result.get("status") == "success":
6647 self.logger.info(
6648 "remove_primary_network_adapter(): VM {} conneced to "
6649 "default NIC type".format(vm_id)
6650 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006651 else:
sousaedu80135b92021-02-17 15:05:18 +01006652 self.logger.error(
6653 "remove_primary_network_adapter(): VM {} failed to "
6654 "connect NIC type".format(vm_id)
6655 )
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006656
sousaedu80135b92021-02-17 15:05:18 +01006657 def add_network_adapter_to_vms(
6658 self, vapp, network_name, primary_nic_index, nicIndex, net, nic_type=None
6659 ):
kasar3ac5dc42017-03-15 06:28:22 -07006660 """
sousaedu80135b92021-02-17 15:05:18 +01006661 Method to add network adapter type to vm
6662 Args :
6663 network_name - name of network
6664 primary_nic_index - int value for primary nic index
6665 nicIndex - int value for nic index
6666 nic_type - specify model name to which add to vm
6667 Returns:
6668 None
kasar3ac5dc42017-03-15 06:28:22 -07006669 """
kasar3ac5dc42017-03-15 06:28:22 -07006670
sousaedu80135b92021-02-17 15:05:18 +01006671 self.logger.info(
6672 "Add network adapter to VM: network_name {} nicIndex {} nic_type {}".format(
6673 network_name, nicIndex, nic_type
6674 )
6675 )
kasar4cb6e902017-03-18 00:17:27 -07006676 try:
kasard2963622017-03-31 05:53:17 -07006677 ip_address = None
kasardc1f02e2017-03-25 07:20:30 -07006678 floating_ip = False
kasarc5bf2932018-03-09 04:15:22 -08006679 mac_address = None
sousaedu80135b92021-02-17 15:05:18 +01006680 if "floating_ip" in net:
6681 floating_ip = net["floating_ip"]
kasard2963622017-03-31 05:53:17 -07006682
6683 # Stub for ip_address feature
sousaedu80135b92021-02-17 15:05:18 +01006684 if "ip_address" in net:
6685 ip_address = net["ip_address"]
kasard2963622017-03-31 05:53:17 -07006686
sousaedu80135b92021-02-17 15:05:18 +01006687 if "mac_address" in net:
6688 mac_address = net["mac_address"]
kasarc5bf2932018-03-09 04:15:22 -08006689
kasard2963622017-03-31 05:53:17 -07006690 if floating_ip:
6691 allocation_mode = "POOL"
6692 elif ip_address:
6693 allocation_mode = "MANUAL"
6694 else:
6695 allocation_mode = "DHCP"
kasardc1f02e2017-03-25 07:20:30 -07006696
kasar3ac5dc42017-03-15 06:28:22 -07006697 if not nic_type:
kasarc5bf2932018-03-09 04:15:22 -08006698 for vms in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01006699 vm_id = vms.get("id").split(":")[-1]
kasar3ac5dc42017-03-15 06:28:22 -07006700
sousaedu80135b92021-02-17 15:05:18 +01006701 url_rest_call = (
6702 "{}/api/vApp/vm-{}/networkConnectionSection/".format(
6703 self.url, vm_id
6704 )
6705 )
kasar3ac5dc42017-03-15 06:28:22 -07006706
sousaedu80135b92021-02-17 15:05:18 +01006707 headers = {
6708 "Accept": "application/*+xml;version=" + API_VERSION,
6709 "x-vcloud-authorization": self.client._session.headers[
6710 "x-vcloud-authorization"
6711 ],
6712 }
6713 response = self.perform_request(
6714 req_type="GET", url=url_rest_call, headers=headers
6715 )
bhangare1a0b97c2017-06-21 02:20:15 -07006716
6717 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006718 response = self.retry_rest("GET", url_rest_call)
bhangare1a0b97c2017-06-21 02:20:15 -07006719
kasar3ac5dc42017-03-15 06:28:22 -07006720 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01006721 self.logger.error(
6722 "REST call {} failed reason : {}"
6723 "status code : {}".format(
6724 url_rest_call, response.text, response.status_code
6725 )
6726 )
6727 raise vimconn.VimConnException(
6728 "add_network_adapter_to_vms : Failed to get "
6729 "network connection section"
6730 )
kasar3ac5dc42017-03-15 06:28:22 -07006731
beierl26fec002019-12-06 17:06:40 -05006732 data = response.text
kasarc5bf2932018-03-09 04:15:22 -08006733 data = data.split('<Link rel="edit"')[0]
sousaedu80135b92021-02-17 15:05:18 +01006734 if "<PrimaryNetworkConnectionIndex>" not in data:
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006735 self.logger.debug("add_network_adapter PrimaryNIC not in data")
kasar3ac5dc42017-03-15 06:28:22 -07006736 item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
6737 <NetworkConnection network="{}">
6738 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
6739 <IsConnected>true</IsConnected>
kasardc1f02e2017-03-25 07:20:30 -07006740 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
sousaedu80135b92021-02-17 15:05:18 +01006741 </NetworkConnection>""".format(
6742 primary_nic_index, network_name, nicIndex, allocation_mode
6743 )
6744
kasard2963622017-03-31 05:53:17 -07006745 # Stub for ip_address feature
6746 if ip_address:
sousaedu80135b92021-02-17 15:05:18 +01006747 ip_tag = "<IpAddress>{}</IpAddress>".format(ip_address)
6748 item = item.replace(
6749 "</NetworkConnectionIndex>\n",
6750 "</NetworkConnectionIndex>\n{}\n".format(ip_tag),
6751 )
kasardc1f02e2017-03-25 07:20:30 -07006752
kasarc5bf2932018-03-09 04:15:22 -08006753 if mac_address:
sousaedu80135b92021-02-17 15:05:18 +01006754 mac_tag = "<MACAddress>{}</MACAddress>".format(mac_address)
6755 item = item.replace(
6756 "</IsConnected>\n",
6757 "</IsConnected>\n{}\n".format(mac_tag),
6758 )
kasarc5bf2932018-03-09 04:15:22 -08006759
sousaedu80135b92021-02-17 15:05:18 +01006760 data = data.replace(
6761 "</ovf:Info>\n",
6762 "</ovf:Info>\n{}\n</NetworkConnectionSection>".format(item),
6763 )
kasar3ac5dc42017-03-15 06:28:22 -07006764 else:
Ravi Chamarty5b2d5c12018-10-22 23:59:10 +00006765 self.logger.debug("add_network_adapter PrimaryNIC in data")
kasar3ac5dc42017-03-15 06:28:22 -07006766 new_item = """<NetworkConnection network="{}">
6767 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
6768 <IsConnected>true</IsConnected>
kasardc1f02e2017-03-25 07:20:30 -07006769 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
sousaedu80135b92021-02-17 15:05:18 +01006770 </NetworkConnection>""".format(
6771 network_name, nicIndex, allocation_mode
6772 )
6773
kasard2963622017-03-31 05:53:17 -07006774 # Stub for ip_address feature
6775 if ip_address:
sousaedu80135b92021-02-17 15:05:18 +01006776 ip_tag = "<IpAddress>{}</IpAddress>".format(ip_address)
6777 new_item = new_item.replace(
6778 "</NetworkConnectionIndex>\n",
6779 "</NetworkConnectionIndex>\n{}\n".format(ip_tag),
6780 )
kasardc1f02e2017-03-25 07:20:30 -07006781
kasarc5bf2932018-03-09 04:15:22 -08006782 if mac_address:
sousaedu80135b92021-02-17 15:05:18 +01006783 mac_tag = "<MACAddress>{}</MACAddress>".format(mac_address)
6784 new_item = new_item.replace(
6785 "</IsConnected>\n",
6786 "</IsConnected>\n{}\n".format(mac_tag),
6787 )
kasar3ac5dc42017-03-15 06:28:22 -07006788
sousaedu80135b92021-02-17 15:05:18 +01006789 data = data + new_item + "</NetworkConnectionSection>"
kasarc5bf2932018-03-09 04:15:22 -08006790
sousaedu80135b92021-02-17 15:05:18 +01006791 headers[
6792 "Content-Type"
6793 ] = "application/vnd.vmware.vcloud.networkConnectionSection+xml"
kasarc5bf2932018-03-09 04:15:22 -08006794
sousaedu80135b92021-02-17 15:05:18 +01006795 response = self.perform_request(
6796 req_type="PUT", url=url_rest_call, headers=headers, data=data
6797 )
bhangare1a0b97c2017-06-21 02:20:15 -07006798
6799 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006800 add_headers = {"Content-Type": headers["Content-Type"]}
6801 response = self.retry_rest(
6802 "PUT", url_rest_call, add_headers, data
6803 )
bhangare1a0b97c2017-06-21 02:20:15 -07006804
kasar3ac5dc42017-03-15 06:28:22 -07006805 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01006806 self.logger.error(
6807 "REST call {} failed reason : {}"
6808 "status code : {} ".format(
6809 url_rest_call, response.text, response.status_code
6810 )
6811 )
6812 raise vimconn.VimConnException(
6813 "add_network_adapter_to_vms : Failed to update "
6814 "network connection section"
6815 )
kasar3ac5dc42017-03-15 06:28:22 -07006816 else:
beierl26fec002019-12-06 17:06:40 -05006817 nic_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01006818 result = self.client.get_task_monitor().wait_for_success(
6819 task=nic_task
6820 )
6821
6822 if result.get("status") == "success":
6823 self.logger.info(
6824 "add_network_adapter_to_vms(): VM {} conneced to "
6825 "default NIC type".format(vm_id)
6826 )
kasar3ac5dc42017-03-15 06:28:22 -07006827 else:
sousaedu80135b92021-02-17 15:05:18 +01006828 self.logger.error(
6829 "add_network_adapter_to_vms(): VM {} failed to "
6830 "connect NIC type".format(vm_id)
6831 )
kasar3ac5dc42017-03-15 06:28:22 -07006832 else:
kasarc5bf2932018-03-09 04:15:22 -08006833 for vms in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01006834 vm_id = vms.get("id").split(":")[-1]
kasar3ac5dc42017-03-15 06:28:22 -07006835
sousaedu80135b92021-02-17 15:05:18 +01006836 url_rest_call = (
6837 "{}/api/vApp/vm-{}/networkConnectionSection/".format(
6838 self.url, vm_id
6839 )
6840 )
kasarc5bf2932018-03-09 04:15:22 -08006841
sousaedu80135b92021-02-17 15:05:18 +01006842 headers = {
6843 "Accept": "application/*+xml;version=" + API_VERSION,
6844 "x-vcloud-authorization": self.client._session.headers[
6845 "x-vcloud-authorization"
6846 ],
6847 }
6848 response = self.perform_request(
6849 req_type="GET", url=url_rest_call, headers=headers
6850 )
bhangare1a0b97c2017-06-21 02:20:15 -07006851
6852 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006853 response = self.retry_rest("GET", url_rest_call)
bhangare1a0b97c2017-06-21 02:20:15 -07006854
kasar3ac5dc42017-03-15 06:28:22 -07006855 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01006856 self.logger.error(
6857 "REST call {} failed reason : {}"
6858 "status code : {}".format(
6859 url_rest_call, response.text, response.status_code
6860 )
6861 )
6862 raise vimconn.VimConnException(
6863 "add_network_adapter_to_vms : Failed to get "
6864 "network connection section"
6865 )
beierl26fec002019-12-06 17:06:40 -05006866 data = response.text
kasarc5bf2932018-03-09 04:15:22 -08006867 data = data.split('<Link rel="edit"')[0]
Ravi Chamartye21c9cc2018-10-24 02:14:53 +00006868 vcd_netadapter_type = nic_type
sousaedu80135b92021-02-17 15:05:18 +01006869
6870 if nic_type in ["SR-IOV", "VF"]:
Ravi Chamartye21c9cc2018-10-24 02:14:53 +00006871 vcd_netadapter_type = "SRIOVETHERNETCARD"
6872
sousaedu80135b92021-02-17 15:05:18 +01006873 if "<PrimaryNetworkConnectionIndex>" not in data:
6874 self.logger.debug(
6875 "add_network_adapter PrimaryNIC not in data nic_type {}".format(
6876 nic_type
6877 )
6878 )
kasar3ac5dc42017-03-15 06:28:22 -07006879 item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
6880 <NetworkConnection network="{}">
6881 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
6882 <IsConnected>true</IsConnected>
kasardc1f02e2017-03-25 07:20:30 -07006883 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
kasar3ac5dc42017-03-15 06:28:22 -07006884 <NetworkAdapterType>{}</NetworkAdapterType>
sousaedu80135b92021-02-17 15:05:18 +01006885 </NetworkConnection>""".format(
6886 primary_nic_index,
6887 network_name,
6888 nicIndex,
6889 allocation_mode,
6890 vcd_netadapter_type,
6891 )
6892
kasard2963622017-03-31 05:53:17 -07006893 # Stub for ip_address feature
6894 if ip_address:
sousaedu80135b92021-02-17 15:05:18 +01006895 ip_tag = "<IpAddress>{}</IpAddress>".format(ip_address)
6896 item = item.replace(
6897 "</NetworkConnectionIndex>\n",
6898 "</NetworkConnectionIndex>\n{}\n".format(ip_tag),
6899 )
kasardc1f02e2017-03-25 07:20:30 -07006900
kasarc5bf2932018-03-09 04:15:22 -08006901 if mac_address:
sousaedu80135b92021-02-17 15:05:18 +01006902 mac_tag = "<MACAddress>{}</MACAddress>".format(mac_address)
6903 item = item.replace(
6904 "</IsConnected>\n",
6905 "</IsConnected>\n{}\n".format(mac_tag),
6906 )
kasarc5bf2932018-03-09 04:15:22 -08006907
sousaedu80135b92021-02-17 15:05:18 +01006908 data = data.replace(
6909 "</ovf:Info>\n",
6910 "</ovf:Info>\n{}\n</NetworkConnectionSection>".format(item),
6911 )
kasar3ac5dc42017-03-15 06:28:22 -07006912 else:
sousaedu80135b92021-02-17 15:05:18 +01006913 self.logger.debug(
6914 "add_network_adapter PrimaryNIC in data nic_type {}".format(
6915 nic_type
6916 )
6917 )
kasar3ac5dc42017-03-15 06:28:22 -07006918 new_item = """<NetworkConnection network="{}">
6919 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
6920 <IsConnected>true</IsConnected>
kasardc1f02e2017-03-25 07:20:30 -07006921 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
kasar3ac5dc42017-03-15 06:28:22 -07006922 <NetworkAdapterType>{}</NetworkAdapterType>
sousaedu80135b92021-02-17 15:05:18 +01006923 </NetworkConnection>""".format(
6924 network_name, nicIndex, allocation_mode, vcd_netadapter_type
6925 )
6926
kasard2963622017-03-31 05:53:17 -07006927 # Stub for ip_address feature
6928 if ip_address:
sousaedu80135b92021-02-17 15:05:18 +01006929 ip_tag = "<IpAddress>{}</IpAddress>".format(ip_address)
6930 new_item = new_item.replace(
6931 "</NetworkConnectionIndex>\n",
6932 "</NetworkConnectionIndex>\n{}\n".format(ip_tag),
6933 )
kasardc1f02e2017-03-25 07:20:30 -07006934
kasarc5bf2932018-03-09 04:15:22 -08006935 if mac_address:
sousaedu80135b92021-02-17 15:05:18 +01006936 mac_tag = "<MACAddress>{}</MACAddress>".format(mac_address)
6937 new_item = new_item.replace(
6938 "</IsConnected>\n",
6939 "</IsConnected>\n{}\n".format(mac_tag),
6940 )
kasar3ac5dc42017-03-15 06:28:22 -07006941
sousaedu80135b92021-02-17 15:05:18 +01006942 data = data + new_item + "</NetworkConnectionSection>"
kasarc5bf2932018-03-09 04:15:22 -08006943
sousaedu80135b92021-02-17 15:05:18 +01006944 headers[
6945 "Content-Type"
6946 ] = "application/vnd.vmware.vcloud.networkConnectionSection+xml"
kasarc5bf2932018-03-09 04:15:22 -08006947
sousaedu80135b92021-02-17 15:05:18 +01006948 response = self.perform_request(
6949 req_type="PUT", url=url_rest_call, headers=headers, data=data
6950 )
bhangare1a0b97c2017-06-21 02:20:15 -07006951
6952 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01006953 add_headers = {"Content-Type": headers["Content-Type"]}
6954 response = self.retry_rest(
6955 "PUT", url_rest_call, add_headers, data
6956 )
kasar3ac5dc42017-03-15 06:28:22 -07006957
6958 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01006959 self.logger.error(
6960 "REST call {} failed reason : {}"
6961 "status code : {}".format(
6962 url_rest_call, response.text, response.status_code
6963 )
6964 )
6965 raise vimconn.VimConnException(
6966 "add_network_adapter_to_vms : Failed to update "
6967 "network connection section"
6968 )
kasar3ac5dc42017-03-15 06:28:22 -07006969 else:
beierl26fec002019-12-06 17:06:40 -05006970 nic_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01006971 result = self.client.get_task_monitor().wait_for_success(
6972 task=nic_task
6973 )
6974
6975 if result.get("status") == "success":
6976 self.logger.info(
6977 "add_network_adapter_to_vms(): VM {} "
6978 "conneced to NIC type {}".format(vm_id, nic_type)
6979 )
kasar3ac5dc42017-03-15 06:28:22 -07006980 else:
sousaedu80135b92021-02-17 15:05:18 +01006981 self.logger.error(
6982 "add_network_adapter_to_vms(): VM {} "
6983 "failed to connect NIC type {}".format(vm_id, nic_type)
6984 )
kasar3ac5dc42017-03-15 06:28:22 -07006985 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01006986 self.logger.error(
6987 "add_network_adapter_to_vms() : exception occurred "
6988 "while adding Network adapter"
6989 )
6990
tierno72774862020-05-04 11:44:15 +00006991 raise vimconn.VimConnException(message=exp)
kasarde691232017-03-25 03:37:31 -07006992
kasarde691232017-03-25 03:37:31 -07006993 def set_numa_affinity(self, vmuuid, paired_threads_id):
6994 """
sousaedu80135b92021-02-17 15:05:18 +01006995 Method to assign numa affinity in vm configuration parammeters
6996 Args :
6997 vmuuid - vm uuid
6998 paired_threads_id - one or more virtual processor
6999 numbers
7000 Returns:
7001 return if True
kasarde691232017-03-25 03:37:31 -07007002 """
7003 try:
kasar204e39e2018-01-25 00:57:02 -08007004 vcenter_conect, content = self.get_vcenter_content()
7005 vm_moref_id = self.get_vm_moref_id(vmuuid)
beierlb22ce2d2019-12-12 12:09:51 -05007006 _, vm_obj = self.get_vm_obj(content, vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01007007
kasar204e39e2018-01-25 00:57:02 -08007008 if vm_obj:
7009 config_spec = vim.vm.ConfigSpec()
7010 config_spec.extraConfig = []
7011 opt = vim.option.OptionValue()
sousaedu80135b92021-02-17 15:05:18 +01007012 opt.key = "numa.nodeAffinity"
kasar204e39e2018-01-25 00:57:02 -08007013 opt.value = str(paired_threads_id)
7014 config_spec.extraConfig.append(opt)
7015 task = vm_obj.ReconfigVM_Task(config_spec)
sousaedu80135b92021-02-17 15:05:18 +01007016
kasar204e39e2018-01-25 00:57:02 -08007017 if task:
beierlb22ce2d2019-12-12 12:09:51 -05007018 self.wait_for_vcenter_task(task, vcenter_conect)
kasar204e39e2018-01-25 00:57:02 -08007019 extra_config = vm_obj.config.extraConfig
7020 flag = False
sousaedu80135b92021-02-17 15:05:18 +01007021
kasar204e39e2018-01-25 00:57:02 -08007022 for opts in extra_config:
sousaedu80135b92021-02-17 15:05:18 +01007023 if "numa.nodeAffinity" in opts.key:
kasar204e39e2018-01-25 00:57:02 -08007024 flag = True
sousaedu80135b92021-02-17 15:05:18 +01007025 self.logger.info(
7026 "set_numa_affinity: Sucessfully assign numa affinity "
7027 "value {} for vm {}".format(opt.value, vm_obj)
7028 )
7029
kasar204e39e2018-01-25 00:57:02 -08007030 if flag:
7031 return
7032 else:
7033 self.logger.error("set_numa_affinity: Failed to assign numa affinity")
kasarde691232017-03-25 03:37:31 -07007034 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007035 self.logger.error(
7036 "set_numa_affinity : exception occurred while setting numa affinity "
7037 "for VM {} : {}".format(vm_obj, vm_moref_id)
7038 )
7039
7040 raise vimconn.VimConnException(
7041 "set_numa_affinity : Error {} failed to assign numa "
7042 "affinity".format(exp)
7043 )
kasardc1f02e2017-03-25 07:20:30 -07007044
7045 def cloud_init(self, vapp, cloud_config):
7046 """
7047 Method to inject ssh-key
7048 vapp - vapp object
7049 cloud_config a dictionary with:
7050 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
7051 'users': (optional) list of users to be inserted, each item is a dict with:
7052 'name': (mandatory) user name,
7053 'key-pairs': (optional) list of strings with the public key to be inserted to the user
tierno40e1bce2017-08-09 09:12:04 +02007054 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
7055 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
kasardc1f02e2017-03-25 07:20:30 -07007056 'config-files': (optional). List of files to be transferred. Each item is a dict with:
7057 'dest': (mandatory) string with the destination absolute path
7058 'encoding': (optional, by default text). Can be one of:
7059 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
7060 'content' (mandatory): string with the content of the file
7061 'permissions': (optional) string with file permissions, typically octal notation '0644'
7062 'owner': (optional) file owner, string with the format 'owner:group'
7063 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk
7064 """
kasardc1f02e2017-03-25 07:20:30 -07007065 try:
kasar2aa50742017-08-08 02:11:22 -07007066 if not isinstance(cloud_config, dict):
sousaedu80135b92021-02-17 15:05:18 +01007067 raise Exception(
7068 "cloud_init : parameter cloud_config is not a dictionary"
7069 )
kasar2aa50742017-08-08 02:11:22 -07007070 else:
kasardc1f02e2017-03-25 07:20:30 -07007071 key_pairs = []
7072 userdata = []
sousaedu80135b92021-02-17 15:05:18 +01007073
kasardc1f02e2017-03-25 07:20:30 -07007074 if "key-pairs" in cloud_config:
7075 key_pairs = cloud_config["key-pairs"]
7076
7077 if "users" in cloud_config:
7078 userdata = cloud_config["users"]
7079
kasar2aa50742017-08-08 02:11:22 -07007080 self.logger.debug("cloud_init : Guest os customization started..")
sousaedu80135b92021-02-17 15:05:18 +01007081 customize_script = self.format_script(
7082 key_pairs=key_pairs, users_list=userdata
7083 )
beierlb22ce2d2019-12-12 12:09:51 -05007084 customize_script = customize_script.replace("&", "&amp;")
kasar2aa50742017-08-08 02:11:22 -07007085 self.guest_customization(vapp, customize_script)
kasardc1f02e2017-03-25 07:20:30 -07007086 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007087 self.logger.error(
7088 "cloud_init : exception occurred while injecting " "ssh-key"
7089 )
7090
7091 raise vimconn.VimConnException(
7092 "cloud_init : Error {} failed to inject " "ssh-key".format(exp)
7093 )
bhangare06312472017-03-30 05:49:07 -07007094
kasar2aa50742017-08-08 02:11:22 -07007095 def format_script(self, key_pairs=[], users_list=[]):
kasarc5bf2932018-03-09 04:15:22 -08007096 bash_script = """#!/bin/sh
beierlb22ce2d2019-12-12 12:09:51 -05007097echo performing customization tasks with param $1 at `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"`>> /root/customization.log
7098if [ "$1" = "precustomization" ];then
7099 echo performing precustomization tasks on `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
7100"""
kasar2aa50742017-08-08 02:11:22 -07007101
7102 keys = "\n".join(key_pairs)
7103 if keys:
7104 keys_data = """
7105 if [ ! -d /root/.ssh ];then
7106 mkdir /root/.ssh
7107 chown root:root /root/.ssh
7108 chmod 700 /root/.ssh
7109 touch /root/.ssh/authorized_keys
7110 chown root:root /root/.ssh/authorized_keys
7111 chmod 600 /root/.ssh/authorized_keys
7112 # make centos with selinux happy
7113 which restorecon && restorecon -Rv /root/.ssh
7114 else
7115 touch /root/.ssh/authorized_keys
7116 chown root:root /root/.ssh/authorized_keys
7117 chmod 600 /root/.ssh/authorized_keys
7118 fi
7119 echo '{key}' >> /root/.ssh/authorized_keys
sousaedu80135b92021-02-17 15:05:18 +01007120 """.format(
7121 key=keys
7122 )
kasar2aa50742017-08-08 02:11:22 -07007123
beierlb22ce2d2019-12-12 12:09:51 -05007124 bash_script += keys_data
kasar2aa50742017-08-08 02:11:22 -07007125
7126 for user in users_list:
sousaedu80135b92021-02-17 15:05:18 +01007127 if "name" in user:
7128 user_name = user["name"]
7129
7130 if "key-pairs" in user:
7131 user_keys = "\n".join(user["key-pairs"])
kasar2aa50742017-08-08 02:11:22 -07007132 else:
7133 user_keys = None
7134
7135 add_user_name = """
7136 useradd -d /home/{user_name} -m -g users -s /bin/bash {user_name}
sousaedu80135b92021-02-17 15:05:18 +01007137 """.format(
7138 user_name=user_name
7139 )
kasar2aa50742017-08-08 02:11:22 -07007140
beierlb22ce2d2019-12-12 12:09:51 -05007141 bash_script += add_user_name
kasar2aa50742017-08-08 02:11:22 -07007142
7143 if user_keys:
7144 user_keys_data = """
7145 mkdir /home/{user_name}/.ssh
7146 chown {user_name}:{user_name} /home/{user_name}/.ssh
7147 chmod 700 /home/{user_name}/.ssh
7148 touch /home/{user_name}/.ssh/authorized_keys
7149 chown {user_name}:{user_name} /home/{user_name}/.ssh/authorized_keys
7150 chmod 600 /home/{user_name}/.ssh/authorized_keys
7151 # make centos with selinux happy
7152 which restorecon && restorecon -Rv /home/{user_name}/.ssh
7153 echo '{user_key}' >> /home/{user_name}/.ssh/authorized_keys
sousaedu80135b92021-02-17 15:05:18 +01007154 """.format(
7155 user_name=user_name, user_key=user_keys
7156 )
beierlb22ce2d2019-12-12 12:09:51 -05007157 bash_script += user_keys_data
kasar2aa50742017-08-08 02:11:22 -07007158
beierlb22ce2d2019-12-12 12:09:51 -05007159 return bash_script + "\n\tfi"
kasar2aa50742017-08-08 02:11:22 -07007160
7161 def guest_customization(self, vapp, customize_script):
7162 """
7163 Method to customize guest os
7164 vapp - Vapp object
7165 customize_script - Customize script to be run at first boot of VM.
7166 """
kasarc5bf2932018-03-09 04:15:22 -08007167 for vm in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01007168 vm_id = vm.get("id").split(":")[-1]
7169 vm_name = vm.get("name")
7170 vm_name = vm_name.replace("_", "-")
sbhangarea8e5b782018-06-21 02:10:03 -07007171
sousaedu80135b92021-02-17 15:05:18 +01007172 vm_customization_url = (
7173 "{}/api/vApp/vm-{}/guestCustomizationSection/".format(self.url, vm_id)
7174 )
7175 headers = {
7176 "Accept": "application/*+xml;version=" + API_VERSION,
7177 "x-vcloud-authorization": self.client._session.headers[
7178 "x-vcloud-authorization"
7179 ],
7180 }
kasarc5bf2932018-03-09 04:15:22 -08007181
sousaedu80135b92021-02-17 15:05:18 +01007182 headers[
7183 "Content-Type"
7184 ] = "application/vnd.vmware.vcloud.guestCustomizationSection+xml"
kasarc5bf2932018-03-09 04:15:22 -08007185
7186 data = """<GuestCustomizationSection
7187 xmlns="http://www.vmware.com/vcloud/v1.5"
7188 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
beierlb22ce2d2019-12-12 12:09:51 -05007189 ovf:required="false" href="{}"
7190 type="application/vnd.vmware.vcloud.guestCustomizationSection+xml">
kasarc5bf2932018-03-09 04:15:22 -08007191 <ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
7192 <Enabled>true</Enabled>
7193 <ChangeSid>false</ChangeSid>
7194 <VirtualMachineId>{}</VirtualMachineId>
7195 <JoinDomainEnabled>false</JoinDomainEnabled>
7196 <UseOrgSettings>false</UseOrgSettings>
7197 <AdminPasswordEnabled>false</AdminPasswordEnabled>
7198 <AdminPasswordAuto>true</AdminPasswordAuto>
7199 <AdminAutoLogonEnabled>false</AdminAutoLogonEnabled>
7200 <AdminAutoLogonCount>0</AdminAutoLogonCount>
7201 <ResetPasswordRequired>false</ResetPasswordRequired>
7202 <CustomizationScript>{}</CustomizationScript>
7203 <ComputerName>{}</ComputerName>
beierlb22ce2d2019-12-12 12:09:51 -05007204 <Link href="{}"
7205 type="application/vnd.vmware.vcloud.guestCustomizationSection+xml" rel="edit"/>
sbhangarea8e5b782018-06-21 02:10:03 -07007206 </GuestCustomizationSection>
sousaedu80135b92021-02-17 15:05:18 +01007207 """.format(
7208 vm_customization_url,
7209 vm_id,
7210 customize_script,
7211 vm_name,
7212 vm_customization_url,
7213 )
kasarc5bf2932018-03-09 04:15:22 -08007214
sousaedu80135b92021-02-17 15:05:18 +01007215 response = self.perform_request(
7216 req_type="PUT", url=vm_customization_url, headers=headers, data=data
7217 )
kasarc5bf2932018-03-09 04:15:22 -08007218 if response.status_code == 202:
beierl26fec002019-12-06 17:06:40 -05007219 guest_task = self.get_task_from_response(response.text)
kasarc5bf2932018-03-09 04:15:22 -08007220 self.client.get_task_monitor().wait_for_success(task=guest_task)
sousaedu80135b92021-02-17 15:05:18 +01007221 self.logger.info(
7222 "guest_customization : customized guest os task "
7223 "completed for VM {}".format(vm_name)
7224 )
kasar2aa50742017-08-08 02:11:22 -07007225 else:
sousaedu80135b92021-02-17 15:05:18 +01007226 self.logger.error(
7227 "guest_customization : task for customized guest os"
7228 "failed for VM {}".format(vm_name)
7229 )
7230
7231 raise vimconn.VimConnException(
7232 "guest_customization : failed to perform"
7233 "guest os customization on VM {}".format(vm_name)
7234 )
bhangare06312472017-03-30 05:49:07 -07007235
bhangare1a0b97c2017-06-21 02:20:15 -07007236 def add_new_disk(self, vapp_uuid, disk_size):
bhangare06312472017-03-30 05:49:07 -07007237 """
sousaedu80135b92021-02-17 15:05:18 +01007238 Method to create an empty vm disk
bhangare06312472017-03-30 05:49:07 -07007239
sousaedu80135b92021-02-17 15:05:18 +01007240 Args:
7241 vapp_uuid - is vapp identifier.
7242 disk_size - size of disk to be created in GB
bhangare06312472017-03-30 05:49:07 -07007243
sousaedu80135b92021-02-17 15:05:18 +01007244 Returns:
7245 None
bhangare06312472017-03-30 05:49:07 -07007246 """
7247 status = False
7248 vm_details = None
7249 try:
beierlb22ce2d2019-12-12 12:09:51 -05007250 # Disk size in GB, convert it into MB
bhangare06312472017-03-30 05:49:07 -07007251 if disk_size is not None:
7252 disk_size_mb = int(disk_size) * 1024
7253 vm_details = self.get_vapp_details_rest(vapp_uuid)
7254
7255 if vm_details and "vm_virtual_hardware" in vm_details:
sousaedu80135b92021-02-17 15:05:18 +01007256 self.logger.info(
7257 "Adding disk to VM: {} disk size:{}GB".format(
7258 vm_details["name"], disk_size
7259 )
7260 )
bhangare06312472017-03-30 05:49:07 -07007261 disk_href = vm_details["vm_virtual_hardware"]["disk_edit_href"]
bhangare1a0b97c2017-06-21 02:20:15 -07007262 status = self.add_new_disk_rest(disk_href, disk_size_mb)
bhangare06312472017-03-30 05:49:07 -07007263 except Exception as exp:
7264 msg = "Error occurred while creating new disk {}.".format(exp)
7265 self.rollback_newvm(vapp_uuid, msg)
7266
7267 if status:
sousaedu80135b92021-02-17 15:05:18 +01007268 self.logger.info(
7269 "Added new disk to VM: {} disk size:{}GB".format(
7270 vm_details["name"], disk_size
7271 )
7272 )
bhangare06312472017-03-30 05:49:07 -07007273 else:
beierlb22ce2d2019-12-12 12:09:51 -05007274 # If failed to add disk, delete VM
sousaedu80135b92021-02-17 15:05:18 +01007275 msg = "add_new_disk: Failed to add new disk to {}".format(
7276 vm_details["name"]
7277 )
bhangare06312472017-03-30 05:49:07 -07007278 self.rollback_newvm(vapp_uuid, msg)
7279
bhangare1a0b97c2017-06-21 02:20:15 -07007280 def add_new_disk_rest(self, disk_href, disk_size_mb):
bhangare06312472017-03-30 05:49:07 -07007281 """
7282 Retrives vApp Disks section & add new empty disk
7283
7284 Args:
7285 disk_href: Disk section href to addd disk
7286 disk_size_mb: Disk size in MB
7287
7288 Returns: Status of add new disk task
7289 """
7290 status = False
kasarc5bf2932018-03-09 04:15:22 -08007291 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01007292 headers = {
7293 "Accept": "application/*+xml;version=" + API_VERSION,
7294 "x-vcloud-authorization": self.client._session.headers[
7295 "x-vcloud-authorization"
7296 ],
7297 }
7298 response = self.perform_request(
7299 req_type="GET", url=disk_href, headers=headers
7300 )
bhangare1a0b97c2017-06-21 02:20:15 -07007301
7302 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01007303 response = self.retry_rest("GET", disk_href)
bhangare06312472017-03-30 05:49:07 -07007304
7305 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01007306 self.logger.error(
7307 "add_new_disk_rest: GET REST API call {} failed. Return status code {}".format(
7308 disk_href, response.status_code
7309 )
7310 )
7311
bhangare06312472017-03-30 05:49:07 -07007312 return status
sousaedu80135b92021-02-17 15:05:18 +01007313
bhangare06312472017-03-30 05:49:07 -07007314 try:
beierlb22ce2d2019-12-12 12:09:51 -05007315 # Find but type & max of instance IDs assigned to disks
beierl01bd6692019-12-09 17:06:20 -05007316 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
sousaedu80135b92021-02-17 15:05:18 +01007317 namespaces = {
7318 prefix: uri for prefix, uri in lxmlroot_respond.nsmap.items() if prefix
7319 }
beierlb22ce2d2019-12-12 12:09:51 -05007320 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
bhangare06312472017-03-30 05:49:07 -07007321 instance_id = 0
sousaedu80135b92021-02-17 15:05:18 +01007322
7323 for item in lxmlroot_respond.iterfind("xmlns:Item", namespaces):
beierlb22ce2d2019-12-12 12:09:51 -05007324 if item.find("rasd:Description", namespaces).text == "Hard disk":
7325 inst_id = int(item.find("rasd:InstanceID", namespaces).text)
sousaedu80135b92021-02-17 15:05:18 +01007326
bhangare06312472017-03-30 05:49:07 -07007327 if inst_id > instance_id:
7328 instance_id = inst_id
beierlb22ce2d2019-12-12 12:09:51 -05007329 disk_item = item.find("rasd:HostResource", namespaces)
sousaedu80135b92021-02-17 15:05:18 +01007330 bus_subtype = disk_item.attrib[
7331 "{" + namespaces["xmlns"] + "}busSubType"
7332 ]
7333 bus_type = disk_item.attrib[
7334 "{" + namespaces["xmlns"] + "}busType"
7335 ]
bhangare06312472017-03-30 05:49:07 -07007336
7337 instance_id = instance_id + 1
beierlb22ce2d2019-12-12 12:09:51 -05007338 new_item = """<Item>
bhangare06312472017-03-30 05:49:07 -07007339 <rasd:Description>Hard disk</rasd:Description>
7340 <rasd:ElementName>New disk</rasd:ElementName>
7341 <rasd:HostResource
7342 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
7343 vcloud:capacity="{}"
7344 vcloud:busSubType="{}"
7345 vcloud:busType="{}"></rasd:HostResource>
7346 <rasd:InstanceID>{}</rasd:InstanceID>
7347 <rasd:ResourceType>17</rasd:ResourceType>
sousaedu80135b92021-02-17 15:05:18 +01007348 </Item>""".format(
7349 disk_size_mb, bus_subtype, bus_type, instance_id
7350 )
bhangare06312472017-03-30 05:49:07 -07007351
beierl26fec002019-12-06 17:06:40 -05007352 new_data = response.text
beierlb22ce2d2019-12-12 12:09:51 -05007353 # Add new item at the bottom
sousaedu80135b92021-02-17 15:05:18 +01007354 new_data = new_data.replace(
7355 "</Item>\n</RasdItemsList>",
7356 "</Item>\n{}\n</RasdItemsList>".format(new_item),
7357 )
bhangare06312472017-03-30 05:49:07 -07007358
7359 # Send PUT request to modify virtual hardware section with new disk
sousaedu80135b92021-02-17 15:05:18 +01007360 headers[
7361 "Content-Type"
7362 ] = "application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1"
bhangare06312472017-03-30 05:49:07 -07007363
sousaedu80135b92021-02-17 15:05:18 +01007364 response = self.perform_request(
7365 req_type="PUT", url=disk_href, data=new_data, headers=headers
7366 )
bhangare1a0b97c2017-06-21 02:20:15 -07007367
7368 if response.status_code == 403:
sousaedu80135b92021-02-17 15:05:18 +01007369 add_headers = {"Content-Type": headers["Content-Type"]}
7370 response = self.retry_rest("PUT", disk_href, add_headers, new_data)
bhangare06312472017-03-30 05:49:07 -07007371
7372 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01007373 self.logger.error(
7374 "PUT REST API call {} failed. Return status code {}. response.text:{}".format(
7375 disk_href, response.status_code, response.text
7376 )
7377 )
bhangare06312472017-03-30 05:49:07 -07007378 else:
beierl26fec002019-12-06 17:06:40 -05007379 add_disk_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01007380 result = self.client.get_task_monitor().wait_for_success(
7381 task=add_disk_task
7382 )
7383
7384 if result.get("status") == "success":
kasarc5bf2932018-03-09 04:15:22 -08007385 status = True
7386 else:
sousaedu80135b92021-02-17 15:05:18 +01007387 self.logger.error(
7388 "Add new disk REST task failed to add {} MB disk".format(
7389 disk_size_mb
7390 )
7391 )
bhangare06312472017-03-30 05:49:07 -07007392 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007393 self.logger.error(
7394 "Error occurred calling rest api for creating new disk {}".format(exp)
7395 )
bhangare06312472017-03-30 05:49:07 -07007396
7397 return status
7398
sousaedu80135b92021-02-17 15:05:18 +01007399 def add_existing_disk(
7400 self,
7401 catalogs=None,
7402 image_id=None,
7403 size=None,
7404 template_name=None,
7405 vapp_uuid=None,
7406 ):
bhangare06312472017-03-30 05:49:07 -07007407 """
sousaedu80135b92021-02-17 15:05:18 +01007408 Method to add existing disk to vm
7409 Args :
7410 catalogs - List of VDC catalogs
7411 image_id - Catalog ID
7412 template_name - Name of template in catalog
7413 vapp_uuid - UUID of vApp
7414 Returns:
7415 None
bhangare06312472017-03-30 05:49:07 -07007416 """
7417 disk_info = None
7418 vcenter_conect, content = self.get_vcenter_content()
beierlb22ce2d2019-12-12 12:09:51 -05007419 # find moref-id of vm in image
sousaedu80135b92021-02-17 15:05:18 +01007420 catalog_vm_info = self.get_vapp_template_details(
7421 catalogs=catalogs,
7422 image_id=image_id,
7423 )
bhangare06312472017-03-30 05:49:07 -07007424
7425 if catalog_vm_info and "vm_vcenter_info" in catalog_vm_info:
7426 if "vm_moref_id" in catalog_vm_info["vm_vcenter_info"]:
sousaedu80135b92021-02-17 15:05:18 +01007427 catalog_vm_moref_id = catalog_vm_info["vm_vcenter_info"].get(
7428 "vm_moref_id", None
7429 )
7430
bhangare06312472017-03-30 05:49:07 -07007431 if catalog_vm_moref_id:
sousaedu80135b92021-02-17 15:05:18 +01007432 self.logger.info(
7433 "Moref_id of VM in catalog : {}".format(catalog_vm_moref_id)
7434 )
beierlb22ce2d2019-12-12 12:09:51 -05007435 _, catalog_vm_obj = self.get_vm_obj(content, catalog_vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01007436
bhangare06312472017-03-30 05:49:07 -07007437 if catalog_vm_obj:
beierlb22ce2d2019-12-12 12:09:51 -05007438 # find existing disk
bhangare06312472017-03-30 05:49:07 -07007439 disk_info = self.find_disk(catalog_vm_obj)
7440 else:
7441 exp_msg = "No VM with image id {} found".format(image_id)
7442 self.rollback_newvm(vapp_uuid, exp_msg, exp_type="NotFound")
7443 else:
7444 exp_msg = "No Image found with image ID {} ".format(image_id)
7445 self.rollback_newvm(vapp_uuid, exp_msg, exp_type="NotFound")
7446
7447 if disk_info:
7448 self.logger.info("Existing disk_info : {}".format(disk_info))
beierlb22ce2d2019-12-12 12:09:51 -05007449 # get VM
bhangare06312472017-03-30 05:49:07 -07007450 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
beierlb22ce2d2019-12-12 12:09:51 -05007451 _, vm_obj = self.get_vm_obj(content, vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01007452
bhangare06312472017-03-30 05:49:07 -07007453 if vm_obj:
sousaedu80135b92021-02-17 15:05:18 +01007454 status = self.add_disk(
7455 vcenter_conect=vcenter_conect,
7456 vm=vm_obj,
7457 disk_info=disk_info,
7458 size=size,
7459 vapp_uuid=vapp_uuid,
7460 )
7461
bhangare06312472017-03-30 05:49:07 -07007462 if status:
sousaedu80135b92021-02-17 15:05:18 +01007463 self.logger.info(
7464 "Disk from image id {} added to {}".format(
7465 image_id, vm_obj.config.name
7466 )
7467 )
bhangare06312472017-03-30 05:49:07 -07007468 else:
7469 msg = "No disk found with image id {} to add in VM {}".format(
sousaedu80135b92021-02-17 15:05:18 +01007470 image_id, vm_obj.config.name
7471 )
bhangare06312472017-03-30 05:49:07 -07007472 self.rollback_newvm(vapp_uuid, msg, exp_type="NotFound")
7473
bhangare06312472017-03-30 05:49:07 -07007474 def find_disk(self, vm_obj):
7475 """
sousaedu80135b92021-02-17 15:05:18 +01007476 Method to find details of existing disk in VM
7477 Args:
bhangare06312472017-03-30 05:49:07 -07007478 vm_obj - vCenter object of VM
bhangare06312472017-03-30 05:49:07 -07007479 Returns:
7480 disk_info : dict of disk details
7481 """
7482 disk_info = {}
7483 if vm_obj:
7484 try:
7485 devices = vm_obj.config.hardware.device
sousaedu80135b92021-02-17 15:05:18 +01007486
bhangare06312472017-03-30 05:49:07 -07007487 for device in devices:
7488 if type(device) is vim.vm.device.VirtualDisk:
aticig2b24d622022-03-11 15:03:55 +03007489 if isinstance(
7490 device.backing,
7491 vim.vm.device.VirtualDisk.FlatVer2BackingInfo,
7492 ) and hasattr(device.backing, "fileName"):
bhangare06312472017-03-30 05:49:07 -07007493 disk_info["full_path"] = device.backing.fileName
7494 disk_info["datastore"] = device.backing.datastore
7495 disk_info["capacityKB"] = device.capacityInKB
7496 break
7497 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007498 self.logger.error(
7499 "find_disk() : exception occurred while "
7500 "getting existing disk details :{}".format(exp)
7501 )
7502
bhangare06312472017-03-30 05:49:07 -07007503 return disk_info
7504
sousaedu80135b92021-02-17 15:05:18 +01007505 def add_disk(
7506 self, vcenter_conect=None, vm=None, size=None, vapp_uuid=None, disk_info={}
7507 ):
bhangare06312472017-03-30 05:49:07 -07007508 """
sousaedu80135b92021-02-17 15:05:18 +01007509 Method to add existing disk in VM
7510 Args :
7511 vcenter_conect - vCenter content object
7512 vm - vCenter vm object
7513 disk_info : dict of disk details
7514 Returns:
7515 status : status of add disk task
bhangare06312472017-03-30 05:49:07 -07007516 """
7517 datastore = disk_info["datastore"] if "datastore" in disk_info else None
7518 fullpath = disk_info["full_path"] if "full_path" in disk_info else None
7519 capacityKB = disk_info["capacityKB"] if "capacityKB" in disk_info else None
7520 if size is not None:
beierlb22ce2d2019-12-12 12:09:51 -05007521 # Convert size from GB to KB
bhangare06312472017-03-30 05:49:07 -07007522 sizeKB = int(size) * 1024 * 1024
beierlb22ce2d2019-12-12 12:09:51 -05007523 # compare size of existing disk and user given size.Assign whicherver is greater
sousaedu80135b92021-02-17 15:05:18 +01007524 self.logger.info(
7525 "Add Existing disk : sizeKB {} , capacityKB {}".format(
7526 sizeKB, capacityKB
7527 )
7528 )
7529
bhangare06312472017-03-30 05:49:07 -07007530 if sizeKB > capacityKB:
7531 capacityKB = sizeKB
7532
7533 if datastore and fullpath and capacityKB:
7534 try:
7535 spec = vim.vm.ConfigSpec()
7536 # get all disks on a VM, set unit_number to the next available
7537 unit_number = 0
7538 for dev in vm.config.hardware.device:
sousaedu80135b92021-02-17 15:05:18 +01007539 if hasattr(dev.backing, "fileName"):
bhangare06312472017-03-30 05:49:07 -07007540 unit_number = int(dev.unitNumber) + 1
7541 # unit_number 7 reserved for scsi controller
sousaedu80135b92021-02-17 15:05:18 +01007542
bhangare06312472017-03-30 05:49:07 -07007543 if unit_number == 7:
7544 unit_number += 1
sousaedu80135b92021-02-17 15:05:18 +01007545
bhangare06312472017-03-30 05:49:07 -07007546 if isinstance(dev, vim.vm.device.VirtualDisk):
beierlb22ce2d2019-12-12 12:09:51 -05007547 # vim.vm.device.VirtualSCSIController
bhangare06312472017-03-30 05:49:07 -07007548 controller_key = dev.controllerKey
7549
sousaedu80135b92021-02-17 15:05:18 +01007550 self.logger.info(
7551 "Add Existing disk : unit number {} , controller key {}".format(
7552 unit_number, controller_key
7553 )
7554 )
bhangare06312472017-03-30 05:49:07 -07007555 # add disk here
7556 dev_changes = []
7557 disk_spec = vim.vm.device.VirtualDeviceSpec()
7558 disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
7559 disk_spec.device = vim.vm.device.VirtualDisk()
sousaedu80135b92021-02-17 15:05:18 +01007560 disk_spec.device.backing = (
bhangare06312472017-03-30 05:49:07 -07007561 vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
sousaedu80135b92021-02-17 15:05:18 +01007562 )
bhangare06312472017-03-30 05:49:07 -07007563 disk_spec.device.backing.thinProvisioned = True
sousaedu80135b92021-02-17 15:05:18 +01007564 disk_spec.device.backing.diskMode = "persistent"
beierlb22ce2d2019-12-12 12:09:51 -05007565 disk_spec.device.backing.datastore = datastore
7566 disk_spec.device.backing.fileName = fullpath
bhangare06312472017-03-30 05:49:07 -07007567
7568 disk_spec.device.unitNumber = unit_number
7569 disk_spec.device.capacityInKB = capacityKB
7570 disk_spec.device.controllerKey = controller_key
7571 dev_changes.append(disk_spec)
7572 spec.deviceChange = dev_changes
7573 task = vm.ReconfigVM_Task(spec=spec)
7574 status = self.wait_for_vcenter_task(task, vcenter_conect)
sousaedu80135b92021-02-17 15:05:18 +01007575
bhangare06312472017-03-30 05:49:07 -07007576 return status
7577 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007578 exp_msg = (
7579 "add_disk() : exception {} occurred while adding disk "
7580 "{} to vm {}".format(exp, fullpath, vm.config.name)
7581 )
bhangare06312472017-03-30 05:49:07 -07007582 self.rollback_newvm(vapp_uuid, exp_msg)
7583 else:
sousaedu80135b92021-02-17 15:05:18 +01007584 msg = "add_disk() : Can not add disk to VM with disk info {} ".format(
7585 disk_info
7586 )
bhangare06312472017-03-30 05:49:07 -07007587 self.rollback_newvm(vapp_uuid, msg)
7588
bhangare06312472017-03-30 05:49:07 -07007589 def get_vcenter_content(self):
7590 """
sousaedu80135b92021-02-17 15:05:18 +01007591 Get the vsphere content object
bhangare06312472017-03-30 05:49:07 -07007592 """
7593 try:
7594 vm_vcenter_info = self.get_vm_vcenter_info()
7595 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007596 self.logger.error(
7597 "Error occurred while getting vCenter infromationn"
7598 " for VM : {}".format(exp)
7599 )
7600
tierno72774862020-05-04 11:44:15 +00007601 raise vimconn.VimConnException(message=exp)
bhangare06312472017-03-30 05:49:07 -07007602
7603 context = None
sousaedu80135b92021-02-17 15:05:18 +01007604 if hasattr(ssl, "_create_unverified_context"):
bhangare06312472017-03-30 05:49:07 -07007605 context = ssl._create_unverified_context()
7606
7607 vcenter_conect = SmartConnect(
beierlb22ce2d2019-12-12 12:09:51 -05007608 host=vm_vcenter_info["vm_vcenter_ip"],
7609 user=vm_vcenter_info["vm_vcenter_user"],
7610 pwd=vm_vcenter_info["vm_vcenter_password"],
7611 port=int(vm_vcenter_info["vm_vcenter_port"]),
sousaedu80135b92021-02-17 15:05:18 +01007612 sslContext=context,
7613 )
bhangare06312472017-03-30 05:49:07 -07007614 atexit.register(Disconnect, vcenter_conect)
7615 content = vcenter_conect.RetrieveContent()
sousaedu80135b92021-02-17 15:05:18 +01007616
bhangare06312472017-03-30 05:49:07 -07007617 return vcenter_conect, content
7618
bhangare06312472017-03-30 05:49:07 -07007619 def get_vm_moref_id(self, vapp_uuid):
7620 """
7621 Get the moref_id of given VM
7622 """
7623 try:
7624 if vapp_uuid:
sousaedu80135b92021-02-17 15:05:18 +01007625 vm_details = self.get_vapp_details_rest(
7626 vapp_uuid, need_admin_access=True
7627 )
7628
bhangare06312472017-03-30 05:49:07 -07007629 if vm_details and "vm_vcenter_info" in vm_details:
7630 vm_moref_id = vm_details["vm_vcenter_info"].get("vm_moref_id", None)
bhangare06312472017-03-30 05:49:07 -07007631
sousaedu80135b92021-02-17 15:05:18 +01007632 return vm_moref_id
bhangare06312472017-03-30 05:49:07 -07007633 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007634 self.logger.error(
7635 "Error occurred while getting VM moref ID " " for VM : {}".format(exp)
7636 )
7637
bhangare06312472017-03-30 05:49:07 -07007638 return None
7639
sousaedu80135b92021-02-17 15:05:18 +01007640 def get_vapp_template_details(
7641 self, catalogs=None, image_id=None, template_name=None
7642 ):
bhangare06312472017-03-30 05:49:07 -07007643 """
sousaedu80135b92021-02-17 15:05:18 +01007644 Method to get vApp template details
7645 Args :
7646 catalogs - list of VDC catalogs
7647 image_id - Catalog ID to find
7648 template_name : template name in catalog
7649 Returns:
7650 parsed_respond : dict of vApp tempalte details
bhangare06312472017-03-30 05:49:07 -07007651 """
7652 parsed_response = {}
7653
7654 vca = self.connect_as_admin()
7655 if not vca:
tierno72774862020-05-04 11:44:15 +00007656 raise vimconn.VimConnConnectionException("Failed to connect vCD")
bhangare06312472017-03-30 05:49:07 -07007657
7658 try:
beierlb22ce2d2019-12-12 12:09:51 -05007659 org, _ = self.get_vdc_details()
bhangare06312472017-03-30 05:49:07 -07007660 catalog = self.get_catalog_obj(image_id, catalogs)
7661 if catalog:
sousaedu80135b92021-02-17 15:05:18 +01007662 items = org.get_catalog_item(catalog.get("name"), catalog.get("name"))
kasarc5bf2932018-03-09 04:15:22 -08007663 catalog_items = [items.attrib]
7664
bhangare06312472017-03-30 05:49:07 -07007665 if len(catalog_items) == 1:
sousaedu80135b92021-02-17 15:05:18 +01007666 headers = {
7667 "Accept": "application/*+xml;version=" + API_VERSION,
7668 "x-vcloud-authorization": vca._session.headers[
7669 "x-vcloud-authorization"
7670 ],
7671 }
7672 response = self.perform_request(
7673 req_type="GET",
7674 url=catalog_items[0].get("href"),
7675 headers=headers,
7676 )
beierl26fec002019-12-06 17:06:40 -05007677 catalogItem = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01007678 entity = [
7679 child
7680 for child in catalogItem
7681 if child.get("type")
7682 == "application/vnd.vmware.vcloud.vAppTemplate+xml"
7683 ][0]
bhangare06312472017-03-30 05:49:07 -07007684 vapp_tempalte_href = entity.get("href")
beierlb22ce2d2019-12-12 12:09:51 -05007685 # get vapp details and parse moref id
bhangare06312472017-03-30 05:49:07 -07007686
beierlb22ce2d2019-12-12 12:09:51 -05007687 namespaces = {
sousaedu80135b92021-02-17 15:05:18 +01007688 "vssd": "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData",
7689 "ovf": "http://schemas.dmtf.org/ovf/envelope/1",
7690 "vmw": "http://www.vmware.com/schema/ovf",
7691 "vm": "http://www.vmware.com/vcloud/v1.5",
7692 "rasd": "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
7693 "vmext": "http://www.vmware.com/vcloud/extension/v1.5",
7694 "xmlns": "http://www.vmware.com/vcloud/v1.5",
beierlb22ce2d2019-12-12 12:09:51 -05007695 }
bhangare06312472017-03-30 05:49:07 -07007696
kasarc5bf2932018-03-09 04:15:22 -08007697 if vca._session:
sousaedu80135b92021-02-17 15:05:18 +01007698 response = self.perform_request(
7699 req_type="GET", url=vapp_tempalte_href, headers=headers
7700 )
bhangare06312472017-03-30 05:49:07 -07007701
7702 if response.status_code != requests.codes.ok:
sousaedu80135b92021-02-17 15:05:18 +01007703 self.logger.debug(
7704 "REST API call {} failed. Return status code {}".format(
7705 vapp_tempalte_href, response.status_code
7706 )
7707 )
bhangare06312472017-03-30 05:49:07 -07007708 else:
beierl26fec002019-12-06 17:06:40 -05007709 xmlroot_respond = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01007710 children_section = xmlroot_respond.find(
7711 "vm:Children/", namespaces
7712 )
7713
bhangare06312472017-03-30 05:49:07 -07007714 if children_section is not None:
sousaedu80135b92021-02-17 15:05:18 +01007715 vCloud_extension_section = children_section.find(
7716 "xmlns:VCloudExtension", namespaces
7717 )
7718
bhangare06312472017-03-30 05:49:07 -07007719 if vCloud_extension_section is not None:
7720 vm_vcenter_info = {}
sousaedu80135b92021-02-17 15:05:18 +01007721 vim_info = vCloud_extension_section.find(
7722 "vmext:VmVimInfo", namespaces
7723 )
7724 vmext = vim_info.find(
7725 "vmext:VmVimObjectRef", namespaces
7726 )
bhangare06312472017-03-30 05:49:07 -07007727
sousaedu80135b92021-02-17 15:05:18 +01007728 if vmext is not None:
7729 vm_vcenter_info["vm_moref_id"] = vmext.find(
7730 "vmext:MoRef", namespaces
7731 ).text
7732
7733 parsed_response["vm_vcenter_info"] = vm_vcenter_info
beierlb22ce2d2019-12-12 12:09:51 -05007734 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007735 self.logger.info(
7736 "Error occurred calling rest api for getting vApp details {}".format(
7737 exp
7738 )
7739 )
bhangare06312472017-03-30 05:49:07 -07007740
7741 return parsed_response
7742
beierlb22ce2d2019-12-12 12:09:51 -05007743 def rollback_newvm(self, vapp_uuid, msg, exp_type="Genric"):
bhangare06312472017-03-30 05:49:07 -07007744 """
sousaedu80135b92021-02-17 15:05:18 +01007745 Method to delete vApp
7746 Args :
7747 vapp_uuid - vApp UUID
7748 msg - Error message to be logged
7749 exp_type : Exception type
7750 Returns:
7751 None
bhangare06312472017-03-30 05:49:07 -07007752 """
7753 if vapp_uuid:
beierlb22ce2d2019-12-12 12:09:51 -05007754 self.delete_vminstance(vapp_uuid)
bhangare06312472017-03-30 05:49:07 -07007755 else:
7756 msg = "No vApp ID"
sousaedu80135b92021-02-17 15:05:18 +01007757
bhangare06312472017-03-30 05:49:07 -07007758 self.logger.error(msg)
sousaedu80135b92021-02-17 15:05:18 +01007759
bhangare06312472017-03-30 05:49:07 -07007760 if exp_type == "Genric":
tierno72774862020-05-04 11:44:15 +00007761 raise vimconn.VimConnException(msg)
bhangare06312472017-03-30 05:49:07 -07007762 elif exp_type == "NotFound":
tierno72774862020-05-04 11:44:15 +00007763 raise vimconn.VimConnNotFoundException(message=msg)
bhangare06312472017-03-30 05:49:07 -07007764
kateac1e3792017-04-01 02:16:39 -07007765 def add_sriov(self, vapp_uuid, sriov_nets, vmname_andid):
7766 """
sousaedu80135b92021-02-17 15:05:18 +01007767 Method to attach SRIOV adapters to VM
kateac1e3792017-04-01 02:16:39 -07007768
sousaedu80135b92021-02-17 15:05:18 +01007769 Args:
7770 vapp_uuid - uuid of vApp/VM
7771 sriov_nets - SRIOV devices infromation as specified in VNFD (flavor)
7772 vmname_andid - vmname
kateac1e3792017-04-01 02:16:39 -07007773
sousaedu80135b92021-02-17 15:05:18 +01007774 Returns:
7775 The status of add SRIOV adapter task , vm object and
7776 vcenter_conect object
kateac1e3792017-04-01 02:16:39 -07007777 """
7778 vm_obj = None
7779 vcenter_conect, content = self.get_vcenter_content()
7780 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
7781
7782 if vm_moref_id:
7783 try:
7784 no_of_sriov_devices = len(sriov_nets)
7785 if no_of_sriov_devices > 0:
beierlb22ce2d2019-12-12 12:09:51 -05007786 # Get VM and its host
kateac1e3792017-04-01 02:16:39 -07007787 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
sousaedu80135b92021-02-17 15:05:18 +01007788 self.logger.info(
7789 "VM {} is currently on host {}".format(vm_obj, host_obj)
7790 )
7791
kateac1e3792017-04-01 02:16:39 -07007792 if host_obj and vm_obj:
beierlb22ce2d2019-12-12 12:09:51 -05007793 # get SRIOV devies from host on which vapp is currently installed
sousaedu80135b92021-02-17 15:05:18 +01007794 avilable_sriov_devices = self.get_sriov_devices(
7795 host_obj,
7796 no_of_sriov_devices,
7797 )
kateac1e3792017-04-01 02:16:39 -07007798
7799 if len(avilable_sriov_devices) == 0:
beierlb22ce2d2019-12-12 12:09:51 -05007800 # find other hosts with active pci devices
sousaedu80135b92021-02-17 15:05:18 +01007801 (
7802 new_host_obj,
7803 avilable_sriov_devices,
7804 ) = self.get_host_and_sriov_devices(
beierlb22ce2d2019-12-12 12:09:51 -05007805 content,
7806 no_of_sriov_devices,
sousaedu80135b92021-02-17 15:05:18 +01007807 )
kateac1e3792017-04-01 02:16:39 -07007808
sousaedu80135b92021-02-17 15:05:18 +01007809 if (
7810 new_host_obj is not None
7811 and len(avilable_sriov_devices) > 0
7812 ):
beierlb22ce2d2019-12-12 12:09:51 -05007813 # Migrate vm to the host where SRIOV devices are available
sousaedu80135b92021-02-17 15:05:18 +01007814 self.logger.info(
7815 "Relocate VM {} on new host {}".format(
7816 vm_obj, new_host_obj
7817 )
7818 )
kateac1e3792017-04-01 02:16:39 -07007819 task = self.relocate_vm(new_host_obj, vm_obj)
sousaedu80135b92021-02-17 15:05:18 +01007820
kateac1e3792017-04-01 02:16:39 -07007821 if task is not None:
sousaedu80135b92021-02-17 15:05:18 +01007822 result = self.wait_for_vcenter_task(
7823 task, vcenter_conect
7824 )
7825 self.logger.info(
7826 "Migrate VM status: {}".format(result)
7827 )
kateac1e3792017-04-01 02:16:39 -07007828 host_obj = new_host_obj
7829 else:
sousaedu80135b92021-02-17 15:05:18 +01007830 self.logger.info(
7831 "Fail to migrate VM : {}".format(result)
7832 )
7833
tierno72774862020-05-04 11:44:15 +00007834 raise vimconn.VimConnNotFoundException(
beierlb22ce2d2019-12-12 12:09:51 -05007835 "Fail to migrate VM : {} to host {}".format(
sousaedu80135b92021-02-17 15:05:18 +01007836 vmname_andid, new_host_obj
kateac1e3792017-04-01 02:16:39 -07007837 )
sousaedu80135b92021-02-17 15:05:18 +01007838 )
kateac1e3792017-04-01 02:16:39 -07007839
sousaedu80135b92021-02-17 15:05:18 +01007840 if (
7841 host_obj is not None
7842 and avilable_sriov_devices is not None
7843 and len(avilable_sriov_devices) > 0
7844 ):
beierlb22ce2d2019-12-12 12:09:51 -05007845 # Add SRIOV devices one by one
kateac1e3792017-04-01 02:16:39 -07007846 for sriov_net in sriov_nets:
sousaedu80135b92021-02-17 15:05:18 +01007847 network_name = sriov_net.get("net_id")
beierlb22ce2d2019-12-12 12:09:51 -05007848 self.create_dvPort_group(network_name)
kateac1e3792017-04-01 02:16:39 -07007849
sousaedu80135b92021-02-17 15:05:18 +01007850 if (
7851 sriov_net.get("type") == "VF"
7852 or sriov_net.get("type") == "SR-IOV"
7853 ):
7854 # add vlan ID ,Modify portgroup for vlan ID
7855 self.configure_vlanID(
7856 content, vcenter_conect, network_name
7857 )
7858
7859 task = self.add_sriov_to_vm(
7860 content,
7861 vm_obj,
7862 host_obj,
7863 network_name,
7864 avilable_sriov_devices[0],
7865 )
7866
kateac1e3792017-04-01 02:16:39 -07007867 if task:
sousaedu80135b92021-02-17 15:05:18 +01007868 status = self.wait_for_vcenter_task(
7869 task, vcenter_conect
7870 )
7871
kateac1e3792017-04-01 02:16:39 -07007872 if status:
sousaedu80135b92021-02-17 15:05:18 +01007873 self.logger.info(
7874 "Added SRIOV {} to VM {}".format(
7875 no_of_sriov_devices, str(vm_obj)
7876 )
kateac1e3792017-04-01 02:16:39 -07007877 )
sousaedu80135b92021-02-17 15:05:18 +01007878 else:
7879 self.logger.error(
7880 "Fail to add SRIOV {} to VM {}".format(
7881 no_of_sriov_devices, str(vm_obj)
7882 )
7883 )
7884
7885 raise vimconn.VimConnUnexpectedResponse(
7886 "Fail to add SRIOV adapter in VM {}".format(
7887 str(vm_obj)
7888 )
7889 )
7890
kateac1e3792017-04-01 02:16:39 -07007891 return True, vm_obj, vcenter_conect
7892 else:
sousaedu80135b92021-02-17 15:05:18 +01007893 self.logger.error(
7894 "Currently there is no host with"
7895 " {} number of avaialble SRIOV "
7896 "VFs required for VM {}".format(
7897 no_of_sriov_devices, vmname_andid
7898 )
7899 )
7900
tierno72774862020-05-04 11:44:15 +00007901 raise vimconn.VimConnNotFoundException(
beierlb22ce2d2019-12-12 12:09:51 -05007902 "Currently there is no host with {} "
7903 "number of avaialble SRIOV devices required for VM {}".format(
sousaedu80135b92021-02-17 15:05:18 +01007904 no_of_sriov_devices, vmname_andid
7905 )
7906 )
kateac1e3792017-04-01 02:16:39 -07007907 else:
sousaedu80135b92021-02-17 15:05:18 +01007908 self.logger.debug(
7909 "No infromation about SRIOV devices {} ", sriov_nets
7910 )
kateac1e3792017-04-01 02:16:39 -07007911 except vmodl.MethodFault as error:
beierlb22ce2d2019-12-12 12:09:51 -05007912 self.logger.error("Error occurred while adding SRIOV {} ", error)
sousaedu80135b92021-02-17 15:05:18 +01007913
kateac1e3792017-04-01 02:16:39 -07007914 return None, vm_obj, vcenter_conect
7915
beierlb22ce2d2019-12-12 12:09:51 -05007916 def get_sriov_devices(self, host, no_of_vfs):
kateac1e3792017-04-01 02:16:39 -07007917 """
sousaedu80135b92021-02-17 15:05:18 +01007918 Method to get the details of SRIOV devices on given host
7919 Args:
7920 host - vSphere host object
7921 no_of_vfs - number of VFs needed on host
kateac1e3792017-04-01 02:16:39 -07007922
sousaedu80135b92021-02-17 15:05:18 +01007923 Returns:
7924 array of SRIOV devices
kateac1e3792017-04-01 02:16:39 -07007925 """
beierlb22ce2d2019-12-12 12:09:51 -05007926 sriovInfo = []
sousaedu80135b92021-02-17 15:05:18 +01007927
kateac1e3792017-04-01 02:16:39 -07007928 if host:
7929 for device in host.config.pciPassthruInfo:
beierlb22ce2d2019-12-12 12:09:51 -05007930 if isinstance(device, vim.host.SriovInfo) and device.sriovActive:
kateac1e3792017-04-01 02:16:39 -07007931 if device.numVirtualFunction >= no_of_vfs:
7932 sriovInfo.append(device)
7933 break
sousaedu80135b92021-02-17 15:05:18 +01007934
kateac1e3792017-04-01 02:16:39 -07007935 return sriovInfo
7936
kateac1e3792017-04-01 02:16:39 -07007937 def get_host_and_sriov_devices(self, content, no_of_vfs):
7938 """
sousaedu80135b92021-02-17 15:05:18 +01007939 Method to get the details of SRIOV devices infromation on all hosts
kateac1e3792017-04-01 02:16:39 -07007940
sousaedu80135b92021-02-17 15:05:18 +01007941 Args:
7942 content - vSphere host object
7943 no_of_vfs - number of pci VFs needed on host
kateac1e3792017-04-01 02:16:39 -07007944
sousaedu80135b92021-02-17 15:05:18 +01007945 Returns:
7946 array of SRIOV devices and host object
kateac1e3792017-04-01 02:16:39 -07007947 """
7948 host_obj = None
7949 sriov_device_objs = None
sousaedu80135b92021-02-17 15:05:18 +01007950
kateac1e3792017-04-01 02:16:39 -07007951 try:
7952 if content:
sousaedu80135b92021-02-17 15:05:18 +01007953 container = content.viewManager.CreateContainerView(
7954 content.rootFolder, [vim.HostSystem], True
7955 )
7956
kateac1e3792017-04-01 02:16:39 -07007957 for host in container.view:
7958 devices = self.get_sriov_devices(host, no_of_vfs)
sousaedu80135b92021-02-17 15:05:18 +01007959
kateac1e3792017-04-01 02:16:39 -07007960 if devices:
7961 host_obj = host
7962 sriov_device_objs = devices
7963 break
7964 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01007965 self.logger.error(
7966 "Error {} occurred while finding SRIOV devices on host: {}".format(
7967 exp, host_obj
7968 )
7969 )
kateac1e3792017-04-01 02:16:39 -07007970
beierlb22ce2d2019-12-12 12:09:51 -05007971 return host_obj, sriov_device_objs
kateac1e3792017-04-01 02:16:39 -07007972
beierlb22ce2d2019-12-12 12:09:51 -05007973 def add_sriov_to_vm(self, content, vm_obj, host_obj, network_name, sriov_device):
kateac1e3792017-04-01 02:16:39 -07007974 """
sousaedu80135b92021-02-17 15:05:18 +01007975 Method to add SRIOV adapter to vm
kateac1e3792017-04-01 02:16:39 -07007976
sousaedu80135b92021-02-17 15:05:18 +01007977 Args:
7978 host_obj - vSphere host object
7979 vm_obj - vSphere vm object
7980 content - vCenter content object
7981 network_name - name of distributed virtaul portgroup
7982 sriov_device - SRIOV device info
kateac1e3792017-04-01 02:16:39 -07007983
sousaedu80135b92021-02-17 15:05:18 +01007984 Returns:
7985 task object
kateac1e3792017-04-01 02:16:39 -07007986 """
7987 devices = []
7988 vnic_label = "sriov nic"
sousaedu80135b92021-02-17 15:05:18 +01007989
kateac1e3792017-04-01 02:16:39 -07007990 try:
7991 dvs_portgr = self.get_dvport_group(network_name)
7992 network_name = dvs_portgr.name
7993 nic = vim.vm.device.VirtualDeviceSpec()
7994 # VM device
7995 nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
7996 nic.device = vim.vm.device.VirtualSriovEthernetCard()
sousaedu80135b92021-02-17 15:05:18 +01007997 nic.device.addressType = "assigned"
beierlb22ce2d2019-12-12 12:09:51 -05007998 # nic.device.key = 13016
kateac1e3792017-04-01 02:16:39 -07007999 nic.device.deviceInfo = vim.Description()
8000 nic.device.deviceInfo.label = vnic_label
8001 nic.device.deviceInfo.summary = network_name
8002 nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
8003
sousaedu80135b92021-02-17 15:05:18 +01008004 nic.device.backing.network = self.get_obj(
8005 content, [vim.Network], network_name
8006 )
kateac1e3792017-04-01 02:16:39 -07008007 nic.device.backing.deviceName = network_name
8008 nic.device.backing.useAutoDetect = False
8009 nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
8010 nic.device.connectable.startConnected = True
8011 nic.device.connectable.allowGuestControl = True
8012
sousaedu80135b92021-02-17 15:05:18 +01008013 nic.device.sriovBacking = (
8014 vim.vm.device.VirtualSriovEthernetCard.SriovBackingInfo()
8015 )
8016 nic.device.sriovBacking.physicalFunctionBacking = (
8017 vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
8018 )
kateac1e3792017-04-01 02:16:39 -07008019 nic.device.sriovBacking.physicalFunctionBacking.id = sriov_device.id
8020
8021 devices.append(nic)
8022 vmconf = vim.vm.ConfigSpec(deviceChange=devices)
8023 task = vm_obj.ReconfigVM_Task(vmconf)
sousaedu80135b92021-02-17 15:05:18 +01008024
kateac1e3792017-04-01 02:16:39 -07008025 return task
8026 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01008027 self.logger.error(
8028 "Error {} occurred while adding SRIOV adapter in VM: {}".format(
8029 exp, vm_obj
8030 )
8031 )
8032
kateac1e3792017-04-01 02:16:39 -07008033 return None
8034
kateac1e3792017-04-01 02:16:39 -07008035 def create_dvPort_group(self, network_name):
8036 """
sousaedu80135b92021-02-17 15:05:18 +01008037 Method to create disributed virtual portgroup
kateac1e3792017-04-01 02:16:39 -07008038
sousaedu80135b92021-02-17 15:05:18 +01008039 Args:
8040 network_name - name of network/portgroup
kateac1e3792017-04-01 02:16:39 -07008041
sousaedu80135b92021-02-17 15:05:18 +01008042 Returns:
8043 portgroup key
kateac1e3792017-04-01 02:16:39 -07008044 """
8045 try:
sousaedu80135b92021-02-17 15:05:18 +01008046 new_network_name = [network_name, "-", str(uuid.uuid4())]
8047 network_name = "".join(new_network_name)
kateac1e3792017-04-01 02:16:39 -07008048 vcenter_conect, content = self.get_vcenter_content()
8049
sousaedu80135b92021-02-17 15:05:18 +01008050 dv_switch = self.get_obj(
8051 content, [vim.DistributedVirtualSwitch], self.dvs_name
8052 )
8053
kateac1e3792017-04-01 02:16:39 -07008054 if dv_switch:
8055 dv_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
8056 dv_pg_spec.name = network_name
8057
sousaedu80135b92021-02-17 15:05:18 +01008058 dv_pg_spec.type = (
8059 vim.dvs.DistributedVirtualPortgroup.PortgroupType.earlyBinding
8060 )
8061 dv_pg_spec.defaultPortConfig = (
8062 vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
8063 )
8064 dv_pg_spec.defaultPortConfig.securityPolicy = (
8065 vim.dvs.VmwareDistributedVirtualSwitch.SecurityPolicy()
8066 )
8067 dv_pg_spec.defaultPortConfig.securityPolicy.allowPromiscuous = (
8068 vim.BoolPolicy(value=False)
8069 )
8070 dv_pg_spec.defaultPortConfig.securityPolicy.forgedTransmits = (
8071 vim.BoolPolicy(value=False)
8072 )
8073 dv_pg_spec.defaultPortConfig.securityPolicy.macChanges = vim.BoolPolicy(
8074 value=False
8075 )
kateac1e3792017-04-01 02:16:39 -07008076
8077 task = dv_switch.AddDVPortgroup_Task([dv_pg_spec])
8078 self.wait_for_vcenter_task(task, vcenter_conect)
8079
sousaedu80135b92021-02-17 15:05:18 +01008080 dvPort_group = self.get_obj(
8081 content, [vim.dvs.DistributedVirtualPortgroup], network_name
8082 )
8083
kateac1e3792017-04-01 02:16:39 -07008084 if dvPort_group:
sousaedu80135b92021-02-17 15:05:18 +01008085 self.logger.info(
8086 "Created disributed virtaul port group: {}".format(dvPort_group)
8087 )
kateac1e3792017-04-01 02:16:39 -07008088 return dvPort_group.key
8089 else:
sousaedu80135b92021-02-17 15:05:18 +01008090 self.logger.debug(
8091 "No disributed virtual switch found with name {}".format(
8092 network_name
8093 )
8094 )
kateac1e3792017-04-01 02:16:39 -07008095
8096 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01008097 self.logger.error(
8098 "Error occurred while creating disributed virtaul port group {}"
8099 " : {}".format(network_name, exp)
8100 )
8101
kateac1e3792017-04-01 02:16:39 -07008102 return None
8103
beierlb22ce2d2019-12-12 12:09:51 -05008104 def reconfig_portgroup(self, content, dvPort_group_name, config_info={}):
kateac1e3792017-04-01 02:16:39 -07008105 """
sousaedu80135b92021-02-17 15:05:18 +01008106 Method to reconfigure disributed virtual portgroup
kateac1e3792017-04-01 02:16:39 -07008107
sousaedu80135b92021-02-17 15:05:18 +01008108 Args:
8109 dvPort_group_name - name of disributed virtual portgroup
8110 content - vCenter content object
8111 config_info - disributed virtual portgroup configuration
kateac1e3792017-04-01 02:16:39 -07008112
sousaedu80135b92021-02-17 15:05:18 +01008113 Returns:
8114 task object
kateac1e3792017-04-01 02:16:39 -07008115 """
8116 try:
8117 dvPort_group = self.get_dvport_group(dvPort_group_name)
sousaedu80135b92021-02-17 15:05:18 +01008118
kateac1e3792017-04-01 02:16:39 -07008119 if dvPort_group:
8120 dv_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
8121 dv_pg_spec.configVersion = dvPort_group.config.configVersion
sousaedu80135b92021-02-17 15:05:18 +01008122 dv_pg_spec.defaultPortConfig = (
8123 vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
8124 )
8125
kateac1e3792017-04-01 02:16:39 -07008126 if "vlanID" in config_info:
sousaedu80135b92021-02-17 15:05:18 +01008127 dv_pg_spec.defaultPortConfig.vlan = (
8128 vim.dvs.VmwareDistributedVirtualSwitch.VlanIdSpec()
8129 )
8130 dv_pg_spec.defaultPortConfig.vlan.vlanId = config_info.get("vlanID")
kateac1e3792017-04-01 02:16:39 -07008131
8132 task = dvPort_group.ReconfigureDVPortgroup_Task(spec=dv_pg_spec)
sousaedu80135b92021-02-17 15:05:18 +01008133
kateac1e3792017-04-01 02:16:39 -07008134 return task
8135 else:
8136 return None
8137 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01008138 self.logger.error(
8139 "Error occurred while reconfiguraing disributed virtaul port group {}"
8140 " : {}".format(dvPort_group_name, exp)
8141 )
8142
kateac1e3792017-04-01 02:16:39 -07008143 return None
8144
beierlb22ce2d2019-12-12 12:09:51 -05008145 def destroy_dvport_group(self, dvPort_group_name):
kateac1e3792017-04-01 02:16:39 -07008146 """
sousaedu80135b92021-02-17 15:05:18 +01008147 Method to destroy disributed virtual portgroup
kateac1e3792017-04-01 02:16:39 -07008148
sousaedu80135b92021-02-17 15:05:18 +01008149 Args:
8150 network_name - name of network/portgroup
kateac1e3792017-04-01 02:16:39 -07008151
sousaedu80135b92021-02-17 15:05:18 +01008152 Returns:
8153 True if portgroup successfully got deleted else false
kateac1e3792017-04-01 02:16:39 -07008154 """
beierlb22ce2d2019-12-12 12:09:51 -05008155 vcenter_conect, _ = self.get_vcenter_content()
sousaedu80135b92021-02-17 15:05:18 +01008156
kateac1e3792017-04-01 02:16:39 -07008157 try:
8158 status = None
8159 dvPort_group = self.get_dvport_group(dvPort_group_name)
sousaedu80135b92021-02-17 15:05:18 +01008160
kateac1e3792017-04-01 02:16:39 -07008161 if dvPort_group:
8162 task = dvPort_group.Destroy_Task()
8163 status = self.wait_for_vcenter_task(task, vcenter_conect)
sousaedu80135b92021-02-17 15:05:18 +01008164
kateac1e3792017-04-01 02:16:39 -07008165 return status
8166 except vmodl.MethodFault as exp:
sousaedu80135b92021-02-17 15:05:18 +01008167 self.logger.error(
8168 "Caught vmodl fault {} while deleting disributed virtaul port group {}".format(
8169 exp, dvPort_group_name
8170 )
8171 )
8172
kateac1e3792017-04-01 02:16:39 -07008173 return None
8174
kateac1e3792017-04-01 02:16:39 -07008175 def get_dvport_group(self, dvPort_group_name):
8176 """
8177 Method to get disributed virtual portgroup
8178
8179 Args:
8180 network_name - name of network/portgroup
8181
8182 Returns:
8183 portgroup object
8184 """
beierlb22ce2d2019-12-12 12:09:51 -05008185 _, content = self.get_vcenter_content()
kateac1e3792017-04-01 02:16:39 -07008186 dvPort_group = None
sousaedu80135b92021-02-17 15:05:18 +01008187
kateac1e3792017-04-01 02:16:39 -07008188 try:
sousaedu80135b92021-02-17 15:05:18 +01008189 container = content.viewManager.CreateContainerView(
8190 content.rootFolder, [vim.dvs.DistributedVirtualPortgroup], True
8191 )
8192
kateac1e3792017-04-01 02:16:39 -07008193 for item in container.view:
8194 if item.key == dvPort_group_name:
8195 dvPort_group = item
8196 break
sousaedu80135b92021-02-17 15:05:18 +01008197
kateac1e3792017-04-01 02:16:39 -07008198 return dvPort_group
8199 except vmodl.MethodFault as exp:
sousaedu80135b92021-02-17 15:05:18 +01008200 self.logger.error(
8201 "Caught vmodl fault {} for disributed virtual port group {}".format(
8202 exp, dvPort_group_name
8203 )
8204 )
8205
kateac1e3792017-04-01 02:16:39 -07008206 return None
8207
8208 def get_vlanID_from_dvs_portgr(self, dvPort_group_name):
8209 """
sousaedu80135b92021-02-17 15:05:18 +01008210 Method to get disributed virtual portgroup vlanID
kateac1e3792017-04-01 02:16:39 -07008211
sousaedu80135b92021-02-17 15:05:18 +01008212 Args:
8213 network_name - name of network/portgroup
kateac1e3792017-04-01 02:16:39 -07008214
sousaedu80135b92021-02-17 15:05:18 +01008215 Returns:
8216 vlan ID
kateac1e3792017-04-01 02:16:39 -07008217 """
8218 vlanId = None
sousaedu80135b92021-02-17 15:05:18 +01008219
kateac1e3792017-04-01 02:16:39 -07008220 try:
8221 dvPort_group = self.get_dvport_group(dvPort_group_name)
sousaedu80135b92021-02-17 15:05:18 +01008222
kateac1e3792017-04-01 02:16:39 -07008223 if dvPort_group:
8224 vlanId = dvPort_group.config.defaultPortConfig.vlan.vlanId
8225 except vmodl.MethodFault as exp:
sousaedu80135b92021-02-17 15:05:18 +01008226 self.logger.error(
8227 "Caught vmodl fault {} for disributed virtaul port group {}".format(
8228 exp, dvPort_group_name
8229 )
8230 )
8231
kateac1e3792017-04-01 02:16:39 -07008232 return vlanId
8233
kateac1e3792017-04-01 02:16:39 -07008234 def configure_vlanID(self, content, vcenter_conect, dvPort_group_name):
8235 """
sousaedu80135b92021-02-17 15:05:18 +01008236 Method to configure vlanID in disributed virtual portgroup vlanID
kateac1e3792017-04-01 02:16:39 -07008237
sousaedu80135b92021-02-17 15:05:18 +01008238 Args:
8239 network_name - name of network/portgroup
kateac1e3792017-04-01 02:16:39 -07008240
sousaedu80135b92021-02-17 15:05:18 +01008241 Returns:
8242 None
kateac1e3792017-04-01 02:16:39 -07008243 """
8244 vlanID = self.get_vlanID_from_dvs_portgr(dvPort_group_name)
sousaedu80135b92021-02-17 15:05:18 +01008245
kateac1e3792017-04-01 02:16:39 -07008246 if vlanID == 0:
beierlb22ce2d2019-12-12 12:09:51 -05008247 # configure vlanID
kateac1e3792017-04-01 02:16:39 -07008248 vlanID = self.genrate_vlanID(dvPort_group_name)
beierlb22ce2d2019-12-12 12:09:51 -05008249 config = {"vlanID": vlanID}
sousaedu80135b92021-02-17 15:05:18 +01008250 task = self.reconfig_portgroup(
8251 content, dvPort_group_name, config_info=config
8252 )
8253
kateac1e3792017-04-01 02:16:39 -07008254 if task:
beierlb22ce2d2019-12-12 12:09:51 -05008255 status = self.wait_for_vcenter_task(task, vcenter_conect)
sousaedu80135b92021-02-17 15:05:18 +01008256
kateac1e3792017-04-01 02:16:39 -07008257 if status:
sousaedu80135b92021-02-17 15:05:18 +01008258 self.logger.info(
8259 "Reconfigured Port group {} for vlan ID {}".format(
8260 dvPort_group_name, vlanID
8261 )
8262 )
kateac1e3792017-04-01 02:16:39 -07008263 else:
sousaedu80135b92021-02-17 15:05:18 +01008264 self.logger.error(
8265 "Fail reconfigure portgroup {} for vlanID{}".format(
8266 dvPort_group_name, vlanID
8267 )
8268 )
kateac1e3792017-04-01 02:16:39 -07008269
8270 def genrate_vlanID(self, network_name):
8271 """
sousaedu80135b92021-02-17 15:05:18 +01008272 Method to get unused vlanID
8273 Args:
8274 network_name - name of network/portgroup
8275 Returns:
8276 vlanID
kateac1e3792017-04-01 02:16:39 -07008277 """
8278 vlan_id = None
8279 used_ids = []
sousaedu80135b92021-02-17 15:05:18 +01008280
8281 if self.config.get("vlanID_range") is None:
8282 raise vimconn.VimConnConflictException(
8283 "You must provide a 'vlanID_range' "
8284 "at config value before creating sriov network with vlan tag"
8285 )
8286
kateac1e3792017-04-01 02:16:39 -07008287 if "used_vlanIDs" not in self.persistent_info:
sousaedu80135b92021-02-17 15:05:18 +01008288 self.persistent_info["used_vlanIDs"] = {}
kateac1e3792017-04-01 02:16:39 -07008289 else:
tierno7d782ef2019-10-04 12:56:31 +00008290 used_ids = list(self.persistent_info["used_vlanIDs"].values())
kateac1e3792017-04-01 02:16:39 -07008291
sousaedu80135b92021-02-17 15:05:18 +01008292 for vlanID_range in self.config.get("vlanID_range"):
tierno1b856002019-11-07 16:28:54 +00008293 start_vlanid, end_vlanid = vlanID_range.split("-")
sousaedu80135b92021-02-17 15:05:18 +01008294
kateac1e3792017-04-01 02:16:39 -07008295 if start_vlanid > end_vlanid:
sousaedu80135b92021-02-17 15:05:18 +01008296 raise vimconn.VimConnConflictException(
8297 "Invalid vlan ID range {}".format(vlanID_range)
8298 )
kateac1e3792017-04-01 02:16:39 -07008299
beierlb22ce2d2019-12-12 12:09:51 -05008300 for vid in range(int(start_vlanid), int(end_vlanid) + 1):
8301 if vid not in used_ids:
8302 vlan_id = vid
kateac1e3792017-04-01 02:16:39 -07008303 self.persistent_info["used_vlanIDs"][network_name] = vlan_id
8304 return vlan_id
sousaedu80135b92021-02-17 15:05:18 +01008305
kateac1e3792017-04-01 02:16:39 -07008306 if vlan_id is None:
tierno72774862020-05-04 11:44:15 +00008307 raise vimconn.VimConnConflictException("All Vlan IDs are in use")
kateac1e3792017-04-01 02:16:39 -07008308
kateac1e3792017-04-01 02:16:39 -07008309 def get_obj(self, content, vimtype, name):
8310 """
sousaedu80135b92021-02-17 15:05:18 +01008311 Get the vsphere object associated with a given text name
kateac1e3792017-04-01 02:16:39 -07008312 """
8313 obj = None
sousaedu80135b92021-02-17 15:05:18 +01008314 container = content.viewManager.CreateContainerView(
8315 content.rootFolder, vimtype, True
8316 )
8317
kateac1e3792017-04-01 02:16:39 -07008318 for item in container.view:
8319 if item.name == name:
8320 obj = item
8321 break
sousaedu80135b92021-02-17 15:05:18 +01008322
kateac1e3792017-04-01 02:16:39 -07008323 return obj
8324
kasar0c007d62017-05-19 03:13:57 -07008325 def insert_media_to_vm(self, vapp, image_id):
8326 """
8327 Method to insert media CD-ROM (ISO image) from catalog to vm.
8328 vapp - vapp object to get vm id
8329 Image_id - image id for cdrom to be inerted to vm
8330 """
8331 # create connection object
8332 vca = self.connect()
8333 try:
8334 # fetching catalog details
kasarc5bf2932018-03-09 04:15:22 -08008335 rest_url = "{}/api/catalog/{}".format(self.url, image_id)
sousaedu80135b92021-02-17 15:05:18 +01008336
kasarc5bf2932018-03-09 04:15:22 -08008337 if vca._session:
sousaedu80135b92021-02-17 15:05:18 +01008338 headers = {
8339 "Accept": "application/*+xml;version=" + API_VERSION,
8340 "x-vcloud-authorization": vca._session.headers[
8341 "x-vcloud-authorization"
8342 ],
8343 }
8344 response = self.perform_request(
8345 req_type="GET", url=rest_url, headers=headers
8346 )
kasar0c007d62017-05-19 03:13:57 -07008347
8348 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01008349 self.logger.error(
8350 "REST call {} failed reason : {}"
8351 "status code : {}".format(
8352 rest_url, response.text, response.status_code
8353 )
8354 )
8355
8356 raise vimconn.VimConnException(
8357 "insert_media_to_vm(): Failed to get " "catalog details"
8358 )
8359
kasar0c007d62017-05-19 03:13:57 -07008360 # searching iso name and id
beierl26fec002019-12-06 17:06:40 -05008361 iso_name, media_id = self.get_media_details(vca, response.text)
kasar0c007d62017-05-19 03:13:57 -07008362
8363 if iso_name and media_id:
beierlb22ce2d2019-12-12 12:09:51 -05008364 data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
kasar0c007d62017-05-19 03:13:57 -07008365 <ns6:MediaInsertOrEjectParams
beierl26fec002019-12-06 17:06:40 -05008366 xmlns="http://www.vmware.com/vcloud/versions" xmlns:ns2="http://schemas.dmtf.org/ovf/envelope/1"
8367 xmlns:ns3="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
8368 xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/common"
8369 xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
8370 xmlns:ns6="http://www.vmware.com/vcloud/v1.5"
8371 xmlns:ns7="http://www.vmware.com/schema/ovf"
8372 xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1"
Ananda Baitharu319c26f2019-03-05 17:34:31 +00008373 xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">
kasar0c007d62017-05-19 03:13:57 -07008374 <ns6:Media
8375 type="application/vnd.vmware.vcloud.media+xml"
Ananda Baitharu319c26f2019-03-05 17:34:31 +00008376 name="{}"
kasar0c007d62017-05-19 03:13:57 -07008377 id="urn:vcloud:media:{}"
8378 href="https://{}/api/media/{}"/>
sousaedu80135b92021-02-17 15:05:18 +01008379 </ns6:MediaInsertOrEjectParams>""".format(
8380 iso_name, media_id, self.url, media_id
8381 )
kasar0c007d62017-05-19 03:13:57 -07008382
kasarc5bf2932018-03-09 04:15:22 -08008383 for vms in vapp.get_all_vms():
sousaedu80135b92021-02-17 15:05:18 +01008384 vm_id = vms.get("id").split(":")[-1]
kasar0c007d62017-05-19 03:13:57 -07008385
sousaedu80135b92021-02-17 15:05:18 +01008386 headers[
8387 "Content-Type"
8388 ] = "application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml"
8389 rest_url = "{}/api/vApp/vm-{}/media/action/insertMedia".format(
8390 self.url, vm_id
8391 )
kasar0c007d62017-05-19 03:13:57 -07008392
sousaedu80135b92021-02-17 15:05:18 +01008393 response = self.perform_request(
8394 req_type="POST", url=rest_url, data=data, headers=headers
8395 )
kasar0c007d62017-05-19 03:13:57 -07008396
8397 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01008398 error_msg = (
8399 "insert_media_to_vm() : Failed to insert CD-ROM to vm. Reason {}. "
8400 "Status code {}".format(response.text, response.status_code)
8401 )
Ananda Baitharu319c26f2019-03-05 17:34:31 +00008402 self.logger.error(error_msg)
sousaedu80135b92021-02-17 15:05:18 +01008403
tierno72774862020-05-04 11:44:15 +00008404 raise vimconn.VimConnException(error_msg)
kasar0c007d62017-05-19 03:13:57 -07008405 else:
beierl26fec002019-12-06 17:06:40 -05008406 task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01008407 result = self.client.get_task_monitor().wait_for_success(
8408 task=task
8409 )
kasarc5bf2932018-03-09 04:15:22 -08008410
sousaedu80135b92021-02-17 15:05:18 +01008411 if result.get("status") == "success":
8412 self.logger.info(
8413 "insert_media_to_vm(): Sucessfully inserted media ISO"
8414 " image to vm {}".format(vm_id)
8415 )
kasar0c007d62017-05-19 03:13:57 -07008416 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01008417 self.logger.error(
8418 "insert_media_to_vm() : exception occurred "
8419 "while inserting media CD-ROM"
8420 )
8421
tierno72774862020-05-04 11:44:15 +00008422 raise vimconn.VimConnException(message=exp)
kasar0c007d62017-05-19 03:13:57 -07008423
kasar0c007d62017-05-19 03:13:57 -07008424 def get_media_details(self, vca, content):
8425 """
8426 Method to get catalog item details
8427 vca - connection object
8428 content - Catalog details
8429 Return - Media name, media id
8430 """
8431 cataloghref_list = []
8432 try:
8433 if content:
8434 vm_list_xmlroot = XmlElementTree.fromstring(content)
sousaedu80135b92021-02-17 15:05:18 +01008435
kasar0c007d62017-05-19 03:13:57 -07008436 for child in vm_list_xmlroot.iter():
sousaedu80135b92021-02-17 15:05:18 +01008437 if "CatalogItem" in child.tag:
8438 cataloghref_list.append(child.attrib.get("href"))
8439
kasar0c007d62017-05-19 03:13:57 -07008440 if cataloghref_list is not None:
8441 for href in cataloghref_list:
8442 if href:
sousaedu80135b92021-02-17 15:05:18 +01008443 headers = {
8444 "Accept": "application/*+xml;version=" + API_VERSION,
8445 "x-vcloud-authorization": vca._session.headers[
8446 "x-vcloud-authorization"
8447 ],
8448 }
8449 response = self.perform_request(
8450 req_type="GET", url=href, headers=headers
8451 )
8452
kasar0c007d62017-05-19 03:13:57 -07008453 if response.status_code != 200:
sousaedu80135b92021-02-17 15:05:18 +01008454 self.logger.error(
8455 "REST call {} failed reason : {}"
8456 "status code : {}".format(
8457 href, response.text, response.status_code
8458 )
8459 )
8460
8461 raise vimconn.VimConnException(
8462 "get_media_details : Failed to get "
8463 "catalogitem details"
8464 )
8465
beierl26fec002019-12-06 17:06:40 -05008466 list_xmlroot = XmlElementTree.fromstring(response.text)
sousaedu80135b92021-02-17 15:05:18 +01008467
kasar0c007d62017-05-19 03:13:57 -07008468 for child in list_xmlroot.iter():
sousaedu80135b92021-02-17 15:05:18 +01008469 if "Entity" in child.tag:
8470 if "media" in child.attrib.get("href"):
8471 name = child.attrib.get("name")
8472 media_id = (
8473 child.attrib.get("href").split("/").pop()
8474 )
8475
beierlb22ce2d2019-12-12 12:09:51 -05008476 return name, media_id
kasar0c007d62017-05-19 03:13:57 -07008477 else:
8478 self.logger.debug("Media name and id not found")
sousaedu80135b92021-02-17 15:05:18 +01008479
beierlb22ce2d2019-12-12 12:09:51 -05008480 return False, False
kasar0c007d62017-05-19 03:13:57 -07008481 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01008482 self.logger.error(
8483 "get_media_details : exception occurred " "getting media details"
8484 )
8485
tierno72774862020-05-04 11:44:15 +00008486 raise vimconn.VimConnException(message=exp)
kasar0c007d62017-05-19 03:13:57 -07008487
kated47ad5f2017-08-03 02:16:13 -07008488 def retry_rest(self, method, url, add_headers=None, data=None):
sousaedu80135b92021-02-17 15:05:18 +01008489 """Method to get Token & retry respective REST request
8490 Args:
8491 api - REST API - Can be one of 'GET' or 'PUT' or 'POST'
8492 url - request url to be used
8493 add_headers - Additional headers (optional)
8494 data - Request payload data to be passed in request
8495 Returns:
8496 response - Response of request
bhangare1a0b97c2017-06-21 02:20:15 -07008497 """
8498 response = None
8499
beierlb22ce2d2019-12-12 12:09:51 -05008500 # Get token
bhangare1a0b97c2017-06-21 02:20:15 -07008501 self.get_token()
8502
kasarc5bf2932018-03-09 04:15:22 -08008503 if self.client._session:
sousaedu80135b92021-02-17 15:05:18 +01008504 headers = {
8505 "Accept": "application/*+xml;version=" + API_VERSION,
8506 "x-vcloud-authorization": self.client._session.headers[
8507 "x-vcloud-authorization"
8508 ],
8509 }
bhangare1a0b97c2017-06-21 02:20:15 -07008510
8511 if add_headers:
8512 headers.update(add_headers)
8513
sousaedu80135b92021-02-17 15:05:18 +01008514 if method == "GET":
8515 response = self.perform_request(req_type="GET", url=url, headers=headers)
8516 elif method == "PUT":
8517 response = self.perform_request(
8518 req_type="PUT", url=url, headers=headers, data=data
8519 )
8520 elif method == "POST":
8521 response = self.perform_request(
8522 req_type="POST", url=url, headers=headers, data=data
8523 )
8524 elif method == "DELETE":
8525 response = self.perform_request(req_type="DELETE", url=url, headers=headers)
8526
kated47ad5f2017-08-03 02:16:13 -07008527 return response
8528
bhangare1a0b97c2017-06-21 02:20:15 -07008529 def get_token(self):
sousaedu80135b92021-02-17 15:05:18 +01008530 """Generate a new token if expired
bhangare1a0b97c2017-06-21 02:20:15 -07008531
sousaedu80135b92021-02-17 15:05:18 +01008532 Returns:
8533 The return client object that letter can be used to connect to vCloud director as admin for VDC
bhangare1a0b97c2017-06-21 02:20:15 -07008534 """
beierl26fec002019-12-06 17:06:40 -05008535 self.client = self.connect()
bhangare1a0b97c2017-06-21 02:20:15 -07008536
8537 def get_vdc_details(self):
sousaedu80135b92021-02-17 15:05:18 +01008538 """Get VDC details using pyVcloud Lib
bhangare1a0b97c2017-06-21 02:20:15 -07008539
sousaedu80135b92021-02-17 15:05:18 +01008540 Returns org and vdc object
bhangare1a0b97c2017-06-21 02:20:15 -07008541 """
Ravi Chamartyb7ff3552018-10-30 19:51:23 +00008542 vdc = None
sousaedu80135b92021-02-17 15:05:18 +01008543
Ravi Chamartyb7ff3552018-10-30 19:51:23 +00008544 try:
8545 org = Org(self.client, resource=self.client.get_org())
8546 vdc = org.get_vdc(self.tenant_name)
8547 except Exception as e:
8548 # pyvcloud not giving a specific exception, Refresh nevertheless
8549 self.logger.debug("Received exception {}, refreshing token ".format(str(e)))
bhangare1a0b97c2017-06-21 02:20:15 -07008550
beierlb22ce2d2019-12-12 12:09:51 -05008551 # Retry once, if failed by refreshing token
bhangare1a0b97c2017-06-21 02:20:15 -07008552 if vdc is None:
8553 self.get_token()
Ravi Chamartyb7ff3552018-10-30 19:51:23 +00008554 org = Org(self.client, resource=self.client.get_org())
kasarc5bf2932018-03-09 04:15:22 -08008555 vdc = org.get_vdc(self.tenant_name)
bhangare1a0b97c2017-06-21 02:20:15 -07008556
kasarc5bf2932018-03-09 04:15:22 -08008557 return org, vdc
8558
kasarc5bf2932018-03-09 04:15:22 -08008559 def perform_request(self, req_type, url, headers=None, data=None):
8560 """Perform the POST/PUT/GET/DELETE request."""
beierlb22ce2d2019-12-12 12:09:51 -05008561 # Log REST request details
kasarc5bf2932018-03-09 04:15:22 -08008562 self.log_request(req_type, url=url, headers=headers, data=data)
8563 # perform request and return its result
sousaedu80135b92021-02-17 15:05:18 +01008564
8565 if req_type == "GET":
8566 response = requests.get(url=url, headers=headers, verify=False)
8567 elif req_type == "PUT":
8568 response = requests.put(url=url, headers=headers, data=data, verify=False)
8569 elif req_type == "POST":
8570 response = requests.post(url=url, headers=headers, data=data, verify=False)
8571 elif req_type == "DELETE":
8572 response = requests.delete(url=url, headers=headers, verify=False)
8573
beierlb22ce2d2019-12-12 12:09:51 -05008574 # Log the REST response
kasarc5bf2932018-03-09 04:15:22 -08008575 self.log_response(response)
8576
8577 return response
8578
kasarc5bf2932018-03-09 04:15:22 -08008579 def log_request(self, req_type, url=None, headers=None, data=None):
8580 """Logs REST request details"""
8581
8582 if req_type is not None:
8583 self.logger.debug("Request type: {}".format(req_type))
8584
8585 if url is not None:
8586 self.logger.debug("Request url: {}".format(url))
8587
8588 if headers is not None:
8589 for header in headers:
sousaedu80135b92021-02-17 15:05:18 +01008590 self.logger.debug(
8591 "Request header: {}: {}".format(header, headers[header])
8592 )
kasarc5bf2932018-03-09 04:15:22 -08008593
8594 if data is not None:
8595 self.logger.debug("Request data: {}".format(data))
8596
kasarc5bf2932018-03-09 04:15:22 -08008597 def log_response(self, response):
8598 """Logs REST response details"""
8599
8600 self.logger.debug("Response status code: {} ".format(response.status_code))
8601
kasarc5bf2932018-03-09 04:15:22 -08008602 def get_task_from_response(self, content):
8603 """
beierl26fec002019-12-06 17:06:40 -05008604 content - API response.text(response.text)
sbhangarea8e5b782018-06-21 02:10:03 -07008605 return task object
kasarc5bf2932018-03-09 04:15:22 -08008606 """
8607 xmlroot = XmlElementTree.fromstring(content)
sousaedu80135b92021-02-17 15:05:18 +01008608
8609 if xmlroot.tag.split("}")[1] == "Task":
kasarc5bf2932018-03-09 04:15:22 -08008610 return xmlroot
sbhangarea8e5b782018-06-21 02:10:03 -07008611 else:
kasarc5bf2932018-03-09 04:15:22 -08008612 for ele in xmlroot:
8613 if ele.tag.split("}")[1] == "Tasks":
8614 task = ele[0]
sbhangarea8e5b782018-06-21 02:10:03 -07008615 break
sousaedu80135b92021-02-17 15:05:18 +01008616
kasarc5bf2932018-03-09 04:15:22 -08008617 return task
8618
beierlb22ce2d2019-12-12 12:09:51 -05008619 def power_on_vapp(self, vapp_id, vapp_name):
kasarc5bf2932018-03-09 04:15:22 -08008620 """
8621 vapp_id - vApp uuid
8622 vapp_name - vAapp name
sbhangarea8e5b782018-06-21 02:10:03 -07008623 return - Task object
kasarc5bf2932018-03-09 04:15:22 -08008624 """
sousaedu80135b92021-02-17 15:05:18 +01008625 headers = {
8626 "Accept": "application/*+xml;version=" + API_VERSION,
8627 "x-vcloud-authorization": self.client._session.headers[
8628 "x-vcloud-authorization"
8629 ],
8630 }
sbhangarea8e5b782018-06-21 02:10:03 -07008631
sousaedu80135b92021-02-17 15:05:18 +01008632 poweron_href = "{}/api/vApp/vapp-{}/power/action/powerOn".format(
8633 self.url, vapp_id
8634 )
8635 response = self.perform_request(
8636 req_type="POST", url=poweron_href, headers=headers
8637 )
kasarc5bf2932018-03-09 04:15:22 -08008638
8639 if response.status_code != 202:
sousaedu80135b92021-02-17 15:05:18 +01008640 self.logger.error(
8641 "REST call {} failed reason : {}"
8642 "status code : {} ".format(
8643 poweron_href, response.text, response.status_code
8644 )
8645 )
8646
8647 raise vimconn.VimConnException(
8648 "power_on_vapp() : Failed to power on " "vApp {}".format(vapp_name)
8649 )
kasarc5bf2932018-03-09 04:15:22 -08008650 else:
beierl26fec002019-12-06 17:06:40 -05008651 poweron_task = self.get_task_from_response(response.text)
sousaedu80135b92021-02-17 15:05:18 +01008652
kasarc5bf2932018-03-09 04:15:22 -08008653 return poweron_task
elumalai8658c2c2022-04-28 19:09:31 +05308654
8655 def migrate_instance(self, vm_id, compute_host=None):
8656 """
8657 Migrate a vdu
8658 param:
8659 vm_id: ID of an instance
8660 compute_host: Host to migrate the vdu to
8661 """
8662 # TODO: Add support for migration
8663 raise vimconn.VimConnNotImplemented("Should have implemented this")
sritharan29a4c1a2022-05-05 12:15:04 +00008664
8665 def resize_instance(self, vm_id, flavor_id=None):
8666 """
8667 resize a vdu
8668 param:
8669 vm_id: ID of an instance
8670 flavor_id: flavor_id to resize the vdu to
8671 """
8672 # TODO: Add support for resize
8673 raise vimconn.VimConnNotImplemented("Should have implemented this")