Bug 714 vcd vimconnector: Make the vCloud API version compatible across different...
[osm/RO.git] / osm_ro / vimconn_vmware.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2016-2017 VMware Inc.
5 # This file is part of ETSI OSM
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # 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
21 # contact: osslegalrouting@vmware.com
22 ##
23
24 """
25 vimconn_vmware implementation an Abstract class in order to interact with VMware vCloud Director.
26 mbayramov@vmware.com
27 """
28 from progressbar import Percentage, Bar, ETA, FileTransferSpeed, ProgressBar
29
30 import vimconn
31 import os
32 import shutil
33 import subprocess
34 import tempfile
35 import traceback
36 import itertools
37 import requests
38 import ssl
39 import atexit
40
41 from pyVmomi import vim, vmodl
42 from pyVim.connect import SmartConnect, Disconnect
43
44 from xml.etree import ElementTree as XmlElementTree
45 from lxml import etree as lxmlElementTree
46
47 import yaml
48 from pyvcloud.vcd.client import BasicLoginCredentials,Client,VcdTaskException
49 from pyvcloud.vcd.vdc import VDC
50 from pyvcloud.vcd.org import Org
51 import re
52 from pyvcloud.vcd.vapp import VApp
53 from xml.sax.saxutils import escape
54 import logging
55 import json
56 import time
57 import uuid
58 import httplib
59 #For python3
60 #import http.client
61 import hashlib
62 import socket
63 import struct
64 import netaddr
65 import random
66
67 # global variable for vcd connector type
68 STANDALONE = 'standalone'
69
70 # key for flavor dicts
71 FLAVOR_RAM_KEY = 'ram'
72 FLAVOR_VCPUS_KEY = 'vcpus'
73 FLAVOR_DISK_KEY = 'disk'
74 DEFAULT_IP_PROFILE = {'dhcp_count':50,
75 'dhcp_enabled':True,
76 'ip_version':"IPv4"
77 }
78 # global variable for wait time
79 INTERVAL_TIME = 5
80 MAX_WAIT_TIME = 1800
81
82 API_VERSION = '27.0'
83
84 __author__ = "Mustafa Bayramov, Arpita Kate, Sachin Bhangare, Prakash Kasar"
85 __date__ = "$09-Mar-2018 11:09:29$"
86 __version__ = '0.2'
87
88 # -1: "Could not be created",
89 # 0: "Unresolved",
90 # 1: "Resolved",
91 # 2: "Deployed",
92 # 3: "Suspended",
93 # 4: "Powered on",
94 # 5: "Waiting for user input",
95 # 6: "Unknown state",
96 # 7: "Unrecognized state",
97 # 8: "Powered off",
98 # 9: "Inconsistent state",
99 # 10: "Children do not all have the same status",
100 # 11: "Upload initiated, OVF descriptor pending",
101 # 12: "Upload initiated, copying contents",
102 # 13: "Upload initiated , disk contents pending",
103 # 14: "Upload has been quarantined",
104 # 15: "Upload quarantine period has expired"
105
106 # mapping vCD status to MANO
107 vcdStatusCode2manoFormat = {4: 'ACTIVE',
108 7: 'PAUSED',
109 3: 'SUSPENDED',
110 8: 'INACTIVE',
111 12: 'BUILD',
112 -1: 'ERROR',
113 14: 'DELETED'}
114
115 #
116 netStatus2manoFormat = {'ACTIVE': 'ACTIVE', 'PAUSED': 'PAUSED', 'INACTIVE': 'INACTIVE', 'BUILD': 'BUILD',
117 'ERROR': 'ERROR', 'DELETED': 'DELETED'
118 }
119
120 class vimconnector(vimconn.vimconnector):
121 # dict used to store flavor in memory
122 flavorlist = {}
123
124 def __init__(self, uuid=None, name=None, tenant_id=None, tenant_name=None,
125 url=None, url_admin=None, user=None, passwd=None, log_level=None, config={}, persistent_info={}):
126 """
127 Constructor create vmware connector to vCloud director.
128
129 By default construct doesn't validate connection state. So client can create object with None arguments.
130 If client specified username , password and host and VDC name. Connector initialize other missing attributes.
131
132 a) It initialize organization UUID
133 b) Initialize tenant_id/vdc ID. (This information derived from tenant name)
134
135 Args:
136 uuid - is organization uuid.
137 name - is organization name that must be presented in vCloud director.
138 tenant_id - is VDC uuid it must be presented in vCloud director
139 tenant_name - is VDC name.
140 url - is hostname or ip address of vCloud director
141 url_admin - same as above.
142 user - is user that administrator for organization. Caller must make sure that
143 username has right privileges.
144
145 password - is password for a user.
146
147 VMware connector also requires PVDC administrative privileges and separate account.
148 This variables must be passed via config argument dict contains keys
149
150 dict['admin_username']
151 dict['admin_password']
152 config - Provide NSX and vCenter information
153
154 Returns:
155 Nothing.
156 """
157
158 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url,
159 url_admin, user, passwd, log_level, config)
160
161 self.logger = logging.getLogger('openmano.vim.vmware')
162 self.logger.setLevel(10)
163 self.persistent_info = persistent_info
164
165 self.name = name
166 self.id = uuid
167 self.url = url
168 self.url_admin = url_admin
169 self.tenant_id = tenant_id
170 self.tenant_name = tenant_name
171 self.user = user
172 self.passwd = passwd
173 self.config = config
174 self.admin_password = None
175 self.admin_user = None
176 self.org_name = ""
177 self.nsx_manager = None
178 self.nsx_user = None
179 self.nsx_password = None
180 self.availability_zone = None
181
182 # Disable warnings from self-signed certificates.
183 requests.packages.urllib3.disable_warnings()
184
185 if tenant_name is not None:
186 orgnameandtenant = tenant_name.split(":")
187 if len(orgnameandtenant) == 2:
188 self.tenant_name = orgnameandtenant[1]
189 self.org_name = orgnameandtenant[0]
190 else:
191 self.tenant_name = tenant_name
192 if "orgname" in config:
193 self.org_name = config['orgname']
194
195 if log_level:
196 self.logger.setLevel(getattr(logging, log_level))
197
198 try:
199 self.admin_user = config['admin_username']
200 self.admin_password = config['admin_password']
201 except KeyError:
202 raise vimconn.vimconnException(message="Error admin username or admin password is empty.")
203
204 try:
205 self.nsx_manager = config['nsx_manager']
206 self.nsx_user = config['nsx_user']
207 self.nsx_password = config['nsx_password']
208 except KeyError:
209 raise vimconn.vimconnException(message="Error: nsx manager or nsx user or nsx password is empty in Config")
210
211 self.vcenter_ip = config.get("vcenter_ip", None)
212 self.vcenter_port = config.get("vcenter_port", None)
213 self.vcenter_user = config.get("vcenter_user", None)
214 self.vcenter_password = config.get("vcenter_password", None)
215
216 #Set availability zone for Affinity rules
217 self.availability_zone = self.set_availability_zones()
218
219 # ############# Stub code for SRIOV #################
220 # try:
221 # self.dvs_name = config['dv_switch_name']
222 # except KeyError:
223 # raise vimconn.vimconnException(message="Error: distributed virtaul switch name is empty in Config")
224 #
225 # self.vlanID_range = config.get("vlanID_range", None)
226
227 self.org_uuid = None
228 self.client = None
229
230 if not url:
231 raise vimconn.vimconnException('url param can not be NoneType')
232
233 if not self.url_admin: # try to use normal url
234 self.url_admin = self.url
235
236 logging.debug("UUID: {} name: {} tenant_id: {} tenant name {}".format(self.id, self.org_name,
237 self.tenant_id, self.tenant_name))
238 logging.debug("vcd url {} vcd username: {} vcd password: {}".format(self.url, self.user, self.passwd))
239 logging.debug("vcd admin username {} vcd admin passowrd {}".format(self.admin_user, self.admin_password))
240
241 # initialize organization
242 if self.user is not None and self.passwd is not None and self.url:
243 self.init_organization()
244
245 def __getitem__(self, index):
246 if index == 'name':
247 return self.name
248 if index == 'tenant_id':
249 return self.tenant_id
250 if index == 'tenant_name':
251 return self.tenant_name
252 elif index == 'id':
253 return self.id
254 elif index == 'org_name':
255 return self.org_name
256 elif index == 'org_uuid':
257 return self.org_uuid
258 elif index == 'user':
259 return self.user
260 elif index == 'passwd':
261 return self.passwd
262 elif index == 'url':
263 return self.url
264 elif index == 'url_admin':
265 return self.url_admin
266 elif index == "config":
267 return self.config
268 else:
269 raise KeyError("Invalid key '%s'" % str(index))
270
271 def __setitem__(self, index, value):
272 if index == 'name':
273 self.name = value
274 if index == 'tenant_id':
275 self.tenant_id = value
276 if index == 'tenant_name':
277 self.tenant_name = value
278 elif index == 'id':
279 self.id = value
280 elif index == 'org_name':
281 self.org_name = value
282 elif index == 'org_uuid':
283 self.org_uuid = value
284 elif index == 'user':
285 self.user = value
286 elif index == 'passwd':
287 self.passwd = value
288 elif index == 'url':
289 self.url = value
290 elif index == 'url_admin':
291 self.url_admin = value
292 else:
293 raise KeyError("Invalid key '%s'" % str(index))
294
295 def connect_as_admin(self):
296 """ Method connect as pvdc admin user to vCloud director.
297 There are certain action that can be done only by provider vdc admin user.
298 Organization creation / provider network creation etc.
299
300 Returns:
301 The return client object that latter can be used to connect to vcloud director as admin for provider vdc
302 """
303 self.logger.debug("Logging into vCD {} as admin.".format(self.org_name))
304
305 try:
306 host = self.url
307 org = 'System'
308 client_as_admin = Client(host, verify_ssl_certs=False)
309 client_as_admin.set_highest_supported_version()
310 client_as_admin.set_credentials(BasicLoginCredentials(self.admin_user, org, self.admin_password))
311 except Exception as e:
312 raise vimconn.vimconnException(
313 "Can't connect to a vCloud director as: {} with exception {}".format(self.admin_user, e))
314
315 return client_as_admin
316
317 def connect(self):
318 """ Method connect as normal user to vCloud director.
319
320 Returns:
321 The return client object that latter can be used to connect to vCloud director as admin for VDC
322 """
323 try:
324 self.logger.debug("Logging into vCD {} as {} to datacenter {}.".format(self.org_name,
325 self.user,
326 self.org_name))
327 host = self.url
328 client = Client(host, verify_ssl_certs=False)
329 client.set_highest_supported_version()
330 client.set_credentials(BasicLoginCredentials(self.user, self.org_name, self.passwd))
331 except:
332 raise vimconn.vimconnConnectionException("Can't connect to a vCloud director org: "
333 "{} as user: {}".format(self.org_name, self.user))
334
335 return client
336
337 def init_organization(self):
338 """ Method initialize organization UUID and VDC parameters.
339
340 At bare minimum client must provide organization name that present in vCloud director and VDC.
341
342 The VDC - UUID ( tenant_id) will be initialized at the run time if client didn't call constructor.
343 The Org - UUID will be initialized at the run time if data center present in vCloud director.
344
345 Returns:
346 The return vca object that letter can be used to connect to vcloud direct as admin
347 """
348 client = self.connect()
349 if not client:
350 raise vimconn.vimconnConnectionException("Failed to connect vCD.")
351
352 self.client = client
353 try:
354 if self.org_uuid is None:
355 org_list = client.get_org_list()
356 for org in org_list.Org:
357 # we set org UUID at the init phase but we can do it only when we have valid credential.
358 if org.get('name') == self.org_name:
359 self.org_uuid = org.get('href').split('/')[-1]
360 self.logger.debug("Setting organization UUID {}".format(self.org_uuid))
361 break
362 else:
363 raise vimconn.vimconnException("Vcloud director organization {} not found".format(self.org_name))
364
365 # if well good we require for org details
366 org_details_dict = self.get_org(org_uuid=self.org_uuid)
367
368 # we have two case if we want to initialize VDC ID or VDC name at run time
369 # tenant_name provided but no tenant id
370 if self.tenant_id is None and self.tenant_name is not None and 'vdcs' in org_details_dict:
371 vdcs_dict = org_details_dict['vdcs']
372 for vdc in vdcs_dict:
373 if vdcs_dict[vdc] == self.tenant_name:
374 self.tenant_id = vdc
375 self.logger.debug("Setting vdc uuid {} for organization UUID {}".format(self.tenant_id,
376 self.org_name))
377 break
378 else:
379 raise vimconn.vimconnException("Tenant name indicated but not present in vcloud director.")
380 # case two we have tenant_id but we don't have tenant name so we find and set it.
381 if self.tenant_id is not None and self.tenant_name is None and 'vdcs' in org_details_dict:
382 vdcs_dict = org_details_dict['vdcs']
383 for vdc in vdcs_dict:
384 if vdc == self.tenant_id:
385 self.tenant_name = vdcs_dict[vdc]
386 self.logger.debug("Setting vdc uuid {} for organization UUID {}".format(self.tenant_id,
387 self.org_name))
388 break
389 else:
390 raise vimconn.vimconnException("Tenant id indicated but not present in vcloud director")
391 self.logger.debug("Setting organization uuid {}".format(self.org_uuid))
392 except:
393 self.logger.debug("Failed initialize organization UUID for org {}".format(self.org_name))
394 self.logger.debug(traceback.format_exc())
395 self.org_uuid = None
396
397 def new_tenant(self, tenant_name=None, tenant_description=None):
398 """ Method adds a new tenant to VIM with this name.
399 This action requires access to create VDC action in vCloud director.
400
401 Args:
402 tenant_name is tenant_name to be created.
403 tenant_description not used for this call
404
405 Return:
406 returns the tenant identifier in UUID format.
407 If action is failed method will throw vimconn.vimconnException method
408 """
409 vdc_task = self.create_vdc(vdc_name=tenant_name)
410 if vdc_task is not None:
411 vdc_uuid, value = vdc_task.popitem()
412 self.logger.info("Created new vdc {} and uuid: {}".format(tenant_name, vdc_uuid))
413 return vdc_uuid
414 else:
415 raise vimconn.vimconnException("Failed create tenant {}".format(tenant_name))
416
417 def delete_tenant(self, tenant_id=None):
418 """ Delete a tenant from VIM
419 Args:
420 tenant_id is tenant_id to be deleted.
421
422 Return:
423 returns the tenant identifier in UUID format.
424 If action is failed method will throw exception
425 """
426 vca = self.connect_as_admin()
427 if not vca:
428 raise vimconn.vimconnConnectionException("Failed to connect vCD")
429
430 if tenant_id is not None:
431 if vca._session:
432 #Get OrgVDC
433 url_list = [self.url, '/api/vdc/', tenant_id]
434 orgvdc_herf = ''.join(url_list)
435
436 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
437 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
438 response = self.perform_request(req_type='GET',
439 url=orgvdc_herf,
440 headers=headers)
441
442 if response.status_code != requests.codes.ok:
443 self.logger.debug("delete_tenant():GET REST API call {} failed. "\
444 "Return status code {}".format(orgvdc_herf,
445 response.status_code))
446 raise vimconn.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id))
447
448 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
449 namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
450 #For python3
451 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
452 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
453 vdc_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
454 vdc_remove_href = vdc_remove_href + '?recursive=true&force=true'
455
456 response = self.perform_request(req_type='DELETE',
457 url=vdc_remove_href,
458 headers=headers)
459
460 if response.status_code == 202:
461 time.sleep(5)
462 return tenant_id
463 else:
464 self.logger.debug("delete_tenant(): DELETE REST API call {} failed. "\
465 "Return status code {}".format(vdc_remove_href,
466 response.status_code))
467 raise vimconn.vimconnException("Fail to delete tenant with ID {}".format(tenant_id))
468 else:
469 self.logger.debug("delete_tenant():Incorrect tenant ID {}".format(tenant_id))
470 raise vimconn.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id))
471
472
473 def get_tenant_list(self, filter_dict={}):
474 """Obtain tenants of VIM
475 filter_dict can contain the following keys:
476 name: filter by tenant name
477 id: filter by tenant uuid/id
478 <other VIM specific>
479 Returns the tenant list of dictionaries:
480 [{'name':'<name>, 'id':'<id>, ...}, ...]
481
482 """
483 org_dict = self.get_org(self.org_uuid)
484 vdcs_dict = org_dict['vdcs']
485
486 vdclist = []
487 try:
488 for k in vdcs_dict:
489 entry = {'name': vdcs_dict[k], 'id': k}
490 # if caller didn't specify dictionary we return all tenants.
491 if filter_dict is not None and filter_dict:
492 filtered_entry = entry.copy()
493 filtered_dict = set(entry.keys()) - set(filter_dict)
494 for unwanted_key in filtered_dict: del entry[unwanted_key]
495 if filter_dict == entry:
496 vdclist.append(filtered_entry)
497 else:
498 vdclist.append(entry)
499 except:
500 self.logger.debug("Error in get_tenant_list()")
501 self.logger.debug(traceback.format_exc())
502 raise vimconn.vimconnException("Incorrect state. {}")
503
504 return vdclist
505
506 def new_network(self, net_name, net_type, ip_profile=None, shared=False, vlan=None):
507 """Adds a tenant network to VIM
508 Params:
509 'net_name': name of the network
510 'net_type': one of:
511 'bridge': overlay isolated network
512 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
513 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
514 'ip_profile': is a dict containing the IP parameters of the network
515 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
516 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
517 'gateway_address': (Optional) ip_schema, that is X.X.X.X
518 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
519 'dhcp_enabled': True or False
520 'dhcp_start_address': ip_schema, first IP to grant
521 'dhcp_count': number of IPs to grant.
522 'shared': if this network can be seen/use by other tenants/organization
523 'vlan': in case of a data or ptp net_type, the intended vlan tag to be used for the network
524 Returns a tuple with the network identifier and created_items, or raises an exception on error
525 created_items can be None or a dictionary where this method can include key-values that will be passed to
526 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
527 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
528 as not present.
529 """
530
531 self.logger.debug("new_network tenant {} net_type {} ip_profile {} shared {}"
532 .format(net_name, net_type, ip_profile, shared))
533
534 created_items = {}
535 isshared = 'false'
536 if shared:
537 isshared = 'true'
538
539 # ############# Stub code for SRIOV #################
540 # if net_type == "data" or net_type == "ptp":
541 # if self.config.get('dv_switch_name') == None:
542 # raise vimconn.vimconnConflictException("You must provide 'dv_switch_name' at config value")
543 # network_uuid = self.create_dvPort_group(net_name)
544
545 network_uuid = self.create_network(network_name=net_name, net_type=net_type,
546 ip_profile=ip_profile, isshared=isshared)
547 if network_uuid is not None:
548 return network_uuid, created_items
549 else:
550 raise vimconn.vimconnUnexpectedResponse("Failed create a new network {}".format(net_name))
551
552 def get_vcd_network_list(self):
553 """ Method available organization for a logged in tenant
554
555 Returns:
556 The return vca object that letter can be used to connect to vcloud direct as admin
557 """
558
559 self.logger.debug("get_vcd_network_list(): retrieving network list for vcd {}".format(self.tenant_name))
560
561 if not self.tenant_name:
562 raise vimconn.vimconnConnectionException("Tenant name is empty.")
563
564 org, vdc = self.get_vdc_details()
565 if vdc is None:
566 raise vimconn.vimconnConnectionException("Can't retrieve information for a VDC {}".format(self.tenant_name))
567
568 vdc_uuid = vdc.get('id').split(":")[3]
569 if self.client._session:
570 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
571 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
572 response = self.perform_request(req_type='GET',
573 url=vdc.get('href'),
574 headers=headers)
575 if response.status_code != 200:
576 self.logger.error("Failed to get vdc content")
577 raise vimconn.vimconnNotFoundException("Failed to get vdc content")
578 else:
579 content = XmlElementTree.fromstring(response.content)
580
581 network_list = []
582 try:
583 for item in content:
584 if item.tag.split('}')[-1] == 'AvailableNetworks':
585 for net in item:
586 response = self.perform_request(req_type='GET',
587 url=net.get('href'),
588 headers=headers)
589
590 if response.status_code != 200:
591 self.logger.error("Failed to get network content")
592 raise vimconn.vimconnNotFoundException("Failed to get network content")
593 else:
594 net_details = XmlElementTree.fromstring(response.content)
595
596 filter_dict = {}
597 net_uuid = net_details.get('id').split(":")
598 if len(net_uuid) != 4:
599 continue
600 else:
601 net_uuid = net_uuid[3]
602 # create dict entry
603 self.logger.debug("get_vcd_network_list(): Adding network {} "
604 "to a list vcd id {} network {}".format(net_uuid,
605 vdc_uuid,
606 net_details.get('name')))
607 filter_dict["name"] = net_details.get('name')
608 filter_dict["id"] = net_uuid
609 if [i.text for i in net_details if i.tag.split('}')[-1] == 'IsShared'][0] == 'true':
610 shared = True
611 else:
612 shared = False
613 filter_dict["shared"] = shared
614 filter_dict["tenant_id"] = vdc_uuid
615 if int(net_details.get('status')) == 1:
616 filter_dict["admin_state_up"] = True
617 else:
618 filter_dict["admin_state_up"] = False
619 filter_dict["status"] = "ACTIVE"
620 filter_dict["type"] = "bridge"
621 network_list.append(filter_dict)
622 self.logger.debug("get_vcd_network_list adding entry {}".format(filter_dict))
623 except:
624 self.logger.debug("Error in get_vcd_network_list", exc_info=True)
625 pass
626
627 self.logger.debug("get_vcd_network_list returning {}".format(network_list))
628 return network_list
629
630 def get_network_list(self, filter_dict={}):
631 """Obtain tenant networks of VIM
632 Filter_dict can be:
633 name: network name OR/AND
634 id: network uuid OR/AND
635 shared: boolean OR/AND
636 tenant_id: tenant OR/AND
637 admin_state_up: boolean
638 status: 'ACTIVE'
639
640 [{key : value , key : value}]
641
642 Returns the network list of dictionaries:
643 [{<the fields at Filter_dict plus some VIM specific>}, ...]
644 List can be empty
645 """
646
647 self.logger.debug("get_network_list(): retrieving network list for vcd {}".format(self.tenant_name))
648
649 if not self.tenant_name:
650 raise vimconn.vimconnConnectionException("Tenant name is empty.")
651
652 org, vdc = self.get_vdc_details()
653 if vdc is None:
654 raise vimconn.vimconnConnectionException("Can't retrieve information for a VDC {}.".format(self.tenant_name))
655
656 try:
657 vdcid = vdc.get('id').split(":")[3]
658
659 if self.client._session:
660 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
661 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
662 response = self.perform_request(req_type='GET',
663 url=vdc.get('href'),
664 headers=headers)
665 if response.status_code != 200:
666 self.logger.error("Failed to get vdc content")
667 raise vimconn.vimconnNotFoundException("Failed to get vdc content")
668 else:
669 content = XmlElementTree.fromstring(response.content)
670
671 network_list = []
672 for item in content:
673 if item.tag.split('}')[-1] == 'AvailableNetworks':
674 for net in item:
675 response = self.perform_request(req_type='GET',
676 url=net.get('href'),
677 headers=headers)
678
679 if response.status_code != 200:
680 self.logger.error("Failed to get network content")
681 raise vimconn.vimconnNotFoundException("Failed to get network content")
682 else:
683 net_details = XmlElementTree.fromstring(response.content)
684
685 filter_entry = {}
686 net_uuid = net_details.get('id').split(":")
687 if len(net_uuid) != 4:
688 continue
689 else:
690 net_uuid = net_uuid[3]
691 # create dict entry
692 self.logger.debug("get_network_list(): Adding net {}"
693 " to a list vcd id {} network {}".format(net_uuid,
694 vdcid,
695 net_details.get('name')))
696 filter_entry["name"] = net_details.get('name')
697 filter_entry["id"] = net_uuid
698 if [i.text for i in net_details if i.tag.split('}')[-1] == 'IsShared'][0] == 'true':
699 shared = True
700 else:
701 shared = False
702 filter_entry["shared"] = shared
703 filter_entry["tenant_id"] = vdcid
704 if int(net_details.get('status')) == 1:
705 filter_entry["admin_state_up"] = True
706 else:
707 filter_entry["admin_state_up"] = False
708 filter_entry["status"] = "ACTIVE"
709 filter_entry["type"] = "bridge"
710 filtered_entry = filter_entry.copy()
711
712 if filter_dict is not None and filter_dict:
713 # we remove all the key : value we don't care and match only
714 # respected field
715 filtered_dict = set(filter_entry.keys()) - set(filter_dict)
716 for unwanted_key in filtered_dict: del filter_entry[unwanted_key]
717 if filter_dict == filter_entry:
718 network_list.append(filtered_entry)
719 else:
720 network_list.append(filtered_entry)
721 except Exception as e:
722 self.logger.debug("Error in get_network_list",exc_info=True)
723 if isinstance(e, vimconn.vimconnException):
724 raise
725 else:
726 raise vimconn.vimconnNotFoundException("Failed : Networks list not found {} ".format(e))
727
728 self.logger.debug("Returning {}".format(network_list))
729 return network_list
730
731 def get_network(self, net_id):
732 """Method obtains network details of net_id VIM network
733 Return a dict with the fields at filter_dict (see get_network_list) plus some VIM specific>}, ...]"""
734
735 try:
736 org, vdc = self.get_vdc_details()
737 vdc_id = vdc.get('id').split(":")[3]
738 if self.client._session:
739 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
740 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
741 response = self.perform_request(req_type='GET',
742 url=vdc.get('href'),
743 headers=headers)
744 if response.status_code != 200:
745 self.logger.error("Failed to get vdc content")
746 raise vimconn.vimconnNotFoundException("Failed to get vdc content")
747 else:
748 content = XmlElementTree.fromstring(response.content)
749
750 filter_dict = {}
751
752 for item in content:
753 if item.tag.split('}')[-1] == 'AvailableNetworks':
754 for net in item:
755 response = self.perform_request(req_type='GET',
756 url=net.get('href'),
757 headers=headers)
758
759 if response.status_code != 200:
760 self.logger.error("Failed to get network content")
761 raise vimconn.vimconnNotFoundException("Failed to get network content")
762 else:
763 net_details = XmlElementTree.fromstring(response.content)
764
765 vdc_network_id = net_details.get('id').split(":")
766 if len(vdc_network_id) == 4 and vdc_network_id[3] == net_id:
767 filter_dict["name"] = net_details.get('name')
768 filter_dict["id"] = vdc_network_id[3]
769 if [i.text for i in net_details if i.tag.split('}')[-1] == 'IsShared'][0] == 'true':
770 shared = True
771 else:
772 shared = False
773 filter_dict["shared"] = shared
774 filter_dict["tenant_id"] = vdc_id
775 if int(net_details.get('status')) == 1:
776 filter_dict["admin_state_up"] = True
777 else:
778 filter_dict["admin_state_up"] = False
779 filter_dict["status"] = "ACTIVE"
780 filter_dict["type"] = "bridge"
781 self.logger.debug("Returning {}".format(filter_dict))
782 return filter_dict
783 else:
784 raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
785 except Exception as e:
786 self.logger.debug("Error in get_network")
787 self.logger.debug(traceback.format_exc())
788 if isinstance(e, vimconn.vimconnException):
789 raise
790 else:
791 raise vimconn.vimconnNotFoundException("Failed : Network not found {} ".format(e))
792
793 return filter_dict
794
795 def delete_network(self, net_id, created_items=None):
796 """
797 Removes a tenant network from VIM and its associated elements
798 :param net_id: VIM identifier of the network, provided by method new_network
799 :param created_items: dictionary with extra items to be deleted. provided by method new_network
800 Returns the network identifier or raises an exception upon error or when network is not found
801 """
802
803 # ############# Stub code for SRIOV #################
804 # dvport_group = self.get_dvport_group(net_id)
805 # if dvport_group:
806 # #delete portgroup
807 # status = self.destroy_dvport_group(net_id)
808 # if status:
809 # # Remove vlanID from persistent info
810 # if net_id in self.persistent_info["used_vlanIDs"]:
811 # del self.persistent_info["used_vlanIDs"][net_id]
812 #
813 # return net_id
814
815 vcd_network = self.get_vcd_network(network_uuid=net_id)
816 if vcd_network is not None and vcd_network:
817 if self.delete_network_action(network_uuid=net_id):
818 return net_id
819 else:
820 raise vimconn.vimconnNotFoundException("Network {} not found".format(net_id))
821
822 def refresh_nets_status(self, net_list):
823 """Get the status of the networks
824 Params: the list of network identifiers
825 Returns a dictionary with:
826 net_id: #VIM id of this network
827 status: #Mandatory. Text with one of:
828 # DELETED (not found at vim)
829 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
830 # OTHER (Vim reported other status not understood)
831 # ERROR (VIM indicates an ERROR status)
832 # ACTIVE, INACTIVE, DOWN (admin down),
833 # BUILD (on building process)
834 #
835 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
836 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
837
838 """
839
840 dict_entry = {}
841 try:
842 for net in net_list:
843 errormsg = ''
844 vcd_network = self.get_vcd_network(network_uuid=net)
845 if vcd_network is not None and vcd_network:
846 if vcd_network['status'] == '1':
847 status = 'ACTIVE'
848 else:
849 status = 'DOWN'
850 else:
851 status = 'DELETED'
852 errormsg = 'Network not found.'
853
854 dict_entry[net] = {'status': status, 'error_msg': errormsg,
855 'vim_info': yaml.safe_dump(vcd_network)}
856 except:
857 self.logger.debug("Error in refresh_nets_status")
858 self.logger.debug(traceback.format_exc())
859
860 return dict_entry
861
862 def get_flavor(self, flavor_id):
863 """Obtain flavor details from the VIM
864 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific } #TODO to concrete
865 """
866 if flavor_id not in vimconnector.flavorlist:
867 raise vimconn.vimconnNotFoundException("Flavor not found.")
868 return vimconnector.flavorlist[flavor_id]
869
870 def new_flavor(self, flavor_data):
871 """Adds a tenant flavor to VIM
872 flavor_data contains a dictionary with information, keys:
873 name: flavor name
874 ram: memory (cloud type) in MBytes
875 vpcus: cpus (cloud type)
876 extended: EPA parameters
877 - numas: #items requested in same NUMA
878 memory: number of 1G huge pages memory
879 paired-threads|cores|threads: number of paired hyperthreads, complete cores OR individual threads
880 interfaces: # passthrough(PT) or SRIOV interfaces attached to this numa
881 - name: interface name
882 dedicated: yes|no|yes:sriov; for PT, SRIOV or only one SRIOV for the physical NIC
883 bandwidth: X Gbps; requested guarantee bandwidth
884 vpci: requested virtual PCI address
885 disk: disk size
886 is_public:
887 #TODO to concrete
888 Returns the flavor identifier"""
889
890 # generate a new uuid put to internal dict and return it.
891 self.logger.debug("Creating new flavor - flavor_data: {}".format(flavor_data))
892 new_flavor=flavor_data
893 ram = flavor_data.get(FLAVOR_RAM_KEY, 1024)
894 cpu = flavor_data.get(FLAVOR_VCPUS_KEY, 1)
895 disk = flavor_data.get(FLAVOR_DISK_KEY, 0)
896
897 if not isinstance(ram, int):
898 raise vimconn.vimconnException("Non-integer value for ram")
899 elif not isinstance(cpu, int):
900 raise vimconn.vimconnException("Non-integer value for cpu")
901 elif not isinstance(disk, int):
902 raise vimconn.vimconnException("Non-integer value for disk")
903
904 extended_flv = flavor_data.get("extended")
905 if extended_flv:
906 numas=extended_flv.get("numas")
907 if numas:
908 for numa in numas:
909 #overwrite ram and vcpus
910 if 'memory' in numa:
911 ram = numa['memory']*1024
912 if 'paired-threads' in numa:
913 cpu = numa['paired-threads']*2
914 elif 'cores' in numa:
915 cpu = numa['cores']
916 elif 'threads' in numa:
917 cpu = numa['threads']
918
919 new_flavor[FLAVOR_RAM_KEY] = ram
920 new_flavor[FLAVOR_VCPUS_KEY] = cpu
921 new_flavor[FLAVOR_DISK_KEY] = disk
922 # generate a new uuid put to internal dict and return it.
923 flavor_id = uuid.uuid4()
924 vimconnector.flavorlist[str(flavor_id)] = new_flavor
925 self.logger.debug("Created flavor - {} : {}".format(flavor_id, new_flavor))
926
927 return str(flavor_id)
928
929 def delete_flavor(self, flavor_id):
930 """Deletes a tenant flavor from VIM identify by its id
931
932 Returns the used id or raise an exception
933 """
934 if flavor_id not in vimconnector.flavorlist:
935 raise vimconn.vimconnNotFoundException("Flavor not found.")
936
937 vimconnector.flavorlist.pop(flavor_id, None)
938 return flavor_id
939
940 def new_image(self, image_dict):
941 """
942 Adds a tenant image to VIM
943 Returns:
944 200, image-id if the image is created
945 <0, message if there is an error
946 """
947
948 return self.get_image_id_from_path(image_dict['location'])
949
950 def delete_image(self, image_id):
951 """
952 Deletes a tenant image from VIM
953 Args:
954 image_id is ID of Image to be deleted
955 Return:
956 returns the image identifier in UUID format or raises an exception on error
957 """
958 conn = self.connect_as_admin()
959 if not conn:
960 raise vimconn.vimconnConnectionException("Failed to connect vCD")
961 # Get Catalog details
962 url_list = [self.url, '/api/catalog/', image_id]
963 catalog_herf = ''.join(url_list)
964
965 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
966 'x-vcloud-authorization': conn._session.headers['x-vcloud-authorization']}
967
968 response = self.perform_request(req_type='GET',
969 url=catalog_herf,
970 headers=headers)
971
972 if response.status_code != requests.codes.ok:
973 self.logger.debug("delete_image():GET REST API call {} failed. "\
974 "Return status code {}".format(catalog_herf,
975 response.status_code))
976 raise vimconn.vimconnNotFoundException("Fail to get image {}".format(image_id))
977
978 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
979 namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
980 #For python3
981 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
982 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
983
984 catalogItems_section = lxmlroot_respond.find("xmlns:CatalogItems",namespaces)
985 catalogItems = catalogItems_section.iterfind("xmlns:CatalogItem",namespaces)
986 for catalogItem in catalogItems:
987 catalogItem_href = catalogItem.attrib['href']
988
989 response = self.perform_request(req_type='GET',
990 url=catalogItem_href,
991 headers=headers)
992
993 if response.status_code != requests.codes.ok:
994 self.logger.debug("delete_image():GET REST API call {} failed. "\
995 "Return status code {}".format(catalog_herf,
996 response.status_code))
997 raise vimconn.vimconnNotFoundException("Fail to get catalogItem {} for catalog {}".format(
998 catalogItem,
999 image_id))
1000
1001 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
1002 namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
1003 #For python3
1004 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
1005 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
1006 catalogitem_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
1007
1008 #Remove catalogItem
1009 response = self.perform_request(req_type='DELETE',
1010 url=catalogitem_remove_href,
1011 headers=headers)
1012 if response.status_code == requests.codes.no_content:
1013 self.logger.debug("Deleted Catalog item {}".format(catalogItem))
1014 else:
1015 raise vimconn.vimconnException("Fail to delete Catalog Item {}".format(catalogItem))
1016
1017 #Remove catalog
1018 url_list = [self.url, '/api/admin/catalog/', image_id]
1019 catalog_remove_herf = ''.join(url_list)
1020 response = self.perform_request(req_type='DELETE',
1021 url=catalog_remove_herf,
1022 headers=headers)
1023
1024 if response.status_code == requests.codes.no_content:
1025 self.logger.debug("Deleted Catalog {}".format(image_id))
1026 return image_id
1027 else:
1028 raise vimconn.vimconnException("Fail to delete Catalog {}".format(image_id))
1029
1030
1031 def catalog_exists(self, catalog_name, catalogs):
1032 """
1033
1034 :param catalog_name:
1035 :param catalogs:
1036 :return:
1037 """
1038 for catalog in catalogs:
1039 if catalog['name'] == catalog_name:
1040 return catalog['id']
1041
1042 def create_vimcatalog(self, vca=None, catalog_name=None):
1043 """ Create new catalog entry in vCloud director.
1044
1045 Args
1046 vca: vCloud director.
1047 catalog_name catalog that client wish to create. Note no validation done for a name.
1048 Client must make sure that provide valid string representation.
1049
1050 Returns catalog id if catalog created else None.
1051
1052 """
1053 try:
1054 lxml_catalog_element = vca.create_catalog(catalog_name, catalog_name)
1055 if lxml_catalog_element:
1056 id_attr_value = lxml_catalog_element.get('id') # 'urn:vcloud:catalog:7490d561-d384-4dac-8229-3575fd1fc7b4'
1057 return id_attr_value.split(':')[-1]
1058 catalogs = vca.list_catalogs()
1059 except Exception as ex:
1060 self.logger.error(
1061 'create_vimcatalog(): Creation of catalog "{}" failed with error: {}'.format(catalog_name, ex))
1062 raise
1063 return self.catalog_exists(catalog_name, catalogs)
1064
1065 # noinspection PyIncorrectDocstring
1066 def upload_ovf(self, vca=None, catalog_name=None, image_name=None, media_file_name=None,
1067 description='', progress=False, chunk_bytes=128 * 1024):
1068 """
1069 Uploads a OVF file to a vCloud catalog
1070
1071 :param chunk_bytes:
1072 :param progress:
1073 :param description:
1074 :param image_name:
1075 :param vca:
1076 :param catalog_name: (str): The name of the catalog to upload the media.
1077 :param media_file_name: (str): The name of the local media file to upload.
1078 :return: (bool) True if the media file was successfully uploaded, false otherwise.
1079 """
1080 os.path.isfile(media_file_name)
1081 statinfo = os.stat(media_file_name)
1082
1083 # find a catalog entry where we upload OVF.
1084 # create vApp Template and check the status if vCD able to read OVF it will respond with appropirate
1085 # status change.
1086 # if VCD can parse OVF we upload VMDK file
1087 try:
1088 for catalog in vca.list_catalogs():
1089 if catalog_name != catalog['name']:
1090 continue
1091 catalog_href = "{}/api/catalog/{}/action/upload".format(self.url, catalog['id'])
1092 data = """
1093 <UploadVAppTemplateParams name="{}" xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"><Description>{} vApp Template</Description></UploadVAppTemplateParams>
1094 """.format(catalog_name, description)
1095
1096 if self.client:
1097 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
1098 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
1099 headers['Content-Type'] = 'application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml'
1100
1101 response = self.perform_request(req_type='POST',
1102 url=catalog_href,
1103 headers=headers,
1104 data=data)
1105
1106 if response.status_code == requests.codes.created:
1107 catalogItem = XmlElementTree.fromstring(response.content)
1108 entity = [child for child in catalogItem if
1109 child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
1110 href = entity.get('href')
1111 template = href
1112
1113 response = self.perform_request(req_type='GET',
1114 url=href,
1115 headers=headers)
1116
1117 if response.status_code == requests.codes.ok:
1118 headers['Content-Type'] = 'Content-Type text/xml'
1119 result = re.search('rel="upload:default"\shref="(.*?\/descriptor.ovf)"',response.content)
1120 if result:
1121 transfer_href = result.group(1)
1122
1123 response = self.perform_request(req_type='PUT',
1124 url=transfer_href,
1125 headers=headers,
1126 data=open(media_file_name, 'rb'))
1127 if response.status_code != requests.codes.ok:
1128 self.logger.debug(
1129 "Failed create vApp template for catalog name {} and image {}".format(catalog_name,
1130 media_file_name))
1131 return False
1132
1133 # TODO fix this with aync block
1134 time.sleep(5)
1135
1136 self.logger.debug("vApp template for catalog name {} and image {}".format(catalog_name, media_file_name))
1137
1138 # uploading VMDK file
1139 # check status of OVF upload and upload remaining files.
1140 response = self.perform_request(req_type='GET',
1141 url=template,
1142 headers=headers)
1143
1144 if response.status_code == requests.codes.ok:
1145 result = re.search('rel="upload:default"\s*href="(.*?vmdk)"',response.content)
1146 if result:
1147 link_href = result.group(1)
1148 # we skip ovf since it already uploaded.
1149 if 'ovf' in link_href:
1150 continue
1151 # The OVF file and VMDK must be in a same directory
1152 head, tail = os.path.split(media_file_name)
1153 file_vmdk = head + '/' + link_href.split("/")[-1]
1154 if not os.path.isfile(file_vmdk):
1155 return False
1156 statinfo = os.stat(file_vmdk)
1157 if statinfo.st_size == 0:
1158 return False
1159 hrefvmdk = link_href
1160
1161 if progress:
1162 widgets = ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
1163 FileTransferSpeed()]
1164 progress_bar = ProgressBar(widgets=widgets, maxval=statinfo.st_size).start()
1165
1166 bytes_transferred = 0
1167 f = open(file_vmdk, 'rb')
1168 while bytes_transferred < statinfo.st_size:
1169 my_bytes = f.read(chunk_bytes)
1170 if len(my_bytes) <= chunk_bytes:
1171 headers['Content-Range'] = 'bytes %s-%s/%s' % (
1172 bytes_transferred, len(my_bytes) - 1, statinfo.st_size)
1173 headers['Content-Length'] = str(len(my_bytes))
1174 response = requests.put(url=hrefvmdk,
1175 headers=headers,
1176 data=my_bytes,
1177 verify=False)
1178 if response.status_code == requests.codes.ok:
1179 bytes_transferred += len(my_bytes)
1180 if progress:
1181 progress_bar.update(bytes_transferred)
1182 else:
1183 self.logger.debug(
1184 'file upload failed with error: [%s] %s' % (response.status_code,
1185 response.content))
1186
1187 f.close()
1188 return False
1189 f.close()
1190 if progress:
1191 progress_bar.finish()
1192 time.sleep(10)
1193 return True
1194 else:
1195 self.logger.debug("Failed retrieve vApp template for catalog name {} for OVF {}".
1196 format(catalog_name, media_file_name))
1197 return False
1198 except Exception as exp:
1199 self.logger.debug("Failed while uploading OVF to catalog {} for OVF file {} with Exception {}"
1200 .format(catalog_name,media_file_name, exp))
1201 raise vimconn.vimconnException(
1202 "Failed while uploading OVF to catalog {} for OVF file {} with Exception {}"
1203 .format(catalog_name,media_file_name, exp))
1204
1205 self.logger.debug("Failed retrieve catalog name {} for OVF file {}".format(catalog_name, media_file_name))
1206 return False
1207
1208 def upload_vimimage(self, vca=None, catalog_name=None, media_name=None, medial_file_name=None, progress=False):
1209 """Upload media file"""
1210 # TODO add named parameters for readability
1211
1212 return self.upload_ovf(vca=vca, catalog_name=catalog_name, image_name=media_name.split(".")[0],
1213 media_file_name=medial_file_name, description='medial_file_name', progress=progress)
1214
1215 def validate_uuid4(self, uuid_string=None):
1216 """ Method validate correct format of UUID.
1217
1218 Return: true if string represent valid uuid
1219 """
1220 try:
1221 val = uuid.UUID(uuid_string, version=4)
1222 except ValueError:
1223 return False
1224 return True
1225
1226 def get_catalogid(self, catalog_name=None, catalogs=None):
1227 """ Method check catalog and return catalog ID in UUID format.
1228
1229 Args
1230 catalog_name: catalog name as string
1231 catalogs: list of catalogs.
1232
1233 Return: catalogs uuid
1234 """
1235
1236 for catalog in catalogs:
1237 if catalog['name'] == catalog_name:
1238 catalog_id = catalog['id']
1239 return catalog_id
1240 return None
1241
1242 def get_catalogbyid(self, catalog_uuid=None, catalogs=None):
1243 """ Method check catalog and return catalog name lookup done by catalog UUID.
1244
1245 Args
1246 catalog_name: catalog name as string
1247 catalogs: list of catalogs.
1248
1249 Return: catalogs name or None
1250 """
1251
1252 if not self.validate_uuid4(uuid_string=catalog_uuid):
1253 return None
1254
1255 for catalog in catalogs:
1256 catalog_id = catalog.get('id')
1257 if catalog_id == catalog_uuid:
1258 return catalog.get('name')
1259 return None
1260
1261 def get_catalog_obj(self, catalog_uuid=None, catalogs=None):
1262 """ Method check catalog and return catalog name lookup done by catalog UUID.
1263
1264 Args
1265 catalog_name: catalog name as string
1266 catalogs: list of catalogs.
1267
1268 Return: catalogs name or None
1269 """
1270
1271 if not self.validate_uuid4(uuid_string=catalog_uuid):
1272 return None
1273
1274 for catalog in catalogs:
1275 catalog_id = catalog.get('id')
1276 if catalog_id == catalog_uuid:
1277 return catalog
1278 return None
1279
1280 def get_image_id_from_path(self, path=None, progress=False):
1281 """ Method upload OVF image to vCloud director.
1282
1283 Each OVF image represented as single catalog entry in vcloud director.
1284 The method check for existing catalog entry. The check done by file name without file extension.
1285
1286 if given catalog name already present method will respond with existing catalog uuid otherwise
1287 it will create new catalog entry and upload OVF file to newly created catalog.
1288
1289 If method can't create catalog entry or upload a file it will throw exception.
1290
1291 Method accept boolean flag progress that will output progress bar. It useful method
1292 for standalone upload use case. In case to test large file upload.
1293
1294 Args
1295 path: - valid path to OVF file.
1296 progress - boolean progress bar show progress bar.
1297
1298 Return: if image uploaded correct method will provide image catalog UUID.
1299 """
1300
1301 if not path:
1302 raise vimconn.vimconnException("Image path can't be None.")
1303
1304 if not os.path.isfile(path):
1305 raise vimconn.vimconnException("Can't read file. File not found.")
1306
1307 if not os.access(path, os.R_OK):
1308 raise vimconn.vimconnException("Can't read file. Check file permission to read.")
1309
1310 self.logger.debug("get_image_id_from_path() client requesting {} ".format(path))
1311
1312 dirpath, filename = os.path.split(path)
1313 flname, file_extension = os.path.splitext(path)
1314 if file_extension != '.ovf':
1315 self.logger.debug("Wrong file extension {} connector support only OVF container.".format(file_extension))
1316 raise vimconn.vimconnException("Wrong container. vCloud director supports only OVF.")
1317
1318 catalog_name = os.path.splitext(filename)[0]
1319 catalog_md5_name = hashlib.md5(path).hexdigest()
1320 self.logger.debug("File name {} Catalog Name {} file path {} "
1321 "vdc catalog name {}".format(filename, catalog_name, path, catalog_md5_name))
1322
1323 try:
1324 org,vdc = self.get_vdc_details()
1325 catalogs = org.list_catalogs()
1326 except Exception as exp:
1327 self.logger.debug("Failed get catalogs() with Exception {} ".format(exp))
1328 raise vimconn.vimconnException("Failed get catalogs() with Exception {} ".format(exp))
1329
1330 if len(catalogs) == 0:
1331 self.logger.info("Creating a new catalog entry {} in vcloud director".format(catalog_name))
1332 if self.create_vimcatalog(org, catalog_md5_name) is None:
1333 raise vimconn.vimconnException("Failed create new catalog {} ".format(catalog_md5_name))
1334
1335 result = self.upload_vimimage(vca=org, catalog_name=catalog_md5_name,
1336 media_name=filename, medial_file_name=path, progress=progress)
1337 if not result:
1338 raise vimconn.vimconnException("Failed create vApp template for catalog {} ".format(catalog_name))
1339 return self.get_catalogid(catalog_name, catalogs)
1340 else:
1341 for catalog in catalogs:
1342 # search for existing catalog if we find same name we return ID
1343 # TODO optimize this
1344 if catalog['name'] == catalog_md5_name:
1345 self.logger.debug("Found existing catalog entry for {} "
1346 "catalog id {}".format(catalog_name,
1347 self.get_catalogid(catalog_md5_name, catalogs)))
1348 return self.get_catalogid(catalog_md5_name, catalogs)
1349
1350 # if we didn't find existing catalog we create a new one and upload image.
1351 self.logger.debug("Creating new catalog entry {} - {}".format(catalog_name, catalog_md5_name))
1352 if self.create_vimcatalog(org, catalog_md5_name) is None:
1353 raise vimconn.vimconnException("Failed create new catalog {} ".format(catalog_md5_name))
1354
1355 result = self.upload_vimimage(vca=org, catalog_name=catalog_md5_name,
1356 media_name=filename, medial_file_name=path, progress=progress)
1357 if not result:
1358 raise vimconn.vimconnException("Failed create vApp template for catalog {} ".format(catalog_md5_name))
1359
1360 return self.get_catalogid(catalog_md5_name, org.list_catalogs())
1361
1362 def get_image_list(self, filter_dict={}):
1363 '''Obtain tenant images from VIM
1364 Filter_dict can be:
1365 name: image name
1366 id: image uuid
1367 checksum: image checksum
1368 location: image path
1369 Returns the image list of dictionaries:
1370 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1371 List can be empty
1372 '''
1373
1374 try:
1375 org, vdc = self.get_vdc_details()
1376 image_list = []
1377 catalogs = org.list_catalogs()
1378 if len(catalogs) == 0:
1379 return image_list
1380 else:
1381 for catalog in catalogs:
1382 catalog_uuid = catalog.get('id')
1383 name = catalog.get('name')
1384 filtered_dict = {}
1385 if filter_dict.get("name") and filter_dict["name"] != name:
1386 continue
1387 if filter_dict.get("id") and filter_dict["id"] != catalog_uuid:
1388 continue
1389 filtered_dict ["name"] = name
1390 filtered_dict ["id"] = catalog_uuid
1391 image_list.append(filtered_dict)
1392
1393 self.logger.debug("List of already created catalog items: {}".format(image_list))
1394 return image_list
1395 except Exception as exp:
1396 raise vimconn.vimconnException("Exception occured while retriving catalog items {}".format(exp))
1397
1398 def get_vappid(self, vdc=None, vapp_name=None):
1399 """ Method takes vdc object and vApp name and returns vapp uuid or None
1400
1401 Args:
1402 vdc: The VDC object.
1403 vapp_name: is application vappp name identifier
1404
1405 Returns:
1406 The return vApp name otherwise None
1407 """
1408 if vdc is None or vapp_name is None:
1409 return None
1410 # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
1411 try:
1412 refs = filter(lambda ref: ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml',
1413 vdc.ResourceEntities.ResourceEntity)
1414 #For python3
1415 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1416 # if ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1417 if len(refs) == 1:
1418 return refs[0].href.split("vapp")[1][1:]
1419 except Exception as e:
1420 self.logger.exception(e)
1421 return False
1422 return None
1423
1424 def check_vapp(self, vdc=None, vapp_uuid=None):
1425 """ Method Method returns True or False if vapp deployed in vCloud director
1426
1427 Args:
1428 vca: Connector to VCA
1429 vdc: The VDC object.
1430 vappid: vappid is application identifier
1431
1432 Returns:
1433 The return True if vApp deployed
1434 :param vdc:
1435 :param vapp_uuid:
1436 """
1437 try:
1438 refs = filter(lambda ref:
1439 ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml',
1440 vdc.ResourceEntities.ResourceEntity)
1441 #For python3
1442 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1443 # if ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1444 for ref in refs:
1445 vappid = ref.href.split("vapp")[1][1:]
1446 # find vapp with respected vapp uuid
1447 if vappid == vapp_uuid:
1448 return True
1449 except Exception as e:
1450 self.logger.exception(e)
1451 return False
1452 return False
1453
1454 def get_namebyvappid(self, vapp_uuid=None):
1455 """Method returns vApp name from vCD and lookup done by vapp_id.
1456
1457 Args:
1458 vapp_uuid: vappid is application identifier
1459
1460 Returns:
1461 The return vApp name otherwise None
1462 """
1463 try:
1464 if self.client and vapp_uuid:
1465 vapp_call = "{}/api/vApp/vapp-{}".format(self.url, vapp_uuid)
1466 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
1467 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
1468
1469 response = self.perform_request(req_type='GET',
1470 url=vapp_call,
1471 headers=headers)
1472 #Retry login if session expired & retry sending request
1473 if response.status_code == 403:
1474 response = self.retry_rest('GET', vapp_call)
1475
1476 tree = XmlElementTree.fromstring(response.content)
1477 return tree.attrib['name']
1478 except Exception as e:
1479 self.logger.exception(e)
1480 return None
1481 return None
1482
1483 def new_vminstance(self, name=None, description="", start=False, image_id=None, flavor_id=None, net_list=[],
1484 cloud_config=None, disk_list=None, availability_zone_index=None, availability_zone_list=None):
1485 """Adds a VM instance to VIM
1486 Params:
1487 'start': (boolean) indicates if VM must start or created in pause mode.
1488 'image_id','flavor_id': image and flavor VIM id to use for the VM
1489 'net_list': list of interfaces, each one is a dictionary with:
1490 'name': (optional) name for the interface.
1491 'net_id': VIM network id where this interface must be connect to. Mandatory for type==virtual
1492 'vpci': (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM capabilities
1493 'model': (optional and only have sense for type==virtual) interface model: virtio, e1000, ...
1494 'mac_address': (optional) mac address to assign to this interface
1495 #TODO: CHECK if an optional 'vlan' parameter is needed for VIMs when type if VF and net_id is not provided,
1496 the VLAN tag to be used. In case net_id is provided, the internal network vlan is used for tagging VF
1497 'type': (mandatory) can be one of:
1498 'virtual', in this case always connected to a network of type 'net_type=bridge'
1499 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a data/ptp network ot it
1500 can created unconnected
1501 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
1502 'VFnotShared'(SRIOV without VLAN tag) same as PF for network connectivity. VF where no other VFs
1503 are allocated on the same physical NIC
1504 'bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
1505 'port_security': (optional) If False it must avoid any traffic filtering at this interface. If missing
1506 or True, it must apply the default VIM behaviour
1507 After execution the method will add the key:
1508 'vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
1509 interface. 'net_list' is modified
1510 'cloud_config': (optional) dictionary with:
1511 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1512 'users': (optional) list of users to be inserted, each item is a dict with:
1513 'name': (mandatory) user name,
1514 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1515 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
1516 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
1517 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1518 'dest': (mandatory) string with the destination absolute path
1519 'encoding': (optional, by default text). Can be one of:
1520 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1521 'content' (mandatory): string with the content of the file
1522 'permissions': (optional) string with file permissions, typically octal notation '0644'
1523 'owner': (optional) file owner, string with the format 'owner:group'
1524 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1525 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1526 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1527 'size': (mandatory) string with the size of the disk in GB
1528 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1529 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1530 availability_zone_index is None
1531 Returns a tuple with the instance identifier and created_items or raises an exception on error
1532 created_items can be None or a dictionary where this method can include key-values that will be passed to
1533 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1534 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1535 as not present.
1536 """
1537 self.logger.info("Creating new instance for entry {}".format(name))
1538 self.logger.debug("desc {} boot {} image_id: {} flavor_id: {} net_list: {} cloud_config {} disk_list {} "\
1539 "availability_zone_index {} availability_zone_list {}"\
1540 .format(description, start, image_id, flavor_id, net_list, cloud_config, disk_list,\
1541 availability_zone_index, availability_zone_list))
1542
1543 #new vm name = vmname + tenant_id + uuid
1544 new_vm_name = [name, '-', str(uuid.uuid4())]
1545 vmname_andid = ''.join(new_vm_name)
1546
1547 for net in net_list:
1548 if net['type'] == "PCI-PASSTHROUGH":
1549 raise vimconn.vimconnNotSupportedException(
1550 "Current vCD version does not support type : {}".format(net['type']))
1551
1552 if len(net_list) > 10:
1553 raise vimconn.vimconnNotSupportedException(
1554 "The VM hardware versions 7 and above support upto 10 NICs only")
1555
1556 # if vm already deployed we return existing uuid
1557 # we check for presence of VDC, Catalog entry and Flavor.
1558 org, vdc = self.get_vdc_details()
1559 if vdc is None:
1560 raise vimconn.vimconnNotFoundException(
1561 "new_vminstance(): Failed create vApp {}: (Failed retrieve VDC information)".format(name))
1562 catalogs = org.list_catalogs()
1563 if catalogs is None:
1564 #Retry once, if failed by refreshing token
1565 self.get_token()
1566 org = Org(self.client, resource=self.client.get_org())
1567 catalogs = org.list_catalogs()
1568 if catalogs is None:
1569 raise vimconn.vimconnNotFoundException(
1570 "new_vminstance(): Failed create vApp {}: (Failed retrieve catalogs list)".format(name))
1571
1572 catalog_hash_name = self.get_catalogbyid(catalog_uuid=image_id, catalogs=catalogs)
1573 if catalog_hash_name:
1574 self.logger.info("Found catalog entry {} for image id {}".format(catalog_hash_name, image_id))
1575 else:
1576 raise vimconn.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1577 "(Failed retrieve catalog information {})".format(name, image_id))
1578
1579 # Set vCPU and Memory based on flavor.
1580 vm_cpus = None
1581 vm_memory = None
1582 vm_disk = None
1583 numas = None
1584
1585 if flavor_id is not None:
1586 if flavor_id not in vimconnector.flavorlist:
1587 raise vimconn.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1588 "Failed retrieve flavor information "
1589 "flavor id {}".format(name, flavor_id))
1590 else:
1591 try:
1592 flavor = vimconnector.flavorlist[flavor_id]
1593 vm_cpus = flavor[FLAVOR_VCPUS_KEY]
1594 vm_memory = flavor[FLAVOR_RAM_KEY]
1595 vm_disk = flavor[FLAVOR_DISK_KEY]
1596 extended = flavor.get("extended", None)
1597 if extended:
1598 numas=extended.get("numas", None)
1599
1600 except Exception as exp:
1601 raise vimconn.vimconnException("Corrupted flavor. {}.Exception: {}".format(flavor_id, exp))
1602
1603 # image upload creates template name as catalog name space Template.
1604 templateName = self.get_catalogbyid(catalog_uuid=image_id, catalogs=catalogs)
1605 power_on = 'false'
1606 if start:
1607 power_on = 'true'
1608
1609 # client must provide at least one entry in net_list if not we report error
1610 #If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
1611 #If no mgmt, then the 1st NN in netlist is considered as primary net.
1612 primary_net = None
1613 primary_netname = None
1614 primary_net_href = None
1615 network_mode = 'bridged'
1616 if net_list is not None and len(net_list) > 0:
1617 for net in net_list:
1618 if 'use' in net and net['use'] == 'mgmt' and not primary_net:
1619 primary_net = net
1620 if primary_net is None:
1621 primary_net = net_list[0]
1622
1623 try:
1624 primary_net_id = primary_net['net_id']
1625 url_list = [self.url, '/api/network/', primary_net_id]
1626 primary_net_href = ''.join(url_list)
1627 network_dict = self.get_vcd_network(network_uuid=primary_net_id)
1628 if 'name' in network_dict:
1629 primary_netname = network_dict['name']
1630
1631 except KeyError:
1632 raise vimconn.vimconnException("Corrupted flavor. {}".format(primary_net))
1633 else:
1634 raise vimconn.vimconnUnexpectedResponse("new_vminstance(): Failed network list is empty.".format(name))
1635
1636 # use: 'data', 'bridge', 'mgmt'
1637 # create vApp. Set vcpu and ram based on flavor id.
1638 try:
1639 vdc_obj = VDC(self.client, resource=org.get_vdc(self.tenant_name))
1640 if not vdc_obj:
1641 raise vimconn.vimconnNotFoundException("new_vminstance(): Failed to get VDC object")
1642
1643 for retry in (1,2):
1644 items = org.get_catalog_item(catalog_hash_name, catalog_hash_name)
1645 catalog_items = [items.attrib]
1646
1647 if len(catalog_items) == 1:
1648 if self.client:
1649 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
1650 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
1651
1652 response = self.perform_request(req_type='GET',
1653 url=catalog_items[0].get('href'),
1654 headers=headers)
1655 catalogItem = XmlElementTree.fromstring(response.content)
1656 entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
1657 vapp_tempalte_href = entity.get("href")
1658
1659 response = self.perform_request(req_type='GET',
1660 url=vapp_tempalte_href,
1661 headers=headers)
1662 if response.status_code != requests.codes.ok:
1663 self.logger.debug("REST API call {} failed. Return status code {}".format(vapp_tempalte_href,
1664 response.status_code))
1665 else:
1666 result = (response.content).replace("\n"," ")
1667
1668 vapp_template_tree = XmlElementTree.fromstring(response.content)
1669 children_element = [child for child in vapp_template_tree if 'Children' in child.tag][0]
1670 vm_element = [child for child in children_element if 'Vm' in child.tag][0]
1671 vm_name = vm_element.get('name')
1672 vm_id = vm_element.get('id')
1673 vm_href = vm_element.get('href')
1674
1675 cpus = re.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',result).group(1)
1676 memory_mb = re.search('<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>',result).group(1)
1677 cores = re.search('<vmw:CoresPerSocket ovf:required.*?>(\d+)</vmw:CoresPerSocket>',result).group(1)
1678
1679 headers['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'
1680 vdc_id = vdc.get('id').split(':')[-1]
1681 instantiate_vapp_href = "{}/api/vdc/{}/action/instantiateVAppTemplate".format(self.url,
1682 vdc_id)
1683 data = """<?xml version="1.0" encoding="UTF-8"?>
1684 <InstantiateVAppTemplateParams
1685 xmlns="http://www.vmware.com/vcloud/v1.5"
1686 name="{}"
1687 deploy="false"
1688 powerOn="false"
1689 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1690 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1">
1691 <Description>Vapp instantiation</Description>
1692 <InstantiationParams>
1693 <NetworkConfigSection>
1694 <ovf:Info>Configuration parameters for logical networks</ovf:Info>
1695 <NetworkConfig networkName="{}">
1696 <Configuration>
1697 <ParentNetwork href="{}" />
1698 <FenceMode>bridged</FenceMode>
1699 </Configuration>
1700 </NetworkConfig>
1701 </NetworkConfigSection>
1702 <LeaseSettingsSection
1703 type="application/vnd.vmware.vcloud.leaseSettingsSection+xml">
1704 <ovf:Info>Lease Settings</ovf:Info>
1705 <StorageLeaseInSeconds>172800</StorageLeaseInSeconds>
1706 <StorageLeaseExpiration>2014-04-25T08:08:16.438-07:00</StorageLeaseExpiration>
1707 </LeaseSettingsSection>
1708 </InstantiationParams>
1709 <Source href="{}"/>
1710 <SourcedItem>
1711 <Source href="{}" id="{}" name="{}"
1712 type="application/vnd.vmware.vcloud.vm+xml"/>
1713 <VmGeneralParams>
1714 <NeedsCustomization>false</NeedsCustomization>
1715 </VmGeneralParams>
1716 <InstantiationParams>
1717 <NetworkConnectionSection>
1718 <ovf:Info>Specifies the available VM network connections</ovf:Info>
1719 <NetworkConnection network="{}">
1720 <NetworkConnectionIndex>0</NetworkConnectionIndex>
1721 <IsConnected>true</IsConnected>
1722 <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
1723 </NetworkConnection>
1724 </NetworkConnectionSection><ovf:VirtualHardwareSection>
1725 <ovf:Info>Virtual hardware requirements</ovf:Info>
1726 <ovf:Item xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
1727 xmlns:vmw="http://www.vmware.com/schema/ovf">
1728 <rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
1729 <rasd:Description>Number of Virtual CPUs</rasd:Description>
1730 <rasd:ElementName xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">{cpu} virtual CPU(s)</rasd:ElementName>
1731 <rasd:InstanceID>4</rasd:InstanceID>
1732 <rasd:Reservation>0</rasd:Reservation>
1733 <rasd:ResourceType>3</rasd:ResourceType>
1734 <rasd:VirtualQuantity xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="int">{cpu}</rasd:VirtualQuantity>
1735 <rasd:Weight>0</rasd:Weight>
1736 <vmw:CoresPerSocket ovf:required="false">{core}</vmw:CoresPerSocket>
1737 </ovf:Item><ovf:Item xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData">
1738 <rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
1739 <rasd:Description>Memory Size</rasd:Description>
1740 <rasd:ElementName xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">{memory} MB of memory</rasd:ElementName>
1741 <rasd:InstanceID>5</rasd:InstanceID>
1742 <rasd:Reservation>0</rasd:Reservation>
1743 <rasd:ResourceType>4</rasd:ResourceType>
1744 <rasd:VirtualQuantity xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="int">{memory}</rasd:VirtualQuantity>
1745 <rasd:Weight>0</rasd:Weight>
1746 </ovf:Item>
1747 </ovf:VirtualHardwareSection>
1748 </InstantiationParams>
1749 </SourcedItem>
1750 <AllEULAsAccepted>false</AllEULAsAccepted>
1751 </InstantiateVAppTemplateParams>""".format(vmname_andid,
1752 primary_netname,
1753 primary_net_href,
1754 vapp_tempalte_href,
1755 vm_href,
1756 vm_id,
1757 vm_name,
1758 primary_netname,
1759 cpu=cpus,
1760 core=cores,
1761 memory=memory_mb)
1762
1763 response = self.perform_request(req_type='POST',
1764 url=instantiate_vapp_href,
1765 headers=headers,
1766 data=data)
1767
1768 if response.status_code != 201:
1769 self.logger.error("REST call {} failed reason : {}"\
1770 "status code : {}".format(instantiate_vapp_href,
1771 response.content,
1772 response.status_code))
1773 raise vimconn.vimconnException("new_vminstance(): Failed to create"\
1774 "vAapp {}".format(vmname_andid))
1775 else:
1776 vapptask = self.get_task_from_response(response.content)
1777
1778 if vapptask is None and retry==1:
1779 self.get_token() # Retry getting token
1780 continue
1781 else:
1782 break
1783
1784 if vapptask is None or vapptask is False:
1785 raise vimconn.vimconnUnexpectedResponse(
1786 "new_vminstance(): failed to create vApp {}".format(vmname_andid))
1787
1788 # wait for task to complete
1789 result = self.client.get_task_monitor().wait_for_success(task=vapptask)
1790
1791 if result.get('status') == 'success':
1792 self.logger.debug("new_vminstance(): Sucessfully created Vapp {}".format(vmname_andid))
1793 else:
1794 raise vimconn.vimconnUnexpectedResponse(
1795 "new_vminstance(): failed to create vApp {}".format(vmname_andid))
1796
1797 except Exception as exp:
1798 raise vimconn.vimconnUnexpectedResponse(
1799 "new_vminstance(): failed to create vApp {} with Exception:{}".format(vmname_andid, exp))
1800
1801 # we should have now vapp in undeployed state.
1802 try:
1803 vdc_obj = VDC(self.client, href=vdc.get('href'))
1804 vapp_resource = vdc_obj.get_vapp(vmname_andid)
1805 vapp_uuid = vapp_resource.get('id').split(':')[-1]
1806 vapp = VApp(self.client, resource=vapp_resource)
1807
1808 except Exception as exp:
1809 raise vimconn.vimconnUnexpectedResponse(
1810 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
1811 .format(vmname_andid, exp))
1812
1813 if vapp_uuid is None:
1814 raise vimconn.vimconnUnexpectedResponse(
1815 "new_vminstance(): Failed to retrieve vApp {} after creation".format(
1816 vmname_andid))
1817
1818 #Add PCI passthrough/SRIOV configrations
1819 vm_obj = None
1820 pci_devices_info = []
1821 reserve_memory = False
1822
1823 for net in net_list:
1824 if net["type"] == "PF" or net["type"] == "PCI-PASSTHROUGH":
1825 pci_devices_info.append(net)
1826 elif (net["type"] == "VF" or net["type"] == "SR-IOV" or net["type"] == "VFnotShared") and 'net_id'in net:
1827 reserve_memory = True
1828
1829 #Add PCI
1830 if len(pci_devices_info) > 0:
1831 self.logger.info("Need to add PCI devices {} into VM {}".format(pci_devices_info,
1832 vmname_andid ))
1833 PCI_devices_status, vm_obj, vcenter_conect = self.add_pci_devices(vapp_uuid,
1834 pci_devices_info,
1835 vmname_andid)
1836 if PCI_devices_status:
1837 self.logger.info("Added PCI devives {} to VM {}".format(
1838 pci_devices_info,
1839 vmname_andid)
1840 )
1841 reserve_memory = True
1842 else:
1843 self.logger.info("Fail to add PCI devives {} to VM {}".format(
1844 pci_devices_info,
1845 vmname_andid)
1846 )
1847
1848 # Modify vm disk
1849 if vm_disk:
1850 #Assuming there is only one disk in ovf and fast provisioning in organization vDC is disabled
1851 result = self.modify_vm_disk(vapp_uuid, vm_disk)
1852 if result :
1853 self.logger.debug("Modified Disk size of VM {} ".format(vmname_andid))
1854
1855 #Add new or existing disks to vApp
1856 if disk_list:
1857 added_existing_disk = False
1858 for disk in disk_list:
1859 if 'device_type' in disk and disk['device_type'] == 'cdrom':
1860 image_id = disk['image_id']
1861 # Adding CD-ROM to VM
1862 # will revisit code once specification ready to support this feature
1863 self.insert_media_to_vm(vapp, image_id)
1864 elif "image_id" in disk and disk["image_id"] is not None:
1865 self.logger.debug("Adding existing disk from image {} to vm {} ".format(
1866 disk["image_id"] , vapp_uuid))
1867 self.add_existing_disk(catalogs=catalogs,
1868 image_id=disk["image_id"],
1869 size = disk["size"],
1870 template_name=templateName,
1871 vapp_uuid=vapp_uuid
1872 )
1873 added_existing_disk = True
1874 else:
1875 #Wait till added existing disk gets reflected into vCD database/API
1876 if added_existing_disk:
1877 time.sleep(5)
1878 added_existing_disk = False
1879 self.add_new_disk(vapp_uuid, disk['size'])
1880
1881 if numas:
1882 # Assigning numa affinity setting
1883 for numa in numas:
1884 if 'paired-threads-id' in numa:
1885 paired_threads_id = numa['paired-threads-id']
1886 self.set_numa_affinity(vapp_uuid, paired_threads_id)
1887
1888 # add NICs & connect to networks in netlist
1889 try:
1890 vdc_obj = VDC(self.client, href=vdc.get('href'))
1891 vapp_resource = vdc_obj.get_vapp(vmname_andid)
1892 vapp = VApp(self.client, resource=vapp_resource)
1893 vapp_id = vapp_resource.get('id').split(':')[-1]
1894
1895 self.logger.info("Removing primary NIC: ")
1896 # First remove all NICs so that NIC properties can be adjusted as needed
1897 self.remove_primary_network_adapter_from_all_vms(vapp)
1898
1899 self.logger.info("Request to connect VM to a network: {}".format(net_list))
1900 primary_nic_index = 0
1901 nicIndex = 0
1902 for net in net_list:
1903 # openmano uses network id in UUID format.
1904 # vCloud Director need a name so we do reverse operation from provided UUID we lookup a name
1905 # [{'use': 'bridge', 'net_id': '527d4bf7-566a-41e7-a9e7-ca3cdd9cef4f', 'type': 'virtual',
1906 # 'vpci': '0000:00:11.0', 'name': 'eth0'}]
1907
1908 if 'net_id' not in net:
1909 continue
1910
1911 #Using net_id as a vim_id i.e. vim interface id, as do not have saperate vim interface id
1912 #Same will be returned in refresh_vms_status() as vim_interface_id
1913 net['vim_id'] = net['net_id'] # Provide the same VIM identifier as the VIM network
1914
1915 interface_net_id = net['net_id']
1916 interface_net_name = self.get_network_name_by_id(network_uuid=interface_net_id)
1917 interface_network_mode = net['use']
1918
1919 if interface_network_mode == 'mgmt':
1920 primary_nic_index = nicIndex
1921
1922 """- POOL (A static IP address is allocated automatically from a pool of addresses.)
1923 - DHCP (The IP address is obtained from a DHCP service.)
1924 - MANUAL (The IP address is assigned manually in the IpAddress element.)
1925 - NONE (No IP addressing mode specified.)"""
1926
1927 if primary_netname is not None:
1928 self.logger.debug("new_vminstance(): Filtering by net name {}".format(interface_net_name))
1929 nets = filter(lambda n: n.get('name') == interface_net_name, self.get_network_list())
1930 #For python3
1931 #nets = [n for n in self.get_network_list() if n.get('name') == interface_net_name]
1932 if len(nets) == 1:
1933 self.logger.info("new_vminstance(): Found requested network: {}".format(nets[0].get('name')))
1934
1935 if interface_net_name != primary_netname:
1936 # connect network to VM - with all DHCP by default
1937 self.logger.info("new_vminstance(): Attaching net {} to vapp".format(interface_net_name))
1938 self.connect_vapp_to_org_vdc_network(vapp_id, nets[0].get('name'))
1939
1940 type_list = ('PF', 'PCI-PASSTHROUGH', 'VFnotShared')
1941 nic_type = 'VMXNET3'
1942 if 'type' in net and net['type'] not in type_list:
1943 # fetching nic type from vnf
1944 if 'model' in net:
1945 if net['model'] is not None:
1946 if net['model'].lower() == 'paravirt' or net['model'].lower() == 'virtio':
1947 nic_type = 'VMXNET3'
1948 else:
1949 nic_type = net['model']
1950
1951 self.logger.info("new_vminstance(): adding network adapter "\
1952 "to a network {}".format(nets[0].get('name')))
1953 self.add_network_adapter_to_vms(vapp, nets[0].get('name'),
1954 primary_nic_index,
1955 nicIndex,
1956 net,
1957 nic_type=nic_type)
1958 else:
1959 self.logger.info("new_vminstance(): adding network adapter "\
1960 "to a network {}".format(nets[0].get('name')))
1961 if net['type'] in ['SR-IOV', 'VF']:
1962 nic_type = net['type']
1963 self.add_network_adapter_to_vms(vapp, nets[0].get('name'),
1964 primary_nic_index,
1965 nicIndex,
1966 net,
1967 nic_type=nic_type)
1968 nicIndex += 1
1969
1970 # cloud-init for ssh-key injection
1971 if cloud_config:
1972 # Create a catalog which will be carrying the config drive ISO
1973 # This catalog is deleted during vApp deletion. The catalog name carries
1974 # vApp UUID and thats how it gets identified during its deletion.
1975 config_drive_catalog_name = 'cfg_drv-' + vapp_uuid
1976 self.logger.info('new_vminstance(): Creating catalog "{}" to carry config drive ISO'.format(
1977 config_drive_catalog_name))
1978 config_drive_catalog_id = self.create_vimcatalog(org, config_drive_catalog_name)
1979 if config_drive_catalog_id is None:
1980 error_msg = "new_vminstance(): Failed to create new catalog '{}' to carry the config drive " \
1981 "ISO".format(config_drive_catalog_name)
1982 raise Exception(error_msg)
1983
1984 # Create config-drive ISO
1985 _, userdata = self._create_user_data(cloud_config)
1986 # self.logger.debug('new_vminstance(): The userdata for cloud-init: {}'.format(userdata))
1987 iso_path = self.create_config_drive_iso(userdata)
1988 self.logger.debug('new_vminstance(): The ISO is successfully created. Path: {}'.format(iso_path))
1989
1990 self.logger.info('new_vminstance(): uploading iso to catalog {}'.format(config_drive_catalog_name))
1991 self.upload_iso_to_catalog(config_drive_catalog_id, iso_path)
1992 # Attach the config-drive ISO to the VM
1993 self.logger.info('new_vminstance(): Attaching the config-drive ISO to the VM')
1994 # The ISO remains in INVALID_STATE right after the PUT request (its a blocking call though)
1995 time.sleep(5)
1996 self.insert_media_to_vm(vapp, config_drive_catalog_id)
1997 shutil.rmtree(os.path.dirname(iso_path), ignore_errors=True)
1998
1999 # If VM has PCI devices or SRIOV reserve memory for VM
2000 if reserve_memory:
2001 self.reserve_memory_for_all_vms(vapp, memory_mb)
2002
2003 self.logger.debug("new_vminstance(): starting power on vApp {} ".format(vmname_andid))
2004
2005 poweron_task = self.power_on_vapp(vapp_id, vmname_andid)
2006 result = self.client.get_task_monitor().wait_for_success(task=poweron_task)
2007 if result.get('status') == 'success':
2008 self.logger.info("new_vminstance(): Successfully power on "\
2009 "vApp {}".format(vmname_andid))
2010 else:
2011 self.logger.error("new_vminstance(): failed to power on vApp "\
2012 "{}".format(vmname_andid))
2013
2014 except Exception as exp:
2015 try:
2016 self.delete_vminstance(vapp_uuid)
2017 except Exception as exp2:
2018 self.logger.error("new_vminstance rollback fail {}".format(exp2))
2019 # it might be a case if specific mandatory entry in dict is empty or some other pyVcloud exception
2020 self.logger.error("new_vminstance(): Failed create new vm instance {} with exception {}"
2021 .format(name, exp))
2022 raise vimconn.vimconnException("new_vminstance(): Failed create new vm instance {} with exception {}"
2023 .format(name, exp))
2024
2025 # check if vApp deployed and if that the case return vApp UUID otherwise -1
2026 wait_time = 0
2027 vapp_uuid = None
2028 while wait_time <= MAX_WAIT_TIME:
2029 try:
2030 vapp_resource = vdc_obj.get_vapp(vmname_andid)
2031 vapp = VApp(self.client, resource=vapp_resource)
2032 except Exception as exp:
2033 raise vimconn.vimconnUnexpectedResponse(
2034 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
2035 .format(vmname_andid, exp))
2036
2037 #if vapp and vapp.me.deployed:
2038 if vapp and vapp_resource.get('deployed') == 'true':
2039 vapp_uuid = vapp_resource.get('id').split(':')[-1]
2040 break
2041 else:
2042 self.logger.debug("new_vminstance(): Wait for vApp {} to deploy".format(name))
2043 time.sleep(INTERVAL_TIME)
2044
2045 wait_time +=INTERVAL_TIME
2046
2047 #SET Affinity Rule for VM
2048 #Pre-requisites: User has created Hosh Groups in vCenter with respective Hosts to be used
2049 #While creating VIM account user has to pass the Host Group names in availability_zone list
2050 #"availability_zone" is a part of VIM "config" parameters
2051 #For example, in VIM config: "availability_zone":["HG_170","HG_174","HG_175"]
2052 #Host groups are referred as availability zones
2053 #With following procedure, deployed VM will be added into a VM group.
2054 #Then A VM to Host Affinity rule will be created using the VM group & Host group.
2055 if(availability_zone_list):
2056 self.logger.debug("Existing Host Groups in VIM {}".format(self.config.get('availability_zone')))
2057 #Admin access required for creating Affinity rules
2058 client = self.connect_as_admin()
2059 if not client:
2060 raise vimconn.vimconnConnectionException("Failed to connect vCD as admin")
2061 else:
2062 self.client = client
2063 if self.client:
2064 headers = {'Accept':'application/*+xml;version=27.0',
2065 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
2066 #Step1: Get provider vdc details from organization
2067 pvdc_href = self.get_pvdc_for_org(self.tenant_name, headers)
2068 if pvdc_href is not None:
2069 #Step2: Found required pvdc, now get resource pool information
2070 respool_href = self.get_resource_pool_details(pvdc_href, headers)
2071 if respool_href is None:
2072 #Raise error if respool_href not found
2073 msg = "new_vminstance():Error in finding resource pool details in pvdc {}"\
2074 .format(pvdc_href)
2075 self.log_message(msg)
2076
2077 #Step3: Verify requested availability zone(hostGroup) is present in vCD
2078 # get availability Zone
2079 vm_az = self.get_vm_availability_zone(availability_zone_index, availability_zone_list)
2080 # check if provided av zone(hostGroup) is present in vCD VIM
2081 status = self.check_availibility_zone(vm_az, respool_href, headers)
2082 if status is False:
2083 msg = "new_vminstance(): Error in finding availability zone(Host Group): {} in "\
2084 "resource pool {} status: {}".format(vm_az,respool_href,status)
2085 self.log_message(msg)
2086 else:
2087 self.logger.debug ("new_vminstance(): Availability zone {} found in VIM".format(vm_az))
2088
2089 #Step4: Find VM group references to create vm group
2090 vmgrp_href = self.find_vmgroup_reference(respool_href, headers)
2091 if vmgrp_href == None:
2092 msg = "new_vminstance(): No reference to VmGroup found in resource pool"
2093 self.log_message(msg)
2094
2095 #Step5: Create a VmGroup with name az_VmGroup
2096 vmgrp_name = vm_az + "_" + name #Formed VM Group name = Host Group name + VM name
2097 status = self.create_vmgroup(vmgrp_name, vmgrp_href, headers)
2098 if status is not True:
2099 msg = "new_vminstance(): Error in creating VM group {}".format(vmgrp_name)
2100 self.log_message(msg)
2101
2102 #VM Group url to add vms to vm group
2103 vmgrpname_url = self.url + "/api/admin/extension/vmGroup/name/"+ vmgrp_name
2104
2105 #Step6: Add VM to VM Group
2106 #Find VM uuid from vapp_uuid
2107 vm_details = self.get_vapp_details_rest(vapp_uuid)
2108 vm_uuid = vm_details['vmuuid']
2109
2110 status = self.add_vm_to_vmgroup(vm_uuid, vmgrpname_url, vmgrp_name, headers)
2111 if status is not True:
2112 msg = "new_vminstance(): Error in adding VM to VM group {}".format(vmgrp_name)
2113 self.log_message(msg)
2114
2115 #Step7: Create VM to Host affinity rule
2116 addrule_href = self.get_add_rule_reference (respool_href, headers)
2117 if addrule_href is None:
2118 msg = "new_vminstance(): Error in finding href to add rule in resource pool: {}"\
2119 .format(respool_href)
2120 self.log_message(msg)
2121
2122 status = self.create_vm_to_host_affinity_rule(addrule_href, vmgrp_name, vm_az, "Affinity", headers)
2123 if status is False:
2124 msg = "new_vminstance(): Error in creating affinity rule for VM {} in Host group {}"\
2125 .format(name, vm_az)
2126 self.log_message(msg)
2127 else:
2128 self.logger.debug("new_vminstance(): Affinity rule created successfully. Added {} in Host group {}"\
2129 .format(name, vm_az))
2130 #Reset token to a normal user to perform other operations
2131 self.get_token()
2132
2133 if vapp_uuid is not None:
2134 return vapp_uuid, None
2135 else:
2136 raise vimconn.vimconnUnexpectedResponse("new_vminstance(): Failed create new vm instance {}".format(name))
2137
2138 def create_config_drive_iso(self, user_data):
2139 tmpdir = tempfile.mkdtemp()
2140 iso_path = os.path.join(tmpdir, 'ConfigDrive.iso')
2141 latest_dir = os.path.join(tmpdir, 'openstack', 'latest')
2142 os.makedirs(latest_dir)
2143 with open(os.path.join(latest_dir, 'meta_data.json'), 'w') as meta_file_obj, \
2144 open(os.path.join(latest_dir, 'user_data'), 'w') as userdata_file_obj:
2145 userdata_file_obj.write(user_data)
2146 meta_file_obj.write(json.dumps({"availability_zone": "nova",
2147 "launch_index": 0,
2148 "name": "ConfigDrive",
2149 "uuid": str(uuid.uuid4())}
2150 )
2151 )
2152 genisoimage_cmd = 'genisoimage -J -r -V config-2 -o {iso_path} {source_dir_path}'.format(
2153 iso_path=iso_path, source_dir_path=tmpdir)
2154 self.logger.info('create_config_drive_iso(): Creating ISO by running command "{}"'.format(genisoimage_cmd))
2155 try:
2156 FNULL = open(os.devnull, 'w')
2157 subprocess.check_call(genisoimage_cmd, shell=True, stdout=FNULL)
2158 except subprocess.CalledProcessError as e:
2159 shutil.rmtree(tmpdir, ignore_errors=True)
2160 error_msg = 'create_config_drive_iso(): Exception while running genisoimage command: {}'.format(e)
2161 self.logger.error(error_msg)
2162 raise Exception(error_msg)
2163 return iso_path
2164
2165 def upload_iso_to_catalog(self, catalog_id, iso_file_path):
2166 if not os.path.isfile(iso_file_path):
2167 error_msg = "upload_iso_to_catalog(): Given iso file is not present. Given path: {}".format(iso_file_path)
2168 self.logger.error(error_msg)
2169 raise Exception(error_msg)
2170 iso_file_stat = os.stat(iso_file_path)
2171 xml_media_elem = '''<?xml version="1.0" encoding="UTF-8"?>
2172 <Media
2173 xmlns="http://www.vmware.com/vcloud/v1.5"
2174 name="{iso_name}"
2175 size="{iso_size}"
2176 imageType="iso">
2177 <Description>ISO image for config-drive</Description>
2178 </Media>'''.format(iso_name=os.path.basename(iso_file_path), iso_size=iso_file_stat.st_size)
2179 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
2180 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
2181 headers['Content-Type'] = 'application/vnd.vmware.vcloud.media+xml'
2182 catalog_href = self.url + '/api/catalog/' + catalog_id + '/action/upload'
2183 response = self.perform_request(req_type='POST', url=catalog_href, headers=headers, data=xml_media_elem)
2184
2185 if response.status_code != 201:
2186 error_msg = "upload_iso_to_catalog(): Failed to POST an action/upload request to {}".format(catalog_href)
2187 self.logger.error(error_msg)
2188 raise Exception(error_msg)
2189
2190 catalogItem = XmlElementTree.fromstring(response.content)
2191 entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.media+xml"][0]
2192 entity_href = entity.get('href')
2193
2194 response = self.perform_request(req_type='GET', url=entity_href, headers=headers)
2195 if response.status_code != 200:
2196 raise Exception("upload_iso_to_catalog(): Failed to GET entity href {}".format(entity_href))
2197
2198 match = re.search(r'<Files>\s+?<File.+?href="(.+?)"/>\s+?</File>\s+?</Files>', response.text, re.DOTALL)
2199 if match:
2200 media_upload_href = match.group(1)
2201 else:
2202 raise Exception('Could not parse the upload URL for the media file from the last response')
2203
2204 headers['Content-Type'] = 'application/octet-stream'
2205 response = self.perform_request(req_type='PUT',
2206 url=media_upload_href,
2207 headers=headers,
2208 data=open(iso_file_path, 'rb'))
2209
2210 if response.status_code != 200:
2211 raise Exception('PUT request to "{}" failed'.format(media_upload_href))
2212
2213 def get_vcd_availibility_zones(self,respool_href, headers):
2214 """ Method to find presence of av zone is VIM resource pool
2215
2216 Args:
2217 respool_href - resource pool href
2218 headers - header information
2219
2220 Returns:
2221 vcd_az - list of azone present in vCD
2222 """
2223 vcd_az = []
2224 url=respool_href
2225 resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
2226
2227 if resp.status_code != requests.codes.ok:
2228 self.logger.debug ("REST API call {} failed. Return status code {}".format(url, resp.status_code))
2229 else:
2230 #Get the href to hostGroups and find provided hostGroup is present in it
2231 resp_xml = XmlElementTree.fromstring(resp.content)
2232 for child in resp_xml:
2233 if 'VMWProviderVdcResourcePool' in child.tag:
2234 for schild in child:
2235 if 'Link' in schild.tag:
2236 if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
2237 hostGroup = schild.attrib.get('href')
2238 hg_resp = self.perform_request(req_type='GET',url=hostGroup, headers=headers)
2239 if hg_resp.status_code != requests.codes.ok:
2240 self.logger.debug ("REST API call {} failed. Return status code {}".format(hostGroup, hg_resp.status_code))
2241 else:
2242 hg_resp_xml = XmlElementTree.fromstring(hg_resp.content)
2243 for hostGroup in hg_resp_xml:
2244 if 'HostGroup' in hostGroup.tag:
2245 #append host group name to the list
2246 vcd_az.append(hostGroup.attrib.get("name"))
2247 return vcd_az
2248
2249
2250 def set_availability_zones(self):
2251 """
2252 Set vim availability zone
2253 """
2254
2255 vim_availability_zones = None
2256 availability_zone = None
2257 if 'availability_zone' in self.config:
2258 vim_availability_zones = self.config.get('availability_zone')
2259 if isinstance(vim_availability_zones, str):
2260 availability_zone = [vim_availability_zones]
2261 elif isinstance(vim_availability_zones, list):
2262 availability_zone = vim_availability_zones
2263 else:
2264 return availability_zone
2265
2266 return availability_zone
2267
2268
2269 def get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
2270 """
2271 Return the availability zone to be used by the created VM.
2272 returns: The VIM availability zone to be used or None
2273 """
2274 if availability_zone_index is None:
2275 if not self.config.get('availability_zone'):
2276 return None
2277 elif isinstance(self.config.get('availability_zone'), str):
2278 return self.config['availability_zone']
2279 else:
2280 return self.config['availability_zone'][0]
2281
2282 vim_availability_zones = self.availability_zone
2283
2284 # check if VIM offer enough availability zones describe in the VNFD
2285 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
2286 # check if all the names of NFV AV match VIM AV names
2287 match_by_index = False
2288 for av in availability_zone_list:
2289 if av not in vim_availability_zones:
2290 match_by_index = True
2291 break
2292 if match_by_index:
2293 self.logger.debug("Required Availability zone or Host Group not found in VIM config")
2294 self.logger.debug("Input Availability zone list: {}".format(availability_zone_list))
2295 self.logger.debug("VIM configured Availability zones: {}".format(vim_availability_zones))
2296 self.logger.debug("VIM Availability zones will be used by index")
2297 return vim_availability_zones[availability_zone_index]
2298 else:
2299 return availability_zone_list[availability_zone_index]
2300 else:
2301 raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
2302
2303
2304 def create_vm_to_host_affinity_rule(self, addrule_href, vmgrpname, hostgrpname, polarity, headers):
2305 """ Method to create VM to Host Affinity rule in vCD
2306
2307 Args:
2308 addrule_href - href to make a POST request
2309 vmgrpname - name of the VM group created
2310 hostgrpnmae - name of the host group created earlier
2311 polarity - Affinity or Anti-affinity (default: Affinity)
2312 headers - headers to make REST call
2313
2314 Returns:
2315 True- if rule is created
2316 False- Failed to create rule due to some error
2317
2318 """
2319 task_status = False
2320 rule_name = polarity + "_" + vmgrpname
2321 payload = """<?xml version="1.0" encoding="UTF-8"?>
2322 <vmext:VMWVmHostAffinityRule
2323 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
2324 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
2325 type="application/vnd.vmware.admin.vmwVmHostAffinityRule+xml">
2326 <vcloud:Name>{}</vcloud:Name>
2327 <vcloud:IsEnabled>true</vcloud:IsEnabled>
2328 <vcloud:IsMandatory>true</vcloud:IsMandatory>
2329 <vcloud:Polarity>{}</vcloud:Polarity>
2330 <vmext:HostGroupName>{}</vmext:HostGroupName>
2331 <vmext:VmGroupName>{}</vmext:VmGroupName>
2332 </vmext:VMWVmHostAffinityRule>""".format(rule_name, polarity, hostgrpname, vmgrpname)
2333
2334 resp = self.perform_request(req_type='POST',url=addrule_href, headers=headers, data=payload)
2335
2336 if resp.status_code != requests.codes.accepted:
2337 self.logger.debug ("REST API call {} failed. Return status code {}".format(addrule_href, resp.status_code))
2338 task_status = False
2339 return task_status
2340 else:
2341 affinity_task = self.get_task_from_response(resp.content)
2342 self.logger.debug ("affinity_task: {}".format(affinity_task))
2343 if affinity_task is None or affinity_task is False:
2344 raise vimconn.vimconnUnexpectedResponse("failed to find affinity task")
2345 # wait for task to complete
2346 result = self.client.get_task_monitor().wait_for_success(task=affinity_task)
2347 if result.get('status') == 'success':
2348 self.logger.debug("Successfully created affinity rule {}".format(rule_name))
2349 return True
2350 else:
2351 raise vimconn.vimconnUnexpectedResponse(
2352 "failed to create affinity rule {}".format(rule_name))
2353
2354
2355 def get_add_rule_reference (self, respool_href, headers):
2356 """ This method finds href to add vm to host affinity rule to vCD
2357
2358 Args:
2359 respool_href- href to resource pool
2360 headers- header information to make REST call
2361
2362 Returns:
2363 None - if no valid href to add rule found or
2364 addrule_href - href to add vm to host affinity rule of resource pool
2365 """
2366 addrule_href = None
2367 resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
2368
2369 if resp.status_code != requests.codes.ok:
2370 self.logger.debug ("REST API call {} failed. Return status code {}".format(respool_href, resp.status_code))
2371 else:
2372
2373 resp_xml = XmlElementTree.fromstring(resp.content)
2374 for child in resp_xml:
2375 if 'VMWProviderVdcResourcePool' in child.tag:
2376 for schild in child:
2377 if 'Link' in schild.tag:
2378 if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwVmHostAffinityRule+xml" and \
2379 schild.attrib.get('rel') == "add":
2380 addrule_href = schild.attrib.get('href')
2381 break
2382
2383 return addrule_href
2384
2385
2386 def add_vm_to_vmgroup(self, vm_uuid, vmGroupNameURL, vmGroup_name, headers):
2387 """ Method to add deployed VM to newly created VM Group.
2388 This is required to create VM to Host affinity in vCD
2389
2390 Args:
2391 vm_uuid- newly created vm uuid
2392 vmGroupNameURL- URL to VM Group name
2393 vmGroup_name- Name of VM group created
2394 headers- Headers for REST request
2395
2396 Returns:
2397 True- if VM added to VM group successfully
2398 False- if any error encounter
2399 """
2400
2401 addvm_resp = self.perform_request(req_type='GET',url=vmGroupNameURL, headers=headers)#, data=payload)
2402
2403 if addvm_resp.status_code != requests.codes.ok:
2404 self.logger.debug ("REST API call to get VM Group Name url {} failed. Return status code {}"\
2405 .format(vmGroupNameURL, addvm_resp.status_code))
2406 return False
2407 else:
2408 resp_xml = XmlElementTree.fromstring(addvm_resp.content)
2409 for child in resp_xml:
2410 if child.tag.split('}')[1] == 'Link':
2411 if child.attrib.get("rel") == "addVms":
2412 addvmtogrpURL = child.attrib.get("href")
2413
2414 #Get vm details
2415 url_list = [self.url, '/api/vApp/vm-',vm_uuid]
2416 vmdetailsURL = ''.join(url_list)
2417
2418 resp = self.perform_request(req_type='GET',url=vmdetailsURL, headers=headers)
2419
2420 if resp.status_code != requests.codes.ok:
2421 self.logger.debug ("REST API call {} failed. Return status code {}".format(vmdetailsURL, resp.status_code))
2422 return False
2423
2424 #Parse VM details
2425 resp_xml = XmlElementTree.fromstring(resp.content)
2426 if resp_xml.tag.split('}')[1] == "Vm":
2427 vm_id = resp_xml.attrib.get("id")
2428 vm_name = resp_xml.attrib.get("name")
2429 vm_href = resp_xml.attrib.get("href")
2430 #print vm_id, vm_name, vm_href
2431 #Add VM into VMgroup
2432 payload = """<?xml version="1.0" encoding="UTF-8"?>\
2433 <ns2:Vms xmlns:ns2="http://www.vmware.com/vcloud/v1.5" \
2434 xmlns="http://www.vmware.com/vcloud/versions" \
2435 xmlns:ns3="http://schemas.dmtf.org/ovf/envelope/1" \
2436 xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" \
2437 xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/common" \
2438 xmlns:ns6="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" \
2439 xmlns:ns7="http://www.vmware.com/schema/ovf" \
2440 xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1" \
2441 xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">\
2442 <ns2:VmReference href="{}" id="{}" name="{}" \
2443 type="application/vnd.vmware.vcloud.vm+xml" />\
2444 </ns2:Vms>""".format(vm_href, vm_id, vm_name)
2445
2446 addvmtogrp_resp = self.perform_request(req_type='POST',url=addvmtogrpURL, headers=headers, data=payload)
2447
2448 if addvmtogrp_resp.status_code != requests.codes.accepted:
2449 self.logger.debug ("REST API call {} failed. Return status code {}".format(addvmtogrpURL, addvmtogrp_resp.status_code))
2450 return False
2451 else:
2452 self.logger.debug ("Done adding VM {} to VMgroup {}".format(vm_name, vmGroup_name))
2453 return True
2454
2455
2456 def create_vmgroup(self, vmgroup_name, vmgroup_href, headers):
2457 """Method to create a VM group in vCD
2458
2459 Args:
2460 vmgroup_name : Name of VM group to be created
2461 vmgroup_href : href for vmgroup
2462 headers- Headers for REST request
2463 """
2464 #POST to add URL with required data
2465 vmgroup_status = False
2466 payload = """<VMWVmGroup xmlns="http://www.vmware.com/vcloud/extension/v1.5" \
2467 xmlns:vcloud_v1.5="http://www.vmware.com/vcloud/v1.5" name="{}">\
2468 <vmCount>1</vmCount>\
2469 </VMWVmGroup>""".format(vmgroup_name)
2470 resp = self.perform_request(req_type='POST',url=vmgroup_href, headers=headers, data=payload)
2471
2472 if resp.status_code != requests.codes.accepted:
2473 self.logger.debug ("REST API call {} failed. Return status code {}".format(vmgroup_href, resp.status_code))
2474 return vmgroup_status
2475 else:
2476 vmgroup_task = self.get_task_from_response(resp.content)
2477 if vmgroup_task is None or vmgroup_task is False:
2478 raise vimconn.vimconnUnexpectedResponse(
2479 "create_vmgroup(): failed to create VM group {}".format(vmgroup_name))
2480
2481 # wait for task to complete
2482 result = self.client.get_task_monitor().wait_for_success(task=vmgroup_task)
2483
2484 if result.get('status') == 'success':
2485 self.logger.debug("create_vmgroup(): Successfully created VM group {}".format(vmgroup_name))
2486 #time.sleep(10)
2487 vmgroup_status = True
2488 return vmgroup_status
2489 else:
2490 raise vimconn.vimconnUnexpectedResponse(\
2491 "create_vmgroup(): failed to create VM group {}".format(vmgroup_name))
2492
2493
2494 def find_vmgroup_reference(self, url, headers):
2495 """ Method to create a new VMGroup which is required to add created VM
2496 Args:
2497 url- resource pool href
2498 headers- header information
2499
2500 Returns:
2501 returns href to VM group to create VM group
2502 """
2503 #Perform GET on resource pool to find 'add' link to create VMGroup
2504 #https://vcd-ip/api/admin/extension/providervdc/<providervdc id>/resourcePools
2505 vmgrp_href = None
2506 resp = self.perform_request(req_type='GET',url=url, headers=headers)
2507
2508 if resp.status_code != requests.codes.ok:
2509 self.logger.debug ("REST API call {} failed. Return status code {}".format(url, resp.status_code))
2510 else:
2511 #Get the href to add vmGroup to vCD
2512 resp_xml = XmlElementTree.fromstring(resp.content)
2513 for child in resp_xml:
2514 if 'VMWProviderVdcResourcePool' in child.tag:
2515 for schild in child:
2516 if 'Link' in schild.tag:
2517 #Find href with type VMGroup and rel with add
2518 if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwVmGroupType+xml"\
2519 and schild.attrib.get('rel') == "add":
2520 vmgrp_href = schild.attrib.get('href')
2521 return vmgrp_href
2522
2523
2524 def check_availibility_zone(self, az, respool_href, headers):
2525 """ Method to verify requested av zone is present or not in provided
2526 resource pool
2527
2528 Args:
2529 az - name of hostgroup (availibility_zone)
2530 respool_href - Resource Pool href
2531 headers - Headers to make REST call
2532 Returns:
2533 az_found - True if availibility_zone is found else False
2534 """
2535 az_found = False
2536 headers['Accept']='application/*+xml;version=27.0'
2537 resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
2538
2539 if resp.status_code != requests.codes.ok:
2540 self.logger.debug ("REST API call {} failed. Return status code {}".format(respool_href, resp.status_code))
2541 else:
2542 #Get the href to hostGroups and find provided hostGroup is present in it
2543 resp_xml = XmlElementTree.fromstring(resp.content)
2544
2545 for child in resp_xml:
2546 if 'VMWProviderVdcResourcePool' in child.tag:
2547 for schild in child:
2548 if 'Link' in schild.tag:
2549 if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
2550 hostGroup_href = schild.attrib.get('href')
2551 hg_resp = self.perform_request(req_type='GET',url=hostGroup_href, headers=headers)
2552 if hg_resp.status_code != requests.codes.ok:
2553 self.logger.debug ("REST API call {} failed. Return status code {}".format(hostGroup_href, hg_resp.status_code))
2554 else:
2555 hg_resp_xml = XmlElementTree.fromstring(hg_resp.content)
2556 for hostGroup in hg_resp_xml:
2557 if 'HostGroup' in hostGroup.tag:
2558 if hostGroup.attrib.get("name") == az:
2559 az_found = True
2560 break
2561 return az_found
2562
2563
2564 def get_pvdc_for_org(self, org_vdc, headers):
2565 """ This method gets provider vdc references from organisation
2566
2567 Args:
2568 org_vdc - name of the organisation VDC to find pvdc
2569 headers - headers to make REST call
2570
2571 Returns:
2572 None - if no pvdc href found else
2573 pvdc_href - href to pvdc
2574 """
2575
2576 #Get provider VDC references from vCD
2577 pvdc_href = None
2578 #url = '<vcd url>/api/admin/extension/providerVdcReferences'
2579 url_list = [self.url, '/api/admin/extension/providerVdcReferences']
2580 url = ''.join(url_list)
2581
2582 response = self.perform_request(req_type='GET',url=url, headers=headers)
2583 if response.status_code != requests.codes.ok:
2584 self.logger.debug ("REST API call {} failed. Return status code {}"\
2585 .format(url, response.status_code))
2586 else:
2587 xmlroot_response = XmlElementTree.fromstring(response.content)
2588 for child in xmlroot_response:
2589 if 'ProviderVdcReference' in child.tag:
2590 pvdc_href = child.attrib.get('href')
2591 #Get vdcReferences to find org
2592 pvdc_resp = self.perform_request(req_type='GET',url=pvdc_href, headers=headers)
2593 if pvdc_resp.status_code != requests.codes.ok:
2594 raise vimconn.vimconnException("REST API call {} failed. "\
2595 "Return status code {}"\
2596 .format(url, pvdc_resp.status_code))
2597
2598 pvdc_resp_xml = XmlElementTree.fromstring(pvdc_resp.content)
2599 for child in pvdc_resp_xml:
2600 if 'Link' in child.tag:
2601 if child.attrib.get('type') == "application/vnd.vmware.admin.vdcReferences+xml":
2602 vdc_href = child.attrib.get('href')
2603
2604 #Check if provided org is present in vdc
2605 vdc_resp = self.perform_request(req_type='GET',
2606 url=vdc_href,
2607 headers=headers)
2608 if vdc_resp.status_code != requests.codes.ok:
2609 raise vimconn.vimconnException("REST API call {} failed. "\
2610 "Return status code {}"\
2611 .format(url, vdc_resp.status_code))
2612 vdc_resp_xml = XmlElementTree.fromstring(vdc_resp.content)
2613 for child in vdc_resp_xml:
2614 if 'VdcReference' in child.tag:
2615 if child.attrib.get('name') == org_vdc:
2616 return pvdc_href
2617
2618
2619 def get_resource_pool_details(self, pvdc_href, headers):
2620 """ Method to get resource pool information.
2621 Host groups are property of resource group.
2622 To get host groups, we need to GET details of resource pool.
2623
2624 Args:
2625 pvdc_href: href to pvdc details
2626 headers: headers
2627
2628 Returns:
2629 respool_href - Returns href link reference to resource pool
2630 """
2631 respool_href = None
2632 resp = self.perform_request(req_type='GET',url=pvdc_href, headers=headers)
2633
2634 if resp.status_code != requests.codes.ok:
2635 self.logger.debug ("REST API call {} failed. Return status code {}"\
2636 .format(pvdc_href, resp.status_code))
2637 else:
2638 respool_resp_xml = XmlElementTree.fromstring(resp.content)
2639 for child in respool_resp_xml:
2640 if 'Link' in child.tag:
2641 if child.attrib.get('type') == "application/vnd.vmware.admin.vmwProviderVdcResourcePoolSet+xml":
2642 respool_href = child.attrib.get("href")
2643 break
2644 return respool_href
2645
2646
2647 def log_message(self, msg):
2648 """
2649 Method to log error messages related to Affinity rule creation
2650 in new_vminstance & raise Exception
2651 Args :
2652 msg - Error message to be logged
2653
2654 """
2655 #get token to connect vCD as a normal user
2656 self.get_token()
2657 self.logger.debug(msg)
2658 raise vimconn.vimconnException(msg)
2659
2660
2661 ##
2662 ##
2663 ## based on current discussion
2664 ##
2665 ##
2666 ## server:
2667 # created: '2016-09-08T11:51:58'
2668 # description: simple-instance.linux1.1
2669 # flavor: ddc6776e-75a9-11e6-ad5f-0800273e724c
2670 # hostId: e836c036-74e7-11e6-b249-0800273e724c
2671 # image: dde30fe6-75a9-11e6-ad5f-0800273e724c
2672 # status: ACTIVE
2673 # error_msg:
2674 # interfaces: …
2675 #
2676 def get_vminstance(self, vim_vm_uuid=None):
2677 """Returns the VM instance information from VIM"""
2678
2679 self.logger.debug("Client requesting vm instance {} ".format(vim_vm_uuid))
2680
2681 org, vdc = self.get_vdc_details()
2682 if vdc is None:
2683 raise vimconn.vimconnConnectionException(
2684 "Failed to get a reference of VDC for a tenant {}".format(self.tenant_name))
2685
2686 vm_info_dict = self.get_vapp_details_rest(vapp_uuid=vim_vm_uuid)
2687 if not vm_info_dict:
2688 self.logger.debug("get_vminstance(): Failed to get vApp name by UUID {}".format(vim_vm_uuid))
2689 raise vimconn.vimconnNotFoundException("Failed to get vApp name by UUID {}".format(vim_vm_uuid))
2690
2691 status_key = vm_info_dict['status']
2692 error = ''
2693 try:
2694 vm_dict = {'created': vm_info_dict['created'],
2695 'description': vm_info_dict['name'],
2696 'status': vcdStatusCode2manoFormat[int(status_key)],
2697 'hostId': vm_info_dict['vmuuid'],
2698 'error_msg': error,
2699 'vim_info': yaml.safe_dump(vm_info_dict), 'interfaces': []}
2700
2701 if 'interfaces' in vm_info_dict:
2702 vm_dict['interfaces'] = vm_info_dict['interfaces']
2703 else:
2704 vm_dict['interfaces'] = []
2705 except KeyError:
2706 vm_dict = {'created': '',
2707 'description': '',
2708 'status': vcdStatusCode2manoFormat[int(-1)],
2709 'hostId': vm_info_dict['vmuuid'],
2710 'error_msg': "Inconsistency state",
2711 'vim_info': yaml.safe_dump(vm_info_dict), 'interfaces': []}
2712
2713 return vm_dict
2714
2715 def delete_vminstance(self, vm__vim_uuid, created_items=None):
2716 """Method poweroff and remove VM instance from vcloud director network.
2717
2718 Args:
2719 vm__vim_uuid: VM UUID
2720
2721 Returns:
2722 Returns the instance identifier
2723 """
2724
2725 self.logger.debug("Client requesting delete vm instance {} ".format(vm__vim_uuid))
2726
2727 org, vdc = self.get_vdc_details()
2728 vdc_obj = VDC(self.client, href=vdc.get('href'))
2729 if vdc_obj is None:
2730 self.logger.debug("delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
2731 self.tenant_name))
2732 raise vimconn.vimconnException(
2733 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(self.tenant_name))
2734
2735 try:
2736 vapp_name = self.get_namebyvappid(vm__vim_uuid)
2737 if vapp_name is None:
2738 self.logger.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid))
2739 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid)
2740 self.logger.info("Deleting vApp {} and UUID {}".format(vapp_name, vm__vim_uuid))
2741 vapp_resource = vdc_obj.get_vapp(vapp_name)
2742 vapp = VApp(self.client, resource=vapp_resource)
2743
2744 # Delete vApp and wait for status change if task executed and vApp is None.
2745
2746 if vapp:
2747 if vapp_resource.get('deployed') == 'true':
2748 self.logger.info("Powering off vApp {}".format(vapp_name))
2749 #Power off vApp
2750 powered_off = False
2751 wait_time = 0
2752 while wait_time <= MAX_WAIT_TIME:
2753 power_off_task = vapp.power_off()
2754 result = self.client.get_task_monitor().wait_for_success(task=power_off_task)
2755
2756 if result.get('status') == 'success':
2757 powered_off = True
2758 break
2759 else:
2760 self.logger.info("Wait for vApp {} to power off".format(vapp_name))
2761 time.sleep(INTERVAL_TIME)
2762
2763 wait_time +=INTERVAL_TIME
2764 if not powered_off:
2765 self.logger.debug("delete_vminstance(): Failed to power off VM instance {} ".format(vm__vim_uuid))
2766 else:
2767 self.logger.info("delete_vminstance(): Powered off VM instance {} ".format(vm__vim_uuid))
2768
2769 #Undeploy vApp
2770 self.logger.info("Undeploy vApp {}".format(vapp_name))
2771 wait_time = 0
2772 undeployed = False
2773 while wait_time <= MAX_WAIT_TIME:
2774 vapp = VApp(self.client, resource=vapp_resource)
2775 if not vapp:
2776 self.logger.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid))
2777 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid)
2778 undeploy_task = vapp.undeploy()
2779
2780 result = self.client.get_task_monitor().wait_for_success(task=undeploy_task)
2781 if result.get('status') == 'success':
2782 undeployed = True
2783 break
2784 else:
2785 self.logger.debug("Wait for vApp {} to undeploy".format(vapp_name))
2786 time.sleep(INTERVAL_TIME)
2787
2788 wait_time +=INTERVAL_TIME
2789
2790 if not undeployed:
2791 self.logger.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid))
2792
2793 # delete vapp
2794 self.logger.info("Start deletion of vApp {} ".format(vapp_name))
2795
2796 if vapp is not None:
2797 wait_time = 0
2798 result = False
2799
2800 while wait_time <= MAX_WAIT_TIME:
2801 vapp = VApp(self.client, resource=vapp_resource)
2802 if not vapp:
2803 self.logger.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid))
2804 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid)
2805
2806 delete_task = vdc_obj.delete_vapp(vapp.name, force=True)
2807
2808 result = self.client.get_task_monitor().wait_for_success(task=delete_task)
2809 if result.get('status') == 'success':
2810 break
2811 else:
2812 self.logger.debug("Wait for vApp {} to delete".format(vapp_name))
2813 time.sleep(INTERVAL_TIME)
2814
2815 wait_time +=INTERVAL_TIME
2816
2817 if result is None:
2818 self.logger.debug("delete_vminstance(): Failed delete uuid {} ".format(vm__vim_uuid))
2819 else:
2820 self.logger.info("Deleted vm instance {} sccessfully".format(vm__vim_uuid))
2821 config_drive_catalog_name, config_drive_catalog_id = 'cfg_drv-' + vm__vim_uuid, None
2822 catalog_list = self.get_image_list()
2823 try:
2824 config_drive_catalog_id = [catalog_['id'] for catalog_ in catalog_list
2825 if catalog_['name'] == config_drive_catalog_name][0]
2826 except IndexError:
2827 pass
2828 if config_drive_catalog_id:
2829 self.logger.debug('delete_vminstance(): Found a config drive catalog {} matching '
2830 'vapp_name"{}". Deleting it.'.format(config_drive_catalog_id, vapp_name))
2831 self.delete_image(config_drive_catalog_id)
2832 return vm__vim_uuid
2833 except:
2834 self.logger.debug(traceback.format_exc())
2835 raise vimconn.vimconnException("delete_vminstance(): Failed delete vm instance {}".format(vm__vim_uuid))
2836
2837
2838 def refresh_vms_status(self, vm_list):
2839 """Get the status of the virtual machines and their interfaces/ports
2840 Params: the list of VM identifiers
2841 Returns a dictionary with:
2842 vm_id: #VIM id of this Virtual Machine
2843 status: #Mandatory. Text with one of:
2844 # DELETED (not found at vim)
2845 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2846 # OTHER (Vim reported other status not understood)
2847 # ERROR (VIM indicates an ERROR status)
2848 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2849 # CREATING (on building process), ERROR
2850 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2851 #
2852 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2853 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2854 interfaces:
2855 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2856 mac_address: #Text format XX:XX:XX:XX:XX:XX
2857 vim_net_id: #network id where this interface is connected
2858 vim_interface_id: #interface/port VIM id
2859 ip_address: #null, or text with IPv4, IPv6 address
2860 """
2861
2862 self.logger.debug("Client requesting refresh vm status for {} ".format(vm_list))
2863
2864 org,vdc = self.get_vdc_details()
2865 if vdc is None:
2866 raise vimconn.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self.tenant_name))
2867
2868 vms_dict = {}
2869 nsx_edge_list = []
2870 for vmuuid in vm_list:
2871 vapp_name = self.get_namebyvappid(vmuuid)
2872 if vapp_name is not None:
2873
2874 try:
2875 vm_pci_details = self.get_vm_pci_details(vmuuid)
2876 vdc_obj = VDC(self.client, href=vdc.get('href'))
2877 vapp_resource = vdc_obj.get_vapp(vapp_name)
2878 the_vapp = VApp(self.client, resource=vapp_resource)
2879
2880 vm_details = {}
2881 for vm in the_vapp.get_all_vms():
2882 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
2883 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
2884 response = self.perform_request(req_type='GET',
2885 url=vm.get('href'),
2886 headers=headers)
2887
2888 if response.status_code != 200:
2889 self.logger.error("refresh_vms_status : REST call {} failed reason : {}"\
2890 "status code : {}".format(vm.get('href'),
2891 response.content,
2892 response.status_code))
2893 raise vimconn.vimconnException("refresh_vms_status : Failed to get "\
2894 "VM details")
2895 xmlroot = XmlElementTree.fromstring(response.content)
2896
2897
2898 result = response.content.replace("\n"," ")
2899 hdd_match = re.search('vcloud:capacity="(\d+)"\svcloud:storageProfileOverrideVmDefault=',result)
2900 if hdd_match:
2901 hdd_mb = hdd_match.group(1)
2902 vm_details['hdd_mb'] = int(hdd_mb) if hdd_mb else None
2903 cpus_match = re.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',result)
2904 if cpus_match:
2905 cpus = cpus_match.group(1)
2906 vm_details['cpus'] = int(cpus) if cpus else None
2907 memory_mb = re.search('<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>',result).group(1)
2908 vm_details['memory_mb'] = int(memory_mb) if memory_mb else None
2909 vm_details['status'] = vcdStatusCode2manoFormat[int(xmlroot.get('status'))]
2910 vm_details['id'] = xmlroot.get('id')
2911 vm_details['name'] = xmlroot.get('name')
2912 vm_info = [vm_details]
2913 if vm_pci_details:
2914 vm_info[0].update(vm_pci_details)
2915
2916 vm_dict = {'status': vcdStatusCode2manoFormat[int(vapp_resource.get('status'))],
2917 'error_msg': vcdStatusCode2manoFormat[int(vapp_resource.get('status'))],
2918 'vim_info': yaml.safe_dump(vm_info), 'interfaces': []}
2919
2920 # get networks
2921 vm_ip = None
2922 vm_mac = None
2923 networks = re.findall('<NetworkConnection needsCustomization=.*?</NetworkConnection>',result)
2924 for network in networks:
2925 mac_s = re.search('<MACAddress>(.*?)</MACAddress>',network)
2926 vm_mac = mac_s.group(1) if mac_s else None
2927 ip_s = re.search('<IpAddress>(.*?)</IpAddress>',network)
2928 vm_ip = ip_s.group(1) if ip_s else None
2929
2930 if vm_ip is None:
2931 if not nsx_edge_list:
2932 nsx_edge_list = self.get_edge_details()
2933 if nsx_edge_list is None:
2934 raise vimconn.vimconnException("refresh_vms_status:"\
2935 "Failed to get edge details from NSX Manager")
2936 if vm_mac is not None:
2937 vm_ip = self.get_ipaddr_from_NSXedge(nsx_edge_list, vm_mac)
2938
2939 net_s = re.search('network="(.*?)"',network)
2940 network_name = net_s.group(1) if net_s else None
2941
2942 vm_net_id = self.get_network_id_by_name(network_name)
2943 interface = {"mac_address": vm_mac,
2944 "vim_net_id": vm_net_id,
2945 "vim_interface_id": vm_net_id,
2946 "ip_address": vm_ip}
2947
2948 vm_dict["interfaces"].append(interface)
2949
2950 # add a vm to vm dict
2951 vms_dict.setdefault(vmuuid, vm_dict)
2952 self.logger.debug("refresh_vms_status : vm info {}".format(vm_dict))
2953 except Exception as exp:
2954 self.logger.debug("Error in response {}".format(exp))
2955 self.logger.debug(traceback.format_exc())
2956
2957 return vms_dict
2958
2959
2960 def get_edge_details(self):
2961 """Get the NSX edge list from NSX Manager
2962 Returns list of NSX edges
2963 """
2964 edge_list = []
2965 rheaders = {'Content-Type': 'application/xml'}
2966 nsx_api_url = '/api/4.0/edges'
2967
2968 self.logger.debug("Get edge details from NSX Manager {} {}".format(self.nsx_manager, nsx_api_url))
2969
2970 try:
2971 resp = requests.get(self.nsx_manager + nsx_api_url,
2972 auth = (self.nsx_user, self.nsx_password),
2973 verify = False, headers = rheaders)
2974 if resp.status_code == requests.codes.ok:
2975 paged_Edge_List = XmlElementTree.fromstring(resp.text)
2976 for edge_pages in paged_Edge_List:
2977 if edge_pages.tag == 'edgePage':
2978 for edge_summary in edge_pages:
2979 if edge_summary.tag == 'pagingInfo':
2980 for element in edge_summary:
2981 if element.tag == 'totalCount' and element.text == '0':
2982 raise vimconn.vimconnException("get_edge_details: No NSX edges details found: {}"
2983 .format(self.nsx_manager))
2984
2985 if edge_summary.tag == 'edgeSummary':
2986 for element in edge_summary:
2987 if element.tag == 'id':
2988 edge_list.append(element.text)
2989 else:
2990 raise vimconn.vimconnException("get_edge_details: No NSX edge details found: {}"
2991 .format(self.nsx_manager))
2992
2993 if not edge_list:
2994 raise vimconn.vimconnException("get_edge_details: "\
2995 "No NSX edge details found: {}"
2996 .format(self.nsx_manager))
2997 else:
2998 self.logger.debug("get_edge_details: Found NSX edges {}".format(edge_list))
2999 return edge_list
3000 else:
3001 self.logger.debug("get_edge_details: "
3002 "Failed to get NSX edge details from NSX Manager: {}"
3003 .format(resp.content))
3004 return None
3005
3006 except Exception as exp:
3007 self.logger.debug("get_edge_details: "\
3008 "Failed to get NSX edge details from NSX Manager: {}"
3009 .format(exp))
3010 raise vimconn.vimconnException("get_edge_details: "\
3011 "Failed to get NSX edge details from NSX Manager: {}"
3012 .format(exp))
3013
3014
3015 def get_ipaddr_from_NSXedge(self, nsx_edges, mac_address):
3016 """Get IP address details from NSX edges, using the MAC address
3017 PARAMS: nsx_edges : List of NSX edges
3018 mac_address : Find IP address corresponding to this MAC address
3019 Returns: IP address corrresponding to the provided MAC address
3020 """
3021
3022 ip_addr = None
3023 rheaders = {'Content-Type': 'application/xml'}
3024
3025 self.logger.debug("get_ipaddr_from_NSXedge: Finding IP addr from NSX edge")
3026
3027 try:
3028 for edge in nsx_edges:
3029 nsx_api_url = '/api/4.0/edges/'+ edge +'/dhcp/leaseInfo'
3030
3031 resp = requests.get(self.nsx_manager + nsx_api_url,
3032 auth = (self.nsx_user, self.nsx_password),
3033 verify = False, headers = rheaders)
3034
3035 if resp.status_code == requests.codes.ok:
3036 dhcp_leases = XmlElementTree.fromstring(resp.text)
3037 for child in dhcp_leases:
3038 if child.tag == 'dhcpLeaseInfo':
3039 dhcpLeaseInfo = child
3040 for leaseInfo in dhcpLeaseInfo:
3041 for elem in leaseInfo:
3042 if (elem.tag)=='macAddress':
3043 edge_mac_addr = elem.text
3044 if (elem.tag)=='ipAddress':
3045 ip_addr = elem.text
3046 if edge_mac_addr is not None:
3047 if edge_mac_addr == mac_address:
3048 self.logger.debug("Found ip addr {} for mac {} at NSX edge {}"
3049 .format(ip_addr, mac_address,edge))
3050 return ip_addr
3051 else:
3052 self.logger.debug("get_ipaddr_from_NSXedge: "\
3053 "Error occurred while getting DHCP lease info from NSX Manager: {}"
3054 .format(resp.content))
3055
3056 self.logger.debug("get_ipaddr_from_NSXedge: No IP addr found in any NSX edge")
3057 return None
3058
3059 except XmlElementTree.ParseError as Err:
3060 self.logger.debug("ParseError in response from NSX Manager {}".format(Err.message), exc_info=True)
3061
3062
3063 def action_vminstance(self, vm__vim_uuid=None, action_dict=None, created_items={}):
3064 """Send and action over a VM instance from VIM
3065 Returns the vm_id if the action was successfully sent to the VIM"""
3066
3067 self.logger.debug("Received action for vm {} and action dict {}".format(vm__vim_uuid, action_dict))
3068 if vm__vim_uuid is None or action_dict is None:
3069 raise vimconn.vimconnException("Invalid request. VM id or action is None.")
3070
3071 org, vdc = self.get_vdc_details()
3072 if vdc is None:
3073 raise vimconn.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self.tenant_name))
3074
3075 vapp_name = self.get_namebyvappid(vm__vim_uuid)
3076 if vapp_name is None:
3077 self.logger.debug("action_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid))
3078 raise vimconn.vimconnException("Failed to get vm by given {} vm uuid".format(vm__vim_uuid))
3079 else:
3080 self.logger.info("Action_vminstance vApp {} and UUID {}".format(vapp_name, vm__vim_uuid))
3081
3082 try:
3083 vdc_obj = VDC(self.client, href=vdc.get('href'))
3084 vapp_resource = vdc_obj.get_vapp(vapp_name)
3085 vapp = VApp(self.client, resource=vapp_resource)
3086 if "start" in action_dict:
3087 self.logger.info("action_vminstance: Power on vApp: {}".format(vapp_name))
3088 poweron_task = self.power_on_vapp(vm__vim_uuid, vapp_name)
3089 result = self.client.get_task_monitor().wait_for_success(task=poweron_task)
3090 self.instance_actions_result("start", result, vapp_name)
3091 elif "rebuild" in action_dict:
3092 self.logger.info("action_vminstance: Rebuild vApp: {}".format(vapp_name))
3093 rebuild_task = vapp.deploy(power_on=True)
3094 result = self.client.get_task_monitor().wait_for_success(task=rebuild_task)
3095 self.instance_actions_result("rebuild", result, vapp_name)
3096 elif "pause" in action_dict:
3097 self.logger.info("action_vminstance: pause vApp: {}".format(vapp_name))
3098 pause_task = vapp.undeploy(action='suspend')
3099 result = self.client.get_task_monitor().wait_for_success(task=pause_task)
3100 self.instance_actions_result("pause", result, vapp_name)
3101 elif "resume" in action_dict:
3102 self.logger.info("action_vminstance: resume vApp: {}".format(vapp_name))
3103 poweron_task = self.power_on_vapp(vm__vim_uuid, vapp_name)
3104 result = self.client.get_task_monitor().wait_for_success(task=poweron_task)
3105 self.instance_actions_result("resume", result, vapp_name)
3106 elif "shutoff" in action_dict or "shutdown" in action_dict:
3107 action_name , value = action_dict.items()[0]
3108 #For python3
3109 #action_name , value = list(action_dict.items())[0]
3110 self.logger.info("action_vminstance: {} vApp: {}".format(action_name, vapp_name))
3111 shutdown_task = vapp.shutdown()
3112 result = self.client.get_task_monitor().wait_for_success(task=shutdown_task)
3113 if action_name == "shutdown":
3114 self.instance_actions_result("shutdown", result, vapp_name)
3115 else:
3116 self.instance_actions_result("shutoff", result, vapp_name)
3117 elif "forceOff" in action_dict:
3118 result = vapp.undeploy(action='powerOff')
3119 self.instance_actions_result("forceOff", result, vapp_name)
3120 elif "reboot" in action_dict:
3121 self.logger.info("action_vminstance: reboot vApp: {}".format(vapp_name))
3122 reboot_task = vapp.reboot()
3123 self.client.get_task_monitor().wait_for_success(task=reboot_task)
3124 else:
3125 raise vimconn.vimconnException("action_vminstance: Invalid action {} or action is None.".format(action_dict))
3126 return vm__vim_uuid
3127 except Exception as exp :
3128 self.logger.debug("action_vminstance: Failed with Exception {}".format(exp))
3129 raise vimconn.vimconnException("action_vminstance: Failed with Exception {}".format(exp))
3130
3131 def instance_actions_result(self, action, result, vapp_name):
3132 if result.get('status') == 'success':
3133 self.logger.info("action_vminstance: Sucessfully {} the vApp: {}".format(action, vapp_name))
3134 else:
3135 self.logger.error("action_vminstance: Failed to {} vApp: {}".format(action, vapp_name))
3136
3137 def get_vminstance_console(self, vm_id, console_type="novnc"):
3138 """
3139 Get a console for the virtual machine
3140 Params:
3141 vm_id: uuid of the VM
3142 console_type, can be:
3143 "novnc" (by default), "xvpvnc" for VNC types,
3144 "rdp-html5" for RDP types, "spice-html5" for SPICE types
3145 Returns dict with the console parameters:
3146 protocol: ssh, ftp, http, https, ...
3147 server: usually ip address
3148 port: the http, ssh, ... port
3149 suffix: extra text, e.g. the http path and query string
3150 """
3151 console_dict = {}
3152
3153 if console_type==None or console_type=='novnc':
3154
3155 url_rest_call = "{}/api/vApp/vm-{}/screen/action/acquireMksTicket".format(self.url, vm_id)
3156
3157 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3158 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3159 response = self.perform_request(req_type='POST',
3160 url=url_rest_call,
3161 headers=headers)
3162
3163 if response.status_code == 403:
3164 response = self.retry_rest('GET', url_rest_call)
3165
3166 if response.status_code != 200:
3167 self.logger.error("REST call {} failed reason : {}"\
3168 "status code : {}".format(url_rest_call,
3169 response.content,
3170 response.status_code))
3171 raise vimconn.vimconnException("get_vminstance_console : Failed to get "\
3172 "VM Mks ticket details")
3173 s = re.search("<Host>(.*?)</Host>",response.content)
3174 console_dict['server'] = s.group(1) if s else None
3175 s1 = re.search("<Port>(\d+)</Port>",response.content)
3176 console_dict['port'] = s1.group(1) if s1 else None
3177
3178
3179 url_rest_call = "{}/api/vApp/vm-{}/screen/action/acquireTicket".format(self.url, vm_id)
3180
3181 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3182 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3183 response = self.perform_request(req_type='POST',
3184 url=url_rest_call,
3185 headers=headers)
3186
3187 if response.status_code == 403:
3188 response = self.retry_rest('GET', url_rest_call)
3189
3190 if response.status_code != 200:
3191 self.logger.error("REST call {} failed reason : {}"\
3192 "status code : {}".format(url_rest_call,
3193 response.content,
3194 response.status_code))
3195 raise vimconn.vimconnException("get_vminstance_console : Failed to get "\
3196 "VM console details")
3197 s = re.search(">.*?/(vm-\d+.*)</",response.content)
3198 console_dict['suffix'] = s.group(1) if s else None
3199 console_dict['protocol'] = "https"
3200
3201 return console_dict
3202
3203 # NOT USED METHODS in current version
3204
3205 def host_vim2gui(self, host, server_dict):
3206 """Transform host dictionary from VIM format to GUI format,
3207 and append to the server_dict
3208 """
3209 raise vimconn.vimconnNotImplemented("Should have implemented this")
3210
3211 def get_hosts_info(self):
3212 """Get the information of deployed hosts
3213 Returns the hosts content"""
3214 raise vimconn.vimconnNotImplemented("Should have implemented this")
3215
3216 def get_hosts(self, vim_tenant):
3217 """Get the hosts and deployed instances
3218 Returns the hosts content"""
3219 raise vimconn.vimconnNotImplemented("Should have implemented this")
3220
3221 def get_processor_rankings(self):
3222 """Get the processor rankings in the VIM database"""
3223 raise vimconn.vimconnNotImplemented("Should have implemented this")
3224
3225 def new_host(self, host_data):
3226 """Adds a new host to VIM"""
3227 '''Returns status code of the VIM response'''
3228 raise vimconn.vimconnNotImplemented("Should have implemented this")
3229
3230 def new_external_port(self, port_data):
3231 """Adds a external port to VIM"""
3232 '''Returns the port identifier'''
3233 raise vimconn.vimconnNotImplemented("Should have implemented this")
3234
3235 def new_external_network(self, net_name, net_type):
3236 """Adds a external network to VIM (shared)"""
3237 '''Returns the network identifier'''
3238 raise vimconn.vimconnNotImplemented("Should have implemented this")
3239
3240 def connect_port_network(self, port_id, network_id, admin=False):
3241 """Connects a external port to a network"""
3242 '''Returns status code of the VIM response'''
3243 raise vimconn.vimconnNotImplemented("Should have implemented this")
3244
3245 def new_vminstancefromJSON(self, vm_data):
3246 """Adds a VM instance to VIM"""
3247 '''Returns the instance identifier'''
3248 raise vimconn.vimconnNotImplemented("Should have implemented this")
3249
3250 def get_network_name_by_id(self, network_uuid=None):
3251 """Method gets vcloud director network named based on supplied uuid.
3252
3253 Args:
3254 network_uuid: network_id
3255
3256 Returns:
3257 The return network name.
3258 """
3259
3260 if not network_uuid:
3261 return None
3262
3263 try:
3264 org_dict = self.get_org(self.org_uuid)
3265 if 'networks' in org_dict:
3266 org_network_dict = org_dict['networks']
3267 for net_uuid in org_network_dict:
3268 if net_uuid == network_uuid:
3269 return org_network_dict[net_uuid]
3270 except:
3271 self.logger.debug("Exception in get_network_name_by_id")
3272 self.logger.debug(traceback.format_exc())
3273
3274 return None
3275
3276 def get_network_id_by_name(self, network_name=None):
3277 """Method gets vcloud director network uuid based on supplied name.
3278
3279 Args:
3280 network_name: network_name
3281 Returns:
3282 The return network uuid.
3283 network_uuid: network_id
3284 """
3285
3286 if not network_name:
3287 self.logger.debug("get_network_id_by_name() : Network name is empty")
3288 return None
3289
3290 try:
3291 org_dict = self.get_org(self.org_uuid)
3292 if org_dict and 'networks' in org_dict:
3293 org_network_dict = org_dict['networks']
3294 for net_uuid,net_name in org_network_dict.iteritems():
3295 #For python3
3296 #for net_uuid,net_name in org_network_dict.items():
3297 if net_name == network_name:
3298 return net_uuid
3299
3300 except KeyError as exp:
3301 self.logger.debug("get_network_id_by_name() : KeyError- {} ".format(exp))
3302
3303 return None
3304
3305 def list_org_action(self):
3306 """
3307 Method leverages vCloud director and query for available organization for particular user
3308
3309 Args:
3310 vca - is active VCA connection.
3311 vdc_name - is a vdc name that will be used to query vms action
3312
3313 Returns:
3314 The return XML respond
3315 """
3316 url_list = [self.url, '/api/org']
3317 vm_list_rest_call = ''.join(url_list)
3318
3319 if self.client._session:
3320 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3321 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3322
3323 response = self.perform_request(req_type='GET',
3324 url=vm_list_rest_call,
3325 headers=headers)
3326
3327 if response.status_code == 403:
3328 response = self.retry_rest('GET', vm_list_rest_call)
3329
3330 if response.status_code == requests.codes.ok:
3331 return response.content
3332
3333 return None
3334
3335 def get_org_action(self, org_uuid=None):
3336 """
3337 Method leverages vCloud director and retrieve available object for organization.
3338
3339 Args:
3340 org_uuid - vCD organization uuid
3341 self.client - is active connection.
3342
3343 Returns:
3344 The return XML respond
3345 """
3346
3347 if org_uuid is None:
3348 return None
3349
3350 url_list = [self.url, '/api/org/', org_uuid]
3351 vm_list_rest_call = ''.join(url_list)
3352
3353 if self.client._session:
3354 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3355 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3356
3357 #response = requests.get(vm_list_rest_call, headers=headers, verify=False)
3358 response = self.perform_request(req_type='GET',
3359 url=vm_list_rest_call,
3360 headers=headers)
3361 if response.status_code == 403:
3362 response = self.retry_rest('GET', vm_list_rest_call)
3363
3364 if response.status_code == requests.codes.ok:
3365 return response.content
3366 return None
3367
3368 def get_org(self, org_uuid=None):
3369 """
3370 Method retrieves available organization in vCloud Director
3371
3372 Args:
3373 org_uuid - is a organization uuid.
3374
3375 Returns:
3376 The return dictionary with following key
3377 "network" - for network list under the org
3378 "catalogs" - for network list under the org
3379 "vdcs" - for vdc list under org
3380 """
3381
3382 org_dict = {}
3383
3384 if org_uuid is None:
3385 return org_dict
3386
3387 content = self.get_org_action(org_uuid=org_uuid)
3388 try:
3389 vdc_list = {}
3390 network_list = {}
3391 catalog_list = {}
3392 vm_list_xmlroot = XmlElementTree.fromstring(content)
3393 for child in vm_list_xmlroot:
3394 if child.attrib['type'] == 'application/vnd.vmware.vcloud.vdc+xml':
3395 vdc_list[child.attrib['href'].split("/")[-1:][0]] = child.attrib['name']
3396 org_dict['vdcs'] = vdc_list
3397 if child.attrib['type'] == 'application/vnd.vmware.vcloud.orgNetwork+xml':
3398 network_list[child.attrib['href'].split("/")[-1:][0]] = child.attrib['name']
3399 org_dict['networks'] = network_list
3400 if child.attrib['type'] == 'application/vnd.vmware.vcloud.catalog+xml':
3401 catalog_list[child.attrib['href'].split("/")[-1:][0]] = child.attrib['name']
3402 org_dict['catalogs'] = catalog_list
3403 except:
3404 pass
3405
3406 return org_dict
3407
3408 def get_org_list(self):
3409 """
3410 Method retrieves available organization in vCloud Director
3411
3412 Args:
3413 vca - is active VCA connection.
3414
3415 Returns:
3416 The return dictionary and key for each entry VDC UUID
3417 """
3418
3419 org_dict = {}
3420
3421 content = self.list_org_action()
3422 try:
3423 vm_list_xmlroot = XmlElementTree.fromstring(content)
3424 for vm_xml in vm_list_xmlroot:
3425 if vm_xml.tag.split("}")[1] == 'Org':
3426 org_uuid = vm_xml.attrib['href'].split('/')[-1:]
3427 org_dict[org_uuid[0]] = vm_xml.attrib['name']
3428 except:
3429 pass
3430
3431 return org_dict
3432
3433 def vms_view_action(self, vdc_name=None):
3434 """ Method leverages vCloud director vms query call
3435
3436 Args:
3437 vca - is active VCA connection.
3438 vdc_name - is a vdc name that will be used to query vms action
3439
3440 Returns:
3441 The return XML respond
3442 """
3443 vca = self.connect()
3444 if vdc_name is None:
3445 return None
3446
3447 url_list = [vca.host, '/api/vms/query']
3448 vm_list_rest_call = ''.join(url_list)
3449
3450 if not (not vca.vcloud_session or not vca.vcloud_session.organization):
3451 refs = filter(lambda ref: ref.name == vdc_name and ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml',
3452 vca.vcloud_session.organization.Link)
3453 #For python3
3454 #refs = [ref for ref in vca.vcloud_session.organization.Link if ref.name == vdc_name and\
3455 # ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml']
3456 if len(refs) == 1:
3457 response = Http.get(url=vm_list_rest_call,
3458 headers=vca.vcloud_session.get_vcloud_headers(),
3459 verify=vca.verify,
3460 logger=vca.logger)
3461 if response.status_code == requests.codes.ok:
3462 return response.content
3463
3464 return None
3465
3466 def get_vapp_list(self, vdc_name=None):
3467 """
3468 Method retrieves vApp list deployed vCloud director and returns a dictionary
3469 contains a list of all vapp deployed for queried VDC.
3470 The key for a dictionary is vApp UUID
3471
3472
3473 Args:
3474 vca - is active VCA connection.
3475 vdc_name - is a vdc name that will be used to query vms action
3476
3477 Returns:
3478 The return dictionary and key for each entry vapp UUID
3479 """
3480
3481 vapp_dict = {}
3482 if vdc_name is None:
3483 return vapp_dict
3484
3485 content = self.vms_view_action(vdc_name=vdc_name)
3486 try:
3487 vm_list_xmlroot = XmlElementTree.fromstring(content)
3488 for vm_xml in vm_list_xmlroot:
3489 if vm_xml.tag.split("}")[1] == 'VMRecord':
3490 if vm_xml.attrib['isVAppTemplate'] == 'true':
3491 rawuuid = vm_xml.attrib['container'].split('/')[-1:]
3492 if 'vappTemplate-' in rawuuid[0]:
3493 # vm in format vappTemplate-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
3494 # vm and use raw UUID as key
3495 vapp_dict[rawuuid[0][13:]] = vm_xml.attrib
3496 except:
3497 pass
3498
3499 return vapp_dict
3500
3501 def get_vm_list(self, vdc_name=None):
3502 """
3503 Method retrieves VM's list deployed vCloud director. It returns a dictionary
3504 contains a list of all VM's deployed for queried VDC.
3505 The key for a dictionary is VM UUID
3506
3507
3508 Args:
3509 vca - is active VCA connection.
3510 vdc_name - is a vdc name that will be used to query vms action
3511
3512 Returns:
3513 The return dictionary and key for each entry vapp UUID
3514 """
3515 vm_dict = {}
3516
3517 if vdc_name is None:
3518 return vm_dict
3519
3520 content = self.vms_view_action(vdc_name=vdc_name)
3521 try:
3522 vm_list_xmlroot = XmlElementTree.fromstring(content)
3523 for vm_xml in vm_list_xmlroot:
3524 if vm_xml.tag.split("}")[1] == 'VMRecord':
3525 if vm_xml.attrib['isVAppTemplate'] == 'false':
3526 rawuuid = vm_xml.attrib['href'].split('/')[-1:]
3527 if 'vm-' in rawuuid[0]:
3528 # vm in format vm-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
3529 # vm and use raw UUID as key
3530 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
3531 except:
3532 pass
3533
3534 return vm_dict
3535
3536 def get_vapp(self, vdc_name=None, vapp_name=None, isuuid=False):
3537 """
3538 Method retrieves VM deployed vCloud director. It returns VM attribute as dictionary
3539 contains a list of all VM's deployed for queried VDC.
3540 The key for a dictionary is VM UUID
3541
3542
3543 Args:
3544 vca - is active VCA connection.
3545 vdc_name - is a vdc name that will be used to query vms action
3546
3547 Returns:
3548 The return dictionary and key for each entry vapp UUID
3549 """
3550 vm_dict = {}
3551 vca = self.connect()
3552 if not vca:
3553 raise vimconn.vimconnConnectionException("self.connect() is failed")
3554
3555 if vdc_name is None:
3556 return vm_dict
3557
3558 content = self.vms_view_action(vdc_name=vdc_name)
3559 try:
3560 vm_list_xmlroot = XmlElementTree.fromstring(content)
3561 for vm_xml in vm_list_xmlroot:
3562 if vm_xml.tag.split("}")[1] == 'VMRecord' and vm_xml.attrib['isVAppTemplate'] == 'false':
3563 # lookup done by UUID
3564 if isuuid:
3565 if vapp_name in vm_xml.attrib['container']:
3566 rawuuid = vm_xml.attrib['href'].split('/')[-1:]
3567 if 'vm-' in rawuuid[0]:
3568 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
3569 break
3570 # lookup done by Name
3571 else:
3572 if vapp_name in vm_xml.attrib['name']:
3573 rawuuid = vm_xml.attrib['href'].split('/')[-1:]
3574 if 'vm-' in rawuuid[0]:
3575 vm_dict[rawuuid[0][3:]] = vm_xml.attrib
3576 break
3577 except:
3578 pass
3579
3580 return vm_dict
3581
3582 def get_network_action(self, network_uuid=None):
3583 """
3584 Method leverages vCloud director and query network based on network uuid
3585
3586 Args:
3587 vca - is active VCA connection.
3588 network_uuid - is a network uuid
3589
3590 Returns:
3591 The return XML respond
3592 """
3593
3594 if network_uuid is None:
3595 return None
3596
3597 url_list = [self.url, '/api/network/', network_uuid]
3598 vm_list_rest_call = ''.join(url_list)
3599
3600 if self.client._session:
3601 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3602 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3603
3604 response = self.perform_request(req_type='GET',
3605 url=vm_list_rest_call,
3606 headers=headers)
3607 #Retry login if session expired & retry sending request
3608 if response.status_code == 403:
3609 response = self.retry_rest('GET', vm_list_rest_call)
3610
3611 if response.status_code == requests.codes.ok:
3612 return response.content
3613
3614 return None
3615
3616 def get_vcd_network(self, network_uuid=None):
3617 """
3618 Method retrieves available network from vCloud Director
3619
3620 Args:
3621 network_uuid - is VCD network UUID
3622
3623 Each element serialized as key : value pair
3624
3625 Following keys available for access. network_configuration['Gateway'}
3626 <Configuration>
3627 <IpScopes>
3628 <IpScope>
3629 <IsInherited>true</IsInherited>
3630 <Gateway>172.16.252.100</Gateway>
3631 <Netmask>255.255.255.0</Netmask>
3632 <Dns1>172.16.254.201</Dns1>
3633 <Dns2>172.16.254.202</Dns2>
3634 <DnsSuffix>vmwarelab.edu</DnsSuffix>
3635 <IsEnabled>true</IsEnabled>
3636 <IpRanges>
3637 <IpRange>
3638 <StartAddress>172.16.252.1</StartAddress>
3639 <EndAddress>172.16.252.99</EndAddress>
3640 </IpRange>
3641 </IpRanges>
3642 </IpScope>
3643 </IpScopes>
3644 <FenceMode>bridged</FenceMode>
3645
3646 Returns:
3647 The return dictionary and key for each entry vapp UUID
3648 """
3649
3650 network_configuration = {}
3651 if network_uuid is None:
3652 return network_uuid
3653
3654 try:
3655 content = self.get_network_action(network_uuid=network_uuid)
3656 vm_list_xmlroot = XmlElementTree.fromstring(content)
3657
3658 network_configuration['status'] = vm_list_xmlroot.get("status")
3659 network_configuration['name'] = vm_list_xmlroot.get("name")
3660 network_configuration['uuid'] = vm_list_xmlroot.get("id").split(":")[3]
3661
3662 for child in vm_list_xmlroot:
3663 if child.tag.split("}")[1] == 'IsShared':
3664 network_configuration['isShared'] = child.text.strip()
3665 if child.tag.split("}")[1] == 'Configuration':
3666 for configuration in child.iter():
3667 tagKey = configuration.tag.split("}")[1].strip()
3668 if tagKey != "":
3669 network_configuration[tagKey] = configuration.text.strip()
3670 return network_configuration
3671 except Exception as exp :
3672 self.logger.debug("get_vcd_network: Failed with Exception {}".format(exp))
3673 raise vimconn.vimconnException("get_vcd_network: Failed with Exception {}".format(exp))
3674
3675 return network_configuration
3676
3677 def delete_network_action(self, network_uuid=None):
3678 """
3679 Method delete given network from vCloud director
3680
3681 Args:
3682 network_uuid - is a network uuid that client wish to delete
3683
3684 Returns:
3685 The return None or XML respond or false
3686 """
3687 client = self.connect_as_admin()
3688 if not client:
3689 raise vimconn.vimconnConnectionException("Failed to connect vCD as admin")
3690 if network_uuid is None:
3691 return False
3692
3693 url_list = [self.url, '/api/admin/network/', network_uuid]
3694 vm_list_rest_call = ''.join(url_list)
3695
3696 if client._session:
3697 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3698 'x-vcloud-authorization': client._session.headers['x-vcloud-authorization']}
3699 response = self.perform_request(req_type='DELETE',
3700 url=vm_list_rest_call,
3701 headers=headers)
3702 if response.status_code == 202:
3703 return True
3704
3705 return False
3706
3707 def create_network(self, network_name=None, net_type='bridge', parent_network_uuid=None,
3708 ip_profile=None, isshared='true'):
3709 """
3710 Method create network in vCloud director
3711
3712 Args:
3713 network_name - is network name to be created.
3714 net_type - can be 'bridge','data','ptp','mgmt'.
3715 ip_profile is a dict containing the IP parameters of the network
3716 isshared - is a boolean
3717 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3718 It optional attribute. by default if no parent network indicate the first available will be used.
3719
3720 Returns:
3721 The return network uuid or return None
3722 """
3723
3724 new_network_name = [network_name, '-', str(uuid.uuid4())]
3725 content = self.create_network_rest(network_name=''.join(new_network_name),
3726 ip_profile=ip_profile,
3727 net_type=net_type,
3728 parent_network_uuid=parent_network_uuid,
3729 isshared=isshared)
3730 if content is None:
3731 self.logger.debug("Failed create network {}.".format(network_name))
3732 return None
3733
3734 try:
3735 vm_list_xmlroot = XmlElementTree.fromstring(content)
3736 vcd_uuid = vm_list_xmlroot.get('id').split(":")
3737 if len(vcd_uuid) == 4:
3738 self.logger.info("Created new network name: {} uuid: {}".format(network_name, vcd_uuid[3]))
3739 return vcd_uuid[3]
3740 except:
3741 self.logger.debug("Failed create network {}".format(network_name))
3742 return None
3743
3744 def create_network_rest(self, network_name=None, net_type='bridge', parent_network_uuid=None,
3745 ip_profile=None, isshared='true'):
3746 """
3747 Method create network in vCloud director
3748
3749 Args:
3750 network_name - is network name to be created.
3751 net_type - can be 'bridge','data','ptp','mgmt'.
3752 ip_profile is a dict containing the IP parameters of the network
3753 isshared - is a boolean
3754 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3755 It optional attribute. by default if no parent network indicate the first available will be used.
3756
3757 Returns:
3758 The return network uuid or return None
3759 """
3760 client_as_admin = self.connect_as_admin()
3761 if not client_as_admin:
3762 raise vimconn.vimconnConnectionException("Failed to connect vCD.")
3763 if network_name is None:
3764 return None
3765
3766 url_list = [self.url, '/api/admin/vdc/', self.tenant_id]
3767 vm_list_rest_call = ''.join(url_list)
3768
3769 if client_as_admin._session:
3770 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3771 'x-vcloud-authorization': client_as_admin._session.headers['x-vcloud-authorization']}
3772
3773 response = self.perform_request(req_type='GET',
3774 url=vm_list_rest_call,
3775 headers=headers)
3776
3777 provider_network = None
3778 available_networks = None
3779 add_vdc_rest_url = None
3780
3781 if response.status_code != requests.codes.ok:
3782 self.logger.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call,
3783 response.status_code))
3784 return None
3785 else:
3786 try:
3787 vm_list_xmlroot = XmlElementTree.fromstring(response.content)
3788 for child in vm_list_xmlroot:
3789 if child.tag.split("}")[1] == 'ProviderVdcReference':
3790 provider_network = child.attrib.get('href')
3791 # application/vnd.vmware.admin.providervdc+xml
3792 if child.tag.split("}")[1] == 'Link':
3793 if child.attrib.get('type') == 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' \
3794 and child.attrib.get('rel') == 'add':
3795 add_vdc_rest_url = child.attrib.get('href')
3796 except:
3797 self.logger.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call))
3798 self.logger.debug("Respond body {}".format(response.content))
3799 return None
3800
3801 # find pvdc provided available network
3802 response = self.perform_request(req_type='GET',
3803 url=provider_network,
3804 headers=headers)
3805 if response.status_code != requests.codes.ok:
3806 self.logger.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call,
3807 response.status_code))
3808 return None
3809
3810 if parent_network_uuid is None:
3811 try:
3812 vm_list_xmlroot = XmlElementTree.fromstring(response.content)
3813 for child in vm_list_xmlroot.iter():
3814 if child.tag.split("}")[1] == 'AvailableNetworks':
3815 for networks in child.iter():
3816 # application/vnd.vmware.admin.network+xml
3817 if networks.attrib.get('href') is not None:
3818 available_networks = networks.attrib.get('href')
3819 break
3820 except:
3821 return None
3822
3823 try:
3824 #Configure IP profile of the network
3825 ip_profile = ip_profile if ip_profile is not None else DEFAULT_IP_PROFILE
3826
3827 if 'subnet_address' not in ip_profile or ip_profile['subnet_address'] is None:
3828 subnet_rand = random.randint(0, 255)
3829 ip_base = "192.168.{}.".format(subnet_rand)
3830 ip_profile['subnet_address'] = ip_base + "0/24"
3831 else:
3832 ip_base = ip_profile['subnet_address'].rsplit('.',1)[0] + '.'
3833
3834 if 'gateway_address' not in ip_profile or ip_profile['gateway_address'] is None:
3835 ip_profile['gateway_address']=ip_base + "1"
3836 if 'dhcp_count' not in ip_profile or ip_profile['dhcp_count'] is None:
3837 ip_profile['dhcp_count']=DEFAULT_IP_PROFILE['dhcp_count']
3838 if 'dhcp_enabled' not in ip_profile or ip_profile['dhcp_enabled'] is None:
3839 ip_profile['dhcp_enabled']=DEFAULT_IP_PROFILE['dhcp_enabled']
3840 if 'dhcp_start_address' not in ip_profile or ip_profile['dhcp_start_address'] is None:
3841 ip_profile['dhcp_start_address']=ip_base + "3"
3842 if 'ip_version' not in ip_profile or ip_profile['ip_version'] is None:
3843 ip_profile['ip_version']=DEFAULT_IP_PROFILE['ip_version']
3844 if 'dns_address' not in ip_profile or ip_profile['dns_address'] is None:
3845 ip_profile['dns_address']=ip_base + "2"
3846
3847 gateway_address=ip_profile['gateway_address']
3848 dhcp_count=int(ip_profile['dhcp_count'])
3849 subnet_address=self.convert_cidr_to_netmask(ip_profile['subnet_address'])
3850
3851 if ip_profile['dhcp_enabled']==True:
3852 dhcp_enabled='true'
3853 else:
3854 dhcp_enabled='false'
3855 dhcp_start_address=ip_profile['dhcp_start_address']
3856
3857 #derive dhcp_end_address from dhcp_start_address & dhcp_count
3858 end_ip_int = int(netaddr.IPAddress(dhcp_start_address))
3859 end_ip_int += dhcp_count - 1
3860 dhcp_end_address = str(netaddr.IPAddress(end_ip_int))
3861
3862 ip_version=ip_profile['ip_version']
3863 dns_address=ip_profile['dns_address']
3864 except KeyError as exp:
3865 self.logger.debug("Create Network REST: Key error {}".format(exp))
3866 raise vimconn.vimconnException("Create Network REST: Key error{}".format(exp))
3867
3868 # either use client provided UUID or search for a first available
3869 # if both are not defined we return none
3870 if parent_network_uuid is not None:
3871 provider_network = None
3872 available_networks = None
3873 add_vdc_rest_url = None
3874
3875 url_list = [self.url, '/api/admin/vdc/', self.tenant_id, '/networks']
3876 add_vdc_rest_url = ''.join(url_list)
3877
3878 url_list = [self.url, '/api/admin/network/', parent_network_uuid]
3879 available_networks = ''.join(url_list)
3880
3881 #Creating all networks as Direct Org VDC type networks.
3882 #Unused in case of Underlay (data/ptp) network interface.
3883 fence_mode="isolated"
3884 is_inherited='false'
3885 dns_list = dns_address.split(";")
3886 dns1 = dns_list[0]
3887 dns2_text = ""
3888 if len(dns_list) >= 2:
3889 dns2_text = "\n <Dns2>{}</Dns2>\n".format(dns_list[1])
3890 data = """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
3891 <Description>Openmano created</Description>
3892 <Configuration>
3893 <IpScopes>
3894 <IpScope>
3895 <IsInherited>{1:s}</IsInherited>
3896 <Gateway>{2:s}</Gateway>
3897 <Netmask>{3:s}</Netmask>
3898 <Dns1>{4:s}</Dns1>{5:s}
3899 <IsEnabled>{6:s}</IsEnabled>
3900 <IpRanges>
3901 <IpRange>
3902 <StartAddress>{7:s}</StartAddress>
3903 <EndAddress>{8:s}</EndAddress>
3904 </IpRange>
3905 </IpRanges>
3906 </IpScope>
3907 </IpScopes>
3908 <FenceMode>{9:s}</FenceMode>
3909 </Configuration>
3910 <IsShared>{10:s}</IsShared>
3911 </OrgVdcNetwork> """.format(escape(network_name), is_inherited, gateway_address,
3912 subnet_address, dns1, dns2_text, dhcp_enabled,
3913 dhcp_start_address, dhcp_end_address,
3914 fence_mode, isshared)
3915
3916 headers['Content-Type'] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'
3917 try:
3918 response = self.perform_request(req_type='POST',
3919 url=add_vdc_rest_url,
3920 headers=headers,
3921 data=data)
3922
3923 if response.status_code != 201:
3924 self.logger.debug("Create Network POST REST API call failed. Return status code {}, Response content: {}"
3925 .format(response.status_code,response.content))
3926 else:
3927 network_task = self.get_task_from_response(response.content)
3928 self.logger.debug("Create Network REST : Waiting for Network creation complete")
3929 time.sleep(5)
3930 result = self.client.get_task_monitor().wait_for_success(task=network_task)
3931 if result.get('status') == 'success':
3932 return response.content
3933 else:
3934 self.logger.debug("create_network_rest task failed. Network Create response : {}"
3935 .format(response.content))
3936 except Exception as exp:
3937 self.logger.debug("create_network_rest : Exception : {} ".format(exp))
3938
3939 return None
3940
3941 def convert_cidr_to_netmask(self, cidr_ip=None):
3942 """
3943 Method sets convert CIDR netmask address to normal IP format
3944 Args:
3945 cidr_ip : CIDR IP address
3946 Returns:
3947 netmask : Converted netmask
3948 """
3949 if cidr_ip is not None:
3950 if '/' in cidr_ip:
3951 network, net_bits = cidr_ip.split('/')
3952 netmask = socket.inet_ntoa(struct.pack(">I", (0xffffffff << (32 - int(net_bits))) & 0xffffffff))
3953 else:
3954 netmask = cidr_ip
3955 return netmask
3956 return None
3957
3958 def get_provider_rest(self, vca=None):
3959 """
3960 Method gets provider vdc view from vcloud director
3961
3962 Args:
3963 network_name - is network name to be created.
3964 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3965 It optional attribute. by default if no parent network indicate the first available will be used.
3966
3967 Returns:
3968 The return xml content of respond or None
3969 """
3970
3971 url_list = [self.url, '/api/admin']
3972 if vca:
3973 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
3974 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
3975 response = self.perform_request(req_type='GET',
3976 url=''.join(url_list),
3977 headers=headers)
3978
3979 if response.status_code == requests.codes.ok:
3980 return response.content
3981 return None
3982
3983 def create_vdc(self, vdc_name=None):
3984
3985 vdc_dict = {}
3986
3987 xml_content = self.create_vdc_from_tmpl_rest(vdc_name=vdc_name)
3988 if xml_content is not None:
3989 try:
3990 task_resp_xmlroot = XmlElementTree.fromstring(xml_content)
3991 for child in task_resp_xmlroot:
3992 if child.tag.split("}")[1] == 'Owner':
3993 vdc_id = child.attrib.get('href').split("/")[-1]
3994 vdc_dict[vdc_id] = task_resp_xmlroot.get('href')
3995 return vdc_dict
3996 except:
3997 self.logger.debug("Respond body {}".format(xml_content))
3998
3999 return None
4000
4001 def create_vdc_from_tmpl_rest(self, vdc_name=None):
4002 """
4003 Method create vdc in vCloud director based on VDC template.
4004 it uses pre-defined template.
4005
4006 Args:
4007 vdc_name - name of a new vdc.
4008
4009 Returns:
4010 The return xml content of respond or None
4011 """
4012 # pre-requesite atleast one vdc template should be available in vCD
4013 self.logger.info("Creating new vdc {}".format(vdc_name))
4014 vca = self.connect_as_admin()
4015 if not vca:
4016 raise vimconn.vimconnConnectionException("Failed to connect vCD")
4017 if vdc_name is None:
4018 return None
4019
4020 url_list = [self.url, '/api/vdcTemplates']
4021 vm_list_rest_call = ''.join(url_list)
4022
4023 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4024 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
4025 response = self.perform_request(req_type='GET',
4026 url=vm_list_rest_call,
4027 headers=headers)
4028
4029 # container url to a template
4030 vdc_template_ref = None
4031 try:
4032 vm_list_xmlroot = XmlElementTree.fromstring(response.content)
4033 for child in vm_list_xmlroot:
4034 # application/vnd.vmware.admin.providervdc+xml
4035 # we need find a template from witch we instantiate VDC
4036 if child.tag.split("}")[1] == 'VdcTemplate':
4037 if child.attrib.get('type') == 'application/vnd.vmware.admin.vdcTemplate+xml':
4038 vdc_template_ref = child.attrib.get('href')
4039 except:
4040 self.logger.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call))
4041 self.logger.debug("Respond body {}".format(response.content))
4042 return None
4043
4044 # if we didn't found required pre defined template we return None
4045 if vdc_template_ref is None:
4046 return None
4047
4048 try:
4049 # instantiate vdc
4050 url_list = [self.url, '/api/org/', self.org_uuid, '/action/instantiate']
4051 vm_list_rest_call = ''.join(url_list)
4052 data = """<InstantiateVdcTemplateParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
4053 <Source href="{1:s}"></Source>
4054 <Description>opnemano</Description>
4055 </InstantiateVdcTemplateParams>""".format(vdc_name, vdc_template_ref)
4056
4057 headers['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml'
4058
4059 response = self.perform_request(req_type='POST',
4060 url=vm_list_rest_call,
4061 headers=headers,
4062 data=data)
4063
4064 vdc_task = self.get_task_from_response(response.content)
4065 self.client.get_task_monitor().wait_for_success(task=vdc_task)
4066
4067 # if we all ok we respond with content otherwise by default None
4068 if response.status_code >= 200 and response.status_code < 300:
4069 return response.content
4070 return None
4071 except:
4072 self.logger.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call))
4073 self.logger.debug("Respond body {}".format(response.content))
4074
4075 return None
4076
4077 def create_vdc_rest(self, vdc_name=None):
4078 """
4079 Method create network in vCloud director
4080
4081 Args:
4082 vdc_name - vdc name to be created
4083 Returns:
4084 The return response
4085 """
4086
4087 self.logger.info("Creating new vdc {}".format(vdc_name))
4088
4089 vca = self.connect_as_admin()
4090 if not vca:
4091 raise vimconn.vimconnConnectionException("Failed to connect vCD")
4092 if vdc_name is None:
4093 return None
4094
4095 url_list = [self.url, '/api/admin/org/', self.org_uuid]
4096 vm_list_rest_call = ''.join(url_list)
4097
4098 if vca._session:
4099 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4100 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4101 response = self.perform_request(req_type='GET',
4102 url=vm_list_rest_call,
4103 headers=headers)
4104
4105 provider_vdc_ref = None
4106 add_vdc_rest_url = None
4107 available_networks = None
4108
4109 if response.status_code != requests.codes.ok:
4110 self.logger.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call,
4111 response.status_code))
4112 return None
4113 else:
4114 try:
4115 vm_list_xmlroot = XmlElementTree.fromstring(response.content)
4116 for child in vm_list_xmlroot:
4117 # application/vnd.vmware.admin.providervdc+xml
4118 if child.tag.split("}")[1] == 'Link':
4119 if child.attrib.get('type') == 'application/vnd.vmware.admin.createVdcParams+xml' \
4120 and child.attrib.get('rel') == 'add':
4121 add_vdc_rest_url = child.attrib.get('href')
4122 except:
4123 self.logger.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call))
4124 self.logger.debug("Respond body {}".format(response.content))
4125 return None
4126
4127 response = self.get_provider_rest(vca=vca)
4128 try:
4129 vm_list_xmlroot = XmlElementTree.fromstring(response)
4130 for child in vm_list_xmlroot:
4131 if child.tag.split("}")[1] == 'ProviderVdcReferences':
4132 for sub_child in child:
4133 provider_vdc_ref = sub_child.attrib.get('href')
4134 except:
4135 self.logger.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call))
4136 self.logger.debug("Respond body {}".format(response))
4137 return None
4138
4139 if add_vdc_rest_url is not None and provider_vdc_ref is not None:
4140 data = """ <CreateVdcParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5"><Description>{1:s}</Description>
4141 <AllocationModel>ReservationPool</AllocationModel>
4142 <ComputeCapacity><Cpu><Units>MHz</Units><Allocated>2048</Allocated><Limit>2048</Limit></Cpu>
4143 <Memory><Units>MB</Units><Allocated>2048</Allocated><Limit>2048</Limit></Memory>
4144 </ComputeCapacity><NicQuota>0</NicQuota><NetworkQuota>100</NetworkQuota>
4145 <VdcStorageProfile><Enabled>true</Enabled><Units>MB</Units><Limit>20480</Limit><Default>true</Default></VdcStorageProfile>
4146 <ProviderVdcReference
4147 name="Main Provider"
4148 href="{2:s}" />
4149 <UsesFastProvisioning>true</UsesFastProvisioning></CreateVdcParams>""".format(escape(vdc_name),
4150 escape(vdc_name),
4151 provider_vdc_ref)
4152
4153 headers['Content-Type'] = 'application/vnd.vmware.admin.createVdcParams+xml'
4154
4155 response = self.perform_request(req_type='POST',
4156 url=add_vdc_rest_url,
4157 headers=headers,
4158 data=data)
4159
4160 # if we all ok we respond with content otherwise by default None
4161 if response.status_code == 201:
4162 return response.content
4163 return None
4164
4165 def get_vapp_details_rest(self, vapp_uuid=None, need_admin_access=False):
4166 """
4167 Method retrieve vapp detail from vCloud director
4168
4169 Args:
4170 vapp_uuid - is vapp identifier.
4171
4172 Returns:
4173 The return network uuid or return None
4174 """
4175
4176 parsed_respond = {}
4177 vca = None
4178
4179 if need_admin_access:
4180 vca = self.connect_as_admin()
4181 else:
4182 vca = self.client
4183
4184 if not vca:
4185 raise vimconn.vimconnConnectionException("Failed to connect vCD")
4186 if vapp_uuid is None:
4187 return None
4188
4189 url_list = [self.url, '/api/vApp/vapp-', vapp_uuid]
4190 get_vapp_restcall = ''.join(url_list)
4191
4192 if vca._session:
4193 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4194 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
4195 response = self.perform_request(req_type='GET',
4196 url=get_vapp_restcall,
4197 headers=headers)
4198
4199 if response.status_code == 403:
4200 if need_admin_access == False:
4201 response = self.retry_rest('GET', get_vapp_restcall)
4202
4203 if response.status_code != requests.codes.ok:
4204 self.logger.debug("REST API call {} failed. Return status code {}".format(get_vapp_restcall,
4205 response.status_code))
4206 return parsed_respond
4207
4208 try:
4209 xmlroot_respond = XmlElementTree.fromstring(response.content)
4210 parsed_respond['ovfDescriptorUploaded'] = xmlroot_respond.attrib['ovfDescriptorUploaded']
4211
4212 namespaces = {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
4213 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
4214 'vmw': 'http://www.vmware.com/schema/ovf',
4215 'vm': 'http://www.vmware.com/vcloud/v1.5',
4216 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
4217 "vmext":"http://www.vmware.com/vcloud/extension/v1.5",
4218 "xmlns":"http://www.vmware.com/vcloud/v1.5"
4219 }
4220
4221 created_section = xmlroot_respond.find('vm:DateCreated', namespaces)
4222 if created_section is not None:
4223 parsed_respond['created'] = created_section.text
4224
4225 network_section = xmlroot_respond.find('vm:NetworkConfigSection/vm:NetworkConfig', namespaces)
4226 if network_section is not None and 'networkName' in network_section.attrib:
4227 parsed_respond['networkname'] = network_section.attrib['networkName']
4228
4229 ipscopes_section = \
4230 xmlroot_respond.find('vm:NetworkConfigSection/vm:NetworkConfig/vm:Configuration/vm:IpScopes',
4231 namespaces)
4232 if ipscopes_section is not None:
4233 for ipscope in ipscopes_section:
4234 for scope in ipscope:
4235 tag_key = scope.tag.split("}")[1]
4236 if tag_key == 'IpRanges':
4237 ip_ranges = scope.getchildren()
4238 for ipblock in ip_ranges:
4239 for block in ipblock:
4240 parsed_respond[block.tag.split("}")[1]] = block.text
4241 else:
4242 parsed_respond[tag_key] = scope.text
4243
4244 # parse children section for other attrib
4245 children_section = xmlroot_respond.find('vm:Children/', namespaces)
4246 if children_section is not None:
4247 parsed_respond['name'] = children_section.attrib['name']
4248 parsed_respond['nestedHypervisorEnabled'] = children_section.attrib['nestedHypervisorEnabled'] \
4249 if "nestedHypervisorEnabled" in children_section.attrib else None
4250 parsed_respond['deployed'] = children_section.attrib['deployed']
4251 parsed_respond['status'] = children_section.attrib['status']
4252 parsed_respond['vmuuid'] = children_section.attrib['id'].split(":")[-1]
4253 network_adapter = children_section.find('vm:NetworkConnectionSection', namespaces)
4254 nic_list = []
4255 for adapters in network_adapter:
4256 adapter_key = adapters.tag.split("}")[1]
4257 if adapter_key == 'PrimaryNetworkConnectionIndex':
4258 parsed_respond['primarynetwork'] = adapters.text
4259 if adapter_key == 'NetworkConnection':
4260 vnic = {}
4261 if 'network' in adapters.attrib:
4262 vnic['network'] = adapters.attrib['network']
4263 for adapter in adapters:
4264 setting_key = adapter.tag.split("}")[1]
4265 vnic[setting_key] = adapter.text
4266 nic_list.append(vnic)
4267
4268 for link in children_section:
4269 if link.tag.split("}")[1] == 'Link' and 'rel' in link.attrib:
4270 if link.attrib['rel'] == 'screen:acquireTicket':
4271 parsed_respond['acquireTicket'] = link.attrib
4272 if link.attrib['rel'] == 'screen:acquireMksTicket':
4273 parsed_respond['acquireMksTicket'] = link.attrib
4274
4275 parsed_respond['interfaces'] = nic_list
4276 vCloud_extension_section = children_section.find('xmlns:VCloudExtension', namespaces)
4277 if vCloud_extension_section is not None:
4278 vm_vcenter_info = {}
4279 vim_info = vCloud_extension_section.find('vmext:VmVimInfo', namespaces)
4280 vmext = vim_info.find('vmext:VmVimObjectRef', namespaces)
4281 if vmext is not None:
4282 vm_vcenter_info["vm_moref_id"] = vmext.find('vmext:MoRef', namespaces).text
4283 parsed_respond["vm_vcenter_info"]= vm_vcenter_info
4284
4285 virtual_hardware_section = children_section.find('ovf:VirtualHardwareSection', namespaces)
4286 vm_virtual_hardware_info = {}
4287 if virtual_hardware_section is not None:
4288 for item in virtual_hardware_section.iterfind('ovf:Item',namespaces):
4289 if item.find("rasd:Description",namespaces).text == "Hard disk":
4290 disk_size = item.find("rasd:HostResource" ,namespaces
4291 ).attrib["{"+namespaces['vm']+"}capacity"]
4292
4293 vm_virtual_hardware_info["disk_size"]= disk_size
4294 break
4295
4296 for link in virtual_hardware_section:
4297 if link.tag.split("}")[1] == 'Link' and 'rel' in link.attrib:
4298 if link.attrib['rel'] == 'edit' and link.attrib['href'].endswith("/disks"):
4299 vm_virtual_hardware_info["disk_edit_href"] = link.attrib['href']
4300 break
4301
4302 parsed_respond["vm_virtual_hardware"]= vm_virtual_hardware_info
4303 except Exception as exp :
4304 self.logger.info("Error occurred calling rest api for getting vApp details {}".format(exp))
4305 return parsed_respond
4306
4307 def acquire_console(self, vm_uuid=None):
4308
4309 if vm_uuid is None:
4310 return None
4311 if self.client._session:
4312 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4313 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4314 vm_dict = self.get_vapp_details_rest(vapp_uuid=vm_uuid)
4315 console_dict = vm_dict['acquireTicket']
4316 console_rest_call = console_dict['href']
4317
4318 response = self.perform_request(req_type='POST',
4319 url=console_rest_call,
4320 headers=headers)
4321
4322 if response.status_code == 403:
4323 response = self.retry_rest('POST', console_rest_call)
4324
4325 if response.status_code == requests.codes.ok:
4326 return response.content
4327
4328 return None
4329
4330 def modify_vm_disk(self, vapp_uuid, flavor_disk):
4331 """
4332 Method retrieve vm disk details
4333
4334 Args:
4335 vapp_uuid - is vapp identifier.
4336 flavor_disk - disk size as specified in VNFD (flavor)
4337
4338 Returns:
4339 The return network uuid or return None
4340 """
4341 status = None
4342 try:
4343 #Flavor disk is in GB convert it into MB
4344 flavor_disk = int(flavor_disk) * 1024
4345 vm_details = self.get_vapp_details_rest(vapp_uuid)
4346 if vm_details:
4347 vm_name = vm_details["name"]
4348 self.logger.info("VM: {} flavor_disk :{}".format(vm_name , flavor_disk))
4349
4350 if vm_details and "vm_virtual_hardware" in vm_details:
4351 vm_disk = int(vm_details["vm_virtual_hardware"]["disk_size"])
4352 disk_edit_href = vm_details["vm_virtual_hardware"]["disk_edit_href"]
4353
4354 self.logger.info("VM: {} VM_disk :{}".format(vm_name , vm_disk))
4355
4356 if flavor_disk > vm_disk:
4357 status = self.modify_vm_disk_rest(disk_edit_href ,flavor_disk)
4358 self.logger.info("Modify disk of VM {} from {} to {} MB".format(vm_name,
4359 vm_disk, flavor_disk ))
4360 else:
4361 status = True
4362 self.logger.info("No need to modify disk of VM {}".format(vm_name))
4363
4364 return status
4365 except Exception as exp:
4366 self.logger.info("Error occurred while modifing disk size {}".format(exp))
4367
4368
4369 def modify_vm_disk_rest(self, disk_href , disk_size):
4370 """
4371 Method retrieve modify vm disk size
4372
4373 Args:
4374 disk_href - vCD API URL to GET and PUT disk data
4375 disk_size - disk size as specified in VNFD (flavor)
4376
4377 Returns:
4378 The return network uuid or return None
4379 """
4380 if disk_href is None or disk_size is None:
4381 return None
4382
4383 if self.client._session:
4384 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4385 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4386 response = self.perform_request(req_type='GET',
4387 url=disk_href,
4388 headers=headers)
4389
4390 if response.status_code == 403:
4391 response = self.retry_rest('GET', disk_href)
4392
4393 if response.status_code != requests.codes.ok:
4394 self.logger.debug("GET REST API call {} failed. Return status code {}".format(disk_href,
4395 response.status_code))
4396 return None
4397 try:
4398 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
4399 namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
4400 #For python3
4401 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
4402 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
4403
4404 for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
4405 if item.find("rasd:Description",namespaces).text == "Hard disk":
4406 disk_item = item.find("rasd:HostResource" ,namespaces )
4407 if disk_item is not None:
4408 disk_item.attrib["{"+namespaces['xmlns']+"}capacity"] = str(disk_size)
4409 break
4410
4411 data = lxmlElementTree.tostring(lxmlroot_respond, encoding='utf8', method='xml',
4412 xml_declaration=True)
4413
4414 #Send PUT request to modify disk size
4415 headers['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
4416
4417 response = self.perform_request(req_type='PUT',
4418 url=disk_href,
4419 headers=headers,
4420 data=data)
4421 if response.status_code == 403:
4422 add_headers = {'Content-Type': headers['Content-Type']}
4423 response = self.retry_rest('PUT', disk_href, add_headers, data)
4424
4425 if response.status_code != 202:
4426 self.logger.debug("PUT REST API call {} failed. Return status code {}".format(disk_href,
4427 response.status_code))
4428 else:
4429 modify_disk_task = self.get_task_from_response(response.content)
4430 result = self.client.get_task_monitor().wait_for_success(task=modify_disk_task)
4431 if result.get('status') == 'success':
4432 return True
4433 else:
4434 return False
4435 return None
4436
4437 except Exception as exp :
4438 self.logger.info("Error occurred calling rest api for modifing disk size {}".format(exp))
4439 return None
4440
4441 def add_pci_devices(self, vapp_uuid , pci_devices , vmname_andid):
4442 """
4443 Method to attach pci devices to VM
4444
4445 Args:
4446 vapp_uuid - uuid of vApp/VM
4447 pci_devices - pci devices infromation as specified in VNFD (flavor)
4448
4449 Returns:
4450 The status of add pci device task , vm object and
4451 vcenter_conect object
4452 """
4453 vm_obj = None
4454 self.logger.info("Add pci devices {} into vApp {}".format(pci_devices , vapp_uuid))
4455 vcenter_conect, content = self.get_vcenter_content()
4456 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
4457
4458 if vm_moref_id:
4459 try:
4460 no_of_pci_devices = len(pci_devices)
4461 if no_of_pci_devices > 0:
4462 #Get VM and its host
4463 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
4464 self.logger.info("VM {} is currently on host {}".format(vm_obj, host_obj))
4465 if host_obj and vm_obj:
4466 #get PCI devies from host on which vapp is currently installed
4467 avilable_pci_devices = self.get_pci_devices(host_obj, no_of_pci_devices)
4468
4469 if avilable_pci_devices is None:
4470 #find other hosts with active pci devices
4471 new_host_obj , avilable_pci_devices = self.get_host_and_PCIdevices(
4472 content,
4473 no_of_pci_devices
4474 )
4475
4476 if new_host_obj is not None and avilable_pci_devices is not None and len(avilable_pci_devices)> 0:
4477 #Migrate vm to the host where PCI devices are availble
4478 self.logger.info("Relocate VM {} on new host {}".format(vm_obj, new_host_obj))
4479 task = self.relocate_vm(new_host_obj, vm_obj)
4480 if task is not None:
4481 result = self.wait_for_vcenter_task(task, vcenter_conect)
4482 self.logger.info("Migrate VM status: {}".format(result))
4483 host_obj = new_host_obj
4484 else:
4485 self.logger.info("Fail to migrate VM : {}".format(result))
4486 raise vimconn.vimconnNotFoundException(
4487 "Fail to migrate VM : {} to host {}".format(
4488 vmname_andid,
4489 new_host_obj)
4490 )
4491
4492 if host_obj is not None and avilable_pci_devices is not None and len(avilable_pci_devices)> 0:
4493 #Add PCI devices one by one
4494 for pci_device in avilable_pci_devices:
4495 task = self.add_pci_to_vm(host_obj, vm_obj, pci_device)
4496 if task:
4497 status= self.wait_for_vcenter_task(task, vcenter_conect)
4498 if status:
4499 self.logger.info("Added PCI device {} to VM {}".format(pci_device,str(vm_obj)))
4500 else:
4501 self.logger.error("Fail to add PCI device {} to VM {}".format(pci_device,str(vm_obj)))
4502 return True, vm_obj, vcenter_conect
4503 else:
4504 self.logger.error("Currently there is no host with"\
4505 " {} number of avaialble PCI devices required for VM {}".format(
4506 no_of_pci_devices,
4507 vmname_andid)
4508 )
4509 raise vimconn.vimconnNotFoundException(
4510 "Currently there is no host with {} "\
4511 "number of avaialble PCI devices required for VM {}".format(
4512 no_of_pci_devices,
4513 vmname_andid))
4514 else:
4515 self.logger.debug("No infromation about PCI devices {} ",pci_devices)
4516
4517 except vmodl.MethodFault as error:
4518 self.logger.error("Error occurred while adding PCI devices {} ",error)
4519 return None, vm_obj, vcenter_conect
4520
4521 def get_vm_obj(self, content, mob_id):
4522 """
4523 Method to get the vsphere VM object associated with a given morf ID
4524 Args:
4525 vapp_uuid - uuid of vApp/VM
4526 content - vCenter content object
4527 mob_id - mob_id of VM
4528
4529 Returns:
4530 VM and host object
4531 """
4532 vm_obj = None
4533 host_obj = None
4534 try :
4535 container = content.viewManager.CreateContainerView(content.rootFolder,
4536 [vim.VirtualMachine], True
4537 )
4538 for vm in container.view:
4539 mobID = vm._GetMoId()
4540 if mobID == mob_id:
4541 vm_obj = vm
4542 host_obj = vm_obj.runtime.host
4543 break
4544 except Exception as exp:
4545 self.logger.error("Error occurred while finding VM object : {}".format(exp))
4546 return host_obj, vm_obj
4547
4548 def get_pci_devices(self, host, need_devices):
4549 """
4550 Method to get the details of pci devices on given host
4551 Args:
4552 host - vSphere host object
4553 need_devices - number of pci devices needed on host
4554
4555 Returns:
4556 array of pci devices
4557 """
4558 all_devices = []
4559 all_device_ids = []
4560 used_devices_ids = []
4561
4562 try:
4563 if host:
4564 pciPassthruInfo = host.config.pciPassthruInfo
4565 pciDevies = host.hardware.pciDevice
4566
4567 for pci_status in pciPassthruInfo:
4568 if pci_status.passthruActive:
4569 for device in pciDevies:
4570 if device.id == pci_status.id:
4571 all_device_ids.append(device.id)
4572 all_devices.append(device)
4573
4574 #check if devices are in use
4575 avalible_devices = all_devices
4576 for vm in host.vm:
4577 if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
4578 vm_devices = vm.config.hardware.device
4579 for device in vm_devices:
4580 if type(device) is vim.vm.device.VirtualPCIPassthrough:
4581 if device.backing.id in all_device_ids:
4582 for use_device in avalible_devices:
4583 if use_device.id == device.backing.id:
4584 avalible_devices.remove(use_device)
4585 used_devices_ids.append(device.backing.id)
4586 self.logger.debug("Device {} from devices {}"\
4587 "is in use".format(device.backing.id,
4588 device)
4589 )
4590 if len(avalible_devices) < need_devices:
4591 self.logger.debug("Host {} don't have {} number of active devices".format(host,
4592 need_devices))
4593 self.logger.debug("found only {} devives {}".format(len(avalible_devices),
4594 avalible_devices))
4595 return None
4596 else:
4597 required_devices = avalible_devices[:need_devices]
4598 self.logger.info("Found {} PCI devivces on host {} but required only {}".format(
4599 len(avalible_devices),
4600 host,
4601 need_devices))
4602 self.logger.info("Retruning {} devices as {}".format(need_devices,
4603 required_devices ))
4604 return required_devices
4605
4606 except Exception as exp:
4607 self.logger.error("Error {} occurred while finding pci devices on host: {}".format(exp, host))
4608
4609 return None
4610
4611 def get_host_and_PCIdevices(self, content, need_devices):
4612 """
4613 Method to get the details of pci devices infromation on all hosts
4614
4615 Args:
4616 content - vSphere host object
4617 need_devices - number of pci devices needed on host
4618
4619 Returns:
4620 array of pci devices and host object
4621 """
4622 host_obj = None
4623 pci_device_objs = None
4624 try:
4625 if content:
4626 container = content.viewManager.CreateContainerView(content.rootFolder,
4627 [vim.HostSystem], True)
4628 for host in container.view:
4629 devices = self.get_pci_devices(host, need_devices)
4630 if devices:
4631 host_obj = host
4632 pci_device_objs = devices
4633 break
4634 except Exception as exp:
4635 self.logger.error("Error {} occurred while finding pci devices on host: {}".format(exp, host_obj))
4636
4637 return host_obj,pci_device_objs
4638
4639 def relocate_vm(self, dest_host, vm) :
4640 """
4641 Method to get the relocate VM to new host
4642
4643 Args:
4644 dest_host - vSphere host object
4645 vm - vSphere VM object
4646
4647 Returns:
4648 task object
4649 """
4650 task = None
4651 try:
4652 relocate_spec = vim.vm.RelocateSpec(host=dest_host)
4653 task = vm.Relocate(relocate_spec)
4654 self.logger.info("Migrating {} to destination host {}".format(vm, dest_host))
4655 except Exception as exp:
4656 self.logger.error("Error occurred while relocate VM {} to new host {}: {}".format(
4657 dest_host, vm, exp))
4658 return task
4659
4660 def wait_for_vcenter_task(self, task, actionName='job', hideResult=False):
4661 """
4662 Waits and provides updates on a vSphere task
4663 """
4664 while task.info.state == vim.TaskInfo.State.running:
4665 time.sleep(2)
4666
4667 if task.info.state == vim.TaskInfo.State.success:
4668 if task.info.result is not None and not hideResult:
4669 self.logger.info('{} completed successfully, result: {}'.format(
4670 actionName,
4671 task.info.result))
4672 else:
4673 self.logger.info('Task {} completed successfully.'.format(actionName))
4674 else:
4675 self.logger.error('{} did not complete successfully: {} '.format(
4676 actionName,
4677 task.info.error)
4678 )
4679
4680 return task.info.result
4681
4682 def add_pci_to_vm(self,host_object, vm_object, host_pci_dev):
4683 """
4684 Method to add pci device in given VM
4685
4686 Args:
4687 host_object - vSphere host object
4688 vm_object - vSphere VM object
4689 host_pci_dev - host_pci_dev must be one of the devices from the
4690 host_object.hardware.pciDevice list
4691 which is configured as a PCI passthrough device
4692
4693 Returns:
4694 task object
4695 """
4696 task = None
4697 if vm_object and host_object and host_pci_dev:
4698 try :
4699 #Add PCI device to VM
4700 pci_passthroughs = vm_object.environmentBrowser.QueryConfigTarget(host=None).pciPassthrough
4701 systemid_by_pciid = {item.pciDevice.id: item.systemId for item in pci_passthroughs}
4702
4703 if host_pci_dev.id not in systemid_by_pciid:
4704 self.logger.error("Device {} is not a passthrough device ".format(host_pci_dev))
4705 return None
4706
4707 deviceId = hex(host_pci_dev.deviceId % 2**16).lstrip('0x')
4708 backing = vim.VirtualPCIPassthroughDeviceBackingInfo(deviceId=deviceId,
4709 id=host_pci_dev.id,
4710 systemId=systemid_by_pciid[host_pci_dev.id],
4711 vendorId=host_pci_dev.vendorId,
4712 deviceName=host_pci_dev.deviceName)
4713
4714 hba_object = vim.VirtualPCIPassthrough(key=-100, backing=backing)
4715
4716 new_device_config = vim.VirtualDeviceConfigSpec(device=hba_object)
4717 new_device_config.operation = "add"
4718 vmConfigSpec = vim.vm.ConfigSpec()
4719 vmConfigSpec.deviceChange = [new_device_config]
4720
4721 task = vm_object.ReconfigVM_Task(spec=vmConfigSpec)
4722 self.logger.info("Adding PCI device {} into VM {} from host {} ".format(
4723 host_pci_dev, vm_object, host_object)
4724 )
4725 except Exception as exp:
4726 self.logger.error("Error occurred while adding pci devive {} to VM {}: {}".format(
4727 host_pci_dev,
4728 vm_object,
4729 exp))
4730 return task
4731
4732 def get_vm_vcenter_info(self):
4733 """
4734 Method to get details of vCenter and vm
4735
4736 Args:
4737 vapp_uuid - uuid of vApp or VM
4738
4739 Returns:
4740 Moref Id of VM and deails of vCenter
4741 """
4742 vm_vcenter_info = {}
4743
4744 if self.vcenter_ip is not None:
4745 vm_vcenter_info["vm_vcenter_ip"] = self.vcenter_ip
4746 else:
4747 raise vimconn.vimconnException(message="vCenter IP is not provided."\
4748 " Please provide vCenter IP while attaching datacenter to tenant in --config")
4749 if self.vcenter_port is not None:
4750 vm_vcenter_info["vm_vcenter_port"] = self.vcenter_port
4751 else:
4752 raise vimconn.vimconnException(message="vCenter port is not provided."\
4753 " Please provide vCenter port while attaching datacenter to tenant in --config")
4754 if self.vcenter_user is not None:
4755 vm_vcenter_info["vm_vcenter_user"] = self.vcenter_user
4756 else:
4757 raise vimconn.vimconnException(message="vCenter user is not provided."\
4758 " Please provide vCenter user while attaching datacenter to tenant in --config")
4759
4760 if self.vcenter_password is not None:
4761 vm_vcenter_info["vm_vcenter_password"] = self.vcenter_password
4762 else:
4763 raise vimconn.vimconnException(message="vCenter user password is not provided."\
4764 " Please provide vCenter user password while attaching datacenter to tenant in --config")
4765
4766 return vm_vcenter_info
4767
4768
4769 def get_vm_pci_details(self, vmuuid):
4770 """
4771 Method to get VM PCI device details from vCenter
4772
4773 Args:
4774 vm_obj - vSphere VM object
4775
4776 Returns:
4777 dict of PCI devives attached to VM
4778
4779 """
4780 vm_pci_devices_info = {}
4781 try:
4782 vcenter_conect, content = self.get_vcenter_content()
4783 vm_moref_id = self.get_vm_moref_id(vmuuid)
4784 if vm_moref_id:
4785 #Get VM and its host
4786 if content:
4787 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
4788 if host_obj and vm_obj:
4789 vm_pci_devices_info["host_name"]= host_obj.name
4790 vm_pci_devices_info["host_ip"]= host_obj.config.network.vnic[0].spec.ip.ipAddress
4791 for device in vm_obj.config.hardware.device:
4792 if type(device) == vim.vm.device.VirtualPCIPassthrough:
4793 device_details={'devide_id':device.backing.id,
4794 'pciSlotNumber':device.slotInfo.pciSlotNumber,
4795 }
4796 vm_pci_devices_info[device.deviceInfo.label] = device_details
4797 else:
4798 self.logger.error("Can not connect to vCenter while getting "\
4799 "PCI devices infromationn")
4800 return vm_pci_devices_info
4801 except Exception as exp:
4802 self.logger.error("Error occurred while getting VM infromationn"\
4803 " for VM : {}".format(exp))
4804 raise vimconn.vimconnException(message=exp)
4805
4806
4807 def reserve_memory_for_all_vms(self, vapp, memory_mb):
4808 """
4809 Method to reserve memory for all VMs
4810 Args :
4811 vapp - VApp
4812 memory_mb - Memory in MB
4813 Returns:
4814 None
4815 """
4816
4817 self.logger.info("Reserve memory for all VMs")
4818 for vms in vapp.get_all_vms():
4819 vm_id = vms.get('id').split(':')[-1]
4820
4821 url_rest_call = "{}/api/vApp/vm-{}/virtualHardwareSection/memory".format(self.url, vm_id)
4822
4823 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4824 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4825 headers['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
4826 response = self.perform_request(req_type='GET',
4827 url=url_rest_call,
4828 headers=headers)
4829
4830 if response.status_code == 403:
4831 response = self.retry_rest('GET', url_rest_call)
4832
4833 if response.status_code != 200:
4834 self.logger.error("REST call {} failed reason : {}"\
4835 "status code : {}".format(url_rest_call,
4836 response.content,
4837 response.status_code))
4838 raise vimconn.vimconnException("reserve_memory_for_all_vms : Failed to get "\
4839 "memory")
4840
4841 bytexml = bytes(bytearray(response.content, encoding='utf-8'))
4842 contentelem = lxmlElementTree.XML(bytexml)
4843 namespaces = {prefix:uri for prefix,uri in contentelem.nsmap.iteritems() if prefix}
4844 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
4845
4846 # Find the reservation element in the response
4847 memelem_list = contentelem.findall(".//rasd:Reservation", namespaces)
4848 for memelem in memelem_list:
4849 memelem.text = str(memory_mb)
4850
4851 newdata = lxmlElementTree.tostring(contentelem, pretty_print=True)
4852
4853 response = self.perform_request(req_type='PUT',
4854 url=url_rest_call,
4855 headers=headers,
4856 data=newdata)
4857
4858 if response.status_code == 403:
4859 add_headers = {'Content-Type': headers['Content-Type']}
4860 response = self.retry_rest('PUT', url_rest_call, add_headers, newdata)
4861
4862 if response.status_code != 202:
4863 self.logger.error("REST call {} failed reason : {}"\
4864 "status code : {} ".format(url_rest_call,
4865 response.content,
4866 response.status_code))
4867 raise vimconn.vimconnException("reserve_memory_for_all_vms : Failed to update "\
4868 "virtual hardware memory section")
4869 else:
4870 mem_task = self.get_task_from_response(response.content)
4871 result = self.client.get_task_monitor().wait_for_success(task=mem_task)
4872 if result.get('status') == 'success':
4873 self.logger.info("reserve_memory_for_all_vms(): VM {} succeeded "\
4874 .format(vm_id))
4875 else:
4876 self.logger.error("reserve_memory_for_all_vms(): VM {} failed "\
4877 .format(vm_id))
4878
4879 def connect_vapp_to_org_vdc_network(self, vapp_id, net_name):
4880 """
4881 Configure VApp network config with org vdc network
4882 Args :
4883 vapp - VApp
4884 Returns:
4885 None
4886 """
4887
4888 self.logger.info("Connecting vapp {} to org vdc network {}".
4889 format(vapp_id, net_name))
4890
4891 url_rest_call = "{}/api/vApp/vapp-{}/networkConfigSection/".format(self.url, vapp_id)
4892
4893 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4894 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4895 response = self.perform_request(req_type='GET',
4896 url=url_rest_call,
4897 headers=headers)
4898
4899 if response.status_code == 403:
4900 response = self.retry_rest('GET', url_rest_call)
4901
4902 if response.status_code != 200:
4903 self.logger.error("REST call {} failed reason : {}"\
4904 "status code : {}".format(url_rest_call,
4905 response.content,
4906 response.status_code))
4907 raise vimconn.vimconnException("connect_vapp_to_org_vdc_network : Failed to get "\
4908 "network config section")
4909
4910 data = response.content
4911 headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConfigSection+xml'
4912 net_id = self.get_network_id_by_name(net_name)
4913 if not net_id:
4914 raise vimconn.vimconnException("connect_vapp_to_org_vdc_network : Failed to find "\
4915 "existing network")
4916
4917 bytexml = bytes(bytearray(data, encoding='utf-8'))
4918 newelem = lxmlElementTree.XML(bytexml)
4919 namespaces = {prefix: uri for prefix, uri in newelem.nsmap.iteritems() if prefix}
4920 namespaces["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
4921 nwcfglist = newelem.findall(".//xmlns:NetworkConfig", namespaces)
4922
4923 # VCD 9.7 returns an incorrect parentnetwork element. Fix it before PUT operation
4924 parentnetworklist = newelem.findall(".//xmlns:ParentNetwork", namespaces)
4925 if parentnetworklist:
4926 for pn in parentnetworklist:
4927 if "href" not in pn.keys():
4928 id_val = pn.get("id")
4929 href_val = "{}/api/network/{}".format(self.url, id_val)
4930 pn.set("href", href_val)
4931
4932 newstr = """<NetworkConfig networkName="{}">
4933 <Configuration>
4934 <ParentNetwork href="{}/api/network/{}"/>
4935 <FenceMode>bridged</FenceMode>
4936 </Configuration>
4937 </NetworkConfig>
4938 """.format(net_name, self.url, net_id)
4939 newcfgelem = lxmlElementTree.fromstring(newstr)
4940 if nwcfglist:
4941 nwcfglist[0].addnext(newcfgelem)
4942
4943 newdata = lxmlElementTree.tostring(newelem, pretty_print=True)
4944
4945 response = self.perform_request(req_type='PUT',
4946 url=url_rest_call,
4947 headers=headers,
4948 data=newdata)
4949
4950 if response.status_code == 403:
4951 add_headers = {'Content-Type': headers['Content-Type']}
4952 response = self.retry_rest('PUT', url_rest_call, add_headers, newdata)
4953
4954 if response.status_code != 202:
4955 self.logger.error("REST call {} failed reason : {}"\
4956 "status code : {} ".format(url_rest_call,
4957 response.content,
4958 response.status_code))
4959 raise vimconn.vimconnException("connect_vapp_to_org_vdc_network : Failed to update "\
4960 "network config section")
4961 else:
4962 vapp_task = self.get_task_from_response(response.content)
4963 result = self.client.get_task_monitor().wait_for_success(task=vapp_task)
4964 if result.get('status') == 'success':
4965 self.logger.info("connect_vapp_to_org_vdc_network(): Vapp {} connected to "\
4966 "network {}".format(vapp_id, net_name))
4967 else:
4968 self.logger.error("connect_vapp_to_org_vdc_network(): Vapp {} failed to "\
4969 "connect to network {}".format(vapp_id, net_name))
4970
4971 def remove_primary_network_adapter_from_all_vms(self, vapp):
4972 """
4973 Method to remove network adapter type to vm
4974 Args :
4975 vapp - VApp
4976 Returns:
4977 None
4978 """
4979
4980 self.logger.info("Removing network adapter from all VMs")
4981 for vms in vapp.get_all_vms():
4982 vm_id = vms.get('id').split(':')[-1]
4983
4984 url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(self.url, vm_id)
4985
4986 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
4987 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
4988 response = self.perform_request(req_type='GET',
4989 url=url_rest_call,
4990 headers=headers)
4991
4992 if response.status_code == 403:
4993 response = self.retry_rest('GET', url_rest_call)
4994
4995 if response.status_code != 200:
4996 self.logger.error("REST call {} failed reason : {}"\
4997 "status code : {}".format(url_rest_call,
4998 response.content,
4999 response.status_code))
5000 raise vimconn.vimconnException("remove_primary_network_adapter : Failed to get "\
5001 "network connection section")
5002
5003 data = response.content
5004 data = data.split('<Link rel="edit"')[0]
5005
5006 headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
5007
5008 newdata = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
5009 <NetworkConnectionSection xmlns="http://www.vmware.com/vcloud/v1.5"
5010 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
5011 xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
5012 xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common"
5013 xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
5014 xmlns:vmw="http://www.vmware.com/schema/ovf"
5015 xmlns:ovfenv="http://schemas.dmtf.org/ovf/environment/1"
5016 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
5017 xmlns:ns9="http://www.vmware.com/vcloud/versions"
5018 href="{url}" type="application/vnd.vmware.vcloud.networkConnectionSection+xml" ovf:required="false">
5019 <ovf:Info>Specifies the available VM network connections</ovf:Info>
5020 <PrimaryNetworkConnectionIndex>0</PrimaryNetworkConnectionIndex>
5021 <Link rel="edit" href="{url}" type="application/vnd.vmware.vcloud.networkConnectionSection+xml"/>
5022 </NetworkConnectionSection>""".format(url=url_rest_call)
5023 response = self.perform_request(req_type='PUT',
5024 url=url_rest_call,
5025 headers=headers,
5026 data=newdata)
5027
5028 if response.status_code == 403:
5029 add_headers = {'Content-Type': headers['Content-Type']}
5030 response = self.retry_rest('PUT', url_rest_call, add_headers, newdata)
5031
5032 if response.status_code != 202:
5033 self.logger.error("REST call {} failed reason : {}"\
5034 "status code : {} ".format(url_rest_call,
5035 response.content,
5036 response.status_code))
5037 raise vimconn.vimconnException("remove_primary_network_adapter : Failed to update "\
5038 "network connection section")
5039 else:
5040 nic_task = self.get_task_from_response(response.content)
5041 result = self.client.get_task_monitor().wait_for_success(task=nic_task)
5042 if result.get('status') == 'success':
5043 self.logger.info("remove_primary_network_adapter(): VM {} conneced to "\
5044 "default NIC type".format(vm_id))
5045 else:
5046 self.logger.error("remove_primary_network_adapter(): VM {} failed to "\
5047 "connect NIC type".format(vm_id))
5048
5049 def add_network_adapter_to_vms(self, vapp, network_name, primary_nic_index, nicIndex, net, nic_type=None):
5050 """
5051 Method to add network adapter type to vm
5052 Args :
5053 network_name - name of network
5054 primary_nic_index - int value for primary nic index
5055 nicIndex - int value for nic index
5056 nic_type - specify model name to which add to vm
5057 Returns:
5058 None
5059 """
5060
5061 self.logger.info("Add network adapter to VM: network_name {} nicIndex {} nic_type {}".\
5062 format(network_name, nicIndex, nic_type))
5063 try:
5064 ip_address = None
5065 floating_ip = False
5066 mac_address = None
5067 if 'floating_ip' in net: floating_ip = net['floating_ip']
5068
5069 # Stub for ip_address feature
5070 if 'ip_address' in net: ip_address = net['ip_address']
5071
5072 if 'mac_address' in net: mac_address = net['mac_address']
5073
5074 if floating_ip:
5075 allocation_mode = "POOL"
5076 elif ip_address:
5077 allocation_mode = "MANUAL"
5078 else:
5079 allocation_mode = "DHCP"
5080
5081 if not nic_type:
5082 for vms in vapp.get_all_vms():
5083 vm_id = vms.get('id').split(':')[-1]
5084
5085 url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(self.url, vm_id)
5086
5087 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
5088 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
5089 response = self.perform_request(req_type='GET',
5090 url=url_rest_call,
5091 headers=headers)
5092
5093 if response.status_code == 403:
5094 response = self.retry_rest('GET', url_rest_call)
5095
5096 if response.status_code != 200:
5097 self.logger.error("REST call {} failed reason : {}"\
5098 "status code : {}".format(url_rest_call,
5099 response.content,
5100 response.status_code))
5101 raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to get "\
5102 "network connection section")
5103
5104 data = response.content
5105 data = data.split('<Link rel="edit"')[0]
5106 if '<PrimaryNetworkConnectionIndex>' not in data:
5107 self.logger.debug("add_network_adapter PrimaryNIC not in data")
5108 item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
5109 <NetworkConnection network="{}">
5110 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5111 <IsConnected>true</IsConnected>
5112 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5113 </NetworkConnection>""".format(primary_nic_index, network_name, nicIndex,
5114 allocation_mode)
5115 # Stub for ip_address feature
5116 if ip_address:
5117 ip_tag = '<IpAddress>{}</IpAddress>'.format(ip_address)
5118 item = item.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag))
5119
5120 if mac_address:
5121 mac_tag = '<MACAddress>{}</MACAddress>'.format(mac_address)
5122 item = item.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag))
5123
5124 data = data.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item))
5125 else:
5126 self.logger.debug("add_network_adapter PrimaryNIC in data")
5127 new_item = """<NetworkConnection network="{}">
5128 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5129 <IsConnected>true</IsConnected>
5130 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5131 </NetworkConnection>""".format(network_name, nicIndex,
5132 allocation_mode)
5133 # Stub for ip_address feature
5134 if ip_address:
5135 ip_tag = '<IpAddress>{}</IpAddress>'.format(ip_address)
5136 new_item = new_item.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag))
5137
5138 if mac_address:
5139 mac_tag = '<MACAddress>{}</MACAddress>'.format(mac_address)
5140 new_item = new_item.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag))
5141
5142 data = data + new_item + '</NetworkConnectionSection>'
5143
5144 headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
5145
5146 response = self.perform_request(req_type='PUT',
5147 url=url_rest_call,
5148 headers=headers,
5149 data=data)
5150
5151 if response.status_code == 403:
5152 add_headers = {'Content-Type': headers['Content-Type']}
5153 response = self.retry_rest('PUT', url_rest_call, add_headers, data)
5154
5155 if response.status_code != 202:
5156 self.logger.error("REST call {} failed reason : {}"\
5157 "status code : {} ".format(url_rest_call,
5158 response.content,
5159 response.status_code))
5160 raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to update "\
5161 "network connection section")
5162 else:
5163 nic_task = self.get_task_from_response(response.content)
5164 result = self.client.get_task_monitor().wait_for_success(task=nic_task)
5165 if result.get('status') == 'success':
5166 self.logger.info("add_network_adapter_to_vms(): VM {} conneced to "\
5167 "default NIC type".format(vm_id))
5168 else:
5169 self.logger.error("add_network_adapter_to_vms(): VM {} failed to "\
5170 "connect NIC type".format(vm_id))
5171 else:
5172 for vms in vapp.get_all_vms():
5173 vm_id = vms.get('id').split(':')[-1]
5174
5175 url_rest_call = "{}/api/vApp/vm-{}/networkConnectionSection/".format(self.url, vm_id)
5176
5177 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
5178 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
5179 response = self.perform_request(req_type='GET',
5180 url=url_rest_call,
5181 headers=headers)
5182
5183 if response.status_code == 403:
5184 response = self.retry_rest('GET', url_rest_call)
5185
5186 if response.status_code != 200:
5187 self.logger.error("REST call {} failed reason : {}"\
5188 "status code : {}".format(url_rest_call,
5189 response.content,
5190 response.status_code))
5191 raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to get "\
5192 "network connection section")
5193 data = response.content
5194 data = data.split('<Link rel="edit"')[0]
5195 vcd_netadapter_type = nic_type
5196 if nic_type in ['SR-IOV', 'VF']:
5197 vcd_netadapter_type = "SRIOVETHERNETCARD"
5198
5199 if '<PrimaryNetworkConnectionIndex>' not in data:
5200 self.logger.debug("add_network_adapter PrimaryNIC not in data nic_type {}".format(nic_type))
5201 item = """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
5202 <NetworkConnection network="{}">
5203 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5204 <IsConnected>true</IsConnected>
5205 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5206 <NetworkAdapterType>{}</NetworkAdapterType>
5207 </NetworkConnection>""".format(primary_nic_index, network_name, nicIndex,
5208 allocation_mode, vcd_netadapter_type)
5209 # Stub for ip_address feature
5210 if ip_address:
5211 ip_tag = '<IpAddress>{}</IpAddress>'.format(ip_address)
5212 item = item.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag))
5213
5214 if mac_address:
5215 mac_tag = '<MACAddress>{}</MACAddress>'.format(mac_address)
5216 item = item.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag))
5217
5218 data = data.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item))
5219 else:
5220 self.logger.debug("add_network_adapter PrimaryNIC in data nic_type {}".format(nic_type))
5221 new_item = """<NetworkConnection network="{}">
5222 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5223 <IsConnected>true</IsConnected>
5224 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5225 <NetworkAdapterType>{}</NetworkAdapterType>
5226 </NetworkConnection>""".format(network_name, nicIndex,
5227 allocation_mode, vcd_netadapter_type)
5228 # Stub for ip_address feature
5229 if ip_address:
5230 ip_tag = '<IpAddress>{}</IpAddress>'.format(ip_address)
5231 new_item = new_item.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag))
5232
5233 if mac_address:
5234 mac_tag = '<MACAddress>{}</MACAddress>'.format(mac_address)
5235 new_item = new_item.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag))
5236
5237 data = data + new_item + '</NetworkConnectionSection>'
5238
5239 headers['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
5240
5241 response = self.perform_request(req_type='PUT',
5242 url=url_rest_call,
5243 headers=headers,
5244 data=data)
5245
5246 if response.status_code == 403:
5247 add_headers = {'Content-Type': headers['Content-Type']}
5248 response = self.retry_rest('PUT', url_rest_call, add_headers, data)
5249
5250 if response.status_code != 202:
5251 self.logger.error("REST call {} failed reason : {}"\
5252 "status code : {}".format(url_rest_call,
5253 response.content,
5254 response.status_code))
5255 raise vimconn.vimconnException("add_network_adapter_to_vms : Failed to update "\
5256 "network connection section")
5257 else:
5258 nic_task = self.get_task_from_response(response.content)
5259 result = self.client.get_task_monitor().wait_for_success(task=nic_task)
5260 if result.get('status') == 'success':
5261 self.logger.info("add_network_adapter_to_vms(): VM {} "\
5262 "conneced to NIC type {}".format(vm_id, nic_type))
5263 else:
5264 self.logger.error("add_network_adapter_to_vms(): VM {} "\
5265 "failed to connect NIC type {}".format(vm_id, nic_type))
5266 except Exception as exp:
5267 self.logger.error("add_network_adapter_to_vms() : exception occurred "\
5268 "while adding Network adapter")
5269 raise vimconn.vimconnException(message=exp)
5270
5271
5272 def set_numa_affinity(self, vmuuid, paired_threads_id):
5273 """
5274 Method to assign numa affinity in vm configuration parammeters
5275 Args :
5276 vmuuid - vm uuid
5277 paired_threads_id - one or more virtual processor
5278 numbers
5279 Returns:
5280 return if True
5281 """
5282 try:
5283 vcenter_conect, content = self.get_vcenter_content()
5284 vm_moref_id = self.get_vm_moref_id(vmuuid)
5285
5286 host_obj, vm_obj = self.get_vm_obj(content ,vm_moref_id)
5287 if vm_obj:
5288 config_spec = vim.vm.ConfigSpec()
5289 config_spec.extraConfig = []
5290 opt = vim.option.OptionValue()
5291 opt.key = 'numa.nodeAffinity'
5292 opt.value = str(paired_threads_id)
5293 config_spec.extraConfig.append(opt)
5294 task = vm_obj.ReconfigVM_Task(config_spec)
5295 if task:
5296 result = self.wait_for_vcenter_task(task, vcenter_conect)
5297 extra_config = vm_obj.config.extraConfig
5298 flag = False
5299 for opts in extra_config:
5300 if 'numa.nodeAffinity' in opts.key:
5301 flag = True
5302 self.logger.info("set_numa_affinity: Sucessfully assign numa affinity "\
5303 "value {} for vm {}".format(opt.value, vm_obj))
5304 if flag:
5305 return
5306 else:
5307 self.logger.error("set_numa_affinity: Failed to assign numa affinity")
5308 except Exception as exp:
5309 self.logger.error("set_numa_affinity : exception occurred while setting numa affinity "\
5310 "for VM {} : {}".format(vm_obj, vm_moref_id))
5311 raise vimconn.vimconnException("set_numa_affinity : Error {} failed to assign numa "\
5312 "affinity".format(exp))
5313
5314
5315 def cloud_init(self, vapp, cloud_config):
5316 """
5317 Method to inject ssh-key
5318 vapp - vapp object
5319 cloud_config a dictionary with:
5320 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
5321 'users': (optional) list of users to be inserted, each item is a dict with:
5322 'name': (mandatory) user name,
5323 'key-pairs': (optional) list of strings with the public key to be inserted to the user
5324 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
5325 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
5326 'config-files': (optional). List of files to be transferred. Each item is a dict with:
5327 'dest': (mandatory) string with the destination absolute path
5328 'encoding': (optional, by default text). Can be one of:
5329 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
5330 'content' (mandatory): string with the content of the file
5331 'permissions': (optional) string with file permissions, typically octal notation '0644'
5332 'owner': (optional) file owner, string with the format 'owner:group'
5333 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk
5334 """
5335 try:
5336 if not isinstance(cloud_config, dict):
5337 raise Exception("cloud_init : parameter cloud_config is not a dictionary")
5338 else:
5339 key_pairs = []
5340 userdata = []
5341 if "key-pairs" in cloud_config:
5342 key_pairs = cloud_config["key-pairs"]
5343
5344 if "users" in cloud_config:
5345 userdata = cloud_config["users"]
5346
5347 self.logger.debug("cloud_init : Guest os customization started..")
5348 customize_script = self.format_script(key_pairs=key_pairs, users_list=userdata)
5349 customize_script = customize_script.replace("&","&amp;")
5350 self.guest_customization(vapp, customize_script)
5351
5352 except Exception as exp:
5353 self.logger.error("cloud_init : exception occurred while injecting "\
5354 "ssh-key")
5355 raise vimconn.vimconnException("cloud_init : Error {} failed to inject "\
5356 "ssh-key".format(exp))
5357
5358 def format_script(self, key_pairs=[], users_list=[]):
5359 bash_script = """#!/bin/sh
5360 echo performing customization tasks with param $1 at `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
5361 if [ "$1" = "precustomization" ];then
5362 echo performing precustomization tasks on `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
5363 """
5364
5365 keys = "\n".join(key_pairs)
5366 if keys:
5367 keys_data = """
5368 if [ ! -d /root/.ssh ];then
5369 mkdir /root/.ssh
5370 chown root:root /root/.ssh
5371 chmod 700 /root/.ssh
5372 touch /root/.ssh/authorized_keys
5373 chown root:root /root/.ssh/authorized_keys
5374 chmod 600 /root/.ssh/authorized_keys
5375 # make centos with selinux happy
5376 which restorecon && restorecon -Rv /root/.ssh
5377 else
5378 touch /root/.ssh/authorized_keys
5379 chown root:root /root/.ssh/authorized_keys
5380 chmod 600 /root/.ssh/authorized_keys
5381 fi
5382 echo '{key}' >> /root/.ssh/authorized_keys
5383 """.format(key=keys)
5384
5385 bash_script+= keys_data
5386
5387 for user in users_list:
5388 if 'name' in user: user_name = user['name']
5389 if 'key-pairs' in user:
5390 user_keys = "\n".join(user['key-pairs'])
5391 else:
5392 user_keys = None
5393
5394 add_user_name = """
5395 useradd -d /home/{user_name} -m -g users -s /bin/bash {user_name}
5396 """.format(user_name=user_name)
5397
5398 bash_script+= add_user_name
5399
5400 if user_keys:
5401 user_keys_data = """
5402 mkdir /home/{user_name}/.ssh
5403 chown {user_name}:{user_name} /home/{user_name}/.ssh
5404 chmod 700 /home/{user_name}/.ssh
5405 touch /home/{user_name}/.ssh/authorized_keys
5406 chown {user_name}:{user_name} /home/{user_name}/.ssh/authorized_keys
5407 chmod 600 /home/{user_name}/.ssh/authorized_keys
5408 # make centos with selinux happy
5409 which restorecon && restorecon -Rv /home/{user_name}/.ssh
5410 echo '{user_key}' >> /home/{user_name}/.ssh/authorized_keys
5411 """.format(user_name=user_name,user_key=user_keys)
5412
5413 bash_script+= user_keys_data
5414
5415 return bash_script+"\n\tfi"
5416
5417 def guest_customization(self, vapp, customize_script):
5418 """
5419 Method to customize guest os
5420 vapp - Vapp object
5421 customize_script - Customize script to be run at first boot of VM.
5422 """
5423 for vm in vapp.get_all_vms():
5424 vm_id = vm.get('id').split(':')[-1]
5425 vm_name = vm.get('name')
5426 vm_name = vm_name.replace('_','-')
5427
5428 vm_customization_url = "{}/api/vApp/vm-{}/guestCustomizationSection/".format(self.url, vm_id)
5429 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
5430 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
5431
5432 headers['Content-Type'] = "application/vnd.vmware.vcloud.guestCustomizationSection+xml"
5433
5434 data = """<GuestCustomizationSection
5435 xmlns="http://www.vmware.com/vcloud/v1.5"
5436 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
5437 ovf:required="false" href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml">
5438 <ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
5439 <Enabled>true</Enabled>
5440 <ChangeSid>false</ChangeSid>
5441 <VirtualMachineId>{}</VirtualMachineId>
5442 <JoinDomainEnabled>false</JoinDomainEnabled>
5443 <UseOrgSettings>false</UseOrgSettings>
5444 <AdminPasswordEnabled>false</AdminPasswordEnabled>
5445 <AdminPasswordAuto>true</AdminPasswordAuto>
5446 <AdminAutoLogonEnabled>false</AdminAutoLogonEnabled>
5447 <AdminAutoLogonCount>0</AdminAutoLogonCount>
5448 <ResetPasswordRequired>false</ResetPasswordRequired>
5449 <CustomizationScript>{}</CustomizationScript>
5450 <ComputerName>{}</ComputerName>
5451 <Link href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml" rel="edit"/>
5452 </GuestCustomizationSection>
5453 """.format(vm_customization_url,
5454 vm_id,
5455 customize_script,
5456 vm_name,
5457 vm_customization_url)
5458
5459 response = self.perform_request(req_type='PUT',
5460 url=vm_customization_url,
5461 headers=headers,
5462 data=data)
5463 if response.status_code == 202:
5464 guest_task = self.get_task_from_response(response.content)
5465 self.client.get_task_monitor().wait_for_success(task=guest_task)
5466 self.logger.info("guest_customization : customized guest os task "\
5467 "completed for VM {}".format(vm_name))
5468 else:
5469 self.logger.error("guest_customization : task for customized guest os"\
5470 "failed for VM {}".format(vm_name))
5471 raise vimconn.vimconnException("guest_customization : failed to perform"\
5472 "guest os customization on VM {}".format(vm_name))
5473
5474 def add_new_disk(self, vapp_uuid, disk_size):
5475 """
5476 Method to create an empty vm disk
5477
5478 Args:
5479 vapp_uuid - is vapp identifier.
5480 disk_size - size of disk to be created in GB
5481
5482 Returns:
5483 None
5484 """
5485 status = False
5486 vm_details = None
5487 try:
5488 #Disk size in GB, convert it into MB
5489 if disk_size is not None:
5490 disk_size_mb = int(disk_size) * 1024
5491 vm_details = self.get_vapp_details_rest(vapp_uuid)
5492
5493 if vm_details and "vm_virtual_hardware" in vm_details:
5494 self.logger.info("Adding disk to VM: {} disk size:{}GB".format(vm_details["name"], disk_size))
5495 disk_href = vm_details["vm_virtual_hardware"]["disk_edit_href"]
5496 status = self.add_new_disk_rest(disk_href, disk_size_mb)
5497
5498 except Exception as exp:
5499 msg = "Error occurred while creating new disk {}.".format(exp)
5500 self.rollback_newvm(vapp_uuid, msg)
5501
5502 if status:
5503 self.logger.info("Added new disk to VM: {} disk size:{}GB".format(vm_details["name"], disk_size))
5504 else:
5505 #If failed to add disk, delete VM
5506 msg = "add_new_disk: Failed to add new disk to {}".format(vm_details["name"])
5507 self.rollback_newvm(vapp_uuid, msg)
5508
5509
5510 def add_new_disk_rest(self, disk_href, disk_size_mb):
5511 """
5512 Retrives vApp Disks section & add new empty disk
5513
5514 Args:
5515 disk_href: Disk section href to addd disk
5516 disk_size_mb: Disk size in MB
5517
5518 Returns: Status of add new disk task
5519 """
5520 status = False
5521 if self.client._session:
5522 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
5523 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
5524 response = self.perform_request(req_type='GET',
5525 url=disk_href,
5526 headers=headers)
5527
5528 if response.status_code == 403:
5529 response = self.retry_rest('GET', disk_href)
5530
5531 if response.status_code != requests.codes.ok:
5532 self.logger.error("add_new_disk_rest: GET REST API call {} failed. Return status code {}"
5533 .format(disk_href, response.status_code))
5534 return status
5535 try:
5536 #Find but type & max of instance IDs assigned to disks
5537 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
5538 namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
5539 #For python3
5540 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
5541 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
5542 instance_id = 0
5543 for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
5544 if item.find("rasd:Description",namespaces).text == "Hard disk":
5545 inst_id = int(item.find("rasd:InstanceID" ,namespaces).text)
5546 if inst_id > instance_id:
5547 instance_id = inst_id
5548 disk_item = item.find("rasd:HostResource" ,namespaces)
5549 bus_subtype = disk_item.attrib["{"+namespaces['xmlns']+"}busSubType"]
5550 bus_type = disk_item.attrib["{"+namespaces['xmlns']+"}busType"]
5551
5552 instance_id = instance_id + 1
5553 new_item = """<Item>
5554 <rasd:Description>Hard disk</rasd:Description>
5555 <rasd:ElementName>New disk</rasd:ElementName>
5556 <rasd:HostResource
5557 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
5558 vcloud:capacity="{}"
5559 vcloud:busSubType="{}"
5560 vcloud:busType="{}"></rasd:HostResource>
5561 <rasd:InstanceID>{}</rasd:InstanceID>
5562 <rasd:ResourceType>17</rasd:ResourceType>
5563 </Item>""".format(disk_size_mb, bus_subtype, bus_type, instance_id)
5564
5565 new_data = response.content
5566 #Add new item at the bottom
5567 new_data = new_data.replace('</Item>\n</RasdItemsList>', '</Item>\n{}\n</RasdItemsList>'.format(new_item))
5568
5569 # Send PUT request to modify virtual hardware section with new disk
5570 headers['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
5571
5572 response = self.perform_request(req_type='PUT',
5573 url=disk_href,
5574 data=new_data,
5575 headers=headers)
5576
5577 if response.status_code == 403:
5578 add_headers = {'Content-Type': headers['Content-Type']}
5579 response = self.retry_rest('PUT', disk_href, add_headers, new_data)
5580
5581 if response.status_code != 202:
5582 self.logger.error("PUT REST API call {} failed. Return status code {}. Response Content:{}"
5583 .format(disk_href, response.status_code, response.content))
5584 else:
5585 add_disk_task = self.get_task_from_response(response.content)
5586 result = self.client.get_task_monitor().wait_for_success(task=add_disk_task)
5587 if result.get('status') == 'success':
5588 status = True
5589 else:
5590 self.logger.error("Add new disk REST task failed to add {} MB disk".format(disk_size_mb))
5591
5592 except Exception as exp:
5593 self.logger.error("Error occurred calling rest api for creating new disk {}".format(exp))
5594
5595 return status
5596
5597
5598 def add_existing_disk(self, catalogs=None, image_id=None, size=None, template_name=None, vapp_uuid=None):
5599 """
5600 Method to add existing disk to vm
5601 Args :
5602 catalogs - List of VDC catalogs
5603 image_id - Catalog ID
5604 template_name - Name of template in catalog
5605 vapp_uuid - UUID of vApp
5606 Returns:
5607 None
5608 """
5609 disk_info = None
5610 vcenter_conect, content = self.get_vcenter_content()
5611 #find moref-id of vm in image
5612 catalog_vm_info = self.get_vapp_template_details(catalogs=catalogs,
5613 image_id=image_id,
5614 )
5615
5616 if catalog_vm_info and "vm_vcenter_info" in catalog_vm_info:
5617 if "vm_moref_id" in catalog_vm_info["vm_vcenter_info"]:
5618 catalog_vm_moref_id = catalog_vm_info["vm_vcenter_info"].get("vm_moref_id", None)
5619 if catalog_vm_moref_id:
5620 self.logger.info("Moref_id of VM in catalog : {}" .format(catalog_vm_moref_id))
5621 host, catalog_vm_obj = self.get_vm_obj(content, catalog_vm_moref_id)
5622 if catalog_vm_obj:
5623 #find existing disk
5624 disk_info = self.find_disk(catalog_vm_obj)
5625 else:
5626 exp_msg = "No VM with image id {} found".format(image_id)
5627 self.rollback_newvm(vapp_uuid, exp_msg, exp_type="NotFound")
5628 else:
5629 exp_msg = "No Image found with image ID {} ".format(image_id)
5630 self.rollback_newvm(vapp_uuid, exp_msg, exp_type="NotFound")
5631
5632 if disk_info:
5633 self.logger.info("Existing disk_info : {}".format(disk_info))
5634 #get VM
5635 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
5636 host, vm_obj = self.get_vm_obj(content, vm_moref_id)
5637 if vm_obj:
5638 status = self.add_disk(vcenter_conect=vcenter_conect,
5639 vm=vm_obj,
5640 disk_info=disk_info,
5641 size=size,
5642 vapp_uuid=vapp_uuid
5643 )
5644 if status:
5645 self.logger.info("Disk from image id {} added to {}".format(image_id,
5646 vm_obj.config.name)
5647 )
5648 else:
5649 msg = "No disk found with image id {} to add in VM {}".format(
5650 image_id,
5651 vm_obj.config.name)
5652 self.rollback_newvm(vapp_uuid, msg, exp_type="NotFound")
5653
5654
5655 def find_disk(self, vm_obj):
5656 """
5657 Method to find details of existing disk in VM
5658 Args :
5659 vm_obj - vCenter object of VM
5660 image_id - Catalog ID
5661 Returns:
5662 disk_info : dict of disk details
5663 """
5664 disk_info = {}
5665 if vm_obj:
5666 try:
5667 devices = vm_obj.config.hardware.device
5668 for device in devices:
5669 if type(device) is vim.vm.device.VirtualDisk:
5670 if isinstance(device.backing,vim.vm.device.VirtualDisk.FlatVer2BackingInfo) and hasattr(device.backing, 'fileName'):
5671 disk_info["full_path"] = device.backing.fileName
5672 disk_info["datastore"] = device.backing.datastore
5673 disk_info["capacityKB"] = device.capacityInKB
5674 break
5675 except Exception as exp:
5676 self.logger.error("find_disk() : exception occurred while "\
5677 "getting existing disk details :{}".format(exp))
5678 return disk_info
5679
5680
5681 def add_disk(self, vcenter_conect=None, vm=None, size=None, vapp_uuid=None, disk_info={}):
5682 """
5683 Method to add existing disk in VM
5684 Args :
5685 vcenter_conect - vCenter content object
5686 vm - vCenter vm object
5687 disk_info : dict of disk details
5688 Returns:
5689 status : status of add disk task
5690 """
5691 datastore = disk_info["datastore"] if "datastore" in disk_info else None
5692 fullpath = disk_info["full_path"] if "full_path" in disk_info else None
5693 capacityKB = disk_info["capacityKB"] if "capacityKB" in disk_info else None
5694 if size is not None:
5695 #Convert size from GB to KB
5696 sizeKB = int(size) * 1024 * 1024
5697 #compare size of existing disk and user given size.Assign whicherver is greater
5698 self.logger.info("Add Existing disk : sizeKB {} , capacityKB {}".format(
5699 sizeKB, capacityKB))
5700 if sizeKB > capacityKB:
5701 capacityKB = sizeKB
5702
5703 if datastore and fullpath and capacityKB:
5704 try:
5705 spec = vim.vm.ConfigSpec()
5706 # get all disks on a VM, set unit_number to the next available
5707 unit_number = 0
5708 for dev in vm.config.hardware.device:
5709 if hasattr(dev.backing, 'fileName'):
5710 unit_number = int(dev.unitNumber) + 1
5711 # unit_number 7 reserved for scsi controller
5712 if unit_number == 7:
5713 unit_number += 1
5714 if isinstance(dev, vim.vm.device.VirtualDisk):
5715 #vim.vm.device.VirtualSCSIController
5716 controller_key = dev.controllerKey
5717
5718 self.logger.info("Add Existing disk : unit number {} , controller key {}".format(
5719 unit_number, controller_key))
5720 # add disk here
5721 dev_changes = []
5722 disk_spec = vim.vm.device.VirtualDeviceSpec()
5723 disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
5724 disk_spec.device = vim.vm.device.VirtualDisk()
5725 disk_spec.device.backing = \
5726 vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
5727 disk_spec.device.backing.thinProvisioned = True
5728 disk_spec.device.backing.diskMode = 'persistent'
5729 disk_spec.device.backing.datastore = datastore
5730 disk_spec.device.backing.fileName = fullpath
5731
5732 disk_spec.device.unitNumber = unit_number
5733 disk_spec.device.capacityInKB = capacityKB
5734 disk_spec.device.controllerKey = controller_key
5735 dev_changes.append(disk_spec)
5736 spec.deviceChange = dev_changes
5737 task = vm.ReconfigVM_Task(spec=spec)
5738 status = self.wait_for_vcenter_task(task, vcenter_conect)
5739 return status
5740 except Exception as exp:
5741 exp_msg = "add_disk() : exception {} occurred while adding disk "\
5742 "{} to vm {}".format(exp,
5743 fullpath,
5744 vm.config.name)
5745 self.rollback_newvm(vapp_uuid, exp_msg)
5746 else:
5747 msg = "add_disk() : Can not add disk to VM with disk info {} ".format(disk_info)
5748 self.rollback_newvm(vapp_uuid, msg)
5749
5750
5751 def get_vcenter_content(self):
5752 """
5753 Get the vsphere content object
5754 """
5755 try:
5756 vm_vcenter_info = self.get_vm_vcenter_info()
5757 except Exception as exp:
5758 self.logger.error("Error occurred while getting vCenter infromationn"\
5759 " for VM : {}".format(exp))
5760 raise vimconn.vimconnException(message=exp)
5761
5762 context = None
5763 if hasattr(ssl, '_create_unverified_context'):
5764 context = ssl._create_unverified_context()
5765
5766 vcenter_conect = SmartConnect(
5767 host=vm_vcenter_info["vm_vcenter_ip"],
5768 user=vm_vcenter_info["vm_vcenter_user"],
5769 pwd=vm_vcenter_info["vm_vcenter_password"],
5770 port=int(vm_vcenter_info["vm_vcenter_port"]),
5771 sslContext=context
5772 )
5773 atexit.register(Disconnect, vcenter_conect)
5774 content = vcenter_conect.RetrieveContent()
5775 return vcenter_conect, content
5776
5777
5778 def get_vm_moref_id(self, vapp_uuid):
5779 """
5780 Get the moref_id of given VM
5781 """
5782 try:
5783 if vapp_uuid:
5784 vm_details = self.get_vapp_details_rest(vapp_uuid, need_admin_access=True)
5785 if vm_details and "vm_vcenter_info" in vm_details:
5786 vm_moref_id = vm_details["vm_vcenter_info"].get("vm_moref_id", None)
5787 return vm_moref_id
5788
5789 except Exception as exp:
5790 self.logger.error("Error occurred while getting VM moref ID "\
5791 " for VM : {}".format(exp))
5792 return None
5793
5794
5795 def get_vapp_template_details(self, catalogs=None, image_id=None , template_name=None):
5796 """
5797 Method to get vApp template details
5798 Args :
5799 catalogs - list of VDC catalogs
5800 image_id - Catalog ID to find
5801 template_name : template name in catalog
5802 Returns:
5803 parsed_respond : dict of vApp tempalte details
5804 """
5805 parsed_response = {}
5806
5807 vca = self.connect_as_admin()
5808 if not vca:
5809 raise vimconn.vimconnConnectionException("Failed to connect vCD")
5810
5811 try:
5812 org, vdc = self.get_vdc_details()
5813 catalog = self.get_catalog_obj(image_id, catalogs)
5814 if catalog:
5815 items = org.get_catalog_item(catalog.get('name'), catalog.get('name'))
5816 catalog_items = [items.attrib]
5817
5818 if len(catalog_items) == 1:
5819 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
5820 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
5821
5822 response = self.perform_request(req_type='GET',
5823 url=catalog_items[0].get('href'),
5824 headers=headers)
5825 catalogItem = XmlElementTree.fromstring(response.content)
5826 entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
5827 vapp_tempalte_href = entity.get("href")
5828 #get vapp details and parse moref id
5829
5830 namespaces = {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
5831 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
5832 'vmw': 'http://www.vmware.com/schema/ovf',
5833 'vm': 'http://www.vmware.com/vcloud/v1.5',
5834 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
5835 'vmext':"http://www.vmware.com/vcloud/extension/v1.5",
5836 'xmlns':"http://www.vmware.com/vcloud/v1.5"
5837 }
5838
5839 if vca._session:
5840 response = self.perform_request(req_type='GET',
5841 url=vapp_tempalte_href,
5842 headers=headers)
5843
5844 if response.status_code != requests.codes.ok:
5845 self.logger.debug("REST API call {} failed. Return status code {}".format(
5846 vapp_tempalte_href, response.status_code))
5847
5848 else:
5849 xmlroot_respond = XmlElementTree.fromstring(response.content)
5850 children_section = xmlroot_respond.find('vm:Children/', namespaces)
5851 if children_section is not None:
5852 vCloud_extension_section = children_section.find('xmlns:VCloudExtension', namespaces)
5853 if vCloud_extension_section is not None:
5854 vm_vcenter_info = {}
5855 vim_info = vCloud_extension_section.find('vmext:VmVimInfo', namespaces)
5856 vmext = vim_info.find('vmext:VmVimObjectRef', namespaces)
5857 if vmext is not None:
5858 vm_vcenter_info["vm_moref_id"] = vmext.find('vmext:MoRef', namespaces).text
5859 parsed_response["vm_vcenter_info"]= vm_vcenter_info
5860
5861 except Exception as exp :
5862 self.logger.info("Error occurred calling rest api for getting vApp details {}".format(exp))
5863
5864 return parsed_response
5865
5866
5867 def rollback_newvm(self, vapp_uuid, msg , exp_type="Genric"):
5868 """
5869 Method to delete vApp
5870 Args :
5871 vapp_uuid - vApp UUID
5872 msg - Error message to be logged
5873 exp_type : Exception type
5874 Returns:
5875 None
5876 """
5877 if vapp_uuid:
5878 status = self.delete_vminstance(vapp_uuid)
5879 else:
5880 msg = "No vApp ID"
5881 self.logger.error(msg)
5882 if exp_type == "Genric":
5883 raise vimconn.vimconnException(msg)
5884 elif exp_type == "NotFound":
5885 raise vimconn.vimconnNotFoundException(message=msg)
5886
5887 def add_sriov(self, vapp_uuid, sriov_nets, vmname_andid):
5888 """
5889 Method to attach SRIOV adapters to VM
5890
5891 Args:
5892 vapp_uuid - uuid of vApp/VM
5893 sriov_nets - SRIOV devices infromation as specified in VNFD (flavor)
5894 vmname_andid - vmname
5895
5896 Returns:
5897 The status of add SRIOV adapter task , vm object and
5898 vcenter_conect object
5899 """
5900 vm_obj = None
5901 vcenter_conect, content = self.get_vcenter_content()
5902 vm_moref_id = self.get_vm_moref_id(vapp_uuid)
5903
5904 if vm_moref_id:
5905 try:
5906 no_of_sriov_devices = len(sriov_nets)
5907 if no_of_sriov_devices > 0:
5908 #Get VM and its host
5909 host_obj, vm_obj = self.get_vm_obj(content, vm_moref_id)
5910 self.logger.info("VM {} is currently on host {}".format(vm_obj, host_obj))
5911 if host_obj and vm_obj:
5912 #get SRIOV devies from host on which vapp is currently installed
5913 avilable_sriov_devices = self.get_sriov_devices(host_obj,
5914 no_of_sriov_devices,
5915 )
5916
5917 if len(avilable_sriov_devices) == 0:
5918 #find other hosts with active pci devices
5919 new_host_obj , avilable_sriov_devices = self.get_host_and_sriov_devices(
5920 content,
5921 no_of_sriov_devices,
5922 )
5923
5924 if new_host_obj is not None and len(avilable_sriov_devices)> 0:
5925 #Migrate vm to the host where SRIOV devices are available
5926 self.logger.info("Relocate VM {} on new host {}".format(vm_obj,
5927 new_host_obj))
5928 task = self.relocate_vm(new_host_obj, vm_obj)
5929 if task is not None:
5930 result = self.wait_for_vcenter_task(task, vcenter_conect)
5931 self.logger.info("Migrate VM status: {}".format(result))
5932 host_obj = new_host_obj
5933 else:
5934 self.logger.info("Fail to migrate VM : {}".format(result))
5935 raise vimconn.vimconnNotFoundException(
5936 "Fail to migrate VM : {} to host {}".format(
5937 vmname_andid,
5938 new_host_obj)
5939 )
5940
5941 if host_obj is not None and avilable_sriov_devices is not None and len(avilable_sriov_devices)> 0:
5942 #Add SRIOV devices one by one
5943 for sriov_net in sriov_nets:
5944 network_name = sriov_net.get('net_id')
5945 dvs_portgr_name = self.create_dvPort_group(network_name)
5946 if sriov_net.get('type') == "VF" or sriov_net.get('type') == "SR-IOV":
5947 #add vlan ID ,Modify portgroup for vlan ID
5948 self.configure_vlanID(content, vcenter_conect, network_name)
5949
5950 task = self.add_sriov_to_vm(content,
5951 vm_obj,
5952 host_obj,
5953 network_name,
5954 avilable_sriov_devices[0]
5955 )
5956 if task:
5957 status= self.wait_for_vcenter_task(task, vcenter_conect)
5958 if status:
5959 self.logger.info("Added SRIOV {} to VM {}".format(
5960 no_of_sriov_devices,
5961 str(vm_obj)))
5962 else:
5963 self.logger.error("Fail to add SRIOV {} to VM {}".format(
5964 no_of_sriov_devices,
5965 str(vm_obj)))
5966 raise vimconn.vimconnUnexpectedResponse(
5967 "Fail to add SRIOV adapter in VM ".format(str(vm_obj))
5968 )
5969 return True, vm_obj, vcenter_conect
5970 else:
5971 self.logger.error("Currently there is no host with"\
5972 " {} number of avaialble SRIOV "\
5973 "VFs required for VM {}".format(
5974 no_of_sriov_devices,
5975 vmname_andid)
5976 )
5977 raise vimconn.vimconnNotFoundException(
5978 "Currently there is no host with {} "\
5979 "number of avaialble SRIOV devices required for VM {}".format(
5980 no_of_sriov_devices,
5981 vmname_andid))
5982 else:
5983 self.logger.debug("No infromation about SRIOV devices {} ",sriov_nets)
5984
5985 except vmodl.MethodFault as error:
5986 self.logger.error("Error occurred while adding SRIOV {} ",error)
5987 return None, vm_obj, vcenter_conect
5988
5989
5990 def get_sriov_devices(self,host, no_of_vfs):
5991 """
5992 Method to get the details of SRIOV devices on given host
5993 Args:
5994 host - vSphere host object
5995 no_of_vfs - number of VFs needed on host
5996
5997 Returns:
5998 array of SRIOV devices
5999 """
6000 sriovInfo=[]
6001 if host:
6002 for device in host.config.pciPassthruInfo:
6003 if isinstance(device,vim.host.SriovInfo) and device.sriovActive:
6004 if device.numVirtualFunction >= no_of_vfs:
6005 sriovInfo.append(device)
6006 break
6007 return sriovInfo
6008
6009
6010 def get_host_and_sriov_devices(self, content, no_of_vfs):
6011 """
6012 Method to get the details of SRIOV devices infromation on all hosts
6013
6014 Args:
6015 content - vSphere host object
6016 no_of_vfs - number of pci VFs needed on host
6017
6018 Returns:
6019 array of SRIOV devices and host object
6020 """
6021 host_obj = None
6022 sriov_device_objs = None
6023 try:
6024 if content:
6025 container = content.viewManager.CreateContainerView(content.rootFolder,
6026 [vim.HostSystem], True)
6027 for host in container.view:
6028 devices = self.get_sriov_devices(host, no_of_vfs)
6029 if devices:
6030 host_obj = host
6031 sriov_device_objs = devices
6032 break
6033 except Exception as exp:
6034 self.logger.error("Error {} occurred while finding SRIOV devices on host: {}".format(exp, host_obj))
6035
6036 return host_obj,sriov_device_objs
6037
6038
6039 def add_sriov_to_vm(self,content, vm_obj, host_obj, network_name, sriov_device):
6040 """
6041 Method to add SRIOV adapter to vm
6042
6043 Args:
6044 host_obj - vSphere host object
6045 vm_obj - vSphere vm object
6046 content - vCenter content object
6047 network_name - name of distributed virtaul portgroup
6048 sriov_device - SRIOV device info
6049
6050 Returns:
6051 task object
6052 """
6053 devices = []
6054 vnic_label = "sriov nic"
6055 try:
6056 dvs_portgr = self.get_dvport_group(network_name)
6057 network_name = dvs_portgr.name
6058 nic = vim.vm.device.VirtualDeviceSpec()
6059 # VM device
6060 nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
6061 nic.device = vim.vm.device.VirtualSriovEthernetCard()
6062 nic.device.addressType = 'assigned'
6063 #nic.device.key = 13016
6064 nic.device.deviceInfo = vim.Description()
6065 nic.device.deviceInfo.label = vnic_label
6066 nic.device.deviceInfo.summary = network_name
6067 nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
6068
6069 nic.device.backing.network = self.get_obj(content, [vim.Network], network_name)
6070 nic.device.backing.deviceName = network_name
6071 nic.device.backing.useAutoDetect = False
6072 nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
6073 nic.device.connectable.startConnected = True
6074 nic.device.connectable.allowGuestControl = True
6075
6076 nic.device.sriovBacking = vim.vm.device.VirtualSriovEthernetCard.SriovBackingInfo()
6077 nic.device.sriovBacking.physicalFunctionBacking = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
6078 nic.device.sriovBacking.physicalFunctionBacking.id = sriov_device.id
6079
6080 devices.append(nic)
6081 vmconf = vim.vm.ConfigSpec(deviceChange=devices)
6082 task = vm_obj.ReconfigVM_Task(vmconf)
6083 return task
6084 except Exception as exp:
6085 self.logger.error("Error {} occurred while adding SRIOV adapter in VM: {}".format(exp, vm_obj))
6086 return None
6087
6088
6089 def create_dvPort_group(self, network_name):
6090 """
6091 Method to create disributed virtual portgroup
6092
6093 Args:
6094 network_name - name of network/portgroup
6095
6096 Returns:
6097 portgroup key
6098 """
6099 try:
6100 new_network_name = [network_name, '-', str(uuid.uuid4())]
6101 network_name=''.join(new_network_name)
6102 vcenter_conect, content = self.get_vcenter_content()
6103
6104 dv_switch = self.get_obj(content, [vim.DistributedVirtualSwitch], self.dvs_name)
6105 if dv_switch:
6106 dv_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
6107 dv_pg_spec.name = network_name
6108
6109 dv_pg_spec.type = vim.dvs.DistributedVirtualPortgroup.PortgroupType.earlyBinding
6110 dv_pg_spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
6111 dv_pg_spec.defaultPortConfig.securityPolicy = vim.dvs.VmwareDistributedVirtualSwitch.SecurityPolicy()
6112 dv_pg_spec.defaultPortConfig.securityPolicy.allowPromiscuous = vim.BoolPolicy(value=False)
6113 dv_pg_spec.defaultPortConfig.securityPolicy.forgedTransmits = vim.BoolPolicy(value=False)
6114 dv_pg_spec.defaultPortConfig.securityPolicy.macChanges = vim.BoolPolicy(value=False)
6115
6116 task = dv_switch.AddDVPortgroup_Task([dv_pg_spec])
6117 self.wait_for_vcenter_task(task, vcenter_conect)
6118
6119 dvPort_group = self.get_obj(content, [vim.dvs.DistributedVirtualPortgroup], network_name)
6120 if dvPort_group:
6121 self.logger.info("Created disributed virtaul port group: {}".format(dvPort_group))
6122 return dvPort_group.key
6123 else:
6124 self.logger.debug("No disributed virtual switch found with name {}".format(network_name))
6125
6126 except Exception as exp:
6127 self.logger.error("Error occurred while creating disributed virtaul port group {}"\
6128 " : {}".format(network_name, exp))
6129 return None
6130
6131 def reconfig_portgroup(self, content, dvPort_group_name , config_info={}):
6132 """
6133 Method to reconfigure disributed virtual portgroup
6134
6135 Args:
6136 dvPort_group_name - name of disributed virtual portgroup
6137 content - vCenter content object
6138 config_info - disributed virtual portgroup configuration
6139
6140 Returns:
6141 task object
6142 """
6143 try:
6144 dvPort_group = self.get_dvport_group(dvPort_group_name)
6145 if dvPort_group:
6146 dv_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
6147 dv_pg_spec.configVersion = dvPort_group.config.configVersion
6148 dv_pg_spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
6149 if "vlanID" in config_info:
6150 dv_pg_spec.defaultPortConfig.vlan = vim.dvs.VmwareDistributedVirtualSwitch.VlanIdSpec()
6151 dv_pg_spec.defaultPortConfig.vlan.vlanId = config_info.get('vlanID')
6152
6153 task = dvPort_group.ReconfigureDVPortgroup_Task(spec=dv_pg_spec)
6154 return task
6155 else:
6156 return None
6157 except Exception as exp:
6158 self.logger.error("Error occurred while reconfiguraing disributed virtaul port group {}"\
6159 " : {}".format(dvPort_group_name, exp))
6160 return None
6161
6162
6163 def destroy_dvport_group(self , dvPort_group_name):
6164 """
6165 Method to destroy disributed virtual portgroup
6166
6167 Args:
6168 network_name - name of network/portgroup
6169
6170 Returns:
6171 True if portgroup successfully got deleted else false
6172 """
6173 vcenter_conect, content = self.get_vcenter_content()
6174 try:
6175 status = None
6176 dvPort_group = self.get_dvport_group(dvPort_group_name)
6177 if dvPort_group:
6178 task = dvPort_group.Destroy_Task()
6179 status = self.wait_for_vcenter_task(task, vcenter_conect)
6180 return status
6181 except vmodl.MethodFault as exp:
6182 self.logger.error("Caught vmodl fault {} while deleting disributed virtaul port group {}".format(
6183 exp, dvPort_group_name))
6184 return None
6185
6186
6187 def get_dvport_group(self, dvPort_group_name):
6188 """
6189 Method to get disributed virtual portgroup
6190
6191 Args:
6192 network_name - name of network/portgroup
6193
6194 Returns:
6195 portgroup object
6196 """
6197 vcenter_conect, content = self.get_vcenter_content()
6198 dvPort_group = None
6199 try:
6200 container = content.viewManager.CreateContainerView(content.rootFolder, [vim.dvs.DistributedVirtualPortgroup], True)
6201 for item in container.view:
6202 if item.key == dvPort_group_name:
6203 dvPort_group = item
6204 break
6205 return dvPort_group
6206 except vmodl.MethodFault as exp:
6207 self.logger.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
6208 exp, dvPort_group_name))
6209 return None
6210
6211 def get_vlanID_from_dvs_portgr(self, dvPort_group_name):
6212 """
6213 Method to get disributed virtual portgroup vlanID
6214
6215 Args:
6216 network_name - name of network/portgroup
6217
6218 Returns:
6219 vlan ID
6220 """
6221 vlanId = None
6222 try:
6223 dvPort_group = self.get_dvport_group(dvPort_group_name)
6224 if dvPort_group:
6225 vlanId = dvPort_group.config.defaultPortConfig.vlan.vlanId
6226 except vmodl.MethodFault as exp:
6227 self.logger.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
6228 exp, dvPort_group_name))
6229 return vlanId
6230
6231
6232 def configure_vlanID(self, content, vcenter_conect, dvPort_group_name):
6233 """
6234 Method to configure vlanID in disributed virtual portgroup vlanID
6235
6236 Args:
6237 network_name - name of network/portgroup
6238
6239 Returns:
6240 None
6241 """
6242 vlanID = self.get_vlanID_from_dvs_portgr(dvPort_group_name)
6243 if vlanID == 0:
6244 #configure vlanID
6245 vlanID = self.genrate_vlanID(dvPort_group_name)
6246 config = {"vlanID":vlanID}
6247 task = self.reconfig_portgroup(content, dvPort_group_name,
6248 config_info=config)
6249 if task:
6250 status= self.wait_for_vcenter_task(task, vcenter_conect)
6251 if status:
6252 self.logger.info("Reconfigured Port group {} for vlan ID {}".format(
6253 dvPort_group_name,vlanID))
6254 else:
6255 self.logger.error("Fail reconfigure portgroup {} for vlanID{}".format(
6256 dvPort_group_name, vlanID))
6257
6258
6259 def genrate_vlanID(self, network_name):
6260 """
6261 Method to get unused vlanID
6262 Args:
6263 network_name - name of network/portgroup
6264 Returns:
6265 vlanID
6266 """
6267 vlan_id = None
6268 used_ids = []
6269 if self.config.get('vlanID_range') == None:
6270 raise vimconn.vimconnConflictException("You must provide a 'vlanID_range' "\
6271 "at config value before creating sriov network with vlan tag")
6272 if "used_vlanIDs" not in self.persistent_info:
6273 self.persistent_info["used_vlanIDs"] = {}
6274 else:
6275 used_ids = self.persistent_info["used_vlanIDs"].values()
6276 #For python3
6277 #used_ids = list(self.persistent_info["used_vlanIDs"].values())
6278
6279 for vlanID_range in self.config.get('vlanID_range'):
6280 start_vlanid , end_vlanid = vlanID_range.split("-")
6281 if start_vlanid > end_vlanid:
6282 raise vimconn.vimconnConflictException("Invalid vlan ID range {}".format(
6283 vlanID_range))
6284
6285 for id in xrange(int(start_vlanid), int(end_vlanid) + 1):
6286 #For python3
6287 #for id in range(int(start_vlanid), int(end_vlanid) + 1):
6288 if id not in used_ids:
6289 vlan_id = id
6290 self.persistent_info["used_vlanIDs"][network_name] = vlan_id
6291 return vlan_id
6292 if vlan_id is None:
6293 raise vimconn.vimconnConflictException("All Vlan IDs are in use")
6294
6295
6296 def get_obj(self, content, vimtype, name):
6297 """
6298 Get the vsphere object associated with a given text name
6299 """
6300 obj = None
6301 container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
6302 for item in container.view:
6303 if item.name == name:
6304 obj = item
6305 break
6306 return obj
6307
6308
6309 def insert_media_to_vm(self, vapp, image_id):
6310 """
6311 Method to insert media CD-ROM (ISO image) from catalog to vm.
6312 vapp - vapp object to get vm id
6313 Image_id - image id for cdrom to be inerted to vm
6314 """
6315 # create connection object
6316 vca = self.connect()
6317 try:
6318 # fetching catalog details
6319 rest_url = "{}/api/catalog/{}".format(self.url, image_id)
6320 if vca._session:
6321 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
6322 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
6323 response = self.perform_request(req_type='GET',
6324 url=rest_url,
6325 headers=headers)
6326
6327 if response.status_code != 200:
6328 self.logger.error("REST call {} failed reason : {}"\
6329 "status code : {}".format(url_rest_call,
6330 response.content,
6331 response.status_code))
6332 raise vimconn.vimconnException("insert_media_to_vm(): Failed to get "\
6333 "catalog details")
6334 # searching iso name and id
6335 iso_name,media_id = self.get_media_details(vca, response.content)
6336
6337 if iso_name and media_id:
6338 data ="""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6339 <ns6:MediaInsertOrEjectParams
6340 xmlns="http://www.vmware.com/vcloud/versions" xmlns:ns2="http://schemas.dmtf.org/ovf/envelope/1"
6341 xmlns:ns3="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
6342 xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/common"
6343 xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
6344 xmlns:ns6="http://www.vmware.com/vcloud/v1.5"
6345 xmlns:ns7="http://www.vmware.com/schema/ovf"
6346 xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1"
6347 xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">
6348 <ns6:Media
6349 type="application/vnd.vmware.vcloud.media+xml"
6350 name="{}"
6351 id="urn:vcloud:media:{}"
6352 href="https://{}/api/media/{}"/>
6353 </ns6:MediaInsertOrEjectParams>""".format(iso_name, media_id,
6354 self.url,media_id)
6355
6356 for vms in vapp.get_all_vms():
6357 vm_id = vms.get('id').split(':')[-1]
6358
6359 headers['Content-Type'] = 'application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml'
6360 rest_url = "{}/api/vApp/vm-{}/media/action/insertMedia".format(self.url,vm_id)
6361
6362 response = self.perform_request(req_type='POST',
6363 url=rest_url,
6364 data=data,
6365 headers=headers)
6366
6367 if response.status_code != 202:
6368 error_msg = "insert_media_to_vm() : Failed to insert CD-ROM to vm. Reason {}. " \
6369 "Status code {}".format(response.text, response.status_code)
6370 self.logger.error(error_msg)
6371 raise vimconn.vimconnException(error_msg)
6372 else:
6373 task = self.get_task_from_response(response.content)
6374 result = self.client.get_task_monitor().wait_for_success(task=task)
6375 if result.get('status') == 'success':
6376 self.logger.info("insert_media_to_vm(): Sucessfully inserted media ISO"\
6377 " image to vm {}".format(vm_id))
6378
6379 except Exception as exp:
6380 self.logger.error("insert_media_to_vm() : exception occurred "\
6381 "while inserting media CD-ROM")
6382 raise vimconn.vimconnException(message=exp)
6383
6384
6385 def get_media_details(self, vca, content):
6386 """
6387 Method to get catalog item details
6388 vca - connection object
6389 content - Catalog details
6390 Return - Media name, media id
6391 """
6392 cataloghref_list = []
6393 try:
6394 if content:
6395 vm_list_xmlroot = XmlElementTree.fromstring(content)
6396 for child in vm_list_xmlroot.iter():
6397 if 'CatalogItem' in child.tag:
6398 cataloghref_list.append(child.attrib.get('href'))
6399 if cataloghref_list is not None:
6400 for href in cataloghref_list:
6401 if href:
6402 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
6403 'x-vcloud-authorization': vca._session.headers['x-vcloud-authorization']}
6404 response = self.perform_request(req_type='GET',
6405 url=href,
6406 headers=headers)
6407 if response.status_code != 200:
6408 self.logger.error("REST call {} failed reason : {}"\
6409 "status code : {}".format(href,
6410 response.content,
6411 response.status_code))
6412 raise vimconn.vimconnException("get_media_details : Failed to get "\
6413 "catalogitem details")
6414 list_xmlroot = XmlElementTree.fromstring(response.content)
6415 for child in list_xmlroot.iter():
6416 if 'Entity' in child.tag:
6417 if 'media' in child.attrib.get('href'):
6418 name = child.attrib.get('name')
6419 media_id = child.attrib.get('href').split('/').pop()
6420 return name,media_id
6421 else:
6422 self.logger.debug("Media name and id not found")
6423 return False,False
6424 except Exception as exp:
6425 self.logger.error("get_media_details : exception occurred "\
6426 "getting media details")
6427 raise vimconn.vimconnException(message=exp)
6428
6429
6430 def retry_rest(self, method, url, add_headers=None, data=None):
6431 """ Method to get Token & retry respective REST request
6432 Args:
6433 api - REST API - Can be one of 'GET' or 'PUT' or 'POST'
6434 url - request url to be used
6435 add_headers - Additional headers (optional)
6436 data - Request payload data to be passed in request
6437 Returns:
6438 response - Response of request
6439 """
6440 response = None
6441
6442 #Get token
6443 self.get_token()
6444
6445 if self.client._session:
6446 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
6447 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
6448
6449 if add_headers:
6450 headers.update(add_headers)
6451
6452 if method == 'GET':
6453 response = self.perform_request(req_type='GET',
6454 url=url,
6455 headers=headers)
6456 elif method == 'PUT':
6457 response = self.perform_request(req_type='PUT',
6458 url=url,
6459 headers=headers,
6460 data=data)
6461 elif method == 'POST':
6462 response = self.perform_request(req_type='POST',
6463 url=url,
6464 headers=headers,
6465 data=data)
6466 elif method == 'DELETE':
6467 response = self.perform_request(req_type='DELETE',
6468 url=url,
6469 headers=headers)
6470 return response
6471
6472
6473 def get_token(self):
6474 """ Generate a new token if expired
6475
6476 Returns:
6477 The return client object that letter can be used to connect to vCloud director as admin for VDC
6478 """
6479 try:
6480 self.logger.debug("Generate token for vca {} as {} to datacenter {}.".format(self.org_name,
6481 self.user,
6482 self.org_name))
6483 host = self.url
6484 client = Client(host, verify_ssl_certs=False)
6485 client.set_credentials(BasicLoginCredentials(self.user, self.org_name, self.passwd))
6486 # connection object
6487 self.client = client
6488
6489 except:
6490 raise vimconn.vimconnConnectionException("Can't connect to a vCloud director org: "
6491 "{} as user: {}".format(self.org_name, self.user))
6492
6493 if not client:
6494 raise vimconn.vimconnConnectionException("Failed while reconnecting vCD")
6495
6496
6497 def get_vdc_details(self):
6498 """ Get VDC details using pyVcloud Lib
6499
6500 Returns org and vdc object
6501 """
6502 vdc = None
6503 try:
6504 org = Org(self.client, resource=self.client.get_org())
6505 vdc = org.get_vdc(self.tenant_name)
6506 except Exception as e:
6507 # pyvcloud not giving a specific exception, Refresh nevertheless
6508 self.logger.debug("Received exception {}, refreshing token ".format(str(e)))
6509
6510 #Retry once, if failed by refreshing token
6511 if vdc is None:
6512 self.get_token()
6513 org = Org(self.client, resource=self.client.get_org())
6514 vdc = org.get_vdc(self.tenant_name)
6515
6516 return org, vdc
6517
6518
6519 def perform_request(self, req_type, url, headers=None, data=None):
6520 """Perform the POST/PUT/GET/DELETE request."""
6521
6522 #Log REST request details
6523 self.log_request(req_type, url=url, headers=headers, data=data)
6524 # perform request and return its result
6525 if req_type == 'GET':
6526 response = requests.get(url=url,
6527 headers=headers,
6528 verify=False)
6529 elif req_type == 'PUT':
6530 response = requests.put(url=url,
6531 headers=headers,
6532 data=data,
6533 verify=False)
6534 elif req_type == 'POST':
6535 response = requests.post(url=url,
6536 headers=headers,
6537 data=data,
6538 verify=False)
6539 elif req_type == 'DELETE':
6540 response = requests.delete(url=url,
6541 headers=headers,
6542 verify=False)
6543 #Log the REST response
6544 self.log_response(response)
6545
6546 return response
6547
6548
6549 def log_request(self, req_type, url=None, headers=None, data=None):
6550 """Logs REST request details"""
6551
6552 if req_type is not None:
6553 self.logger.debug("Request type: {}".format(req_type))
6554
6555 if url is not None:
6556 self.logger.debug("Request url: {}".format(url))
6557
6558 if headers is not None:
6559 for header in headers:
6560 self.logger.debug("Request header: {}: {}".format(header, headers[header]))
6561
6562 if data is not None:
6563 self.logger.debug("Request data: {}".format(data))
6564
6565
6566 def log_response(self, response):
6567 """Logs REST response details"""
6568
6569 self.logger.debug("Response status code: {} ".format(response.status_code))
6570
6571
6572 def get_task_from_response(self, content):
6573 """
6574 content - API response content(response.content)
6575 return task object
6576 """
6577 xmlroot = XmlElementTree.fromstring(content)
6578 if xmlroot.tag.split('}')[1] == "Task":
6579 return xmlroot
6580 else:
6581 for ele in xmlroot:
6582 if ele.tag.split("}")[1] == "Tasks":
6583 task = ele[0]
6584 break
6585 return task
6586
6587
6588 def power_on_vapp(self,vapp_id, vapp_name):
6589 """
6590 vapp_id - vApp uuid
6591 vapp_name - vAapp name
6592 return - Task object
6593 """
6594 headers = {'Accept':'application/*+xml;version=' + API_VERSION,
6595 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
6596
6597 poweron_href = "{}/api/vApp/vapp-{}/power/action/powerOn".format(self.url,
6598 vapp_id)
6599 response = self.perform_request(req_type='POST',
6600 url=poweron_href,
6601 headers=headers)
6602
6603 if response.status_code != 202:
6604 self.logger.error("REST call {} failed reason : {}"\
6605 "status code : {} ".format(poweron_href,
6606 response.content,
6607 response.status_code))
6608 raise vimconn.vimconnException("power_on_vapp() : Failed to power on "\
6609 "vApp {}".format(vapp_name))
6610 else:
6611 poweron_task = self.get_task_from_response(response.content)
6612 return poweron_task
6613
6614