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