1 # -*- coding: utf-8 -*-
4 # Copyright 2016-2017 VMware Inc.
5 # This file is part of ETSI OSM
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
12 # http://www.apache.org/licenses/LICENSE-2.0
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
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact: osslegalrouting@vmware.com
25 vimconn_vmware implementation an Abstract class in order to interact with VMware vCloud Director.
28 from progressbar
import Percentage
, Bar
, ETA
, FileTransferSpeed
, ProgressBar
38 from pyVmomi
import vim
, vmodl
39 from pyVim
.connect
import SmartConnect
, Disconnect
41 from xml
.etree
import ElementTree
as XmlElementTree
42 from lxml
import etree
as lxmlElementTree
45 from pyvcloud
.vcd
.client
import BasicLoginCredentials
,Client
,VcdTaskException
46 from pyvcloud
.vcd
.vdc
import VDC
47 from pyvcloud
.vcd
.org
import Org
49 from pyvcloud
.vcd
.vapp
import VApp
50 from xml
.sax
.saxutils
import escape
64 # global variable for vcd connector type
65 STANDALONE
= 'standalone'
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,
75 # global variable for wait time
81 __author__
= "Mustafa Bayramov, Arpita Kate, Sachin Bhangare, Prakash Kasar"
82 __date__
= "$09-Mar-2018 11:09:29$"
85 # -1: "Could not be created",
91 # 5: "Waiting for user input",
93 # 7: "Unrecognized state",
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"
103 # mapping vCD status to MANO
104 vcdStatusCode2manoFormat
= {4: 'ACTIVE',
113 netStatus2manoFormat
= {'ACTIVE': 'ACTIVE', 'PAUSED': 'PAUSED', 'INACTIVE': 'INACTIVE', 'BUILD': 'BUILD',
114 'ERROR': 'ERROR', 'DELETED': 'DELETED'
117 class vimconnector(vimconn
.vimconnector
):
118 # dict used to store flavor in memory
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
={}):
124 Constructor create vmware connector to vCloud director.
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.
129 a) It initialize organization UUID
130 b) Initialize tenant_id/vdc ID. (This information derived from tenant name)
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.
142 password - is password for a user.
144 VMware connector also requires PVDC administrative privileges and separate account.
145 This variables must be passed via config argument dict contains keys
147 dict['admin_username']
148 dict['admin_password']
149 config - Provide NSX and vCenter information
155 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
,
156 url_admin
, user
, passwd
, log_level
, config
)
158 self
.logger
= logging
.getLogger('openmano.vim.vmware')
159 self
.logger
.setLevel(10)
160 self
.persistent_info
= persistent_info
165 self
.url_admin
= url_admin
166 self
.tenant_id
= tenant_id
167 self
.tenant_name
= tenant_name
171 self
.admin_password
= None
172 self
.admin_user
= None
174 self
.nsx_manager
= None
176 self
.nsx_password
= None
177 self
.availability_zone
= None
179 # Disable warnings from self-signed certificates.
180 requests
.packages
.urllib3
.disable_warnings()
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]
188 self
.tenant_name
= tenant_name
189 if "orgname" in config
:
190 self
.org_name
= config
['orgname']
193 self
.logger
.setLevel(getattr(logging
, log_level
))
196 self
.admin_user
= config
['admin_username']
197 self
.admin_password
= config
['admin_password']
199 raise vimconn
.vimconnException(message
="Error admin username or admin password is empty.")
202 self
.nsx_manager
= config
['nsx_manager']
203 self
.nsx_user
= config
['nsx_user']
204 self
.nsx_password
= config
['nsx_password']
206 raise vimconn
.vimconnException(message
="Error: nsx manager or nsx user or nsx password is empty in Config")
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)
213 #Set availability zone for Affinity rules
214 self
.availability_zone
= self
.set_availability_zones()
216 # ############# Stub code for SRIOV #################
218 # self.dvs_name = config['dv_switch_name']
220 # raise vimconn.vimconnException(message="Error: distributed virtaul switch name is empty in Config")
222 # self.vlanID_range = config.get("vlanID_range", None)
228 raise vimconn
.vimconnException('url param can not be NoneType')
230 if not self
.url_admin
: # try to use normal url
231 self
.url_admin
= self
.url
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
))
238 # initialize organization
239 if self
.user
is not None and self
.passwd
is not None and self
.url
:
240 self
.init_organization()
242 def __getitem__(self
, index
):
245 if index
== 'tenant_id':
246 return self
.tenant_id
247 if index
== 'tenant_name':
248 return self
.tenant_name
251 elif index
== 'org_name':
253 elif index
== 'org_uuid':
255 elif index
== 'user':
257 elif index
== 'passwd':
261 elif index
== 'url_admin':
262 return self
.url_admin
263 elif index
== "config":
266 raise KeyError("Invalid key '%s'" % str(index
))
268 def __setitem__(self
, index
, value
):
271 if index
== 'tenant_id':
272 self
.tenant_id
= value
273 if index
== 'tenant_name':
274 self
.tenant_name
= 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':
283 elif index
== 'passwd':
287 elif index
== 'url_admin':
288 self
.url_admin
= value
290 raise KeyError("Invalid key '%s'" % str(index
))
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.
298 The return client object that latter can be used to connect to vcloud director as admin for provider vdc
301 self
.logger
.debug("Logging into vCD {} as admin.".format(self
.org_name
))
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
))
312 return client_as_admin
315 """ Method connect as normal user to vCloud director.
318 The return client object that latter can be used to connect to vCloud director as admin for VDC
322 self
.logger
.debug("Logging into vCD {} as {} to datacenter {}.".format(self
.org_name
,
326 client
= Client(host
, verify_ssl_certs
=False)
327 client
.set_credentials(BasicLoginCredentials(self
.user
, self
.org_name
, self
.passwd
))
329 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director org: "
330 "{} as user: {}".format(self
.org_name
, self
.user
))
334 def init_organization(self
):
335 """ Method initialize organization UUID and VDC parameters.
337 At bare minimum client must provide organization name that present in vCloud director and VDC.
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.
343 The return vca object that letter can be used to connect to vcloud direct as admin
345 client
= self
.connect()
347 raise vimconn
.vimconnConnectionException("Failed to connect vCD.")
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
))
360 raise vimconn
.vimconnException("Vcloud director organization {} not found".format(self
.org_name
))
362 # if well good we require for org details
363 org_details_dict
= self
.get_org(org_uuid
=self
.org_uuid
)
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
:
372 self
.logger
.debug("Setting vdc uuid {} for organization UUID {}".format(self
.tenant_id
,
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
,
387 raise vimconn
.vimconnException("Tenant id indicated but not present in vcloud director")
388 self
.logger
.debug("Setting organization uuid {}".format(self
.org_uuid
))
390 self
.logger
.debug("Failed initialize organization UUID for org {}".format(self
.org_name
))
391 self
.logger
.debug(traceback
.format_exc())
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.
399 tenant_name is tenant_name to be created.
400 tenant_description not used for this call
403 returns the tenant identifier in UUID format.
404 If action is failed method will throw vimconn.vimconnException method
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
))
412 raise vimconn
.vimconnException("Failed create tenant {}".format(tenant_name
))
414 def delete_tenant(self
, tenant_id
=None):
415 """ Delete a tenant from VIM
417 tenant_id is tenant_id to be deleted.
420 returns the tenant identifier in UUID format.
421 If action is failed method will throw exception
423 vca
= self
.connect_as_admin()
425 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
427 if tenant_id
is not None:
430 url_list
= [self
.url
, '/api/vdc/', tenant_id
]
431 orgvdc_herf
= ''.join(url_list
)
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',
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
))
445 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
446 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
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'
453 response
= self
.perform_request(req_type
='DELETE',
457 if response
.status_code
== 202:
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
))
466 self
.logger
.debug("delete_tenant():Incorrect tenant ID {}".format(tenant_id
))
467 raise vimconn
.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id
))
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
476 Returns the tenant list of dictionaries:
477 [{'name':'<name>, 'id':'<id>, ...}, ...]
480 org_dict
= self
.get_org(self
.org_uuid
)
481 vdcs_dict
= org_dict
['vdcs']
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
)
495 vdclist
.append(entry
)
497 self
.logger
.debug("Error in get_tenant_list()")
498 self
.logger
.debug(traceback
.format_exc())
499 raise vimconn
.vimconnException("Incorrect state. {}")
503 def new_network(self
, net_name
, net_type
, ip_profile
=None, shared
=False):
504 """Adds a tenant network to VIM
506 net_type can be 'bridge','data'.'ptp'.
507 ip_profile is a dict containing the IP parameters of the network
509 Returns the network identifier"""
511 self
.logger
.debug("new_network tenant {} net_type {} ip_profile {} shared {}"
512 .format(net_name
, net_type
, ip_profile
, shared
))
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)
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:
529 raise vimconn
.vimconnUnexpectedResponse("Failed create a new network {}".format(net_name
))
531 def get_vcd_network_list(self
):
532 """ Method available organization for a logged in tenant
535 The return vca object that letter can be used to connect to vcloud direct as admin
538 self
.logger
.debug("get_vcd_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
540 if not self
.tenant_name
:
541 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
543 org
, vdc
= self
.get_vdc_details()
545 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}".format(self
.tenant_name
))
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',
554 if response
.status_code
!= 200:
555 self
.logger
.error("Failed to get vdc content")
556 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
558 content
= XmlElementTree
.fromstring(response
.content
)
563 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
565 response
= self
.perform_request(req_type
='GET',
569 if response
.status_code
!= 200:
570 self
.logger
.error("Failed to get network content")
571 raise vimconn
.vimconnNotFoundException("Failed to get network content")
573 net_details
= XmlElementTree
.fromstring(response
.content
)
576 net_uuid
= net_details
.get('id').split(":")
577 if len(net_uuid
) != 4:
580 net_uuid
= net_uuid
[3]
582 self
.logger
.debug("get_vcd_network_list(): Adding network {} "
583 "to a list vcd id {} network {}".format(net_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':
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
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
))
603 self
.logger
.debug("Error in get_vcd_network_list", exc_info
=True)
606 self
.logger
.debug("get_vcd_network_list returning {}".format(network_list
))
609 def get_network_list(self
, filter_dict
={}):
610 """Obtain tenant networks of VIM
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
619 [{key : value , key : value}]
621 Returns the network list of dictionaries:
622 [{<the fields at Filter_dict plus some VIM specific>}, ...]
626 self
.logger
.debug("get_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
628 if not self
.tenant_name
:
629 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
631 org
, vdc
= self
.get_vdc_details()
633 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}.".format(self
.tenant_name
))
636 vdcid
= vdc
.get('id').split(":")[3]
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',
644 if response
.status_code
!= 200:
645 self
.logger
.error("Failed to get vdc content")
646 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
648 content
= XmlElementTree
.fromstring(response
.content
)
652 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
654 response
= self
.perform_request(req_type
='GET',
658 if response
.status_code
!= 200:
659 self
.logger
.error("Failed to get network content")
660 raise vimconn
.vimconnNotFoundException("Failed to get network content")
662 net_details
= XmlElementTree
.fromstring(response
.content
)
665 net_uuid
= net_details
.get('id').split(":")
666 if len(net_uuid
) != 4:
669 net_uuid
= net_uuid
[3]
671 self
.logger
.debug("get_network_list(): Adding net {}"
672 " to a list vcd id {} network {}".format(net_uuid
,
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':
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
686 filter_entry
["admin_state_up"] = False
687 filter_entry
["status"] = "ACTIVE"
688 filter_entry
["type"] = "bridge"
689 filtered_entry
= filter_entry
.copy()
691 if filter_dict
is not None and filter_dict
:
692 # we remove all the key : value we don't care and match only
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
)
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
):
705 raise vimconn
.vimconnNotFoundException("Failed : Networks list not found {} ".format(e
))
707 self
.logger
.debug("Returning {}".format(network_list
))
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>}, ...]"""
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',
723 if response
.status_code
!= 200:
724 self
.logger
.error("Failed to get vdc content")
725 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
727 content
= XmlElementTree
.fromstring(response
.content
)
732 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
734 response
= self
.perform_request(req_type
='GET',
738 if response
.status_code
!= 200:
739 self
.logger
.error("Failed to get network content")
740 raise vimconn
.vimconnNotFoundException("Failed to get network content")
742 net_details
= XmlElementTree
.fromstring(response
.content
)
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':
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
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
))
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
):
770 raise vimconn
.vimconnNotFoundException("Failed : Network not found {} ".format(e
))
774 def delete_network(self
, net_id
):
776 Method Deletes a tenant network from VIM, provide the network id.
778 Returns the network identifier or raise an exception
781 # ############# Stub code for SRIOV #################
782 # dvport_group = self.get_dvport_group(net_id)
785 # status = self.destroy_dvport_group(net_id)
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]
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
):
798 raise vimconn
.vimconnNotFoundException("Network {} not found".format(net_id
))
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)
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)
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':
830 errormsg
= 'Network not found.'
832 dict_entry
[net
] = {'status': status
, 'error_msg': errormsg
,
833 'vim_info': yaml
.safe_dump(vcd_network
)}
835 self
.logger
.debug("Error in refresh_nets_status")
836 self
.logger
.debug(traceback
.format_exc())
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
844 if flavor_id
not in vimconnector
.flavorlist
:
845 raise vimconn
.vimconnNotFoundException("Flavor not found.")
846 return vimconnector
.flavorlist
[flavor_id
]
848 def new_flavor(self
, flavor_data
):
849 """Adds a tenant flavor to VIM
850 flavor_data contains a dictionary with information, keys:
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
866 Returns the flavor identifier"""
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)
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")
882 extended_flv
= flavor_data
.get("extended")
884 numas
=extended_flv
.get("numas")
887 #overwrite ram and vcpus
889 ram
= numa
['memory']*1024
890 if 'paired-threads' in numa
:
891 cpu
= numa
['paired-threads']*2
892 elif 'cores' in numa
:
894 elif 'threads' in numa
:
895 cpu
= numa
['threads']
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
))
905 return str(flavor_id
)
907 def delete_flavor(self
, flavor_id
):
908 """Deletes a tenant flavor from VIM identify by its id
910 Returns the used id or raise an exception
912 if flavor_id
not in vimconnector
.flavorlist
:
913 raise vimconn
.vimconnNotFoundException("Flavor not found.")
915 vimconnector
.flavorlist
.pop(flavor_id
, None)
918 def new_image(self
, image_dict
):
920 Adds a tenant image to VIM
922 200, image-id if the image is created
923 <0, message if there is an error
926 return self
.get_image_id_from_path(image_dict
['location'])
928 def delete_image(self
, image_id
):
930 Deletes a tenant image from VIM
932 image_id is ID of Image to be deleted
934 returns the image identifier in UUID format or raises an exception on error
936 conn
= self
.connect_as_admin()
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
)
943 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
944 'x-vcloud-authorization': conn
._session
.headers
['x-vcloud-authorization']}
946 response
= self
.perform_request(req_type
='GET',
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
))
956 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
957 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
959 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
960 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
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']
967 response
= self
.perform_request(req_type
='GET',
968 url
=catalogItem_href
,
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(
979 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
980 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
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']
987 response
= self
.perform_request(req_type
='DELETE',
988 url
=catalogitem_remove_href
,
990 if response
.status_code
== requests
.codes
.no_content
:
991 self
.logger
.debug("Deleted Catalog item {}".format(catalogItem
))
993 raise vimconn
.vimconnException("Fail to delete Catalog Item {}".format(catalogItem
))
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
,
1002 if response
.status_code
== requests
.codes
.no_content
:
1003 self
.logger
.debug("Deleted Catalog {}".format(image_id
))
1006 raise vimconn
.vimconnException("Fail to delete Catalog {}".format(image_id
))
1009 def catalog_exists(self
, catalog_name
, catalogs
):
1012 :param catalog_name:
1016 for catalog
in catalogs
:
1017 if catalog
['name'] == catalog_name
:
1021 def create_vimcatalog(self
, vca
=None, catalog_name
=None):
1022 """ Create new catalog entry in vCloud director.
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.
1029 Return (bool) True if catalog created.
1033 result
= vca
.create_catalog(catalog_name
, catalog_name
)
1034 if result
is not None:
1036 catalogs
= vca
.list_catalogs()
1039 return self
.catalog_exists(catalog_name
, catalogs
)
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):
1045 Uploads a OVF file to a vCloud catalog
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.
1056 os
.path
.isfile(media_file_name
)
1057 statinfo
= os
.stat(media_file_name
)
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
1062 # if VCD can parse OVF we upload VMDK file
1064 for catalog
in vca
.list_catalogs():
1065 if catalog_name
!= catalog
['name']:
1067 catalog_href
= "{}/api/catalog/{}/action/upload".format(self
.url
, catalog
['id'])
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
)
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'
1077 response
= self
.perform_request(req_type
='POST',
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')
1089 response
= self
.perform_request(req_type
='GET',
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
)
1097 transfer_href
= result
.group(1)
1099 response
= self
.perform_request(req_type
='PUT',
1102 data
=open(media_file_name
, 'rb'))
1103 if response
.status_code
!= requests
.codes
.ok
:
1105 "Failed create vApp template for catalog name {} and image {}".format(catalog_name
,
1109 # TODO fix this with aync block
1112 self
.logger
.debug("vApp template for catalog name {} and image {}".format(catalog_name
, media_file_name
))
1114 # uploading VMDK file
1115 # check status of OVF upload and upload remaining files.
1116 response
= self
.perform_request(req_type
='GET',
1120 if response
.status_code
== requests
.codes
.ok
:
1121 result
= re
.search('rel="upload:default"\s*href="(.*?vmdk)"',response
.content
)
1123 link_href
= result
.group(1)
1124 # we skip ovf since it already uploaded.
1125 if 'ovf' in link_href
:
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
):
1132 statinfo
= os
.stat(file_vmdk
)
1133 if statinfo
.st_size
== 0:
1135 hrefvmdk
= link_href
1138 widgets
= ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
1139 FileTransferSpeed()]
1140 progress_bar
= ProgressBar(widgets
=widgets
, maxval
=statinfo
.st_size
).start()
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
,
1154 if response
.status_code
== requests
.codes
.ok
:
1155 bytes_transferred
+= len(my_bytes
)
1157 progress_bar
.update(bytes_transferred
)
1160 'file upload failed with error: [%s] %s' % (response
.status_code
,
1167 progress_bar
.finish()
1171 self
.logger
.debug("Failed retrieve vApp template for catalog name {} for OVF {}".
1172 format(catalog_name
, media_file_name
))
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
))
1181 self
.logger
.debug("Failed retrieve catalog name {} for OVF file {}".format(catalog_name
, media_file_name
))
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
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
)
1191 def validate_uuid4(self
, uuid_string
=None):
1192 """ Method validate correct format of UUID.
1194 Return: true if string represent valid uuid
1197 val
= uuid
.UUID(uuid_string
, version
=4)
1202 def get_catalogid(self
, catalog_name
=None, catalogs
=None):
1203 """ Method check catalog and return catalog ID in UUID format.
1206 catalog_name: catalog name as string
1207 catalogs: list of catalogs.
1209 Return: catalogs uuid
1212 for catalog
in catalogs
:
1213 if catalog
['name'] == catalog_name
:
1214 catalog_id
= catalog
['id']
1218 def get_catalogbyid(self
, catalog_uuid
=None, catalogs
=None):
1219 """ Method check catalog and return catalog name lookup done by catalog UUID.
1222 catalog_name: catalog name as string
1223 catalogs: list of catalogs.
1225 Return: catalogs name or None
1228 if not self
.validate_uuid4(uuid_string
=catalog_uuid
):
1231 for catalog
in catalogs
:
1232 catalog_id
= catalog
.get('id')
1233 if catalog_id
== catalog_uuid
:
1234 return catalog
.get('name')
1237 def get_catalog_obj(self
, catalog_uuid
=None, catalogs
=None):
1238 """ Method check catalog and return catalog name lookup done by catalog UUID.
1241 catalog_name: catalog name as string
1242 catalogs: list of catalogs.
1244 Return: catalogs name or None
1247 if not self
.validate_uuid4(uuid_string
=catalog_uuid
):
1250 for catalog
in catalogs
:
1251 catalog_id
= catalog
.get('id')
1252 if catalog_id
== catalog_uuid
:
1256 def get_image_id_from_path(self
, path
=None, progress
=False):
1257 """ Method upload OVF image to vCloud director.
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.
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.
1265 If method can't create catalog entry or upload a file it will throw exception.
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.
1271 path: - valid path to OVF file.
1272 progress - boolean progress bar show progress bar.
1274 Return: if image uploaded correct method will provide image catalog UUID.
1278 raise vimconn
.vimconnException("Image path can't be None.")
1280 if not os
.path
.isfile(path
):
1281 raise vimconn
.vimconnException("Can't read file. File not found.")
1283 if not os
.access(path
, os
.R_OK
):
1284 raise vimconn
.vimconnException("Can't read file. Check file permission to read.")
1286 self
.logger
.debug("get_image_id_from_path() client requesting {} ".format(path
))
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.")
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
))
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
))
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
)
1310 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1312 result
= self
.upload_vimimage(vca
=org
, catalog_name
=catalog_md5_name
,
1313 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1315 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_name
))
1316 return self
.get_catalogid(catalog_name
, catalogs
)
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
)
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
)
1331 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1333 result
= self
.upload_vimimage(vca
=org
, catalog_name
=catalog_md5_name
,
1334 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1336 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_md5_name
))
1338 return self
.get_catalogid(catalog_md5_name
, org
.list_catalogs())
1340 def get_image_list(self
, filter_dict
={}):
1341 '''Obtain tenant images from VIM
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>}, ...]
1353 org
, vdc
= self
.get_vdc_details()
1355 catalogs
= org
.list_catalogs()
1356 if len(catalogs
) == 0:
1359 for catalog
in catalogs
:
1360 catalog_uuid
= catalog
.get('id')
1361 name
= catalog
.get('name')
1363 if filter_dict
.get("name") and filter_dict
["name"] != name
:
1365 if filter_dict
.get("id") and filter_dict
["id"] != catalog_uuid
:
1367 filtered_dict
["name"] = name
1368 filtered_dict
["id"] = catalog_uuid
1369 image_list
.append(filtered_dict
)
1371 self
.logger
.debug("List of already created catalog items: {}".format(image_list
))
1373 except Exception as exp
:
1374 raise vimconn
.vimconnException("Exception occured while retriving catalog items {}".format(exp
))
1376 def get_vappid(self
, vdc
=None, vapp_name
=None):
1377 """ Method takes vdc object and vApp name and returns vapp uuid or None
1380 vdc: The VDC object.
1381 vapp_name: is application vappp name identifier
1384 The return vApp name otherwise None
1386 if vdc
is None or vapp_name
is None:
1388 # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
1390 refs
= filter(lambda ref
: ref
.name
== vapp_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1391 vdc
.ResourceEntities
.ResourceEntity
)
1393 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1394 # if ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1396 return refs
[0].href
.split("vapp")[1][1:]
1397 except Exception as e
:
1398 self
.logger
.exception(e
)
1402 def check_vapp(self
, vdc
=None, vapp_uuid
=None):
1403 """ Method Method returns True or False if vapp deployed in vCloud director
1406 vca: Connector to VCA
1407 vdc: The VDC object.
1408 vappid: vappid is application identifier
1411 The return True if vApp deployed
1416 refs
= filter(lambda ref
:
1417 ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1418 vdc
.ResourceEntities
.ResourceEntity
)
1420 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1421 # if ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1423 vappid
= ref
.href
.split("vapp")[1][1:]
1424 # find vapp with respected vapp uuid
1425 if vappid
== vapp_uuid
:
1427 except Exception as e
:
1428 self
.logger
.exception(e
)
1432 def get_namebyvappid(self
, vapp_uuid
=None):
1433 """Method returns vApp name from vCD and lookup done by vapp_id.
1436 vapp_uuid: vappid is application identifier
1439 The return vApp name otherwise None
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']}
1447 response
= self
.perform_request(req_type
='GET',
1450 #Retry login if session expired & retry sending request
1451 if response
.status_code
== 403:
1452 response
= self
.retry_rest('GET', vapp_call
)
1454 tree
= XmlElementTree
.fromstring(response
.content
)
1455 return tree
.attrib
['name']
1456 except Exception as e
:
1457 self
.logger
.exception(e
)
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
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, e1000, ...
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
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
))
1521 #new vm name = vmname + tenant_id + uuid
1522 new_vm_name
= [name
, '-', str(uuid
.uuid4())]
1523 vmname_andid
= ''.join(new_vm_name
)
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']))
1530 if len(net_list
) > 10:
1531 raise vimconn
.vimconnNotSupportedException(
1532 "The VM hardware versions 7 and above support upto 10 NICs only")
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()
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
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
))
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
))
1554 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1555 "(Failed retrieve catalog information {})".format(name
, image_id
))
1557 # Set vCPU and Memory based on flavor.
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
))
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)
1576 numas
=extended
.get("numas", None)
1578 except Exception as exp
:
1579 raise vimconn
.vimconnException("Corrupted flavor. {}.Exception: {}".format(flavor_id
, exp
))
1581 # image upload creates template name as catalog name space Template.
1582 templateName
= self
.get_catalogbyid(catalog_uuid
=image_id
, catalogs
=catalogs
)
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.
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
:
1598 if primary_net
is None:
1599 primary_net
= net_list
[0]
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']
1610 raise vimconn
.vimconnException("Corrupted flavor. {}".format(primary_net
))
1612 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed network list is empty.".format(name
))
1614 # use: 'data', 'bridge', 'mgmt'
1615 # create vApp. Set vcpu and ram based on flavor id.
1617 vdc_obj
= VDC(self
.client
, resource
=org
.get_vdc(self
.tenant_name
))
1619 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed to get VDC object")
1622 items
= org
.get_catalog_item(catalog_hash_name
, catalog_hash_name
)
1623 catalog_items
= [items
.attrib
]
1625 if len(catalog_items
) == 1:
1627 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
1628 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
1630 response
= self
.perform_request(req_type
='GET',
1631 url
=catalog_items
[0].get('href'),
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")
1637 response
= self
.perform_request(req_type
='GET',
1638 url
=vapp_tempalte_href
,
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
))
1644 result
= (response
.content
).replace("\n"," ")
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
)
1650 vm_name
= src
.group(1)
1651 vm_id
= src
.group(2)
1652 vm_href
= src
.group(3)
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)
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
,
1662 data
= """<?xml version="1.0" encoding="UTF-8"?>
1663 <InstantiateVAppTemplateParams
1664 xmlns="http://www.vmware.com/vcloud/v1.5"
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="{}">
1676 <ParentNetwork href="{}" />
1677 <FenceMode>bridged</FenceMode>
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>
1690 <Source href="{}" id="{}" name="{}"
1691 type="application/vnd.vmware.vcloud.vm+xml"/>
1693 <NeedsCustomization>false</NeedsCustomization>
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>
1726 </ovf:VirtualHardwareSection>
1727 </InstantiationParams>
1729 <AllEULAsAccepted>false</AllEULAsAccepted>
1730 </InstantiateVAppTemplateParams>""".format(vmname_andid
,
1742 response
= self
.perform_request(req_type
='POST',
1743 url
=instantiate_vapp_href
,
1747 if response
.status_code
!= 201:
1748 self
.logger
.error("REST call {} failed reason : {}"\
1749 "status code : {}".format(instantiate_vapp_href
,
1751 response
.status_code
))
1752 raise vimconn
.vimconnException("new_vminstance(): Failed to create"\
1753 "vAapp {}".format(vmname_andid
))
1755 vapptask
= self
.get_task_from_response(response
.content
)
1757 if vapptask
is None and retry
==1:
1758 self
.get_token() # Retry getting token
1763 if vapptask
is None or vapptask
is False:
1764 raise vimconn
.vimconnUnexpectedResponse(
1765 "new_vminstance(): failed to create vApp {}".format(vmname_andid
))
1767 # wait for task to complete
1768 result
= self
.client
.get_task_monitor().wait_for_success(task
=vapptask
)
1770 if result
.get('status') == 'success':
1771 self
.logger
.debug("new_vminstance(): Sucessfully created Vapp {}".format(vmname_andid
))
1773 raise vimconn
.vimconnUnexpectedResponse(
1774 "new_vminstance(): failed to create vApp {}".format(vmname_andid
))
1776 except Exception as exp
:
1777 raise vimconn
.vimconnUnexpectedResponse(
1778 "new_vminstance(): failed to create vApp {} with Exception:{}".format(vmname_andid
, exp
))
1780 # we should have now vapp in undeployed state.
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
)
1787 except Exception as exp
:
1788 raise vimconn
.vimconnUnexpectedResponse(
1789 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
1790 .format(vmname_andid
, exp
))
1792 if vapp_uuid
is None:
1793 raise vimconn
.vimconnUnexpectedResponse(
1794 "new_vminstance(): Failed to retrieve vApp {} after creation".format(
1797 #Add PCI passthrough/SRIOV configrations
1799 pci_devices_info
= []
1800 reserve_memory
= False
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
1809 if len(pci_devices_info
) > 0:
1810 self
.logger
.info("Need to add PCI devices {} into VM {}".format(pci_devices_info
,
1812 PCI_devices_status
, vm_obj
, vcenter_conect
= self
.add_pci_devices(vapp_uuid
,
1815 if PCI_devices_status
:
1816 self
.logger
.info("Added PCI devives {} to VM {}".format(
1820 reserve_memory
= True
1822 self
.logger
.info("Fail to add PCI devives {} to VM {}".format(
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
)
1832 self
.logger
.debug("Modified Disk size of VM {} ".format(vmname_andid
))
1834 #Add new or existing disks to vApp
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
,
1852 added_existing_disk
= True
1854 #Wait till added existing disk gets reflected into vCD database/API
1855 if added_existing_disk
:
1857 added_existing_disk
= False
1858 self
.add_new_disk(vapp_uuid
, disk
['size'])
1861 # Assigning numa affinity setting
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
)
1867 # add NICs & connect to networks in netlist
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]
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
)
1878 self
.logger
.info("Request to connect VM to a network: {}".format(net_list
))
1879 primary_nic_index
= 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'}]
1887 if 'net_id' not in net
:
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
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']
1898 if interface_network_mode
== 'mgmt':
1899 primary_nic_index
= nicIndex
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.)"""
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())
1910 #nets = [n for n in self.get_network_list() if n.get('name') == interface_net_name]
1912 self
.logger
.info("new_vminstance(): Found requested network: {}".format(nets
[0].get('name')))
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'))
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
1923 if net
['model'] is not None:
1924 if net
['model'].lower() == 'paravirt' or net
['model'].lower() == 'virtio':
1925 nic_type
= 'VMXNET3'
1927 nic_type
= net
['model']
1929 self
.logger
.info("new_vminstance(): adding network adapter "\
1930 "to a network {}".format(nets
[0].get('name')))
1931 self
.add_network_adapter_to_vms(vapp
, nets
[0].get('name'),
1937 self
.logger
.info("new_vminstance(): adding network adapter "\
1938 "to a network {}".format(nets
[0].get('name')))
1939 nic_type
= 'VMXNET3'
1940 if net
['type'] in ['SR-IOV', 'VF']:
1941 nic_type
= net
['type']
1942 self
.add_network_adapter_to_vms(vapp
, nets
[0].get('name'),
1949 # cloud-init for ssh-key injection
1951 self
.cloud_init(vapp
,cloud_config
)
1953 # If VM has PCI devices or SRIOV reserve memory for VM
1955 self
.reserve_memory_for_all_vms(vapp
, memory_mb
)
1957 self
.logger
.debug("new_vminstance(): starting power on vApp {} ".format(vmname_andid
))
1959 poweron_task
= self
.power_on_vapp(vapp_id
, vmname_andid
)
1960 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
1961 if result
.get('status') == 'success':
1962 self
.logger
.info("new_vminstance(): Successfully power on "\
1963 "vApp {}".format(vmname_andid
))
1965 self
.logger
.error("new_vminstance(): failed to power on vApp "\
1966 "{}".format(vmname_andid
))
1968 except Exception as exp
:
1969 # it might be a case if specific mandatory entry in dict is empty or some other pyVcloud exception
1970 self
.logger
.error("new_vminstance(): Failed create new vm instance {} with exception {}"
1972 raise vimconn
.vimconnException("new_vminstance(): Failed create new vm instance {} with exception {}"
1975 # check if vApp deployed and if that the case return vApp UUID otherwise -1
1978 while wait_time
<= MAX_WAIT_TIME
:
1980 vapp_resource
= vdc_obj
.get_vapp(vmname_andid
)
1981 vapp
= VApp(self
.client
, resource
=vapp_resource
)
1982 except Exception as exp
:
1983 raise vimconn
.vimconnUnexpectedResponse(
1984 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
1985 .format(vmname_andid
, exp
))
1987 #if vapp and vapp.me.deployed:
1988 if vapp
and vapp_resource
.get('deployed') == 'true':
1989 vapp_uuid
= vapp_resource
.get('id').split(':')[-1]
1992 self
.logger
.debug("new_vminstance(): Wait for vApp {} to deploy".format(name
))
1993 time
.sleep(INTERVAL_TIME
)
1995 wait_time
+=INTERVAL_TIME
1997 #SET Affinity Rule for VM
1998 #Pre-requisites: User has created Hosh Groups in vCenter with respective Hosts to be used
1999 #While creating VIM account user has to pass the Host Group names in availability_zone list
2000 #"availability_zone" is a part of VIM "config" parameters
2001 #For example, in VIM config: "availability_zone":["HG_170","HG_174","HG_175"]
2002 #Host groups are referred as availability zones
2003 #With following procedure, deployed VM will be added into a VM group.
2004 #Then A VM to Host Affinity rule will be created using the VM group & Host group.
2005 if(availability_zone_list
):
2006 self
.logger
.debug("Existing Host Groups in VIM {}".format(self
.config
.get('availability_zone')))
2007 #Admin access required for creating Affinity rules
2008 client
= self
.connect_as_admin()
2010 raise vimconn
.vimconnConnectionException("Failed to connect vCD as admin")
2012 self
.client
= client
2014 headers
= {'Accept':'application/*+xml;version=27.0',
2015 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2016 #Step1: Get provider vdc details from organization
2017 pvdc_href
= self
.get_pvdc_for_org(self
.tenant_name
, headers
)
2018 if pvdc_href
is not None:
2019 #Step2: Found required pvdc, now get resource pool information
2020 respool_href
= self
.get_resource_pool_details(pvdc_href
, headers
)
2021 if respool_href
is None:
2022 #Raise error if respool_href not found
2023 msg
= "new_vminstance():Error in finding resource pool details in pvdc {}"\
2025 self
.log_message(msg
)
2027 #Step3: Verify requested availability zone(hostGroup) is present in vCD
2028 # get availability Zone
2029 vm_az
= self
.get_vm_availability_zone(availability_zone_index
, availability_zone_list
)
2030 # check if provided av zone(hostGroup) is present in vCD VIM
2031 status
= self
.check_availibility_zone(vm_az
, respool_href
, headers
)
2033 msg
= "new_vminstance(): Error in finding availability zone(Host Group): {} in "\
2034 "resource pool {} status: {}".format(vm_az
,respool_href
,status
)
2035 self
.log_message(msg
)
2037 self
.logger
.debug ("new_vminstance(): Availability zone {} found in VIM".format(vm_az
))
2039 #Step4: Find VM group references to create vm group
2040 vmgrp_href
= self
.find_vmgroup_reference(respool_href
, headers
)
2041 if vmgrp_href
== None:
2042 msg
= "new_vminstance(): No reference to VmGroup found in resource pool"
2043 self
.log_message(msg
)
2045 #Step5: Create a VmGroup with name az_VmGroup
2046 vmgrp_name
= vm_az
+ "_" + name
#Formed VM Group name = Host Group name + VM name
2047 status
= self
.create_vmgroup(vmgrp_name
, vmgrp_href
, headers
)
2048 if status
is not True:
2049 msg
= "new_vminstance(): Error in creating VM group {}".format(vmgrp_name
)
2050 self
.log_message(msg
)
2052 #VM Group url to add vms to vm group
2053 vmgrpname_url
= self
.url
+ "/api/admin/extension/vmGroup/name/"+ vmgrp_name
2055 #Step6: Add VM to VM Group
2056 #Find VM uuid from vapp_uuid
2057 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
2058 vm_uuid
= vm_details
['vmuuid']
2060 status
= self
.add_vm_to_vmgroup(vm_uuid
, vmgrpname_url
, vmgrp_name
, headers
)
2061 if status
is not True:
2062 msg
= "new_vminstance(): Error in adding VM to VM group {}".format(vmgrp_name
)
2063 self
.log_message(msg
)
2065 #Step7: Create VM to Host affinity rule
2066 addrule_href
= self
.get_add_rule_reference (respool_href
, headers
)
2067 if addrule_href
is None:
2068 msg
= "new_vminstance(): Error in finding href to add rule in resource pool: {}"\
2069 .format(respool_href
)
2070 self
.log_message(msg
)
2072 status
= self
.create_vm_to_host_affinity_rule(addrule_href
, vmgrp_name
, vm_az
, "Affinity", headers
)
2074 msg
= "new_vminstance(): Error in creating affinity rule for VM {} in Host group {}"\
2075 .format(name
, vm_az
)
2076 self
.log_message(msg
)
2078 self
.logger
.debug("new_vminstance(): Affinity rule created successfully. Added {} in Host group {}"\
2079 .format(name
, vm_az
))
2080 #Reset token to a normal user to perform other operations
2083 if vapp_uuid
is not None:
2084 return vapp_uuid
, None
2086 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed create new vm instance {}".format(name
))
2089 def get_vcd_availibility_zones(self
,respool_href
, headers
):
2090 """ Method to find presence of av zone is VIM resource pool
2093 respool_href - resource pool href
2094 headers - header information
2097 vcd_az - list of azone present in vCD
2101 resp
= self
.perform_request(req_type
='GET',url
=respool_href
, headers
=headers
)
2103 if resp
.status_code
!= requests
.codes
.ok
:
2104 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(url
, resp
.status_code
))
2106 #Get the href to hostGroups and find provided hostGroup is present in it
2107 resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2108 for child
in resp_xml
:
2109 if 'VMWProviderVdcResourcePool' in child
.tag
:
2110 for schild
in child
:
2111 if 'Link' in schild
.tag
:
2112 if schild
.attrib
.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
2113 hostGroup
= schild
.attrib
.get('href')
2114 hg_resp
= self
.perform_request(req_type
='GET',url
=hostGroup
, headers
=headers
)
2115 if hg_resp
.status_code
!= requests
.codes
.ok
:
2116 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(hostGroup
, hg_resp
.status_code
))
2118 hg_resp_xml
= XmlElementTree
.fromstring(hg_resp
.content
)
2119 for hostGroup
in hg_resp_xml
:
2120 if 'HostGroup' in hostGroup
.tag
:
2121 #append host group name to the list
2122 vcd_az
.append(hostGroup
.attrib
.get("name"))
2126 def set_availability_zones(self
):
2128 Set vim availability zone
2131 vim_availability_zones
= None
2132 availability_zone
= None
2133 if 'availability_zone' in self
.config
:
2134 vim_availability_zones
= self
.config
.get('availability_zone')
2135 if isinstance(vim_availability_zones
, str):
2136 availability_zone
= [vim_availability_zones
]
2137 elif isinstance(vim_availability_zones
, list):
2138 availability_zone
= vim_availability_zones
2140 return availability_zone
2142 return availability_zone
2145 def get_vm_availability_zone(self
, availability_zone_index
, availability_zone_list
):
2147 Return the availability zone to be used by the created VM.
2148 returns: The VIM availability zone to be used or None
2150 if availability_zone_index
is None:
2151 if not self
.config
.get('availability_zone'):
2153 elif isinstance(self
.config
.get('availability_zone'), str):
2154 return self
.config
['availability_zone']
2156 return self
.config
['availability_zone'][0]
2158 vim_availability_zones
= self
.availability_zone
2160 # check if VIM offer enough availability zones describe in the VNFD
2161 if vim_availability_zones
and len(availability_zone_list
) <= len(vim_availability_zones
):
2162 # check if all the names of NFV AV match VIM AV names
2163 match_by_index
= False
2164 for av
in availability_zone_list
:
2165 if av
not in vim_availability_zones
:
2166 match_by_index
= True
2169 self
.logger
.debug("Required Availability zone or Host Group not found in VIM config")
2170 self
.logger
.debug("Input Availability zone list: {}".format(availability_zone_list
))
2171 self
.logger
.debug("VIM configured Availability zones: {}".format(vim_availability_zones
))
2172 self
.logger
.debug("VIM Availability zones will be used by index")
2173 return vim_availability_zones
[availability_zone_index
]
2175 return availability_zone_list
[availability_zone_index
]
2177 raise vimconn
.vimconnConflictException("No enough availability zones at VIM for this deployment")
2180 def create_vm_to_host_affinity_rule(self
, addrule_href
, vmgrpname
, hostgrpname
, polarity
, headers
):
2181 """ Method to create VM to Host Affinity rule in vCD
2184 addrule_href - href to make a POST request
2185 vmgrpname - name of the VM group created
2186 hostgrpnmae - name of the host group created earlier
2187 polarity - Affinity or Anti-affinity (default: Affinity)
2188 headers - headers to make REST call
2191 True- if rule is created
2192 False- Failed to create rule due to some error
2196 rule_name
= polarity
+ "_" + vmgrpname
2197 payload
= """<?xml version="1.0" encoding="UTF-8"?>
2198 <vmext:VMWVmHostAffinityRule
2199 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
2200 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
2201 type="application/vnd.vmware.admin.vmwVmHostAffinityRule+xml">
2202 <vcloud:Name>{}</vcloud:Name>
2203 <vcloud:IsEnabled>true</vcloud:IsEnabled>
2204 <vcloud:IsMandatory>true</vcloud:IsMandatory>
2205 <vcloud:Polarity>{}</vcloud:Polarity>
2206 <vmext:HostGroupName>{}</vmext:HostGroupName>
2207 <vmext:VmGroupName>{}</vmext:VmGroupName>
2208 </vmext:VMWVmHostAffinityRule>""".format(rule_name
, polarity
, hostgrpname
, vmgrpname
)
2210 resp
= self
.perform_request(req_type
='POST',url
=addrule_href
, headers
=headers
, data
=payload
)
2212 if resp
.status_code
!= requests
.codes
.accepted
:
2213 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(addrule_href
, resp
.status_code
))
2217 affinity_task
= self
.get_task_from_response(resp
.content
)
2218 self
.logger
.debug ("affinity_task: {}".format(affinity_task
))
2219 if affinity_task
is None or affinity_task
is False:
2220 raise vimconn
.vimconnUnexpectedResponse("failed to find affinity task")
2221 # wait for task to complete
2222 result
= self
.client
.get_task_monitor().wait_for_success(task
=affinity_task
)
2223 if result
.get('status') == 'success':
2224 self
.logger
.debug("Successfully created affinity rule {}".format(rule_name
))
2227 raise vimconn
.vimconnUnexpectedResponse(
2228 "failed to create affinity rule {}".format(rule_name
))
2231 def get_add_rule_reference (self
, respool_href
, headers
):
2232 """ This method finds href to add vm to host affinity rule to vCD
2235 respool_href- href to resource pool
2236 headers- header information to make REST call
2239 None - if no valid href to add rule found or
2240 addrule_href - href to add vm to host affinity rule of resource pool
2243 resp
= self
.perform_request(req_type
='GET',url
=respool_href
, headers
=headers
)
2245 if resp
.status_code
!= requests
.codes
.ok
:
2246 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(respool_href
, resp
.status_code
))
2249 resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2250 for child
in resp_xml
:
2251 if 'VMWProviderVdcResourcePool' in child
.tag
:
2252 for schild
in child
:
2253 if 'Link' in schild
.tag
:
2254 if schild
.attrib
.get('type') == "application/vnd.vmware.admin.vmwVmHostAffinityRule+xml" and \
2255 schild
.attrib
.get('rel') == "add":
2256 addrule_href
= schild
.attrib
.get('href')
2262 def add_vm_to_vmgroup(self
, vm_uuid
, vmGroupNameURL
, vmGroup_name
, headers
):
2263 """ Method to add deployed VM to newly created VM Group.
2264 This is required to create VM to Host affinity in vCD
2267 vm_uuid- newly created vm uuid
2268 vmGroupNameURL- URL to VM Group name
2269 vmGroup_name- Name of VM group created
2270 headers- Headers for REST request
2273 True- if VM added to VM group successfully
2274 False- if any error encounter
2277 addvm_resp
= self
.perform_request(req_type
='GET',url
=vmGroupNameURL
, headers
=headers
)#, data=payload)
2279 if addvm_resp
.status_code
!= requests
.codes
.ok
:
2280 self
.logger
.debug ("REST API call to get VM Group Name url {} failed. Return status code {}"\
2281 .format(vmGroupNameURL
, addvm_resp
.status_code
))
2284 resp_xml
= XmlElementTree
.fromstring(addvm_resp
.content
)
2285 for child
in resp_xml
:
2286 if child
.tag
.split('}')[1] == 'Link':
2287 if child
.attrib
.get("rel") == "addVms":
2288 addvmtogrpURL
= child
.attrib
.get("href")
2291 url_list
= [self
.url
, '/api/vApp/vm-',vm_uuid
]
2292 vmdetailsURL
= ''.join(url_list
)
2294 resp
= self
.perform_request(req_type
='GET',url
=vmdetailsURL
, headers
=headers
)
2296 if resp
.status_code
!= requests
.codes
.ok
:
2297 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(vmdetailsURL
, resp
.status_code
))
2301 resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2302 if resp_xml
.tag
.split('}')[1] == "Vm":
2303 vm_id
= resp_xml
.attrib
.get("id")
2304 vm_name
= resp_xml
.attrib
.get("name")
2305 vm_href
= resp_xml
.attrib
.get("href")
2306 #print vm_id, vm_name, vm_href
2307 #Add VM into VMgroup
2308 payload
= """<?xml version="1.0" encoding="UTF-8"?>\
2309 <ns2:Vms xmlns:ns2="http://www.vmware.com/vcloud/v1.5" \
2310 xmlns="http://www.vmware.com/vcloud/versions" \
2311 xmlns:ns3="http://schemas.dmtf.org/ovf/envelope/1" \
2312 xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" \
2313 xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/common" \
2314 xmlns:ns6="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" \
2315 xmlns:ns7="http://www.vmware.com/schema/ovf" \
2316 xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1" \
2317 xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">\
2318 <ns2:VmReference href="{}" id="{}" name="{}" \
2319 type="application/vnd.vmware.vcloud.vm+xml" />\
2320 </ns2:Vms>""".format(vm_href
, vm_id
, vm_name
)
2322 addvmtogrp_resp
= self
.perform_request(req_type
='POST',url
=addvmtogrpURL
, headers
=headers
, data
=payload
)
2324 if addvmtogrp_resp
.status_code
!= requests
.codes
.accepted
:
2325 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(addvmtogrpURL
, addvmtogrp_resp
.status_code
))
2328 self
.logger
.debug ("Done adding VM {} to VMgroup {}".format(vm_name
, vmGroup_name
))
2332 def create_vmgroup(self
, vmgroup_name
, vmgroup_href
, headers
):
2333 """Method to create a VM group in vCD
2336 vmgroup_name : Name of VM group to be created
2337 vmgroup_href : href for vmgroup
2338 headers- Headers for REST request
2340 #POST to add URL with required data
2341 vmgroup_status
= False
2342 payload
= """<VMWVmGroup xmlns="http://www.vmware.com/vcloud/extension/v1.5" \
2343 xmlns:vcloud_v1.5="http://www.vmware.com/vcloud/v1.5" name="{}">\
2344 <vmCount>1</vmCount>\
2345 </VMWVmGroup>""".format(vmgroup_name
)
2346 resp
= self
.perform_request(req_type
='POST',url
=vmgroup_href
, headers
=headers
, data
=payload
)
2348 if resp
.status_code
!= requests
.codes
.accepted
:
2349 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(vmgroup_href
, resp
.status_code
))
2350 return vmgroup_status
2352 vmgroup_task
= self
.get_task_from_response(resp
.content
)
2353 if vmgroup_task
is None or vmgroup_task
is False:
2354 raise vimconn
.vimconnUnexpectedResponse(
2355 "create_vmgroup(): failed to create VM group {}".format(vmgroup_name
))
2357 # wait for task to complete
2358 result
= self
.client
.get_task_monitor().wait_for_success(task
=vmgroup_task
)
2360 if result
.get('status') == 'success':
2361 self
.logger
.debug("create_vmgroup(): Successfully created VM group {}".format(vmgroup_name
))
2363 vmgroup_status
= True
2364 return vmgroup_status
2366 raise vimconn
.vimconnUnexpectedResponse(\
2367 "create_vmgroup(): failed to create VM group {}".format(vmgroup_name
))
2370 def find_vmgroup_reference(self
, url
, headers
):
2371 """ Method to create a new VMGroup which is required to add created VM
2373 url- resource pool href
2374 headers- header information
2377 returns href to VM group to create VM group
2379 #Perform GET on resource pool to find 'add' link to create VMGroup
2380 #https://vcd-ip/api/admin/extension/providervdc/<providervdc id>/resourcePools
2382 resp
= self
.perform_request(req_type
='GET',url
=url
, headers
=headers
)
2384 if resp
.status_code
!= requests
.codes
.ok
:
2385 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(url
, resp
.status_code
))
2387 #Get the href to add vmGroup to vCD
2388 resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2389 for child
in resp_xml
:
2390 if 'VMWProviderVdcResourcePool' in child
.tag
:
2391 for schild
in child
:
2392 if 'Link' in schild
.tag
:
2393 #Find href with type VMGroup and rel with add
2394 if schild
.attrib
.get('type') == "application/vnd.vmware.admin.vmwVmGroupType+xml"\
2395 and schild
.attrib
.get('rel') == "add":
2396 vmgrp_href
= schild
.attrib
.get('href')
2400 def check_availibility_zone(self
, az
, respool_href
, headers
):
2401 """ Method to verify requested av zone is present or not in provided
2405 az - name of hostgroup (availibility_zone)
2406 respool_href - Resource Pool href
2407 headers - Headers to make REST call
2409 az_found - True if availibility_zone is found else False
2412 headers
['Accept']='application/*+xml;version=27.0'
2413 resp
= self
.perform_request(req_type
='GET',url
=respool_href
, headers
=headers
)
2415 if resp
.status_code
!= requests
.codes
.ok
:
2416 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(respool_href
, resp
.status_code
))
2418 #Get the href to hostGroups and find provided hostGroup is present in it
2419 resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2421 for child
in resp_xml
:
2422 if 'VMWProviderVdcResourcePool' in child
.tag
:
2423 for schild
in child
:
2424 if 'Link' in schild
.tag
:
2425 if schild
.attrib
.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
2426 hostGroup_href
= schild
.attrib
.get('href')
2427 hg_resp
= self
.perform_request(req_type
='GET',url
=hostGroup_href
, headers
=headers
)
2428 if hg_resp
.status_code
!= requests
.codes
.ok
:
2429 self
.logger
.debug ("REST API call {} failed. Return status code {}".format(hostGroup_href
, hg_resp
.status_code
))
2431 hg_resp_xml
= XmlElementTree
.fromstring(hg_resp
.content
)
2432 for hostGroup
in hg_resp_xml
:
2433 if 'HostGroup' in hostGroup
.tag
:
2434 if hostGroup
.attrib
.get("name") == az
:
2440 def get_pvdc_for_org(self
, org_vdc
, headers
):
2441 """ This method gets provider vdc references from organisation
2444 org_vdc - name of the organisation VDC to find pvdc
2445 headers - headers to make REST call
2448 None - if no pvdc href found else
2449 pvdc_href - href to pvdc
2452 #Get provider VDC references from vCD
2454 #url = '<vcd url>/api/admin/extension/providerVdcReferences'
2455 url_list
= [self
.url
, '/api/admin/extension/providerVdcReferences']
2456 url
= ''.join(url_list
)
2458 response
= self
.perform_request(req_type
='GET',url
=url
, headers
=headers
)
2459 if response
.status_code
!= requests
.codes
.ok
:
2460 self
.logger
.debug ("REST API call {} failed. Return status code {}"\
2461 .format(url
, response
.status_code
))
2463 xmlroot_response
= XmlElementTree
.fromstring(response
.content
)
2464 for child
in xmlroot_response
:
2465 if 'ProviderVdcReference' in child
.tag
:
2466 pvdc_href
= child
.attrib
.get('href')
2467 #Get vdcReferences to find org
2468 pvdc_resp
= self
.perform_request(req_type
='GET',url
=pvdc_href
, headers
=headers
)
2469 if pvdc_resp
.status_code
!= requests
.codes
.ok
:
2470 raise vimconn
.vimconnException("REST API call {} failed. "\
2471 "Return status code {}"\
2472 .format(url
, pvdc_resp
.status_code
))
2474 pvdc_resp_xml
= XmlElementTree
.fromstring(pvdc_resp
.content
)
2475 for child
in pvdc_resp_xml
:
2476 if 'Link' in child
.tag
:
2477 if child
.attrib
.get('type') == "application/vnd.vmware.admin.vdcReferences+xml":
2478 vdc_href
= child
.attrib
.get('href')
2480 #Check if provided org is present in vdc
2481 vdc_resp
= self
.perform_request(req_type
='GET',
2484 if vdc_resp
.status_code
!= requests
.codes
.ok
:
2485 raise vimconn
.vimconnException("REST API call {} failed. "\
2486 "Return status code {}"\
2487 .format(url
, vdc_resp
.status_code
))
2488 vdc_resp_xml
= XmlElementTree
.fromstring(vdc_resp
.content
)
2489 for child
in vdc_resp_xml
:
2490 if 'VdcReference' in child
.tag
:
2491 if child
.attrib
.get('name') == org_vdc
:
2495 def get_resource_pool_details(self
, pvdc_href
, headers
):
2496 """ Method to get resource pool information.
2497 Host groups are property of resource group.
2498 To get host groups, we need to GET details of resource pool.
2501 pvdc_href: href to pvdc details
2505 respool_href - Returns href link reference to resource pool
2508 resp
= self
.perform_request(req_type
='GET',url
=pvdc_href
, headers
=headers
)
2510 if resp
.status_code
!= requests
.codes
.ok
:
2511 self
.logger
.debug ("REST API call {} failed. Return status code {}"\
2512 .format(pvdc_href
, resp
.status_code
))
2514 respool_resp_xml
= XmlElementTree
.fromstring(resp
.content
)
2515 for child
in respool_resp_xml
:
2516 if 'Link' in child
.tag
:
2517 if child
.attrib
.get('type') == "application/vnd.vmware.admin.vmwProviderVdcResourcePoolSet+xml":
2518 respool_href
= child
.attrib
.get("href")
2523 def log_message(self
, msg
):
2525 Method to log error messages related to Affinity rule creation
2526 in new_vminstance & raise Exception
2528 msg - Error message to be logged
2531 #get token to connect vCD as a normal user
2533 self
.logger
.debug(msg
)
2534 raise vimconn
.vimconnException(msg
)
2539 ## based on current discussion
2543 # created: '2016-09-08T11:51:58'
2544 # description: simple-instance.linux1.1
2545 # flavor: ddc6776e-75a9-11e6-ad5f-0800273e724c
2546 # hostId: e836c036-74e7-11e6-b249-0800273e724c
2547 # image: dde30fe6-75a9-11e6-ad5f-0800273e724c
2552 def get_vminstance(self
, vim_vm_uuid
=None):
2553 """Returns the VM instance information from VIM"""
2555 self
.logger
.debug("Client requesting vm instance {} ".format(vim_vm_uuid
))
2557 org
, vdc
= self
.get_vdc_details()
2559 raise vimconn
.vimconnConnectionException(
2560 "Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2562 vm_info_dict
= self
.get_vapp_details_rest(vapp_uuid
=vim_vm_uuid
)
2563 if not vm_info_dict
:
2564 self
.logger
.debug("get_vminstance(): Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
2565 raise vimconn
.vimconnNotFoundException("Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
2567 status_key
= vm_info_dict
['status']
2570 vm_dict
= {'created': vm_info_dict
['created'],
2571 'description': vm_info_dict
['name'],
2572 'status': vcdStatusCode2manoFormat
[int(status_key
)],
2573 'hostId': vm_info_dict
['vmuuid'],
2575 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
2577 if 'interfaces' in vm_info_dict
:
2578 vm_dict
['interfaces'] = vm_info_dict
['interfaces']
2580 vm_dict
['interfaces'] = []
2582 vm_dict
= {'created': '',
2584 'status': vcdStatusCode2manoFormat
[int(-1)],
2585 'hostId': vm_info_dict
['vmuuid'],
2586 'error_msg': "Inconsistency state",
2587 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
2591 def delete_vminstance(self
, vm__vim_uuid
, created_items
=None):
2592 """Method poweroff and remove VM instance from vcloud director network.
2595 vm__vim_uuid: VM UUID
2598 Returns the instance identifier
2601 self
.logger
.debug("Client requesting delete vm instance {} ".format(vm__vim_uuid
))
2603 org
, vdc
= self
.get_vdc_details()
2604 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2606 self
.logger
.debug("delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
2608 raise vimconn
.vimconnException(
2609 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2612 vapp_name
= self
.get_namebyvappid(vm__vim_uuid
)
2613 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2614 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2615 if vapp_name
is None:
2616 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2617 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2619 self
.logger
.info("Deleting vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
2621 # Delete vApp and wait for status change if task executed and vApp is None.
2624 if vapp_resource
.get('deployed') == 'true':
2625 self
.logger
.info("Powering off vApp {}".format(vapp_name
))
2629 while wait_time
<= MAX_WAIT_TIME
:
2630 power_off_task
= vapp
.power_off()
2631 result
= self
.client
.get_task_monitor().wait_for_success(task
=power_off_task
)
2633 if result
.get('status') == 'success':
2637 self
.logger
.info("Wait for vApp {} to power off".format(vapp_name
))
2638 time
.sleep(INTERVAL_TIME
)
2640 wait_time
+=INTERVAL_TIME
2642 self
.logger
.debug("delete_vminstance(): Failed to power off VM instance {} ".format(vm__vim_uuid
))
2644 self
.logger
.info("delete_vminstance(): Powered off VM instance {} ".format(vm__vim_uuid
))
2647 self
.logger
.info("Undeploy vApp {}".format(vapp_name
))
2650 while wait_time
<= MAX_WAIT_TIME
:
2651 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2653 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2654 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2655 undeploy_task
= vapp
.undeploy()
2657 result
= self
.client
.get_task_monitor().wait_for_success(task
=undeploy_task
)
2658 if result
.get('status') == 'success':
2662 self
.logger
.debug("Wait for vApp {} to undeploy".format(vapp_name
))
2663 time
.sleep(INTERVAL_TIME
)
2665 wait_time
+=INTERVAL_TIME
2668 self
.logger
.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid
))
2671 self
.logger
.info("Start deletion of vApp {} ".format(vapp_name
))
2673 if vapp
is not None:
2677 while wait_time
<= MAX_WAIT_TIME
:
2678 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2680 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2681 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2683 delete_task
= vdc_obj
.delete_vapp(vapp
.name
, force
=True)
2685 result
= self
.client
.get_task_monitor().wait_for_success(task
=delete_task
)
2686 if result
.get('status') == 'success':
2689 self
.logger
.debug("Wait for vApp {} to delete".format(vapp_name
))
2690 time
.sleep(INTERVAL_TIME
)
2692 wait_time
+=INTERVAL_TIME
2695 self
.logger
.debug("delete_vminstance(): Failed delete uuid {} ".format(vm__vim_uuid
))
2697 self
.logger
.info("Deleted vm instance {} sccessfully".format(vm__vim_uuid
))
2700 self
.logger
.debug(traceback
.format_exc())
2701 raise vimconn
.vimconnException("delete_vminstance(): Failed delete vm instance {}".format(vm__vim_uuid
))
2704 def refresh_vms_status(self
, vm_list
):
2705 """Get the status of the virtual machines and their interfaces/ports
2706 Params: the list of VM identifiers
2707 Returns a dictionary with:
2708 vm_id: #VIM id of this Virtual Machine
2709 status: #Mandatory. Text with one of:
2710 # DELETED (not found at vim)
2711 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2712 # OTHER (Vim reported other status not understood)
2713 # ERROR (VIM indicates an ERROR status)
2714 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2715 # CREATING (on building process), ERROR
2716 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2718 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2719 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2721 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2722 mac_address: #Text format XX:XX:XX:XX:XX:XX
2723 vim_net_id: #network id where this interface is connected
2724 vim_interface_id: #interface/port VIM id
2725 ip_address: #null, or text with IPv4, IPv6 address
2728 self
.logger
.debug("Client requesting refresh vm status for {} ".format(vm_list
))
2730 org
,vdc
= self
.get_vdc_details()
2732 raise vimconn
.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2736 for vmuuid
in vm_list
:
2737 vapp_name
= self
.get_namebyvappid(vmuuid
)
2738 if vapp_name
is not None:
2741 vm_pci_details
= self
.get_vm_pci_details(vmuuid
)
2742 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2743 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2744 the_vapp
= VApp(self
.client
, resource
=vapp_resource
)
2747 for vm
in the_vapp
.get_all_vms():
2748 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2749 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2750 response
= self
.perform_request(req_type
='GET',
2754 if response
.status_code
!= 200:
2755 self
.logger
.error("refresh_vms_status : REST call {} failed reason : {}"\
2756 "status code : {}".format(vm
.get('href'),
2758 response
.status_code
))
2759 raise vimconn
.vimconnException("refresh_vms_status : Failed to get "\
2761 xmlroot
= XmlElementTree
.fromstring(response
.content
)
2764 result
= response
.content
.replace("\n"," ")
2765 hdd_match
= re
.search('vcloud:capacity="(\d+)"\svcloud:storageProfileOverrideVmDefault=',result
)
2767 hdd_mb
= hdd_match
.group(1)
2768 vm_details
['hdd_mb'] = int(hdd_mb
) if hdd_mb
else None
2769 cpus_match
= re
.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',result
)
2771 cpus
= cpus_match
.group(1)
2772 vm_details
['cpus'] = int(cpus
) if cpus
else None
2773 memory_mb
= re
.search('<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>',result
).group(1)
2774 vm_details
['memory_mb'] = int(memory_mb
) if memory_mb
else None
2775 vm_details
['status'] = vcdStatusCode2manoFormat
[int(xmlroot
.get('status'))]
2776 vm_details
['id'] = xmlroot
.get('id')
2777 vm_details
['name'] = xmlroot
.get('name')
2778 vm_info
= [vm_details
]
2780 vm_info
[0].update(vm_pci_details
)
2782 vm_dict
= {'status': vcdStatusCode2manoFormat
[int(vapp_resource
.get('status'))],
2783 'error_msg': vcdStatusCode2manoFormat
[int(vapp_resource
.get('status'))],
2784 'vim_info': yaml
.safe_dump(vm_info
), 'interfaces': []}
2789 networks
= re
.findall('<NetworkConnection needsCustomization=.*?</NetworkConnection>',result
)
2790 for network
in networks
:
2791 mac_s
= re
.search('<MACAddress>(.*?)</MACAddress>',network
)
2792 vm_mac
= mac_s
.group(1) if mac_s
else None
2793 ip_s
= re
.search('<IpAddress>(.*?)</IpAddress>',network
)
2794 vm_ip
= ip_s
.group(1) if ip_s
else None
2797 if not nsx_edge_list
:
2798 nsx_edge_list
= self
.get_edge_details()
2799 if nsx_edge_list
is None:
2800 raise vimconn
.vimconnException("refresh_vms_status:"\
2801 "Failed to get edge details from NSX Manager")
2802 if vm_mac
is not None:
2803 vm_ip
= self
.get_ipaddr_from_NSXedge(nsx_edge_list
, vm_mac
)
2805 net_s
= re
.search('network="(.*?)"',network
)
2806 network_name
= net_s
.group(1) if net_s
else None
2808 vm_net_id
= self
.get_network_id_by_name(network_name
)
2809 interface
= {"mac_address": vm_mac
,
2810 "vim_net_id": vm_net_id
,
2811 "vim_interface_id": vm_net_id
,
2812 "ip_address": vm_ip
}
2814 vm_dict
["interfaces"].append(interface
)
2816 # add a vm to vm dict
2817 vms_dict
.setdefault(vmuuid
, vm_dict
)
2818 self
.logger
.debug("refresh_vms_status : vm info {}".format(vm_dict
))
2819 except Exception as exp
:
2820 self
.logger
.debug("Error in response {}".format(exp
))
2821 self
.logger
.debug(traceback
.format_exc())
2826 def get_edge_details(self
):
2827 """Get the NSX edge list from NSX Manager
2828 Returns list of NSX edges
2831 rheaders
= {'Content-Type': 'application/xml'}
2832 nsx_api_url
= '/api/4.0/edges'
2834 self
.logger
.debug("Get edge details from NSX Manager {} {}".format(self
.nsx_manager
, nsx_api_url
))
2837 resp
= requests
.get(self
.nsx_manager
+ nsx_api_url
,
2838 auth
= (self
.nsx_user
, self
.nsx_password
),
2839 verify
= False, headers
= rheaders
)
2840 if resp
.status_code
== requests
.codes
.ok
:
2841 paged_Edge_List
= XmlElementTree
.fromstring(resp
.text
)
2842 for edge_pages
in paged_Edge_List
:
2843 if edge_pages
.tag
== 'edgePage':
2844 for edge_summary
in edge_pages
:
2845 if edge_summary
.tag
== 'pagingInfo':
2846 for element
in edge_summary
:
2847 if element
.tag
== 'totalCount' and element
.text
== '0':
2848 raise vimconn
.vimconnException("get_edge_details: No NSX edges details found: {}"
2849 .format(self
.nsx_manager
))
2851 if edge_summary
.tag
== 'edgeSummary':
2852 for element
in edge_summary
:
2853 if element
.tag
== 'id':
2854 edge_list
.append(element
.text
)
2856 raise vimconn
.vimconnException("get_edge_details: No NSX edge details found: {}"
2857 .format(self
.nsx_manager
))
2860 raise vimconn
.vimconnException("get_edge_details: "\
2861 "No NSX edge details found: {}"
2862 .format(self
.nsx_manager
))
2864 self
.logger
.debug("get_edge_details: Found NSX edges {}".format(edge_list
))
2867 self
.logger
.debug("get_edge_details: "
2868 "Failed to get NSX edge details from NSX Manager: {}"
2869 .format(resp
.content
))
2872 except Exception as exp
:
2873 self
.logger
.debug("get_edge_details: "\
2874 "Failed to get NSX edge details from NSX Manager: {}"
2876 raise vimconn
.vimconnException("get_edge_details: "\
2877 "Failed to get NSX edge details from NSX Manager: {}"
2881 def get_ipaddr_from_NSXedge(self
, nsx_edges
, mac_address
):
2882 """Get IP address details from NSX edges, using the MAC address
2883 PARAMS: nsx_edges : List of NSX edges
2884 mac_address : Find IP address corresponding to this MAC address
2885 Returns: IP address corrresponding to the provided MAC address
2889 rheaders
= {'Content-Type': 'application/xml'}
2891 self
.logger
.debug("get_ipaddr_from_NSXedge: Finding IP addr from NSX edge")
2894 for edge
in nsx_edges
:
2895 nsx_api_url
= '/api/4.0/edges/'+ edge
+'/dhcp/leaseInfo'
2897 resp
= requests
.get(self
.nsx_manager
+ nsx_api_url
,
2898 auth
= (self
.nsx_user
, self
.nsx_password
),
2899 verify
= False, headers
= rheaders
)
2901 if resp
.status_code
== requests
.codes
.ok
:
2902 dhcp_leases
= XmlElementTree
.fromstring(resp
.text
)
2903 for child
in dhcp_leases
:
2904 if child
.tag
== 'dhcpLeaseInfo':
2905 dhcpLeaseInfo
= child
2906 for leaseInfo
in dhcpLeaseInfo
:
2907 for elem
in leaseInfo
:
2908 if (elem
.tag
)=='macAddress':
2909 edge_mac_addr
= elem
.text
2910 if (elem
.tag
)=='ipAddress':
2912 if edge_mac_addr
is not None:
2913 if edge_mac_addr
== mac_address
:
2914 self
.logger
.debug("Found ip addr {} for mac {} at NSX edge {}"
2915 .format(ip_addr
, mac_address
,edge
))
2918 self
.logger
.debug("get_ipaddr_from_NSXedge: "\
2919 "Error occurred while getting DHCP lease info from NSX Manager: {}"
2920 .format(resp
.content
))
2922 self
.logger
.debug("get_ipaddr_from_NSXedge: No IP addr found in any NSX edge")
2925 except XmlElementTree
.ParseError
as Err
:
2926 self
.logger
.debug("ParseError in response from NSX Manager {}".format(Err
.message
), exc_info
=True)
2929 def action_vminstance(self
, vm__vim_uuid
=None, action_dict
=None, created_items
={}):
2930 """Send and action over a VM instance from VIM
2931 Returns the vm_id if the action was successfully sent to the VIM"""
2933 self
.logger
.debug("Received action for vm {} and action dict {}".format(vm__vim_uuid
, action_dict
))
2934 if vm__vim_uuid
is None or action_dict
is None:
2935 raise vimconn
.vimconnException("Invalid request. VM id or action is None.")
2937 org
, vdc
= self
.get_vdc_details()
2939 raise vimconn
.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2941 vapp_name
= self
.get_namebyvappid(vm__vim_uuid
)
2942 if vapp_name
is None:
2943 self
.logger
.debug("action_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2944 raise vimconn
.vimconnException("Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2946 self
.logger
.info("Action_vminstance vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
2949 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2950 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2951 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2952 if "start" in action_dict
:
2953 self
.logger
.info("action_vminstance: Power on vApp: {}".format(vapp_name
))
2954 poweron_task
= self
.power_on_vapp(vm__vim_uuid
, vapp_name
)
2955 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
2956 self
.instance_actions_result("start", result
, vapp_name
)
2957 elif "rebuild" in action_dict
:
2958 self
.logger
.info("action_vminstance: Rebuild vApp: {}".format(vapp_name
))
2959 rebuild_task
= vapp
.deploy(power_on
=True)
2960 result
= self
.client
.get_task_monitor().wait_for_success(task
=rebuild_task
)
2961 self
.instance_actions_result("rebuild", result
, vapp_name
)
2962 elif "pause" in action_dict
:
2963 self
.logger
.info("action_vminstance: pause vApp: {}".format(vapp_name
))
2964 pause_task
= vapp
.undeploy(action
='suspend')
2965 result
= self
.client
.get_task_monitor().wait_for_success(task
=pause_task
)
2966 self
.instance_actions_result("pause", result
, vapp_name
)
2967 elif "resume" in action_dict
:
2968 self
.logger
.info("action_vminstance: resume vApp: {}".format(vapp_name
))
2969 poweron_task
= self
.power_on_vapp(vm__vim_uuid
, vapp_name
)
2970 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
2971 self
.instance_actions_result("resume", result
, vapp_name
)
2972 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
2973 action_name
, value
= action_dict
.items()[0]
2975 #action_name , value = list(action_dict.items())[0]
2976 self
.logger
.info("action_vminstance: {} vApp: {}".format(action_name
, vapp_name
))
2977 shutdown_task
= vapp
.shutdown()
2978 result
= self
.client
.get_task_monitor().wait_for_success(task
=shutdown_task
)
2979 if action_name
== "shutdown":
2980 self
.instance_actions_result("shutdown", result
, vapp_name
)
2982 self
.instance_actions_result("shutoff", result
, vapp_name
)
2983 elif "forceOff" in action_dict
:
2984 result
= vapp
.undeploy(action
='powerOff')
2985 self
.instance_actions_result("forceOff", result
, vapp_name
)
2986 elif "reboot" in action_dict
:
2987 self
.logger
.info("action_vminstance: reboot vApp: {}".format(vapp_name
))
2988 reboot_task
= vapp
.reboot()
2989 self
.client
.get_task_monitor().wait_for_success(task
=reboot_task
)
2991 raise vimconn
.vimconnException("action_vminstance: Invalid action {} or action is None.".format(action_dict
))
2993 except Exception as exp
:
2994 self
.logger
.debug("action_vminstance: Failed with Exception {}".format(exp
))
2995 raise vimconn
.vimconnException("action_vminstance: Failed with Exception {}".format(exp
))
2997 def instance_actions_result(self
, action
, result
, vapp_name
):
2998 if result
.get('status') == 'success':
2999 self
.logger
.info("action_vminstance: Sucessfully {} the vApp: {}".format(action
, vapp_name
))
3001 self
.logger
.error("action_vminstance: Failed to {} vApp: {}".format(action
, vapp_name
))
3003 def get_vminstance_console(self
, vm_id
, console_type
="vnc"):
3005 Get a console for the virtual machine
3007 vm_id: uuid of the VM
3008 console_type, can be:
3009 "novnc" (by default), "xvpvnc" for VNC types,
3010 "rdp-html5" for RDP types, "spice-html5" for SPICE types
3011 Returns dict with the console parameters:
3012 protocol: ssh, ftp, http, https, ...
3013 server: usually ip address
3014 port: the http, ssh, ... port
3015 suffix: extra text, e.g. the http path and query string
3017 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3019 # NOT USED METHODS in current version
3021 def host_vim2gui(self
, host
, server_dict
):
3022 """Transform host dictionary from VIM format to GUI format,
3023 and append to the server_dict
3025 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3027 def get_hosts_info(self
):
3028 """Get the information of deployed hosts
3029 Returns the hosts content"""
3030 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3032 def get_hosts(self
, vim_tenant
):
3033 """Get the hosts and deployed instances
3034 Returns the hosts content"""
3035 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3037 def get_processor_rankings(self
):
3038 """Get the processor rankings in the VIM database"""
3039 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3041 def new_host(self
, host_data
):
3042 """Adds a new host to VIM"""
3043 '''Returns status code of the VIM response'''
3044 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3046 def new_external_port(self
, port_data
):
3047 """Adds a external port to VIM"""
3048 '''Returns the port identifier'''
3049 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3051 def new_external_network(self
, net_name
, net_type
):
3052 """Adds a external network to VIM (shared)"""
3053 '''Returns the network identifier'''
3054 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3056 def connect_port_network(self
, port_id
, network_id
, admin
=False):
3057 """Connects a external port to a network"""
3058 '''Returns status code of the VIM response'''
3059 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3061 def new_vminstancefromJSON(self
, vm_data
):
3062 """Adds a VM instance to VIM"""
3063 '''Returns the instance identifier'''
3064 raise vimconn
.vimconnNotImplemented("Should have implemented this")
3066 def get_network_name_by_id(self
, network_uuid
=None):
3067 """Method gets vcloud director network named based on supplied uuid.
3070 network_uuid: network_id
3073 The return network name.
3076 if not network_uuid
:
3080 org_dict
= self
.get_org(self
.org_uuid
)
3081 if 'networks' in org_dict
:
3082 org_network_dict
= org_dict
['networks']
3083 for net_uuid
in org_network_dict
:
3084 if net_uuid
== network_uuid
:
3085 return org_network_dict
[net_uuid
]
3087 self
.logger
.debug("Exception in get_network_name_by_id")
3088 self
.logger
.debug(traceback
.format_exc())
3092 def get_network_id_by_name(self
, network_name
=None):
3093 """Method gets vcloud director network uuid based on supplied name.
3096 network_name: network_name
3098 The return network uuid.
3099 network_uuid: network_id
3102 if not network_name
:
3103 self
.logger
.debug("get_network_id_by_name() : Network name is empty")
3107 org_dict
= self
.get_org(self
.org_uuid
)
3108 if org_dict
and 'networks' in org_dict
:
3109 org_network_dict
= org_dict
['networks']
3110 for net_uuid
,net_name
in org_network_dict
.iteritems():
3112 #for net_uuid,net_name in org_network_dict.items():
3113 if net_name
== network_name
:
3116 except KeyError as exp
:
3117 self
.logger
.debug("get_network_id_by_name() : KeyError- {} ".format(exp
))
3121 def list_org_action(self
):
3123 Method leverages vCloud director and query for available organization for particular user
3126 vca - is active VCA connection.
3127 vdc_name - is a vdc name that will be used to query vms action
3130 The return XML respond
3132 url_list
= [self
.url
, '/api/org']
3133 vm_list_rest_call
= ''.join(url_list
)
3135 if self
.client
._session
:
3136 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3137 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3139 response
= self
.perform_request(req_type
='GET',
3140 url
=vm_list_rest_call
,
3143 if response
.status_code
== 403:
3144 response
= self
.retry_rest('GET', vm_list_rest_call
)
3146 if response
.status_code
== requests
.codes
.ok
:
3147 return response
.content
3151 def get_org_action(self
, org_uuid
=None):
3153 Method leverages vCloud director and retrieve available object for organization.
3156 org_uuid - vCD organization uuid
3157 self.client - is active connection.
3160 The return XML respond
3163 if org_uuid
is None:
3166 url_list
= [self
.url
, '/api/org/', org_uuid
]
3167 vm_list_rest_call
= ''.join(url_list
)
3169 if self
.client
._session
:
3170 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3171 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3173 #response = requests.get(vm_list_rest_call, headers=headers, verify=False)
3174 response
= self
.perform_request(req_type
='GET',
3175 url
=vm_list_rest_call
,
3177 if response
.status_code
== 403:
3178 response
= self
.retry_rest('GET', vm_list_rest_call
)
3180 if response
.status_code
== requests
.codes
.ok
:
3181 return response
.content
3184 def get_org(self
, org_uuid
=None):
3186 Method retrieves available organization in vCloud Director
3189 org_uuid - is a organization uuid.
3192 The return dictionary with following key
3193 "network" - for network list under the org
3194 "catalogs" - for network list under the org
3195 "vdcs" - for vdc list under org
3200 if org_uuid
is None:
3203 content
= self
.get_org_action(org_uuid
=org_uuid
)
3208 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3209 for child
in vm_list_xmlroot
:
3210 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.vdc+xml':
3211 vdc_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
3212 org_dict
['vdcs'] = vdc_list
3213 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.orgNetwork+xml':
3214 network_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
3215 org_dict
['networks'] = network_list
3216 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.catalog+xml':
3217 catalog_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
3218 org_dict
['catalogs'] = catalog_list
3224 def get_org_list(self
):
3226 Method retrieves available organization in vCloud Director
3229 vca - is active VCA connection.
3232 The return dictionary and key for each entry VDC UUID
3237 content
= self
.list_org_action()
3239 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3240 for vm_xml
in vm_list_xmlroot
:
3241 if vm_xml
.tag
.split("}")[1] == 'Org':
3242 org_uuid
= vm_xml
.attrib
['href'].split('/')[-1:]
3243 org_dict
[org_uuid
[0]] = vm_xml
.attrib
['name']
3249 def vms_view_action(self
, vdc_name
=None):
3250 """ Method leverages vCloud director vms query call
3253 vca - is active VCA connection.
3254 vdc_name - is a vdc name that will be used to query vms action
3257 The return XML respond
3259 vca
= self
.connect()
3260 if vdc_name
is None:
3263 url_list
= [vca
.host
, '/api/vms/query']
3264 vm_list_rest_call
= ''.join(url_list
)
3266 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
3267 refs
= filter(lambda ref
: ref
.name
== vdc_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vdc+xml',
3268 vca
.vcloud_session
.organization
.Link
)
3270 #refs = [ref for ref in vca.vcloud_session.organization.Link if ref.name == vdc_name and\
3271 # ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml']
3273 response
= Http
.get(url
=vm_list_rest_call
,
3274 headers
=vca
.vcloud_session
.get_vcloud_headers(),
3277 if response
.status_code
== requests
.codes
.ok
:
3278 return response
.content
3282 def get_vapp_list(self
, vdc_name
=None):
3284 Method retrieves vApp list deployed vCloud director and returns a dictionary
3285 contains a list of all vapp deployed for queried VDC.
3286 The key for a dictionary is vApp UUID
3290 vca - is active VCA connection.
3291 vdc_name - is a vdc name that will be used to query vms action
3294 The return dictionary and key for each entry vapp UUID
3298 if vdc_name
is None:
3301 content
= self
.vms_view_action(vdc_name
=vdc_name
)
3303 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3304 for vm_xml
in vm_list_xmlroot
:
3305 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
3306 if vm_xml
.attrib
['isVAppTemplate'] == 'true':
3307 rawuuid
= vm_xml
.attrib
['container'].split('/')[-1:]
3308 if 'vappTemplate-' in rawuuid
[0]:
3309 # vm in format vappTemplate-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
3310 # vm and use raw UUID as key
3311 vapp_dict
[rawuuid
[0][13:]] = vm_xml
.attrib
3317 def get_vm_list(self
, vdc_name
=None):
3319 Method retrieves VM's list deployed vCloud director. It returns a dictionary
3320 contains a list of all VM's deployed for queried VDC.
3321 The key for a dictionary is VM UUID
3325 vca - is active VCA connection.
3326 vdc_name - is a vdc name that will be used to query vms action
3329 The return dictionary and key for each entry vapp UUID
3333 if vdc_name
is None:
3336 content
= self
.vms_view_action(vdc_name
=vdc_name
)
3338 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3339 for vm_xml
in vm_list_xmlroot
:
3340 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
3341 if vm_xml
.attrib
['isVAppTemplate'] == 'false':
3342 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
3343 if 'vm-' in rawuuid
[0]:
3344 # vm in format vm-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
3345 # vm and use raw UUID as key
3346 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
3352 def get_vapp(self
, vdc_name
=None, vapp_name
=None, isuuid
=False):
3354 Method retrieves VM deployed vCloud director. It returns VM attribute as dictionary
3355 contains a list of all VM's deployed for queried VDC.
3356 The key for a dictionary is VM UUID
3360 vca - is active VCA connection.
3361 vdc_name - is a vdc name that will be used to query vms action
3364 The return dictionary and key for each entry vapp UUID
3367 vca
= self
.connect()
3369 raise vimconn
.vimconnConnectionException("self.connect() is failed")
3371 if vdc_name
is None:
3374 content
= self
.vms_view_action(vdc_name
=vdc_name
)
3376 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3377 for vm_xml
in vm_list_xmlroot
:
3378 if vm_xml
.tag
.split("}")[1] == 'VMRecord' and vm_xml
.attrib
['isVAppTemplate'] == 'false':
3379 # lookup done by UUID
3381 if vapp_name
in vm_xml
.attrib
['container']:
3382 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
3383 if 'vm-' in rawuuid
[0]:
3384 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
3386 # lookup done by Name
3388 if vapp_name
in vm_xml
.attrib
['name']:
3389 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
3390 if 'vm-' in rawuuid
[0]:
3391 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
3398 def get_network_action(self
, network_uuid
=None):
3400 Method leverages vCloud director and query network based on network uuid
3403 vca - is active VCA connection.
3404 network_uuid - is a network uuid
3407 The return XML respond
3410 if network_uuid
is None:
3413 url_list
= [self
.url
, '/api/network/', network_uuid
]
3414 vm_list_rest_call
= ''.join(url_list
)
3416 if self
.client
._session
:
3417 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3418 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3420 response
= self
.perform_request(req_type
='GET',
3421 url
=vm_list_rest_call
,
3423 #Retry login if session expired & retry sending request
3424 if response
.status_code
== 403:
3425 response
= self
.retry_rest('GET', vm_list_rest_call
)
3427 if response
.status_code
== requests
.codes
.ok
:
3428 return response
.content
3432 def get_vcd_network(self
, network_uuid
=None):
3434 Method retrieves available network from vCloud Director
3437 network_uuid - is VCD network UUID
3439 Each element serialized as key : value pair
3441 Following keys available for access. network_configuration['Gateway'}
3445 <IsInherited>true</IsInherited>
3446 <Gateway>172.16.252.100</Gateway>
3447 <Netmask>255.255.255.0</Netmask>
3448 <Dns1>172.16.254.201</Dns1>
3449 <Dns2>172.16.254.202</Dns2>
3450 <DnsSuffix>vmwarelab.edu</DnsSuffix>
3451 <IsEnabled>true</IsEnabled>
3454 <StartAddress>172.16.252.1</StartAddress>
3455 <EndAddress>172.16.252.99</EndAddress>
3460 <FenceMode>bridged</FenceMode>
3463 The return dictionary and key for each entry vapp UUID
3466 network_configuration
= {}
3467 if network_uuid
is None:
3471 content
= self
.get_network_action(network_uuid
=network_uuid
)
3472 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3474 network_configuration
['status'] = vm_list_xmlroot
.get("status")
3475 network_configuration
['name'] = vm_list_xmlroot
.get("name")
3476 network_configuration
['uuid'] = vm_list_xmlroot
.get("id").split(":")[3]
3478 for child
in vm_list_xmlroot
:
3479 if child
.tag
.split("}")[1] == 'IsShared':
3480 network_configuration
['isShared'] = child
.text
.strip()
3481 if child
.tag
.split("}")[1] == 'Configuration':
3482 for configuration
in child
.iter():
3483 tagKey
= configuration
.tag
.split("}")[1].strip()
3485 network_configuration
[tagKey
] = configuration
.text
.strip()
3486 return network_configuration
3487 except Exception as exp
:
3488 self
.logger
.debug("get_vcd_network: Failed with Exception {}".format(exp
))
3489 raise vimconn
.vimconnException("get_vcd_network: Failed with Exception {}".format(exp
))
3491 return network_configuration
3493 def delete_network_action(self
, network_uuid
=None):
3495 Method delete given network from vCloud director
3498 network_uuid - is a network uuid that client wish to delete
3501 The return None or XML respond or false
3503 client
= self
.connect_as_admin()
3505 raise vimconn
.vimconnConnectionException("Failed to connect vCD as admin")
3506 if network_uuid
is None:
3509 url_list
= [self
.url
, '/api/admin/network/', network_uuid
]
3510 vm_list_rest_call
= ''.join(url_list
)
3513 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3514 'x-vcloud-authorization': client
._session
.headers
['x-vcloud-authorization']}
3515 response
= self
.perform_request(req_type
='DELETE',
3516 url
=vm_list_rest_call
,
3518 if response
.status_code
== 202:
3523 def create_network(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
3524 ip_profile
=None, isshared
='true'):
3526 Method create network in vCloud director
3529 network_name - is network name to be created.
3530 net_type - can be 'bridge','data','ptp','mgmt'.
3531 ip_profile is a dict containing the IP parameters of the network
3532 isshared - is a boolean
3533 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3534 It optional attribute. by default if no parent network indicate the first available will be used.
3537 The return network uuid or return None
3540 new_network_name
= [network_name
, '-', str(uuid
.uuid4())]
3541 content
= self
.create_network_rest(network_name
=''.join(new_network_name
),
3542 ip_profile
=ip_profile
,
3544 parent_network_uuid
=parent_network_uuid
,
3547 self
.logger
.debug("Failed create network {}.".format(network_name
))
3551 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3552 vcd_uuid
= vm_list_xmlroot
.get('id').split(":")
3553 if len(vcd_uuid
) == 4:
3554 self
.logger
.info("Created new network name: {} uuid: {}".format(network_name
, vcd_uuid
[3]))
3557 self
.logger
.debug("Failed create network {}".format(network_name
))
3560 def create_network_rest(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
3561 ip_profile
=None, isshared
='true'):
3563 Method create network in vCloud director
3566 network_name - is network name to be created.
3567 net_type - can be 'bridge','data','ptp','mgmt'.
3568 ip_profile is a dict containing the IP parameters of the network
3569 isshared - is a boolean
3570 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3571 It optional attribute. by default if no parent network indicate the first available will be used.
3574 The return network uuid or return None
3576 client_as_admin
= self
.connect_as_admin()
3577 if not client_as_admin
:
3578 raise vimconn
.vimconnConnectionException("Failed to connect vCD.")
3579 if network_name
is None:
3582 url_list
= [self
.url
, '/api/admin/vdc/', self
.tenant_id
]
3583 vm_list_rest_call
= ''.join(url_list
)
3585 if client_as_admin
._session
:
3586 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3587 'x-vcloud-authorization': client_as_admin
._session
.headers
['x-vcloud-authorization']}
3589 response
= self
.perform_request(req_type
='GET',
3590 url
=vm_list_rest_call
,
3593 provider_network
= None
3594 available_networks
= None
3595 add_vdc_rest_url
= None
3597 if response
.status_code
!= requests
.codes
.ok
:
3598 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3599 response
.status_code
))
3603 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3604 for child
in vm_list_xmlroot
:
3605 if child
.tag
.split("}")[1] == 'ProviderVdcReference':
3606 provider_network
= child
.attrib
.get('href')
3607 # application/vnd.vmware.admin.providervdc+xml
3608 if child
.tag
.split("}")[1] == 'Link':
3609 if child
.attrib
.get('type') == 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' \
3610 and child
.attrib
.get('rel') == 'add':
3611 add_vdc_rest_url
= child
.attrib
.get('href')
3613 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3614 self
.logger
.debug("Respond body {}".format(response
.content
))
3617 # find pvdc provided available network
3618 response
= self
.perform_request(req_type
='GET',
3619 url
=provider_network
,
3621 if response
.status_code
!= requests
.codes
.ok
:
3622 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3623 response
.status_code
))
3626 if parent_network_uuid
is None:
3628 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3629 for child
in vm_list_xmlroot
.iter():
3630 if child
.tag
.split("}")[1] == 'AvailableNetworks':
3631 for networks
in child
.iter():
3632 # application/vnd.vmware.admin.network+xml
3633 if networks
.attrib
.get('href') is not None:
3634 available_networks
= networks
.attrib
.get('href')
3640 #Configure IP profile of the network
3641 ip_profile
= ip_profile
if ip_profile
is not None else DEFAULT_IP_PROFILE
3643 if 'subnet_address' not in ip_profile
or ip_profile
['subnet_address'] is None:
3644 subnet_rand
= random
.randint(0, 255)
3645 ip_base
= "192.168.{}.".format(subnet_rand
)
3646 ip_profile
['subnet_address'] = ip_base
+ "0/24"
3648 ip_base
= ip_profile
['subnet_address'].rsplit('.',1)[0] + '.'
3650 if 'gateway_address' not in ip_profile
or ip_profile
['gateway_address'] is None:
3651 ip_profile
['gateway_address']=ip_base
+ "1"
3652 if 'dhcp_count' not in ip_profile
or ip_profile
['dhcp_count'] is None:
3653 ip_profile
['dhcp_count']=DEFAULT_IP_PROFILE
['dhcp_count']
3654 if 'dhcp_enabled' not in ip_profile
or ip_profile
['dhcp_enabled'] is None:
3655 ip_profile
['dhcp_enabled']=DEFAULT_IP_PROFILE
['dhcp_enabled']
3656 if 'dhcp_start_address' not in ip_profile
or ip_profile
['dhcp_start_address'] is None:
3657 ip_profile
['dhcp_start_address']=ip_base
+ "3"
3658 if 'ip_version' not in ip_profile
or ip_profile
['ip_version'] is None:
3659 ip_profile
['ip_version']=DEFAULT_IP_PROFILE
['ip_version']
3660 if 'dns_address' not in ip_profile
or ip_profile
['dns_address'] is None:
3661 ip_profile
['dns_address']=ip_base
+ "2"
3663 gateway_address
=ip_profile
['gateway_address']
3664 dhcp_count
=int(ip_profile
['dhcp_count'])
3665 subnet_address
=self
.convert_cidr_to_netmask(ip_profile
['subnet_address'])
3667 if ip_profile
['dhcp_enabled']==True:
3670 dhcp_enabled
='false'
3671 dhcp_start_address
=ip_profile
['dhcp_start_address']
3673 #derive dhcp_end_address from dhcp_start_address & dhcp_count
3674 end_ip_int
= int(netaddr
.IPAddress(dhcp_start_address
))
3675 end_ip_int
+= dhcp_count
- 1
3676 dhcp_end_address
= str(netaddr
.IPAddress(end_ip_int
))
3678 ip_version
=ip_profile
['ip_version']
3679 dns_address
=ip_profile
['dns_address']
3680 except KeyError as exp
:
3681 self
.logger
.debug("Create Network REST: Key error {}".format(exp
))
3682 raise vimconn
.vimconnException("Create Network REST: Key error{}".format(exp
))
3684 # either use client provided UUID or search for a first available
3685 # if both are not defined we return none
3686 if parent_network_uuid
is not None:
3687 provider_network
= None
3688 available_networks
= None
3689 add_vdc_rest_url
= None
3691 url_list
= [self
.url
, '/api/admin/vdc/', self
.tenant_id
, '/networks']
3692 add_vdc_rest_url
= ''.join(url_list
)
3694 url_list
= [self
.url
, '/api/admin/network/', parent_network_uuid
]
3695 available_networks
= ''.join(url_list
)
3697 #Creating all networks as Direct Org VDC type networks.
3698 #Unused in case of Underlay (data/ptp) network interface.
3699 fence_mode
="bridged"
3700 is_inherited
='false'
3701 dns_list
= dns_address
.split(";")
3704 if len(dns_list
) >= 2:
3705 dns2_text
= "\n <Dns2>{}</Dns2>\n".format(dns_list
[1])
3706 data
= """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
3707 <Description>Openmano created</Description>
3711 <IsInherited>{1:s}</IsInherited>
3712 <Gateway>{2:s}</Gateway>
3713 <Netmask>{3:s}</Netmask>
3714 <Dns1>{4:s}</Dns1>{5:s}
3715 <IsEnabled>{6:s}</IsEnabled>
3718 <StartAddress>{7:s}</StartAddress>
3719 <EndAddress>{8:s}</EndAddress>
3724 <ParentNetwork href="{9:s}"/>
3725 <FenceMode>{10:s}</FenceMode>
3727 <IsShared>{11:s}</IsShared>
3728 </OrgVdcNetwork> """.format(escape(network_name
), is_inherited
, gateway_address
,
3729 subnet_address
, dns1
, dns2_text
, dhcp_enabled
,
3730 dhcp_start_address
, dhcp_end_address
, available_networks
,
3731 fence_mode
, isshared
)
3733 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'
3735 response
= self
.perform_request(req_type
='POST',
3736 url
=add_vdc_rest_url
,
3740 if response
.status_code
!= 201:
3741 self
.logger
.debug("Create Network POST REST API call failed. Return status code {}, Response content: {}"
3742 .format(response
.status_code
,response
.content
))
3744 network_task
= self
.get_task_from_response(response
.content
)
3745 self
.logger
.debug("Create Network REST : Waiting for Network creation complete")
3747 result
= self
.client
.get_task_monitor().wait_for_success(task
=network_task
)
3748 if result
.get('status') == 'success':
3749 return response
.content
3751 self
.logger
.debug("create_network_rest task failed. Network Create response : {}"
3752 .format(response
.content
))
3753 except Exception as exp
:
3754 self
.logger
.debug("create_network_rest : Exception : {} ".format(exp
))
3758 def convert_cidr_to_netmask(self
, cidr_ip
=None):
3760 Method sets convert CIDR netmask address to normal IP format
3762 cidr_ip : CIDR IP address
3764 netmask : Converted netmask
3766 if cidr_ip
is not None:
3768 network
, net_bits
= cidr_ip
.split('/')
3769 netmask
= socket
.inet_ntoa(struct
.pack(">I", (0xffffffff << (32 - int(net_bits
))) & 0xffffffff))
3775 def get_provider_rest(self
, vca
=None):
3777 Method gets provider vdc view from vcloud director
3780 network_name - is network name to be created.
3781 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3782 It optional attribute. by default if no parent network indicate the first available will be used.
3785 The return xml content of respond or None
3788 url_list
= [self
.url
, '/api/admin']
3790 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3791 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3792 response
= self
.perform_request(req_type
='GET',
3793 url
=''.join(url_list
),
3796 if response
.status_code
== requests
.codes
.ok
:
3797 return response
.content
3800 def create_vdc(self
, vdc_name
=None):
3804 xml_content
= self
.create_vdc_from_tmpl_rest(vdc_name
=vdc_name
)
3805 if xml_content
is not None:
3807 task_resp_xmlroot
= XmlElementTree
.fromstring(xml_content
)
3808 for child
in task_resp_xmlroot
:
3809 if child
.tag
.split("}")[1] == 'Owner':
3810 vdc_id
= child
.attrib
.get('href').split("/")[-1]
3811 vdc_dict
[vdc_id
] = task_resp_xmlroot
.get('href')
3814 self
.logger
.debug("Respond body {}".format(xml_content
))
3818 def create_vdc_from_tmpl_rest(self
, vdc_name
=None):
3820 Method create vdc in vCloud director based on VDC template.
3821 it uses pre-defined template.
3824 vdc_name - name of a new vdc.
3827 The return xml content of respond or None
3829 # pre-requesite atleast one vdc template should be available in vCD
3830 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
3831 vca
= self
.connect_as_admin()
3833 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
3834 if vdc_name
is None:
3837 url_list
= [self
.url
, '/api/vdcTemplates']
3838 vm_list_rest_call
= ''.join(url_list
)
3840 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3841 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
3842 response
= self
.perform_request(req_type
='GET',
3843 url
=vm_list_rest_call
,
3846 # container url to a template
3847 vdc_template_ref
= None
3849 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3850 for child
in vm_list_xmlroot
:
3851 # application/vnd.vmware.admin.providervdc+xml
3852 # we need find a template from witch we instantiate VDC
3853 if child
.tag
.split("}")[1] == 'VdcTemplate':
3854 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.vdcTemplate+xml':
3855 vdc_template_ref
= child
.attrib
.get('href')
3857 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3858 self
.logger
.debug("Respond body {}".format(response
.content
))
3861 # if we didn't found required pre defined template we return None
3862 if vdc_template_ref
is None:
3867 url_list
= [self
.url
, '/api/org/', self
.org_uuid
, '/action/instantiate']
3868 vm_list_rest_call
= ''.join(url_list
)
3869 data
= """<InstantiateVdcTemplateParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
3870 <Source href="{1:s}"></Source>
3871 <Description>opnemano</Description>
3872 </InstantiateVdcTemplateParams>""".format(vdc_name
, vdc_template_ref
)
3874 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml'
3876 response
= self
.perform_request(req_type
='POST',
3877 url
=vm_list_rest_call
,
3881 vdc_task
= self
.get_task_from_response(response
.content
)
3882 self
.client
.get_task_monitor().wait_for_success(task
=vdc_task
)
3884 # if we all ok we respond with content otherwise by default None
3885 if response
.status_code
>= 200 and response
.status_code
< 300:
3886 return response
.content
3889 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3890 self
.logger
.debug("Respond body {}".format(response
.content
))
3894 def create_vdc_rest(self
, vdc_name
=None):
3896 Method create network in vCloud director
3899 vdc_name - vdc name to be created
3904 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
3906 vca
= self
.connect_as_admin()
3908 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
3909 if vdc_name
is None:
3912 url_list
= [self
.url
, '/api/admin/org/', self
.org_uuid
]
3913 vm_list_rest_call
= ''.join(url_list
)
3916 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3917 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3918 response
= self
.perform_request(req_type
='GET',
3919 url
=vm_list_rest_call
,
3922 provider_vdc_ref
= None
3923 add_vdc_rest_url
= None
3924 available_networks
= None
3926 if response
.status_code
!= requests
.codes
.ok
:
3927 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3928 response
.status_code
))
3932 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3933 for child
in vm_list_xmlroot
:
3934 # application/vnd.vmware.admin.providervdc+xml
3935 if child
.tag
.split("}")[1] == 'Link':
3936 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.createVdcParams+xml' \
3937 and child
.attrib
.get('rel') == 'add':
3938 add_vdc_rest_url
= child
.attrib
.get('href')
3940 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3941 self
.logger
.debug("Respond body {}".format(response
.content
))
3944 response
= self
.get_provider_rest(vca
=vca
)
3946 vm_list_xmlroot
= XmlElementTree
.fromstring(response
)
3947 for child
in vm_list_xmlroot
:
3948 if child
.tag
.split("}")[1] == 'ProviderVdcReferences':
3949 for sub_child
in child
:
3950 provider_vdc_ref
= sub_child
.attrib
.get('href')
3952 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3953 self
.logger
.debug("Respond body {}".format(response
))
3956 if add_vdc_rest_url
is not None and provider_vdc_ref
is not None:
3957 data
= """ <CreateVdcParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5"><Description>{1:s}</Description>
3958 <AllocationModel>ReservationPool</AllocationModel>
3959 <ComputeCapacity><Cpu><Units>MHz</Units><Allocated>2048</Allocated><Limit>2048</Limit></Cpu>
3960 <Memory><Units>MB</Units><Allocated>2048</Allocated><Limit>2048</Limit></Memory>
3961 </ComputeCapacity><NicQuota>0</NicQuota><NetworkQuota>100</NetworkQuota>
3962 <VdcStorageProfile><Enabled>true</Enabled><Units>MB</Units><Limit>20480</Limit><Default>true</Default></VdcStorageProfile>
3963 <ProviderVdcReference
3964 name="Main Provider"
3966 <UsesFastProvisioning>true</UsesFastProvisioning></CreateVdcParams>""".format(escape(vdc_name
),
3970 headers
['Content-Type'] = 'application/vnd.vmware.admin.createVdcParams+xml'
3972 response
= self
.perform_request(req_type
='POST',
3973 url
=add_vdc_rest_url
,
3977 # if we all ok we respond with content otherwise by default None
3978 if response
.status_code
== 201:
3979 return response
.content
3982 def get_vapp_details_rest(self
, vapp_uuid
=None, need_admin_access
=False):
3984 Method retrieve vapp detail from vCloud director
3987 vapp_uuid - is vapp identifier.
3990 The return network uuid or return None
3996 if need_admin_access
:
3997 vca
= self
.connect_as_admin()
4002 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
4003 if vapp_uuid
is None:
4006 url_list
= [self
.url
, '/api/vApp/vapp-', vapp_uuid
]
4007 get_vapp_restcall
= ''.join(url_list
)
4010 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4011 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
4012 response
= self
.perform_request(req_type
='GET',
4013 url
=get_vapp_restcall
,
4016 if response
.status_code
== 403:
4017 if need_admin_access
== False:
4018 response
= self
.retry_rest('GET', get_vapp_restcall
)
4020 if response
.status_code
!= requests
.codes
.ok
:
4021 self
.logger
.debug("REST API call {} failed. Return status code {}".format(get_vapp_restcall
,
4022 response
.status_code
))
4023 return parsed_respond
4026 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
4027 parsed_respond
['ovfDescriptorUploaded'] = xmlroot_respond
.attrib
['ovfDescriptorUploaded']
4029 namespaces
= {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
4030 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
4031 'vmw': 'http://www.vmware.com/schema/ovf',
4032 'vm': 'http://www.vmware.com/vcloud/v1.5',
4033 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
4034 "vmext":"http://www.vmware.com/vcloud/extension/v1.5",
4035 "xmlns":"http://www.vmware.com/vcloud/v1.5"
4038 created_section
= xmlroot_respond
.find('vm:DateCreated', namespaces
)
4039 if created_section
is not None:
4040 parsed_respond
['created'] = created_section
.text
4042 network_section
= xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig', namespaces
)
4043 if network_section
is not None and 'networkName' in network_section
.attrib
:
4044 parsed_respond
['networkname'] = network_section
.attrib
['networkName']
4046 ipscopes_section
= \
4047 xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig/vm:Configuration/vm:IpScopes',
4049 if ipscopes_section
is not None:
4050 for ipscope
in ipscopes_section
:
4051 for scope
in ipscope
:
4052 tag_key
= scope
.tag
.split("}")[1]
4053 if tag_key
== 'IpRanges':
4054 ip_ranges
= scope
.getchildren()
4055 for ipblock
in ip_ranges
:
4056 for block
in ipblock
:
4057 parsed_respond
[block
.tag
.split("}")[1]] = block
.text
4059 parsed_respond
[tag_key
] = scope
.text
4061 # parse children section for other attrib
4062 children_section
= xmlroot_respond
.find('vm:Children/', namespaces
)
4063 if children_section
is not None:
4064 parsed_respond
['name'] = children_section
.attrib
['name']
4065 parsed_respond
['nestedHypervisorEnabled'] = children_section
.attrib
['nestedHypervisorEnabled'] \
4066 if "nestedHypervisorEnabled" in children_section
.attrib
else None
4067 parsed_respond
['deployed'] = children_section
.attrib
['deployed']
4068 parsed_respond
['status'] = children_section
.attrib
['status']
4069 parsed_respond
['vmuuid'] = children_section
.attrib
['id'].split(":")[-1]
4070 network_adapter
= children_section
.find('vm:NetworkConnectionSection', namespaces
)
4072 for adapters
in network_adapter
:
4073 adapter_key
= adapters
.tag
.split("}")[1]
4074 if adapter_key
== 'PrimaryNetworkConnectionIndex':
4075 parsed_respond
['primarynetwork'] = adapters
.text
4076 if adapter_key
== 'NetworkConnection':
4078 if 'network' in adapters
.attrib
:
4079 vnic
['network'] = adapters
.attrib
['network']
4080 for adapter
in adapters
:
4081 setting_key
= adapter
.tag
.split("}")[1]
4082 vnic
[setting_key
] = adapter
.text
4083 nic_list
.append(vnic
)
4085 for link
in children_section
:
4086 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
4087 if link
.attrib
['rel'] == 'screen:acquireTicket':
4088 parsed_respond
['acquireTicket'] = link
.attrib
4089 if link
.attrib
['rel'] == 'screen:acquireMksTicket':
4090 parsed_respond
['acquireMksTicket'] = link
.attrib
4092 parsed_respond
['interfaces'] = nic_list
4093 vCloud_extension_section
= children_section
.find('xmlns:VCloudExtension', namespaces
)
4094 if vCloud_extension_section
is not None:
4095 vm_vcenter_info
= {}
4096 vim_info
= vCloud_extension_section
.find('vmext:VmVimInfo', namespaces
)
4097 vmext
= vim_info
.find('vmext:VmVimObjectRef', namespaces
)
4098 if vmext
is not None:
4099 vm_vcenter_info
["vm_moref_id"] = vmext
.find('vmext:MoRef', namespaces
).text
4100 parsed_respond
["vm_vcenter_info"]= vm_vcenter_info
4102 virtual_hardware_section
= children_section
.find('ovf:VirtualHardwareSection', namespaces
)
4103 vm_virtual_hardware_info
= {}
4104 if virtual_hardware_section
is not None:
4105 for item
in virtual_hardware_section
.iterfind('ovf:Item',namespaces
):
4106 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
4107 disk_size
= item
.find("rasd:HostResource" ,namespaces
4108 ).attrib
["{"+namespaces
['vm']+"}capacity"]
4110 vm_virtual_hardware_info
["disk_size"]= disk_size
4113 for link
in virtual_hardware_section
:
4114 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
4115 if link
.attrib
['rel'] == 'edit' and link
.attrib
['href'].endswith("/disks"):
4116 vm_virtual_hardware_info
["disk_edit_href"] = link
.attrib
['href']
4119 parsed_respond
["vm_virtual_hardware"]= vm_virtual_hardware_info
4120 except Exception as exp
:
4121 self
.logger
.info("Error occurred calling rest api for getting vApp details {}".format(exp
))
4122 return parsed_respond
4124 def acquire_console(self
, vm_uuid
=None):
4128 if self
.client
._session
:
4129 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4130 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4131 vm_dict
= self
.get_vapp_details_rest(vapp_uuid
=vm_uuid
)
4132 console_dict
= vm_dict
['acquireTicket']
4133 console_rest_call
= console_dict
['href']
4135 response
= self
.perform_request(req_type
='POST',
4136 url
=console_rest_call
,
4139 if response
.status_code
== 403:
4140 response
= self
.retry_rest('POST', console_rest_call
)
4142 if response
.status_code
== requests
.codes
.ok
:
4143 return response
.content
4147 def modify_vm_disk(self
, vapp_uuid
, flavor_disk
):
4149 Method retrieve vm disk details
4152 vapp_uuid - is vapp identifier.
4153 flavor_disk - disk size as specified in VNFD (flavor)
4156 The return network uuid or return None
4160 #Flavor disk is in GB convert it into MB
4161 flavor_disk
= int(flavor_disk
) * 1024
4162 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
4164 vm_name
= vm_details
["name"]
4165 self
.logger
.info("VM: {} flavor_disk :{}".format(vm_name
, flavor_disk
))
4167 if vm_details
and "vm_virtual_hardware" in vm_details
:
4168 vm_disk
= int(vm_details
["vm_virtual_hardware"]["disk_size"])
4169 disk_edit_href
= vm_details
["vm_virtual_hardware"]["disk_edit_href"]
4171 self
.logger
.info("VM: {} VM_disk :{}".format(vm_name
, vm_disk
))
4173 if flavor_disk
> vm_disk
:
4174 status
= self
.modify_vm_disk_rest(disk_edit_href
,flavor_disk
)
4175 self
.logger
.info("Modify disk of VM {} from {} to {} MB".format(vm_name
,
4176 vm_disk
, flavor_disk
))
4179 self
.logger
.info("No need to modify disk of VM {}".format(vm_name
))
4182 except Exception as exp
:
4183 self
.logger
.info("Error occurred while modifing disk size {}".format(exp
))
4186 def modify_vm_disk_rest(self
, disk_href
, disk_size
):
4188 Method retrieve modify vm disk size
4191 disk_href - vCD API URL to GET and PUT disk data
4192 disk_size - disk size as specified in VNFD (flavor)
4195 The return network uuid or return None
4197 if disk_href
is None or disk_size
is None:
4200 if self
.client
._session
:
4201 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4202 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4203 response
= self
.perform_request(req_type
='GET',
4207 if response
.status_code
== 403:
4208 response
= self
.retry_rest('GET', disk_href
)
4210 if response
.status_code
!= requests
.codes
.ok
:
4211 self
.logger
.debug("GET REST API call {} failed. Return status code {}".format(disk_href
,
4212 response
.status_code
))
4215 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
4216 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
4218 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
4219 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
4221 for item
in lxmlroot_respond
.iterfind('xmlns:Item',namespaces
):
4222 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
4223 disk_item
= item
.find("rasd:HostResource" ,namespaces
)
4224 if disk_item
is not None:
4225 disk_item
.attrib
["{"+namespaces
['xmlns']+"}capacity"] = str(disk_size
)
4228 data
= lxmlElementTree
.tostring(lxmlroot_respond
, encoding
='utf8', method
='xml',
4229 xml_declaration
=True)
4231 #Send PUT request to modify disk size
4232 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
4234 response
= self
.perform_request(req_type
='PUT',
4238 if response
.status_code
== 403:
4239 add_headers
= {'Content-Type': headers
['Content-Type']}
4240 response
= self
.retry_rest('PUT', disk_href
, add_headers
, data
)
4242 if response
.status_code
!= 202:
4243 self
.logger
.debug("PUT REST API call {} failed. Return status code {}".format(disk_href
,
4244 response
.status_code
))
4246 modify_disk_task
= self
.get_task_from_response(response
.content
)
4247 result
= self
.client
.get_task_monitor().wait_for_success(task
=modify_disk_task
)
4248 if result
.get('status') == 'success':
4254 except Exception as exp
:
4255 self
.logger
.info("Error occurred calling rest api for modifing disk size {}".format(exp
))
4258 def add_pci_devices(self
, vapp_uuid
, pci_devices
, vmname_andid
):
4260 Method to attach pci devices to VM
4263 vapp_uuid - uuid of vApp/VM
4264 pci_devices - pci devices infromation as specified in VNFD (flavor)
4267 The status of add pci device task , vm object and
4268 vcenter_conect object
4271 self
.logger
.info("Add pci devices {} into vApp {}".format(pci_devices
, vapp_uuid
))
4272 vcenter_conect
, content
= self
.get_vcenter_content()
4273 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
4277 no_of_pci_devices
= len(pci_devices
)
4278 if no_of_pci_devices
> 0:
4279 #Get VM and its host
4280 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
4281 self
.logger
.info("VM {} is currently on host {}".format(vm_obj
, host_obj
))
4282 if host_obj
and vm_obj
:
4283 #get PCI devies from host on which vapp is currently installed
4284 avilable_pci_devices
= self
.get_pci_devices(host_obj
, no_of_pci_devices
)
4286 if avilable_pci_devices
is None:
4287 #find other hosts with active pci devices
4288 new_host_obj
, avilable_pci_devices
= self
.get_host_and_PCIdevices(
4293 if new_host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
4294 #Migrate vm to the host where PCI devices are availble
4295 self
.logger
.info("Relocate VM {} on new host {}".format(vm_obj
, new_host_obj
))
4296 task
= self
.relocate_vm(new_host_obj
, vm_obj
)
4297 if task
is not None:
4298 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4299 self
.logger
.info("Migrate VM status: {}".format(result
))
4300 host_obj
= new_host_obj
4302 self
.logger
.info("Fail to migrate VM : {}".format(result
))
4303 raise vimconn
.vimconnNotFoundException(
4304 "Fail to migrate VM : {} to host {}".format(
4309 if host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
4310 #Add PCI devices one by one
4311 for pci_device
in avilable_pci_devices
:
4312 task
= self
.add_pci_to_vm(host_obj
, vm_obj
, pci_device
)
4314 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4316 self
.logger
.info("Added PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
4318 self
.logger
.error("Fail to add PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
4319 return True, vm_obj
, vcenter_conect
4321 self
.logger
.error("Currently there is no host with"\
4322 " {} number of avaialble PCI devices required for VM {}".format(
4326 raise vimconn
.vimconnNotFoundException(
4327 "Currently there is no host with {} "\
4328 "number of avaialble PCI devices required for VM {}".format(
4332 self
.logger
.debug("No infromation about PCI devices {} ",pci_devices
)
4334 except vmodl
.MethodFault
as error
:
4335 self
.logger
.error("Error occurred while adding PCI devices {} ",error
)
4336 return None, vm_obj
, vcenter_conect
4338 def get_vm_obj(self
, content
, mob_id
):
4340 Method to get the vsphere VM object associated with a given morf ID
4342 vapp_uuid - uuid of vApp/VM
4343 content - vCenter content object
4344 mob_id - mob_id of VM
4352 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
4353 [vim
.VirtualMachine
], True
4355 for vm
in container
.view
:
4356 mobID
= vm
._GetMoId
()
4359 host_obj
= vm_obj
.runtime
.host
4361 except Exception as exp
:
4362 self
.logger
.error("Error occurred while finding VM object : {}".format(exp
))
4363 return host_obj
, vm_obj
4365 def get_pci_devices(self
, host
, need_devices
):
4367 Method to get the details of pci devices on given host
4369 host - vSphere host object
4370 need_devices - number of pci devices needed on host
4373 array of pci devices
4377 used_devices_ids
= []
4381 pciPassthruInfo
= host
.config
.pciPassthruInfo
4382 pciDevies
= host
.hardware
.pciDevice
4384 for pci_status
in pciPassthruInfo
:
4385 if pci_status
.passthruActive
:
4386 for device
in pciDevies
:
4387 if device
.id == pci_status
.id:
4388 all_device_ids
.append(device
.id)
4389 all_devices
.append(device
)
4391 #check if devices are in use
4392 avalible_devices
= all_devices
4394 if vm
.runtime
.powerState
== vim
.VirtualMachinePowerState
.poweredOn
:
4395 vm_devices
= vm
.config
.hardware
.device
4396 for device
in vm_devices
:
4397 if type(device
) is vim
.vm
.device
.VirtualPCIPassthrough
:
4398 if device
.backing
.id in all_device_ids
:
4399 for use_device
in avalible_devices
:
4400 if use_device
.id == device
.backing
.id:
4401 avalible_devices
.remove(use_device
)
4402 used_devices_ids
.append(device
.backing
.id)
4403 self
.logger
.debug("Device {} from devices {}"\
4404 "is in use".format(device
.backing
.id,
4407 if len(avalible_devices
) < need_devices
:
4408 self
.logger
.debug("Host {} don't have {} number of active devices".format(host
,
4410 self
.logger
.debug("found only {} devives {}".format(len(avalible_devices
),
4414 required_devices
= avalible_devices
[:need_devices
]
4415 self
.logger
.info("Found {} PCI devivces on host {} but required only {}".format(
4416 len(avalible_devices
),
4419 self
.logger
.info("Retruning {} devices as {}".format(need_devices
,
4421 return required_devices
4423 except Exception as exp
:
4424 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host
))
4428 def get_host_and_PCIdevices(self
, content
, need_devices
):
4430 Method to get the details of pci devices infromation on all hosts
4433 content - vSphere host object
4434 need_devices - number of pci devices needed on host
4437 array of pci devices and host object
4440 pci_device_objs
= None
4443 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
4444 [vim
.HostSystem
], True)
4445 for host
in container
.view
:
4446 devices
= self
.get_pci_devices(host
, need_devices
)
4449 pci_device_objs
= devices
4451 except Exception as exp
:
4452 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host_obj
))
4454 return host_obj
,pci_device_objs
4456 def relocate_vm(self
, dest_host
, vm
) :
4458 Method to get the relocate VM to new host
4461 dest_host - vSphere host object
4462 vm - vSphere VM object
4469 relocate_spec
= vim
.vm
.RelocateSpec(host
=dest_host
)
4470 task
= vm
.Relocate(relocate_spec
)
4471 self
.logger
.info("Migrating {} to destination host {}".format(vm
, dest_host
))
4472 except Exception as exp
:
4473 self
.logger
.error("Error occurred while relocate VM {} to new host {}: {}".format(
4474 dest_host
, vm
, exp
))
4477 def wait_for_vcenter_task(self
, task
, actionName
='job', hideResult
=False):
4479 Waits and provides updates on a vSphere task
4481 while task
.info
.state
== vim
.TaskInfo
.State
.running
:
4484 if task
.info
.state
== vim
.TaskInfo
.State
.success
:
4485 if task
.info
.result
is not None and not hideResult
:
4486 self
.logger
.info('{} completed successfully, result: {}'.format(
4490 self
.logger
.info('Task {} completed successfully.'.format(actionName
))
4492 self
.logger
.error('{} did not complete successfully: {} '.format(
4497 return task
.info
.result
4499 def add_pci_to_vm(self
,host_object
, vm_object
, host_pci_dev
):
4501 Method to add pci device in given VM
4504 host_object - vSphere host object
4505 vm_object - vSphere VM object
4506 host_pci_dev - host_pci_dev must be one of the devices from the
4507 host_object.hardware.pciDevice list
4508 which is configured as a PCI passthrough device
4514 if vm_object
and host_object
and host_pci_dev
:
4516 #Add PCI device to VM
4517 pci_passthroughs
= vm_object
.environmentBrowser
.QueryConfigTarget(host
=None).pciPassthrough
4518 systemid_by_pciid
= {item
.pciDevice
.id: item
.systemId
for item
in pci_passthroughs
}
4520 if host_pci_dev
.id not in systemid_by_pciid
:
4521 self
.logger
.error("Device {} is not a passthrough device ".format(host_pci_dev
))
4524 deviceId
= hex(host_pci_dev
.deviceId
% 2**16).lstrip('0x')
4525 backing
= vim
.VirtualPCIPassthroughDeviceBackingInfo(deviceId
=deviceId
,
4527 systemId
=systemid_by_pciid
[host_pci_dev
.id],
4528 vendorId
=host_pci_dev
.vendorId
,
4529 deviceName
=host_pci_dev
.deviceName
)
4531 hba_object
= vim
.VirtualPCIPassthrough(key
=-100, backing
=backing
)
4533 new_device_config
= vim
.VirtualDeviceConfigSpec(device
=hba_object
)
4534 new_device_config
.operation
= "add"
4535 vmConfigSpec
= vim
.vm
.ConfigSpec()
4536 vmConfigSpec
.deviceChange
= [new_device_config
]
4538 task
= vm_object
.ReconfigVM_Task(spec
=vmConfigSpec
)
4539 self
.logger
.info("Adding PCI device {} into VM {} from host {} ".format(
4540 host_pci_dev
, vm_object
, host_object
)
4542 except Exception as exp
:
4543 self
.logger
.error("Error occurred while adding pci devive {} to VM {}: {}".format(
4549 def get_vm_vcenter_info(self
):
4551 Method to get details of vCenter and vm
4554 vapp_uuid - uuid of vApp or VM
4557 Moref Id of VM and deails of vCenter
4559 vm_vcenter_info
= {}
4561 if self
.vcenter_ip
is not None:
4562 vm_vcenter_info
["vm_vcenter_ip"] = self
.vcenter_ip
4564 raise vimconn
.vimconnException(message
="vCenter IP is not provided."\
4565 " Please provide vCenter IP while attaching datacenter to tenant in --config")
4566 if self
.vcenter_port
is not None:
4567 vm_vcenter_info
["vm_vcenter_port"] = self
.vcenter_port
4569 raise vimconn
.vimconnException(message
="vCenter port is not provided."\
4570 " Please provide vCenter port while attaching datacenter to tenant in --config")
4571 if self
.vcenter_user
is not None:
4572 vm_vcenter_info
["vm_vcenter_user"] = self
.vcenter_user
4574 raise vimconn
.vimconnException(message
="vCenter user is not provided."\
4575 " Please provide vCenter user while attaching datacenter to tenant in --config")
4577 if self
.vcenter_password
is not None:
4578 vm_vcenter_info
["vm_vcenter_password"] = self
.vcenter_password
4580 raise vimconn
.vimconnException(message
="vCenter user password is not provided."\
4581 " Please provide vCenter user password while attaching datacenter to tenant in --config")
4583 return vm_vcenter_info
4586 def get_vm_pci_details(self
, vmuuid
):
4588 Method to get VM PCI device details from vCenter
4591 vm_obj - vSphere VM object
4594 dict of PCI devives attached to VM
4597 vm_pci_devices_info
= {}
4599 vcenter_conect
, content
= self
.get_vcenter_content()
4600 vm_moref_id
= self
.get_vm_moref_id(vmuuid
)
4602 #Get VM and its host
4604 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
4605 if host_obj
and vm_obj
:
4606 vm_pci_devices_info
["host_name"]= host_obj
.name
4607 vm_pci_devices_info
["host_ip"]= host_obj
.config
.network
.vnic
[0].spec
.ip
.ipAddress
4608 for device
in vm_obj
.config
.hardware
.device
:
4609 if type(device
) == vim
.vm
.device
.VirtualPCIPassthrough
:
4610 device_details
={'devide_id':device
.backing
.id,
4611 'pciSlotNumber':device
.slotInfo
.pciSlotNumber
,
4613 vm_pci_devices_info
[device
.deviceInfo
.label
] = device_details
4615 self
.logger
.error("Can not connect to vCenter while getting "\
4616 "PCI devices infromationn")
4617 return vm_pci_devices_info
4618 except Exception as exp
:
4619 self
.logger
.error("Error occurred while getting VM infromationn"\
4620 " for VM : {}".format(exp
))
4621 raise vimconn
.vimconnException(message
=exp
)
4624 def reserve_memory_for_all_vms(self
, vapp
, memory_mb
):
4626 Method to reserve memory for all VMs
4629 memory_mb - Memory in MB
4634 self
.logger
.info("Reserve memory for all VMs")
4635 for vms
in vapp
.get_all_vms():
4636 vm_id
= vms
.get('id').split(':')[-1]
4638 url_rest_call
= "{}/api/vApp/vm-{}/virtualHardwareSection/memory".format(self
.url
, vm_id
)
4640 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4641 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4642 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
4643 response
= self
.perform_request(req_type
='GET',
4647 if response
.status_code
== 403:
4648 response
= self
.retry_rest('GET', url_rest_call
)
4650 if response
.status_code
!= 200:
4651 self
.logger
.error("REST call {} failed reason : {}"\
4652 "status code : {}".format(url_rest_call
,
4654 response
.status_code
))
4655 raise vimconn
.vimconnException("reserve_memory_for_all_vms : Failed to get "\
4658 bytexml
= bytes(bytearray(response
.content
, encoding
='utf-8'))
4659 contentelem
= lxmlElementTree
.XML(bytexml
)
4660 namespaces
= {prefix
:uri
for prefix
,uri
in contentelem
.nsmap
.iteritems() if prefix
}
4661 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
4663 # Find the reservation element in the response
4664 memelem_list
= contentelem
.findall(".//rasd:Reservation", namespaces
)
4665 for memelem
in memelem_list
:
4666 memelem
.text
= str(memory_mb
)
4668 newdata
= lxmlElementTree
.tostring(contentelem
, pretty_print
=True)
4670 response
= self
.perform_request(req_type
='PUT',
4675 if response
.status_code
== 403:
4676 add_headers
= {'Content-Type': headers
['Content-Type']}
4677 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, newdata
)
4679 if response
.status_code
!= 202:
4680 self
.logger
.error("REST call {} failed reason : {}"\
4681 "status code : {} ".format(url_rest_call
,
4683 response
.status_code
))
4684 raise vimconn
.vimconnException("reserve_memory_for_all_vms : Failed to update "\
4685 "virtual hardware memory section")
4687 mem_task
= self
.get_task_from_response(response
.content
)
4688 result
= self
.client
.get_task_monitor().wait_for_success(task
=mem_task
)
4689 if result
.get('status') == 'success':
4690 self
.logger
.info("reserve_memory_for_all_vms(): VM {} succeeded "\
4693 self
.logger
.error("reserve_memory_for_all_vms(): VM {} failed "\
4696 def connect_vapp_to_org_vdc_network(self
, vapp_id
, net_name
):
4698 Configure VApp network config with org vdc network
4705 self
.logger
.info("Connecting vapp {} to org vdc network {}".
4706 format(vapp_id
, net_name
))
4708 url_rest_call
= "{}/api/vApp/vapp-{}/networkConfigSection/".format(self
.url
, vapp_id
)
4710 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4711 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4712 response
= self
.perform_request(req_type
='GET',
4716 if response
.status_code
== 403:
4717 response
= self
.retry_rest('GET', url_rest_call
)
4719 if response
.status_code
!= 200:
4720 self
.logger
.error("REST call {} failed reason : {}"\
4721 "status code : {}".format(url_rest_call
,
4723 response
.status_code
))
4724 raise vimconn
.vimconnException("connect_vapp_to_org_vdc_network : Failed to get "\
4725 "network config section")
4727 data
= response
.content
4728 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConfigSection+xml'
4729 net_id
= self
.get_network_id_by_name(net_name
)
4731 raise vimconn
.vimconnException("connect_vapp_to_org_vdc_network : Failed to find "\
4734 bytexml
= bytes(bytearray(data
, encoding
='utf-8'))
4735 newelem
= lxmlElementTree
.XML(bytexml
)
4736 namespaces
= {prefix
: uri
for prefix
, uri
in newelem
.nsmap
.iteritems() if prefix
}
4737 namespaces
["xmlns"] = "http://www.vmware.com/vcloud/v1.5"
4738 nwcfglist
= newelem
.findall(".//xmlns:NetworkConfig", namespaces
)
4740 newstr
= """<NetworkConfig networkName="{}">
4742 <ParentNetwork href="{}/api/network/{}"/>
4743 <FenceMode>bridged</FenceMode>
4746 """.format(net_name
, self
.url
, net_id
)
4747 newcfgelem
= lxmlElementTree
.fromstring(newstr
)
4749 nwcfglist
[0].addnext(newcfgelem
)
4751 newdata
= lxmlElementTree
.tostring(newelem
, pretty_print
=True)
4753 response
= self
.perform_request(req_type
='PUT',
4758 if response
.status_code
== 403:
4759 add_headers
= {'Content-Type': headers
['Content-Type']}
4760 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, newdata
)
4762 if response
.status_code
!= 202:
4763 self
.logger
.error("REST call {} failed reason : {}"\
4764 "status code : {} ".format(url_rest_call
,
4766 response
.status_code
))
4767 raise vimconn
.vimconnException("connect_vapp_to_org_vdc_network : Failed to update "\
4768 "network config section")
4770 vapp_task
= self
.get_task_from_response(response
.content
)
4771 result
= self
.client
.get_task_monitor().wait_for_success(task
=vapp_task
)
4772 if result
.get('status') == 'success':
4773 self
.logger
.info("connect_vapp_to_org_vdc_network(): Vapp {} connected to "\
4774 "network {}".format(vapp_id
, net_name
))
4776 self
.logger
.error("connect_vapp_to_org_vdc_network(): Vapp {} failed to "\
4777 "connect to network {}".format(vapp_id
, net_name
))
4779 def remove_primary_network_adapter_from_all_vms(self
, vapp
):
4781 Method to remove network adapter type to vm
4788 self
.logger
.info("Removing network adapter from all VMs")
4789 for vms
in vapp
.get_all_vms():
4790 vm_id
= vms
.get('id').split(':')[-1]
4792 url_rest_call
= "{}/api/vApp/vm-{}/networkConnectionSection/".format(self
.url
, vm_id
)
4794 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4795 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4796 response
= self
.perform_request(req_type
='GET',
4800 if response
.status_code
== 403:
4801 response
= self
.retry_rest('GET', url_rest_call
)
4803 if response
.status_code
!= 200:
4804 self
.logger
.error("REST call {} failed reason : {}"\
4805 "status code : {}".format(url_rest_call
,
4807 response
.status_code
))
4808 raise vimconn
.vimconnException("remove_primary_network_adapter : Failed to get "\
4809 "network connection section")
4811 data
= response
.content
4812 data
= data
.split('<Link rel="edit"')[0]
4814 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
4816 newdata
= """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4817 <NetworkConnectionSection xmlns="http://www.vmware.com/vcloud/v1.5"
4818 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
4819 xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData"
4820 xmlns:common="http://schemas.dmtf.org/wbem/wscim/1/common"
4821 xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
4822 xmlns:vmw="http://www.vmware.com/schema/ovf"
4823 xmlns:ovfenv="http://schemas.dmtf.org/ovf/environment/1"
4824 xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
4825 xmlns:ns9="http://www.vmware.com/vcloud/versions"
4826 href="{url}" type="application/vnd.vmware.vcloud.networkConnectionSection+xml" ovf:required="false">
4827 <ovf:Info>Specifies the available VM network connections</ovf:Info>
4828 <PrimaryNetworkConnectionIndex>0</PrimaryNetworkConnectionIndex>
4829 <Link rel="edit" href="{url}" type="application/vnd.vmware.vcloud.networkConnectionSection+xml"/>
4830 </NetworkConnectionSection>""".format(url
=url_rest_call
)
4831 response
= self
.perform_request(req_type
='PUT',
4836 if response
.status_code
== 403:
4837 add_headers
= {'Content-Type': headers
['Content-Type']}
4838 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, newdata
)
4840 if response
.status_code
!= 202:
4841 self
.logger
.error("REST call {} failed reason : {}"\
4842 "status code : {} ".format(url_rest_call
,
4844 response
.status_code
))
4845 raise vimconn
.vimconnException("remove_primary_network_adapter : Failed to update "\
4846 "network connection section")
4848 nic_task
= self
.get_task_from_response(response
.content
)
4849 result
= self
.client
.get_task_monitor().wait_for_success(task
=nic_task
)
4850 if result
.get('status') == 'success':
4851 self
.logger
.info("remove_primary_network_adapter(): VM {} conneced to "\
4852 "default NIC type".format(vm_id
))
4854 self
.logger
.error("remove_primary_network_adapter(): VM {} failed to "\
4855 "connect NIC type".format(vm_id
))
4857 def add_network_adapter_to_vms(self
, vapp
, network_name
, primary_nic_index
, nicIndex
, net
, nic_type
=None):
4859 Method to add network adapter type to vm
4861 network_name - name of network
4862 primary_nic_index - int value for primary nic index
4863 nicIndex - int value for nic index
4864 nic_type - specify model name to which add to vm
4869 self
.logger
.info("Add network adapter to VM: network_name {} nicIndex {} nic_type {}".\
4870 format(network_name
, nicIndex
, nic_type
))
4875 if 'floating_ip' in net
: floating_ip
= net
['floating_ip']
4877 # Stub for ip_address feature
4878 if 'ip_address' in net
: ip_address
= net
['ip_address']
4880 if 'mac_address' in net
: mac_address
= net
['mac_address']
4883 allocation_mode
= "POOL"
4885 allocation_mode
= "MANUAL"
4887 allocation_mode
= "DHCP"
4890 for vms
in vapp
.get_all_vms():
4891 vm_id
= vms
.get('id').split(':')[-1]
4893 url_rest_call
= "{}/api/vApp/vm-{}/networkConnectionSection/".format(self
.url
, vm_id
)
4895 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4896 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4897 response
= self
.perform_request(req_type
='GET',
4901 if response
.status_code
== 403:
4902 response
= self
.retry_rest('GET', url_rest_call
)
4904 if response
.status_code
!= 200:
4905 self
.logger
.error("REST call {} failed reason : {}"\
4906 "status code : {}".format(url_rest_call
,
4908 response
.status_code
))
4909 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to get "\
4910 "network connection section")
4912 data
= response
.content
4913 data
= data
.split('<Link rel="edit"')[0]
4914 if '<PrimaryNetworkConnectionIndex>' not in data
:
4915 self
.logger
.debug("add_network_adapter PrimaryNIC not in data")
4916 item
= """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
4917 <NetworkConnection network="{}">
4918 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4919 <IsConnected>true</IsConnected>
4920 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4921 </NetworkConnection>""".format(primary_nic_index
, network_name
, nicIndex
,
4923 # Stub for ip_address feature
4925 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4926 item
= item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4929 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4930 item
= item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4932 data
= data
.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item
))
4934 self
.logger
.debug("add_network_adapter PrimaryNIC in data")
4935 new_item
= """<NetworkConnection network="{}">
4936 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4937 <IsConnected>true</IsConnected>
4938 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4939 </NetworkConnection>""".format(network_name
, nicIndex
,
4941 # Stub for ip_address feature
4943 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4944 new_item
= new_item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4947 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4948 new_item
= new_item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4950 data
= data
+ new_item
+ '</NetworkConnectionSection>'
4952 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
4954 response
= self
.perform_request(req_type
='PUT',
4959 if response
.status_code
== 403:
4960 add_headers
= {'Content-Type': headers
['Content-Type']}
4961 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, data
)
4963 if response
.status_code
!= 202:
4964 self
.logger
.error("REST call {} failed reason : {}"\
4965 "status code : {} ".format(url_rest_call
,
4967 response
.status_code
))
4968 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to update "\
4969 "network connection section")
4971 nic_task
= self
.get_task_from_response(response
.content
)
4972 result
= self
.client
.get_task_monitor().wait_for_success(task
=nic_task
)
4973 if result
.get('status') == 'success':
4974 self
.logger
.info("add_network_adapter_to_vms(): VM {} conneced to "\
4975 "default NIC type".format(vm_id
))
4977 self
.logger
.error("add_network_adapter_to_vms(): VM {} failed to "\
4978 "connect NIC type".format(vm_id
))
4980 for vms
in vapp
.get_all_vms():
4981 vm_id
= vms
.get('id').split(':')[-1]
4983 url_rest_call
= "{}/api/vApp/vm-{}/networkConnectionSection/".format(self
.url
, vm_id
)
4985 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4986 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4987 response
= self
.perform_request(req_type
='GET',
4991 if response
.status_code
== 403:
4992 response
= self
.retry_rest('GET', url_rest_call
)
4994 if response
.status_code
!= 200:
4995 self
.logger
.error("REST call {} failed reason : {}"\
4996 "status code : {}".format(url_rest_call
,
4998 response
.status_code
))
4999 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to get "\
5000 "network connection section")
5001 data
= response
.content
5002 data
= data
.split('<Link rel="edit"')[0]
5003 vcd_netadapter_type
= nic_type
5004 if nic_type
in ['SR-IOV', 'VF']:
5005 vcd_netadapter_type
= "SRIOVETHERNETCARD"
5007 if '<PrimaryNetworkConnectionIndex>' not in data
:
5008 self
.logger
.debug("add_network_adapter PrimaryNIC not in data nic_type {}".format(nic_type
))
5009 item
= """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
5010 <NetworkConnection network="{}">
5011 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5012 <IsConnected>true</IsConnected>
5013 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5014 <NetworkAdapterType>{}</NetworkAdapterType>
5015 </NetworkConnection>""".format(primary_nic_index
, network_name
, nicIndex
,
5016 allocation_mode
, vcd_netadapter_type
)
5017 # Stub for ip_address feature
5019 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
5020 item
= item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
5023 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
5024 item
= item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
5026 data
= data
.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item
))
5028 self
.logger
.debug("add_network_adapter PrimaryNIC in data nic_type {}".format(nic_type
))
5029 new_item
= """<NetworkConnection network="{}">
5030 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
5031 <IsConnected>true</IsConnected>
5032 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
5033 <NetworkAdapterType>{}</NetworkAdapterType>
5034 </NetworkConnection>""".format(network_name
, nicIndex
,
5035 allocation_mode
, vcd_netadapter_type
)
5036 # Stub for ip_address feature
5038 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
5039 new_item
= new_item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
5042 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
5043 new_item
= new_item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
5045 data
= data
+ new_item
+ '</NetworkConnectionSection>'
5047 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
5049 response
= self
.perform_request(req_type
='PUT',
5054 if response
.status_code
== 403:
5055 add_headers
= {'Content-Type': headers
['Content-Type']}
5056 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, data
)
5058 if response
.status_code
!= 202:
5059 self
.logger
.error("REST call {} failed reason : {}"\
5060 "status code : {}".format(url_rest_call
,
5062 response
.status_code
))
5063 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to update "\
5064 "network connection section")
5066 nic_task
= self
.get_task_from_response(response
.content
)
5067 result
= self
.client
.get_task_monitor().wait_for_success(task
=nic_task
)
5068 if result
.get('status') == 'success':
5069 self
.logger
.info("add_network_adapter_to_vms(): VM {} "\
5070 "conneced to NIC type {}".format(vm_id
, nic_type
))
5072 self
.logger
.error("add_network_adapter_to_vms(): VM {} "\
5073 "failed to connect NIC type {}".format(vm_id
, nic_type
))
5074 except Exception as exp
:
5075 self
.logger
.error("add_network_adapter_to_vms() : exception occurred "\
5076 "while adding Network adapter")
5077 raise vimconn
.vimconnException(message
=exp
)
5080 def set_numa_affinity(self
, vmuuid
, paired_threads_id
):
5082 Method to assign numa affinity in vm configuration parammeters
5085 paired_threads_id - one or more virtual processor
5091 vcenter_conect
, content
= self
.get_vcenter_content()
5092 vm_moref_id
= self
.get_vm_moref_id(vmuuid
)
5094 host_obj
, vm_obj
= self
.get_vm_obj(content
,vm_moref_id
)
5096 config_spec
= vim
.vm
.ConfigSpec()
5097 config_spec
.extraConfig
= []
5098 opt
= vim
.option
.OptionValue()
5099 opt
.key
= 'numa.nodeAffinity'
5100 opt
.value
= str(paired_threads_id
)
5101 config_spec
.extraConfig
.append(opt
)
5102 task
= vm_obj
.ReconfigVM_Task(config_spec
)
5104 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5105 extra_config
= vm_obj
.config
.extraConfig
5107 for opts
in extra_config
:
5108 if 'numa.nodeAffinity' in opts
.key
:
5110 self
.logger
.info("set_numa_affinity: Sucessfully assign numa affinity "\
5111 "value {} for vm {}".format(opt
.value
, vm_obj
))
5115 self
.logger
.error("set_numa_affinity: Failed to assign numa affinity")
5116 except Exception as exp
:
5117 self
.logger
.error("set_numa_affinity : exception occurred while setting numa affinity "\
5118 "for VM {} : {}".format(vm_obj
, vm_moref_id
))
5119 raise vimconn
.vimconnException("set_numa_affinity : Error {} failed to assign numa "\
5120 "affinity".format(exp
))
5123 def cloud_init(self
, vapp
, cloud_config
):
5125 Method to inject ssh-key
5127 cloud_config a dictionary with:
5128 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
5129 'users': (optional) list of users to be inserted, each item is a dict with:
5130 'name': (mandatory) user name,
5131 'key-pairs': (optional) list of strings with the public key to be inserted to the user
5132 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
5133 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
5134 'config-files': (optional). List of files to be transferred. Each item is a dict with:
5135 'dest': (mandatory) string with the destination absolute path
5136 'encoding': (optional, by default text). Can be one of:
5137 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
5138 'content' (mandatory): string with the content of the file
5139 'permissions': (optional) string with file permissions, typically octal notation '0644'
5140 'owner': (optional) file owner, string with the format 'owner:group'
5141 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk
5144 if not isinstance(cloud_config
, dict):
5145 raise Exception("cloud_init : parameter cloud_config is not a dictionary")
5149 if "key-pairs" in cloud_config
:
5150 key_pairs
= cloud_config
["key-pairs"]
5152 if "users" in cloud_config
:
5153 userdata
= cloud_config
["users"]
5155 self
.logger
.debug("cloud_init : Guest os customization started..")
5156 customize_script
= self
.format_script(key_pairs
=key_pairs
, users_list
=userdata
)
5157 customize_script
= customize_script
.replace("&","&")
5158 self
.guest_customization(vapp
, customize_script
)
5160 except Exception as exp
:
5161 self
.logger
.error("cloud_init : exception occurred while injecting "\
5163 raise vimconn
.vimconnException("cloud_init : Error {} failed to inject "\
5164 "ssh-key".format(exp
))
5166 def format_script(self
, key_pairs
=[], users_list
=[]):
5167 bash_script
= """#!/bin/sh
5168 echo performing customization tasks with param $1 at `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
5169 if [ "$1" = "precustomization" ];then
5170 echo performing precustomization tasks on `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
5173 keys
= "\n".join(key_pairs
)
5176 if [ ! -d /root/.ssh ];then
5178 chown root:root /root/.ssh
5179 chmod 700 /root/.ssh
5180 touch /root/.ssh/authorized_keys
5181 chown root:root /root/.ssh/authorized_keys
5182 chmod 600 /root/.ssh/authorized_keys
5183 # make centos with selinux happy
5184 which restorecon && restorecon -Rv /root/.ssh
5186 touch /root/.ssh/authorized_keys
5187 chown root:root /root/.ssh/authorized_keys
5188 chmod 600 /root/.ssh/authorized_keys
5190 echo '{key}' >> /root/.ssh/authorized_keys
5191 """.format(key
=keys
)
5193 bash_script
+= keys_data
5195 for user
in users_list
:
5196 if 'name' in user
: user_name
= user
['name']
5197 if 'key-pairs' in user
:
5198 user_keys
= "\n".join(user
['key-pairs'])
5203 useradd -d /home/{user_name} -m -g users -s /bin/bash {user_name}
5204 """.format(user_name
=user_name
)
5206 bash_script
+= add_user_name
5209 user_keys_data
= """
5210 mkdir /home/{user_name}/.ssh
5211 chown {user_name}:{user_name} /home/{user_name}/.ssh
5212 chmod 700 /home/{user_name}/.ssh
5213 touch /home/{user_name}/.ssh/authorized_keys
5214 chown {user_name}:{user_name} /home/{user_name}/.ssh/authorized_keys
5215 chmod 600 /home/{user_name}/.ssh/authorized_keys
5216 # make centos with selinux happy
5217 which restorecon && restorecon -Rv /home/{user_name}/.ssh
5218 echo '{user_key}' >> /home/{user_name}/.ssh/authorized_keys
5219 """.format(user_name
=user_name
,user_key
=user_keys
)
5221 bash_script
+= user_keys_data
5223 return bash_script
+"\n\tfi"
5225 def guest_customization(self
, vapp
, customize_script
):
5227 Method to customize guest os
5229 customize_script - Customize script to be run at first boot of VM.
5231 for vm
in vapp
.get_all_vms():
5232 vm_id
= vm
.get('id').split(':')[-1]
5233 vm_name
= vm
.get('name')
5234 vm_name
= vm_name
.replace('_','-')
5236 vm_customization_url
= "{}/api/vApp/vm-{}/guestCustomizationSection/".format(self
.url
, vm_id
)
5237 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5238 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
5240 headers
['Content-Type'] = "application/vnd.vmware.vcloud.guestCustomizationSection+xml"
5242 data
= """<GuestCustomizationSection
5243 xmlns="http://www.vmware.com/vcloud/v1.5"
5244 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
5245 ovf:required="false" href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml">
5246 <ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
5247 <Enabled>true</Enabled>
5248 <ChangeSid>false</ChangeSid>
5249 <VirtualMachineId>{}</VirtualMachineId>
5250 <JoinDomainEnabled>false</JoinDomainEnabled>
5251 <UseOrgSettings>false</UseOrgSettings>
5252 <AdminPasswordEnabled>false</AdminPasswordEnabled>
5253 <AdminPasswordAuto>true</AdminPasswordAuto>
5254 <AdminAutoLogonEnabled>false</AdminAutoLogonEnabled>
5255 <AdminAutoLogonCount>0</AdminAutoLogonCount>
5256 <ResetPasswordRequired>false</ResetPasswordRequired>
5257 <CustomizationScript>{}</CustomizationScript>
5258 <ComputerName>{}</ComputerName>
5259 <Link href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml" rel="edit"/>
5260 </GuestCustomizationSection>
5261 """.format(vm_customization_url
,
5265 vm_customization_url
)
5267 response
= self
.perform_request(req_type
='PUT',
5268 url
=vm_customization_url
,
5271 if response
.status_code
== 202:
5272 guest_task
= self
.get_task_from_response(response
.content
)
5273 self
.client
.get_task_monitor().wait_for_success(task
=guest_task
)
5274 self
.logger
.info("guest_customization : customized guest os task "\
5275 "completed for VM {}".format(vm_name
))
5277 self
.logger
.error("guest_customization : task for customized guest os"\
5278 "failed for VM {}".format(vm_name
))
5279 raise vimconn
.vimconnException("guest_customization : failed to perform"\
5280 "guest os customization on VM {}".format(vm_name
))
5282 def add_new_disk(self
, vapp_uuid
, disk_size
):
5284 Method to create an empty vm disk
5287 vapp_uuid - is vapp identifier.
5288 disk_size - size of disk to be created in GB
5296 #Disk size in GB, convert it into MB
5297 if disk_size
is not None:
5298 disk_size_mb
= int(disk_size
) * 1024
5299 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
5301 if vm_details
and "vm_virtual_hardware" in vm_details
:
5302 self
.logger
.info("Adding disk to VM: {} disk size:{}GB".format(vm_details
["name"], disk_size
))
5303 disk_href
= vm_details
["vm_virtual_hardware"]["disk_edit_href"]
5304 status
= self
.add_new_disk_rest(disk_href
, disk_size_mb
)
5306 except Exception as exp
:
5307 msg
= "Error occurred while creating new disk {}.".format(exp
)
5308 self
.rollback_newvm(vapp_uuid
, msg
)
5311 self
.logger
.info("Added new disk to VM: {} disk size:{}GB".format(vm_details
["name"], disk_size
))
5313 #If failed to add disk, delete VM
5314 msg
= "add_new_disk: Failed to add new disk to {}".format(vm_details
["name"])
5315 self
.rollback_newvm(vapp_uuid
, msg
)
5318 def add_new_disk_rest(self
, disk_href
, disk_size_mb
):
5320 Retrives vApp Disks section & add new empty disk
5323 disk_href: Disk section href to addd disk
5324 disk_size_mb: Disk size in MB
5326 Returns: Status of add new disk task
5329 if self
.client
._session
:
5330 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5331 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
5332 response
= self
.perform_request(req_type
='GET',
5336 if response
.status_code
== 403:
5337 response
= self
.retry_rest('GET', disk_href
)
5339 if response
.status_code
!= requests
.codes
.ok
:
5340 self
.logger
.error("add_new_disk_rest: GET REST API call {} failed. Return status code {}"
5341 .format(disk_href
, response
.status_code
))
5344 #Find but type & max of instance IDs assigned to disks
5345 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
5346 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
5348 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
5349 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
5351 for item
in lxmlroot_respond
.iterfind('xmlns:Item',namespaces
):
5352 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
5353 inst_id
= int(item
.find("rasd:InstanceID" ,namespaces
).text
)
5354 if inst_id
> instance_id
:
5355 instance_id
= inst_id
5356 disk_item
= item
.find("rasd:HostResource" ,namespaces
)
5357 bus_subtype
= disk_item
.attrib
["{"+namespaces
['xmlns']+"}busSubType"]
5358 bus_type
= disk_item
.attrib
["{"+namespaces
['xmlns']+"}busType"]
5360 instance_id
= instance_id
+ 1
5361 new_item
= """<Item>
5362 <rasd:Description>Hard disk</rasd:Description>
5363 <rasd:ElementName>New disk</rasd:ElementName>
5365 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
5366 vcloud:capacity="{}"
5367 vcloud:busSubType="{}"
5368 vcloud:busType="{}"></rasd:HostResource>
5369 <rasd:InstanceID>{}</rasd:InstanceID>
5370 <rasd:ResourceType>17</rasd:ResourceType>
5371 </Item>""".format(disk_size_mb
, bus_subtype
, bus_type
, instance_id
)
5373 new_data
= response
.content
5374 #Add new item at the bottom
5375 new_data
= new_data
.replace('</Item>\n</RasdItemsList>', '</Item>\n{}\n</RasdItemsList>'.format(new_item
))
5377 # Send PUT request to modify virtual hardware section with new disk
5378 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
5380 response
= self
.perform_request(req_type
='PUT',
5385 if response
.status_code
== 403:
5386 add_headers
= {'Content-Type': headers
['Content-Type']}
5387 response
= self
.retry_rest('PUT', disk_href
, add_headers
, new_data
)
5389 if response
.status_code
!= 202:
5390 self
.logger
.error("PUT REST API call {} failed. Return status code {}. Response Content:{}"
5391 .format(disk_href
, response
.status_code
, response
.content
))
5393 add_disk_task
= self
.get_task_from_response(response
.content
)
5394 result
= self
.client
.get_task_monitor().wait_for_success(task
=add_disk_task
)
5395 if result
.get('status') == 'success':
5398 self
.logger
.error("Add new disk REST task failed to add {} MB disk".format(disk_size_mb
))
5400 except Exception as exp
:
5401 self
.logger
.error("Error occurred calling rest api for creating new disk {}".format(exp
))
5406 def add_existing_disk(self
, catalogs
=None, image_id
=None, size
=None, template_name
=None, vapp_uuid
=None):
5408 Method to add existing disk to vm
5410 catalogs - List of VDC catalogs
5411 image_id - Catalog ID
5412 template_name - Name of template in catalog
5413 vapp_uuid - UUID of vApp
5418 vcenter_conect
, content
= self
.get_vcenter_content()
5419 #find moref-id of vm in image
5420 catalog_vm_info
= self
.get_vapp_template_details(catalogs
=catalogs
,
5424 if catalog_vm_info
and "vm_vcenter_info" in catalog_vm_info
:
5425 if "vm_moref_id" in catalog_vm_info
["vm_vcenter_info"]:
5426 catalog_vm_moref_id
= catalog_vm_info
["vm_vcenter_info"].get("vm_moref_id", None)
5427 if catalog_vm_moref_id
:
5428 self
.logger
.info("Moref_id of VM in catalog : {}" .format(catalog_vm_moref_id
))
5429 host
, catalog_vm_obj
= self
.get_vm_obj(content
, catalog_vm_moref_id
)
5432 disk_info
= self
.find_disk(catalog_vm_obj
)
5434 exp_msg
= "No VM with image id {} found".format(image_id
)
5435 self
.rollback_newvm(vapp_uuid
, exp_msg
, exp_type
="NotFound")
5437 exp_msg
= "No Image found with image ID {} ".format(image_id
)
5438 self
.rollback_newvm(vapp_uuid
, exp_msg
, exp_type
="NotFound")
5441 self
.logger
.info("Existing disk_info : {}".format(disk_info
))
5443 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
5444 host
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
5446 status
= self
.add_disk(vcenter_conect
=vcenter_conect
,
5448 disk_info
=disk_info
,
5453 self
.logger
.info("Disk from image id {} added to {}".format(image_id
,
5457 msg
= "No disk found with image id {} to add in VM {}".format(
5460 self
.rollback_newvm(vapp_uuid
, msg
, exp_type
="NotFound")
5463 def find_disk(self
, vm_obj
):
5465 Method to find details of existing disk in VM
5467 vm_obj - vCenter object of VM
5468 image_id - Catalog ID
5470 disk_info : dict of disk details
5475 devices
= vm_obj
.config
.hardware
.device
5476 for device
in devices
:
5477 if type(device
) is vim
.vm
.device
.VirtualDisk
:
5478 if isinstance(device
.backing
,vim
.vm
.device
.VirtualDisk
.FlatVer2BackingInfo
) and hasattr(device
.backing
, 'fileName'):
5479 disk_info
["full_path"] = device
.backing
.fileName
5480 disk_info
["datastore"] = device
.backing
.datastore
5481 disk_info
["capacityKB"] = device
.capacityInKB
5483 except Exception as exp
:
5484 self
.logger
.error("find_disk() : exception occurred while "\
5485 "getting existing disk details :{}".format(exp
))
5489 def add_disk(self
, vcenter_conect
=None, vm
=None, size
=None, vapp_uuid
=None, disk_info
={}):
5491 Method to add existing disk in VM
5493 vcenter_conect - vCenter content object
5494 vm - vCenter vm object
5495 disk_info : dict of disk details
5497 status : status of add disk task
5499 datastore
= disk_info
["datastore"] if "datastore" in disk_info
else None
5500 fullpath
= disk_info
["full_path"] if "full_path" in disk_info
else None
5501 capacityKB
= disk_info
["capacityKB"] if "capacityKB" in disk_info
else None
5502 if size
is not None:
5503 #Convert size from GB to KB
5504 sizeKB
= int(size
) * 1024 * 1024
5505 #compare size of existing disk and user given size.Assign whicherver is greater
5506 self
.logger
.info("Add Existing disk : sizeKB {} , capacityKB {}".format(
5507 sizeKB
, capacityKB
))
5508 if sizeKB
> capacityKB
:
5511 if datastore
and fullpath
and capacityKB
:
5513 spec
= vim
.vm
.ConfigSpec()
5514 # get all disks on a VM, set unit_number to the next available
5516 for dev
in vm
.config
.hardware
.device
:
5517 if hasattr(dev
.backing
, 'fileName'):
5518 unit_number
= int(dev
.unitNumber
) + 1
5519 # unit_number 7 reserved for scsi controller
5520 if unit_number
== 7:
5522 if isinstance(dev
, vim
.vm
.device
.VirtualDisk
):
5523 #vim.vm.device.VirtualSCSIController
5524 controller_key
= dev
.controllerKey
5526 self
.logger
.info("Add Existing disk : unit number {} , controller key {}".format(
5527 unit_number
, controller_key
))
5530 disk_spec
= vim
.vm
.device
.VirtualDeviceSpec()
5531 disk_spec
.operation
= vim
.vm
.device
.VirtualDeviceSpec
.Operation
.add
5532 disk_spec
.device
= vim
.vm
.device
.VirtualDisk()
5533 disk_spec
.device
.backing
= \
5534 vim
.vm
.device
.VirtualDisk
.FlatVer2BackingInfo()
5535 disk_spec
.device
.backing
.thinProvisioned
= True
5536 disk_spec
.device
.backing
.diskMode
= 'persistent'
5537 disk_spec
.device
.backing
.datastore
= datastore
5538 disk_spec
.device
.backing
.fileName
= fullpath
5540 disk_spec
.device
.unitNumber
= unit_number
5541 disk_spec
.device
.capacityInKB
= capacityKB
5542 disk_spec
.device
.controllerKey
= controller_key
5543 dev_changes
.append(disk_spec
)
5544 spec
.deviceChange
= dev_changes
5545 task
= vm
.ReconfigVM_Task(spec
=spec
)
5546 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5548 except Exception as exp
:
5549 exp_msg
= "add_disk() : exception {} occurred while adding disk "\
5550 "{} to vm {}".format(exp
,
5553 self
.rollback_newvm(vapp_uuid
, exp_msg
)
5555 msg
= "add_disk() : Can not add disk to VM with disk info {} ".format(disk_info
)
5556 self
.rollback_newvm(vapp_uuid
, msg
)
5559 def get_vcenter_content(self
):
5561 Get the vsphere content object
5564 vm_vcenter_info
= self
.get_vm_vcenter_info()
5565 except Exception as exp
:
5566 self
.logger
.error("Error occurred while getting vCenter infromationn"\
5567 " for VM : {}".format(exp
))
5568 raise vimconn
.vimconnException(message
=exp
)
5571 if hasattr(ssl
, '_create_unverified_context'):
5572 context
= ssl
._create
_unverified
_context
()
5574 vcenter_conect
= SmartConnect(
5575 host
=vm_vcenter_info
["vm_vcenter_ip"],
5576 user
=vm_vcenter_info
["vm_vcenter_user"],
5577 pwd
=vm_vcenter_info
["vm_vcenter_password"],
5578 port
=int(vm_vcenter_info
["vm_vcenter_port"]),
5581 atexit
.register(Disconnect
, vcenter_conect
)
5582 content
= vcenter_conect
.RetrieveContent()
5583 return vcenter_conect
, content
5586 def get_vm_moref_id(self
, vapp_uuid
):
5588 Get the moref_id of given VM
5592 vm_details
= self
.get_vapp_details_rest(vapp_uuid
, need_admin_access
=True)
5593 if vm_details
and "vm_vcenter_info" in vm_details
:
5594 vm_moref_id
= vm_details
["vm_vcenter_info"].get("vm_moref_id", None)
5597 except Exception as exp
:
5598 self
.logger
.error("Error occurred while getting VM moref ID "\
5599 " for VM : {}".format(exp
))
5603 def get_vapp_template_details(self
, catalogs
=None, image_id
=None , template_name
=None):
5605 Method to get vApp template details
5607 catalogs - list of VDC catalogs
5608 image_id - Catalog ID to find
5609 template_name : template name in catalog
5611 parsed_respond : dict of vApp tempalte details
5613 parsed_response
= {}
5615 vca
= self
.connect_as_admin()
5617 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
5620 org
, vdc
= self
.get_vdc_details()
5621 catalog
= self
.get_catalog_obj(image_id
, catalogs
)
5623 items
= org
.get_catalog_item(catalog
.get('name'), catalog
.get('name'))
5624 catalog_items
= [items
.attrib
]
5626 if len(catalog_items
) == 1:
5627 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5628 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
5630 response
= self
.perform_request(req_type
='GET',
5631 url
=catalog_items
[0].get('href'),
5633 catalogItem
= XmlElementTree
.fromstring(response
.content
)
5634 entity
= [child
for child
in catalogItem
if child
.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
5635 vapp_tempalte_href
= entity
.get("href")
5636 #get vapp details and parse moref id
5638 namespaces
= {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
5639 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
5640 'vmw': 'http://www.vmware.com/schema/ovf',
5641 'vm': 'http://www.vmware.com/vcloud/v1.5',
5642 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
5643 'vmext':"http://www.vmware.com/vcloud/extension/v1.5",
5644 'xmlns':"http://www.vmware.com/vcloud/v1.5"
5648 response
= self
.perform_request(req_type
='GET',
5649 url
=vapp_tempalte_href
,
5652 if response
.status_code
!= requests
.codes
.ok
:
5653 self
.logger
.debug("REST API call {} failed. Return status code {}".format(
5654 vapp_tempalte_href
, response
.status_code
))
5657 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
5658 children_section
= xmlroot_respond
.find('vm:Children/', namespaces
)
5659 if children_section
is not None:
5660 vCloud_extension_section
= children_section
.find('xmlns:VCloudExtension', namespaces
)
5661 if vCloud_extension_section
is not None:
5662 vm_vcenter_info
= {}
5663 vim_info
= vCloud_extension_section
.find('vmext:VmVimInfo', namespaces
)
5664 vmext
= vim_info
.find('vmext:VmVimObjectRef', namespaces
)
5665 if vmext
is not None:
5666 vm_vcenter_info
["vm_moref_id"] = vmext
.find('vmext:MoRef', namespaces
).text
5667 parsed_response
["vm_vcenter_info"]= vm_vcenter_info
5669 except Exception as exp
:
5670 self
.logger
.info("Error occurred calling rest api for getting vApp details {}".format(exp
))
5672 return parsed_response
5675 def rollback_newvm(self
, vapp_uuid
, msg
, exp_type
="Genric"):
5677 Method to delete vApp
5679 vapp_uuid - vApp UUID
5680 msg - Error message to be logged
5681 exp_type : Exception type
5686 status
= self
.delete_vminstance(vapp_uuid
)
5689 self
.logger
.error(msg
)
5690 if exp_type
== "Genric":
5691 raise vimconn
.vimconnException(msg
)
5692 elif exp_type
== "NotFound":
5693 raise vimconn
.vimconnNotFoundException(message
=msg
)
5695 def add_sriov(self
, vapp_uuid
, sriov_nets
, vmname_andid
):
5697 Method to attach SRIOV adapters to VM
5700 vapp_uuid - uuid of vApp/VM
5701 sriov_nets - SRIOV devices infromation as specified in VNFD (flavor)
5702 vmname_andid - vmname
5705 The status of add SRIOV adapter task , vm object and
5706 vcenter_conect object
5709 vcenter_conect
, content
= self
.get_vcenter_content()
5710 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
5714 no_of_sriov_devices
= len(sriov_nets
)
5715 if no_of_sriov_devices
> 0:
5716 #Get VM and its host
5717 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
5718 self
.logger
.info("VM {} is currently on host {}".format(vm_obj
, host_obj
))
5719 if host_obj
and vm_obj
:
5720 #get SRIOV devies from host on which vapp is currently installed
5721 avilable_sriov_devices
= self
.get_sriov_devices(host_obj
,
5722 no_of_sriov_devices
,
5725 if len(avilable_sriov_devices
) == 0:
5726 #find other hosts with active pci devices
5727 new_host_obj
, avilable_sriov_devices
= self
.get_host_and_sriov_devices(
5729 no_of_sriov_devices
,
5732 if new_host_obj
is not None and len(avilable_sriov_devices
)> 0:
5733 #Migrate vm to the host where SRIOV devices are available
5734 self
.logger
.info("Relocate VM {} on new host {}".format(vm_obj
,
5736 task
= self
.relocate_vm(new_host_obj
, vm_obj
)
5737 if task
is not None:
5738 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5739 self
.logger
.info("Migrate VM status: {}".format(result
))
5740 host_obj
= new_host_obj
5742 self
.logger
.info("Fail to migrate VM : {}".format(result
))
5743 raise vimconn
.vimconnNotFoundException(
5744 "Fail to migrate VM : {} to host {}".format(
5749 if host_obj
is not None and avilable_sriov_devices
is not None and len(avilable_sriov_devices
)> 0:
5750 #Add SRIOV devices one by one
5751 for sriov_net
in sriov_nets
:
5752 network_name
= sriov_net
.get('net_id')
5753 dvs_portgr_name
= self
.create_dvPort_group(network_name
)
5754 if sriov_net
.get('type') == "VF" or sriov_net
.get('type') == "SR-IOV":
5755 #add vlan ID ,Modify portgroup for vlan ID
5756 self
.configure_vlanID(content
, vcenter_conect
, network_name
)
5758 task
= self
.add_sriov_to_vm(content
,
5762 avilable_sriov_devices
[0]
5765 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5767 self
.logger
.info("Added SRIOV {} to VM {}".format(
5768 no_of_sriov_devices
,
5771 self
.logger
.error("Fail to add SRIOV {} to VM {}".format(
5772 no_of_sriov_devices
,
5774 raise vimconn
.vimconnUnexpectedResponse(
5775 "Fail to add SRIOV adapter in VM ".format(str(vm_obj
))
5777 return True, vm_obj
, vcenter_conect
5779 self
.logger
.error("Currently there is no host with"\
5780 " {} number of avaialble SRIOV "\
5781 "VFs required for VM {}".format(
5782 no_of_sriov_devices
,
5785 raise vimconn
.vimconnNotFoundException(
5786 "Currently there is no host with {} "\
5787 "number of avaialble SRIOV devices required for VM {}".format(
5788 no_of_sriov_devices
,
5791 self
.logger
.debug("No infromation about SRIOV devices {} ",sriov_nets
)
5793 except vmodl
.MethodFault
as error
:
5794 self
.logger
.error("Error occurred while adding SRIOV {} ",error
)
5795 return None, vm_obj
, vcenter_conect
5798 def get_sriov_devices(self
,host
, no_of_vfs
):
5800 Method to get the details of SRIOV devices on given host
5802 host - vSphere host object
5803 no_of_vfs - number of VFs needed on host
5806 array of SRIOV devices
5810 for device
in host
.config
.pciPassthruInfo
:
5811 if isinstance(device
,vim
.host
.SriovInfo
) and device
.sriovActive
:
5812 if device
.numVirtualFunction
>= no_of_vfs
:
5813 sriovInfo
.append(device
)
5818 def get_host_and_sriov_devices(self
, content
, no_of_vfs
):
5820 Method to get the details of SRIOV devices infromation on all hosts
5823 content - vSphere host object
5824 no_of_vfs - number of pci VFs needed on host
5827 array of SRIOV devices and host object
5830 sriov_device_objs
= None
5833 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
5834 [vim
.HostSystem
], True)
5835 for host
in container
.view
:
5836 devices
= self
.get_sriov_devices(host
, no_of_vfs
)
5839 sriov_device_objs
= devices
5841 except Exception as exp
:
5842 self
.logger
.error("Error {} occurred while finding SRIOV devices on host: {}".format(exp
, host_obj
))
5844 return host_obj
,sriov_device_objs
5847 def add_sriov_to_vm(self
,content
, vm_obj
, host_obj
, network_name
, sriov_device
):
5849 Method to add SRIOV adapter to vm
5852 host_obj - vSphere host object
5853 vm_obj - vSphere vm object
5854 content - vCenter content object
5855 network_name - name of distributed virtaul portgroup
5856 sriov_device - SRIOV device info
5862 vnic_label
= "sriov nic"
5864 dvs_portgr
= self
.get_dvport_group(network_name
)
5865 network_name
= dvs_portgr
.name
5866 nic
= vim
.vm
.device
.VirtualDeviceSpec()
5868 nic
.operation
= vim
.vm
.device
.VirtualDeviceSpec
.Operation
.add
5869 nic
.device
= vim
.vm
.device
.VirtualSriovEthernetCard()
5870 nic
.device
.addressType
= 'assigned'
5871 #nic.device.key = 13016
5872 nic
.device
.deviceInfo
= vim
.Description()
5873 nic
.device
.deviceInfo
.label
= vnic_label
5874 nic
.device
.deviceInfo
.summary
= network_name
5875 nic
.device
.backing
= vim
.vm
.device
.VirtualEthernetCard
.NetworkBackingInfo()
5877 nic
.device
.backing
.network
= self
.get_obj(content
, [vim
.Network
], network_name
)
5878 nic
.device
.backing
.deviceName
= network_name
5879 nic
.device
.backing
.useAutoDetect
= False
5880 nic
.device
.connectable
= vim
.vm
.device
.VirtualDevice
.ConnectInfo()
5881 nic
.device
.connectable
.startConnected
= True
5882 nic
.device
.connectable
.allowGuestControl
= True
5884 nic
.device
.sriovBacking
= vim
.vm
.device
.VirtualSriovEthernetCard
.SriovBackingInfo()
5885 nic
.device
.sriovBacking
.physicalFunctionBacking
= vim
.vm
.device
.VirtualPCIPassthrough
.DeviceBackingInfo()
5886 nic
.device
.sriovBacking
.physicalFunctionBacking
.id = sriov_device
.id
5889 vmconf
= vim
.vm
.ConfigSpec(deviceChange
=devices
)
5890 task
= vm_obj
.ReconfigVM_Task(vmconf
)
5892 except Exception as exp
:
5893 self
.logger
.error("Error {} occurred while adding SRIOV adapter in VM: {}".format(exp
, vm_obj
))
5897 def create_dvPort_group(self
, network_name
):
5899 Method to create disributed virtual portgroup
5902 network_name - name of network/portgroup
5908 new_network_name
= [network_name
, '-', str(uuid
.uuid4())]
5909 network_name
=''.join(new_network_name
)
5910 vcenter_conect
, content
= self
.get_vcenter_content()
5912 dv_switch
= self
.get_obj(content
, [vim
.DistributedVirtualSwitch
], self
.dvs_name
)
5914 dv_pg_spec
= vim
.dvs
.DistributedVirtualPortgroup
.ConfigSpec()
5915 dv_pg_spec
.name
= network_name
5917 dv_pg_spec
.type = vim
.dvs
.DistributedVirtualPortgroup
.PortgroupType
.earlyBinding
5918 dv_pg_spec
.defaultPortConfig
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VmwarePortConfigPolicy()
5919 dv_pg_spec
.defaultPortConfig
.securityPolicy
= vim
.dvs
.VmwareDistributedVirtualSwitch
.SecurityPolicy()
5920 dv_pg_spec
.defaultPortConfig
.securityPolicy
.allowPromiscuous
= vim
.BoolPolicy(value
=False)
5921 dv_pg_spec
.defaultPortConfig
.securityPolicy
.forgedTransmits
= vim
.BoolPolicy(value
=False)
5922 dv_pg_spec
.defaultPortConfig
.securityPolicy
.macChanges
= vim
.BoolPolicy(value
=False)
5924 task
= dv_switch
.AddDVPortgroup_Task([dv_pg_spec
])
5925 self
.wait_for_vcenter_task(task
, vcenter_conect
)
5927 dvPort_group
= self
.get_obj(content
, [vim
.dvs
.DistributedVirtualPortgroup
], network_name
)
5929 self
.logger
.info("Created disributed virtaul port group: {}".format(dvPort_group
))
5930 return dvPort_group
.key
5932 self
.logger
.debug("No disributed virtual switch found with name {}".format(network_name
))
5934 except Exception as exp
:
5935 self
.logger
.error("Error occurred while creating disributed virtaul port group {}"\
5936 " : {}".format(network_name
, exp
))
5939 def reconfig_portgroup(self
, content
, dvPort_group_name
, config_info
={}):
5941 Method to reconfigure disributed virtual portgroup
5944 dvPort_group_name - name of disributed virtual portgroup
5945 content - vCenter content object
5946 config_info - disributed virtual portgroup configuration
5952 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
5954 dv_pg_spec
= vim
.dvs
.DistributedVirtualPortgroup
.ConfigSpec()
5955 dv_pg_spec
.configVersion
= dvPort_group
.config
.configVersion
5956 dv_pg_spec
.defaultPortConfig
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VmwarePortConfigPolicy()
5957 if "vlanID" in config_info
:
5958 dv_pg_spec
.defaultPortConfig
.vlan
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VlanIdSpec()
5959 dv_pg_spec
.defaultPortConfig
.vlan
.vlanId
= config_info
.get('vlanID')
5961 task
= dvPort_group
.ReconfigureDVPortgroup_Task(spec
=dv_pg_spec
)
5965 except Exception as exp
:
5966 self
.logger
.error("Error occurred while reconfiguraing disributed virtaul port group {}"\
5967 " : {}".format(dvPort_group_name
, exp
))
5971 def destroy_dvport_group(self
, dvPort_group_name
):
5973 Method to destroy disributed virtual portgroup
5976 network_name - name of network/portgroup
5979 True if portgroup successfully got deleted else false
5981 vcenter_conect
, content
= self
.get_vcenter_content()
5984 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
5986 task
= dvPort_group
.Destroy_Task()
5987 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5989 except vmodl
.MethodFault
as exp
:
5990 self
.logger
.error("Caught vmodl fault {} while deleting disributed virtaul port group {}".format(
5991 exp
, dvPort_group_name
))
5995 def get_dvport_group(self
, dvPort_group_name
):
5997 Method to get disributed virtual portgroup
6000 network_name - name of network/portgroup
6005 vcenter_conect
, content
= self
.get_vcenter_content()
6008 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
, [vim
.dvs
.DistributedVirtualPortgroup
], True)
6009 for item
in container
.view
:
6010 if item
.key
== dvPort_group_name
:
6014 except vmodl
.MethodFault
as exp
:
6015 self
.logger
.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
6016 exp
, dvPort_group_name
))
6019 def get_vlanID_from_dvs_portgr(self
, dvPort_group_name
):
6021 Method to get disributed virtual portgroup vlanID
6024 network_name - name of network/portgroup
6031 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
6033 vlanId
= dvPort_group
.config
.defaultPortConfig
.vlan
.vlanId
6034 except vmodl
.MethodFault
as exp
:
6035 self
.logger
.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
6036 exp
, dvPort_group_name
))
6040 def configure_vlanID(self
, content
, vcenter_conect
, dvPort_group_name
):
6042 Method to configure vlanID in disributed virtual portgroup vlanID
6045 network_name - name of network/portgroup
6050 vlanID
= self
.get_vlanID_from_dvs_portgr(dvPort_group_name
)
6053 vlanID
= self
.genrate_vlanID(dvPort_group_name
)
6054 config
= {"vlanID":vlanID
}
6055 task
= self
.reconfig_portgroup(content
, dvPort_group_name
,
6058 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
6060 self
.logger
.info("Reconfigured Port group {} for vlan ID {}".format(
6061 dvPort_group_name
,vlanID
))
6063 self
.logger
.error("Fail reconfigure portgroup {} for vlanID{}".format(
6064 dvPort_group_name
, vlanID
))
6067 def genrate_vlanID(self
, network_name
):
6069 Method to get unused vlanID
6071 network_name - name of network/portgroup
6077 if self
.config
.get('vlanID_range') == None:
6078 raise vimconn
.vimconnConflictException("You must provide a 'vlanID_range' "\
6079 "at config value before creating sriov network with vlan tag")
6080 if "used_vlanIDs" not in self
.persistent_info
:
6081 self
.persistent_info
["used_vlanIDs"] = {}
6083 used_ids
= self
.persistent_info
["used_vlanIDs"].values()
6085 #used_ids = list(self.persistent_info["used_vlanIDs"].values())
6087 for vlanID_range
in self
.config
.get('vlanID_range'):
6088 start_vlanid
, end_vlanid
= vlanID_range
.split("-")
6089 if start_vlanid
> end_vlanid
:
6090 raise vimconn
.vimconnConflictException("Invalid vlan ID range {}".format(
6093 for id in xrange(int(start_vlanid
), int(end_vlanid
) + 1):
6095 #for id in range(int(start_vlanid), int(end_vlanid) + 1):
6096 if id not in used_ids
:
6098 self
.persistent_info
["used_vlanIDs"][network_name
] = vlan_id
6101 raise vimconn
.vimconnConflictException("All Vlan IDs are in use")
6104 def get_obj(self
, content
, vimtype
, name
):
6106 Get the vsphere object associated with a given text name
6109 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
, vimtype
, True)
6110 for item
in container
.view
:
6111 if item
.name
== name
:
6117 def insert_media_to_vm(self
, vapp
, image_id
):
6119 Method to insert media CD-ROM (ISO image) from catalog to vm.
6120 vapp - vapp object to get vm id
6121 Image_id - image id for cdrom to be inerted to vm
6123 # create connection object
6124 vca
= self
.connect()
6126 # fetching catalog details
6127 rest_url
= "{}/api/catalog/{}".format(self
.url
, image_id
)
6129 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
6130 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
6131 response
= self
.perform_request(req_type
='GET',
6135 if response
.status_code
!= 200:
6136 self
.logger
.error("REST call {} failed reason : {}"\
6137 "status code : {}".format(url_rest_call
,
6139 response
.status_code
))
6140 raise vimconn
.vimconnException("insert_media_to_vm(): Failed to get "\
6142 # searching iso name and id
6143 iso_name
,media_id
= self
.get_media_details(vca
, response
.content
)
6145 if iso_name
and media_id
:
6146 data
="""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6147 <ns6:MediaInsertOrEjectParams
6148 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">
6150 type="application/vnd.vmware.vcloud.media+xml"
6152 id="urn:vcloud:media:{}"
6153 href="https://{}/api/media/{}"/>
6154 </ns6:MediaInsertOrEjectParams>""".format(iso_name
, media_id
,
6157 for vms
in vapp
.get_all_vms():
6158 vm_id
= vms
.get('id').split(':')[-1]
6160 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml'
6161 rest_url
= "{}/api/vApp/vm-{}/media/action/insertMedia".format(self
.url
,vm_id
)
6163 response
= self
.perform_request(req_type
='POST',
6168 if response
.status_code
!= 202:
6169 self
.logger
.error("Failed to insert CD-ROM to vm")
6170 raise vimconn
.vimconnException("insert_media_to_vm() : Failed to insert"\
6173 task
= self
.get_task_from_response(response
.content
)
6174 result
= self
.client
.get_task_monitor().wait_for_success(task
=task
)
6175 if result
.get('status') == 'success':
6176 self
.logger
.info("insert_media_to_vm(): Sucessfully inserted media ISO"\
6177 " image to vm {}".format(vm_id
))
6179 except Exception as exp
:
6180 self
.logger
.error("insert_media_to_vm() : exception occurred "\
6181 "while inserting media CD-ROM")
6182 raise vimconn
.vimconnException(message
=exp
)
6185 def get_media_details(self
, vca
, content
):
6187 Method to get catalog item details
6188 vca - connection object
6189 content - Catalog details
6190 Return - Media name, media id
6192 cataloghref_list
= []
6195 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
6196 for child
in vm_list_xmlroot
.iter():
6197 if 'CatalogItem' in child
.tag
:
6198 cataloghref_list
.append(child
.attrib
.get('href'))
6199 if cataloghref_list
is not None:
6200 for href
in cataloghref_list
:
6202 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
6203 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
6204 response
= self
.perform_request(req_type
='GET',
6207 if response
.status_code
!= 200:
6208 self
.logger
.error("REST call {} failed reason : {}"\
6209 "status code : {}".format(href
,
6211 response
.status_code
))
6212 raise vimconn
.vimconnException("get_media_details : Failed to get "\
6213 "catalogitem details")
6214 list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
6215 for child
in list_xmlroot
.iter():
6216 if 'Entity' in child
.tag
:
6217 if 'media' in child
.attrib
.get('href'):
6218 name
= child
.attrib
.get('name')
6219 media_id
= child
.attrib
.get('href').split('/').pop()
6220 return name
,media_id
6222 self
.logger
.debug("Media name and id not found")
6224 except Exception as exp
:
6225 self
.logger
.error("get_media_details : exception occurred "\
6226 "getting media details")
6227 raise vimconn
.vimconnException(message
=exp
)
6230 def retry_rest(self
, method
, url
, add_headers
=None, data
=None):
6231 """ Method to get Token & retry respective REST request
6233 api - REST API - Can be one of 'GET' or 'PUT' or 'POST'
6234 url - request url to be used
6235 add_headers - Additional headers (optional)
6236 data - Request payload data to be passed in request
6238 response - Response of request
6245 if self
.client
._session
:
6246 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
6247 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
6250 headers
.update(add_headers
)
6253 response
= self
.perform_request(req_type
='GET',
6256 elif method
== 'PUT':
6257 response
= self
.perform_request(req_type
='PUT',
6261 elif method
== 'POST':
6262 response
= self
.perform_request(req_type
='POST',
6266 elif method
== 'DELETE':
6267 response
= self
.perform_request(req_type
='DELETE',
6273 def get_token(self
):
6274 """ Generate a new token if expired
6277 The return client object that letter can be used to connect to vCloud director as admin for VDC
6280 self
.logger
.debug("Generate token for vca {} as {} to datacenter {}.".format(self
.org_name
,
6284 client
= Client(host
, verify_ssl_certs
=False)
6285 client
.set_credentials(BasicLoginCredentials(self
.user
, self
.org_name
, self
.passwd
))
6287 self
.client
= client
6290 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director org: "
6291 "{} as user: {}".format(self
.org_name
, self
.user
))
6294 raise vimconn
.vimconnConnectionException("Failed while reconnecting vCD")
6297 def get_vdc_details(self
):
6298 """ Get VDC details using pyVcloud Lib
6300 Returns org and vdc object
6304 org
= Org(self
.client
, resource
=self
.client
.get_org())
6305 vdc
= org
.get_vdc(self
.tenant_name
)
6306 except Exception as e
:
6307 # pyvcloud not giving a specific exception, Refresh nevertheless
6308 self
.logger
.debug("Received exception {}, refreshing token ".format(str(e
)))
6310 #Retry once, if failed by refreshing token
6313 org
= Org(self
.client
, resource
=self
.client
.get_org())
6314 vdc
= org
.get_vdc(self
.tenant_name
)
6319 def perform_request(self
, req_type
, url
, headers
=None, data
=None):
6320 """Perform the POST/PUT/GET/DELETE request."""
6322 #Log REST request details
6323 self
.log_request(req_type
, url
=url
, headers
=headers
, data
=data
)
6324 # perform request and return its result
6325 if req_type
== 'GET':
6326 response
= requests
.get(url
=url
,
6329 elif req_type
== 'PUT':
6330 response
= requests
.put(url
=url
,
6334 elif req_type
== 'POST':
6335 response
= requests
.post(url
=url
,
6339 elif req_type
== 'DELETE':
6340 response
= requests
.delete(url
=url
,
6343 #Log the REST response
6344 self
.log_response(response
)
6349 def log_request(self
, req_type
, url
=None, headers
=None, data
=None):
6350 """Logs REST request details"""
6352 if req_type
is not None:
6353 self
.logger
.debug("Request type: {}".format(req_type
))
6356 self
.logger
.debug("Request url: {}".format(url
))
6358 if headers
is not None:
6359 for header
in headers
:
6360 self
.logger
.debug("Request header: {}: {}".format(header
, headers
[header
]))
6362 if data
is not None:
6363 self
.logger
.debug("Request data: {}".format(data
))
6366 def log_response(self
, response
):
6367 """Logs REST response details"""
6369 self
.logger
.debug("Response status code: {} ".format(response
.status_code
))
6372 def get_task_from_response(self
, content
):
6374 content - API response content(response.content)
6377 xmlroot
= XmlElementTree
.fromstring(content
)
6378 if xmlroot
.tag
.split('}')[1] == "Task":
6382 if ele
.tag
.split("}")[1] == "Tasks":
6388 def power_on_vapp(self
,vapp_id
, vapp_name
):
6391 vapp_name - vAapp name
6392 return - Task object
6394 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
6395 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
6397 poweron_href
= "{}/api/vApp/vapp-{}/power/action/powerOn".format(self
.url
,
6399 response
= self
.perform_request(req_type
='POST',
6403 if response
.status_code
!= 202:
6404 self
.logger
.error("REST call {} failed reason : {}"\
6405 "status code : {} ".format(poweron_href
,
6407 response
.status_code
))
6408 raise vimconn
.vimconnException("power_on_vapp() : Failed to power on "\
6409 "vApp {}".format(vapp_name
))
6411 poweron_task
= self
.get_task_from_response(response
.content
)