1 # -*- coding: utf-8 -*-
4 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5 # This file is part of openmano
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 with: nfvlabs@tid.es
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
import Http
46 from pyvcloud
.vcloudair
import VCA
47 from pyvcloud
.schema
.vcd
.v1_5
.schemas
.vcloud
import sessionType
, organizationType
, \
48 vAppType
, organizationListType
, vdcType
, catalogType
, queryRecordViewType
, \
49 networkType
, vcloudType
, taskType
, diskType
, vmsType
, vdcTemplateListType
, mediaType
50 from xml
.sax
.saxutils
import escape
52 from pyvcloud
.schema
.vcd
.v1_5
.schemas
.admin
.vCloudEntities
import TaskType
53 from pyvcloud
.schema
.vcd
.v1_5
.schemas
.vcloud
.taskType
import TaskType
as GenericTask
54 from pyvcloud
.schema
.vcd
.v1_5
.schemas
.vcloud
.vAppType
import TaskType
as VappTask
55 from pyvcloud
.schema
.vcd
.v1_5
.schemas
.admin
.vCloudEntities
import TasksInProgressType
67 # global variable for vcd connector type
68 STANDALONE
= 'standalone'
70 # key for flavor dicts
71 FLAVOR_RAM_KEY
= 'ram'
72 FLAVOR_VCPUS_KEY
= 'vcpus'
73 FLAVOR_DISK_KEY
= 'disk'
74 DEFAULT_IP_PROFILE
= {'gateway_address':"192.168.1.1",
76 'subnet_address':"192.168.1.0/24",
78 'dhcp_start_address':"192.168.1.3",
80 'dns_address':"192.168.1.2"
82 # global variable for wait time
88 __author__
= "Mustafa Bayramov, Arpita Kate, Sachin Bhangare"
89 __date__
= "$12-Jan-2017 11:09:29$"
92 # -1: "Could not be created",
98 # 5: "Waiting for user input",
100 # 7: "Unrecognized state",
102 # 9: "Inconsistent state",
103 # 10: "Children do not all have the same status",
104 # 11: "Upload initiated, OVF descriptor pending",
105 # 12: "Upload initiated, copying contents",
106 # 13: "Upload initiated , disk contents pending",
107 # 14: "Upload has been quarantined",
108 # 15: "Upload quarantine period has expired"
110 # mapping vCD status to MANO
111 vcdStatusCode2manoFormat
= {4: 'ACTIVE',
120 netStatus2manoFormat
= {'ACTIVE': 'ACTIVE', 'PAUSED': 'PAUSED', 'INACTIVE': 'INACTIVE', 'BUILD': 'BUILD',
121 'ERROR': 'ERROR', 'DELETED': 'DELETED'
124 # dict used to store flavor in memory
128 class vimconnector(vimconn
.vimconnector
):
129 def __init__(self
, uuid
=None, name
=None, tenant_id
=None, tenant_name
=None,
130 url
=None, url_admin
=None, user
=None, passwd
=None, log_level
=None, config
={}):
132 Constructor create vmware connector to vCloud director.
134 By default construct doesn't validate connection state. So client can create object with None arguments.
135 If client specified username , password and host and VDC name. Connector initialize other missing attributes.
137 a) It initialize organization UUID
138 b) Initialize tenant_id/vdc ID. (This information derived from tenant name)
141 uuid - is organization uuid.
142 name - is organization name that must be presented in vCloud director.
143 tenant_id - is VDC uuid it must be presented in vCloud director
144 tenant_name - is VDC name.
145 url - is hostname or ip address of vCloud director
146 url_admin - same as above.
147 user - is user that administrator for organization. Caller must make sure that
148 username has right privileges.
150 password - is password for a user.
152 VMware connector also requires PVDC administrative privileges and separate account.
153 This variables must be passed via config argument dict contains keys
155 dict['admin_username']
156 dict['admin_password']
162 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
,
163 url_admin
, user
, passwd
, log_level
, config
)
165 self
.logger
= logging
.getLogger('openmano.vim.vmware')
166 self
.logger
.setLevel(10)
171 self
.url_admin
= url_admin
172 self
.tenant_id
= tenant_id
173 self
.tenant_name
= tenant_name
177 self
.admin_password
= None
178 self
.admin_user
= None
180 self
.nsx_manager
= None
182 self
.nsx_password
= None
184 if tenant_name
is not None:
185 orgnameandtenant
= tenant_name
.split(":")
186 if len(orgnameandtenant
) == 2:
187 self
.tenant_name
= orgnameandtenant
[1]
188 self
.org_name
= orgnameandtenant
[0]
190 self
.tenant_name
= tenant_name
191 if "orgname" in config
:
192 self
.org_name
= config
['orgname']
195 self
.logger
.setLevel(getattr(logging
, log_level
))
198 self
.admin_user
= config
['admin_username']
199 self
.admin_password
= config
['admin_password']
201 raise vimconn
.vimconnException(message
="Error admin username or admin password is empty.")
204 self
.nsx_manager
= config
['nsx_manager']
205 self
.nsx_user
= config
['nsx_user']
206 self
.nsx_password
= config
['nsx_password']
208 raise vimconn
.vimconnException(message
="Error: nsx manager or nsx user or nsx password is empty in Config")
214 raise vimconn
.vimconnException('url param can not be NoneType')
216 if not self
.url_admin
: # try to use normal url
217 self
.url_admin
= self
.url
219 logging
.debug("UUID: {} name: {} tenant_id: {} tenant name {}".format(self
.id, self
.org_name
,
220 self
.tenant_id
, self
.tenant_name
))
221 logging
.debug("vcd url {} vcd username: {} vcd password: {}".format(self
.url
, self
.user
, self
.passwd
))
222 logging
.debug("vcd admin username {} vcd admin passowrd {}".format(self
.admin_user
, self
.admin_password
))
224 # initialize organization
225 if self
.user
is not None and self
.passwd
is not None and self
.url
:
226 self
.init_organization()
228 def __getitem__(self
, index
):
231 if index
== 'tenant_id':
232 return self
.tenant_id
233 if index
== 'tenant_name':
234 return self
.tenant_name
237 elif index
== 'org_name':
239 elif index
== 'org_uuid':
241 elif index
== 'user':
243 elif index
== 'passwd':
247 elif index
== 'url_admin':
248 return self
.url_admin
249 elif index
== "config":
252 raise KeyError("Invalid key '%s'" % str(index
))
254 def __setitem__(self
, index
, value
):
257 if index
== 'tenant_id':
258 self
.tenant_id
= value
259 if index
== 'tenant_name':
260 self
.tenant_name
= value
263 elif index
== 'org_name':
264 self
.org_name
= value
265 elif index
== 'org_uuid':
266 self
.org_uuid
= value
267 elif index
== 'user':
269 elif index
== 'passwd':
273 elif index
== 'url_admin':
274 self
.url_admin
= value
276 raise KeyError("Invalid key '%s'" % str(index
))
278 def connect_as_admin(self
):
279 """ Method connect as pvdc admin user to vCloud director.
280 There are certain action that can be done only by provider vdc admin user.
281 Organization creation / provider network creation etc.
284 The return vca object that letter can be used to connect to vcloud direct as admin for provider vdc
287 self
.logger
.debug("Logging in to a vca {} as admin.".format(self
.org_name
))
289 vca_admin
= VCA(host
=self
.url
,
290 username
=self
.admin_user
,
291 service_type
=STANDALONE
,
295 result
= vca_admin
.login(password
=self
.admin_password
, org
='System')
297 raise vimconn
.vimconnConnectionException(
298 "Can't connect to a vCloud director as: {}".format(self
.admin_user
))
299 result
= vca_admin
.login(token
=vca_admin
.token
, org
='System', org_url
=vca_admin
.vcloud_session
.org_url
)
302 "Successfully logged to a vcloud direct org: {} as user: {}".format('System', self
.admin_user
))
307 """ Method connect as normal user to vCloud director.
310 The return vca object that letter can be used to connect to vCloud director as admin for VDC
314 self
.logger
.debug("Logging in to a vca {} as {} to datacenter {}.".format(self
.org_name
,
317 vca
= VCA(host
=self
.url
,
319 service_type
=STANDALONE
,
324 result
= vca
.login(password
=self
.passwd
, org
=self
.org_name
)
326 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director as: {}".format(self
.user
))
327 result
= vca
.login(token
=vca
.token
, org
=self
.org_name
, org_url
=vca
.vcloud_session
.org_url
)
330 "Successfully logged to a vcloud direct org: {} as user: {}".format(self
.org_name
, self
.user
))
333 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director org: "
334 "{} as user: {}".format(self
.org_name
, self
.user
))
338 def init_organization(self
):
339 """ Method initialize organization UUID and VDC parameters.
341 At bare minimum client must provide organization name that present in vCloud director and VDC.
343 The VDC - UUID ( tenant_id) will be initialized at the run time if client didn't call constructor.
344 The Org - UUID will be initialized at the run time if data center present in vCloud director.
347 The return vca object that letter can be used to connect to vcloud direct as admin
350 if self
.org_uuid
is None:
351 org_dict
= self
.get_org_list()
353 # we set org UUID at the init phase but we can do it only when we have valid credential.
354 if org_dict
[org
] == self
.org_name
:
356 self
.logger
.debug("Setting organization UUID {}".format(self
.org_uuid
))
359 raise vimconn
.vimconnException("Vcloud director organization {} not found".format(self
.org_name
))
361 # if well good we require for org details
362 org_details_dict
= self
.get_org(org_uuid
=self
.org_uuid
)
364 # we have two case if we want to initialize VDC ID or VDC name at run time
365 # tenant_name provided but no tenant id
366 if self
.tenant_id
is None and self
.tenant_name
is not None and 'vdcs' in org_details_dict
:
367 vdcs_dict
= org_details_dict
['vdcs']
368 for vdc
in vdcs_dict
:
369 if vdcs_dict
[vdc
] == self
.tenant_name
:
371 self
.logger
.debug("Setting vdc uuid {} for organization UUID {}".format(self
.tenant_id
,
375 raise vimconn
.vimconnException("Tenant name indicated but not present in vcloud director.")
376 # case two we have tenant_id but we don't have tenant name so we find and set it.
377 if self
.tenant_id
is not None and self
.tenant_name
is None and 'vdcs' in org_details_dict
:
378 vdcs_dict
= org_details_dict
['vdcs']
379 for vdc
in vdcs_dict
:
380 if vdc
== self
.tenant_id
:
381 self
.tenant_name
= vdcs_dict
[vdc
]
382 self
.logger
.debug("Setting vdc uuid {} for organization UUID {}".format(self
.tenant_id
,
386 raise vimconn
.vimconnException("Tenant id indicated but not present in vcloud director")
387 self
.logger
.debug("Setting organization uuid {}".format(self
.org_uuid
))
389 self
.logger
.debug("Failed initialize organization UUID for org {}".format(self
.org_name
))
390 self
.logger
.debug(traceback
.format_exc())
393 def new_tenant(self
, tenant_name
=None, tenant_description
=None):
394 """ Method adds a new tenant to VIM with this name.
395 This action requires access to create VDC action in vCloud director.
398 tenant_name is tenant_name to be created.
399 tenant_description not used for this call
402 returns the tenant identifier in UUID format.
403 If action is failed method will throw vimconn.vimconnException method
405 vdc_task
= self
.create_vdc(vdc_name
=tenant_name
)
406 if vdc_task
is not None:
407 vdc_uuid
, value
= vdc_task
.popitem()
408 self
.logger
.info("Crated new vdc {} and uuid: {}".format(tenant_name
, vdc_uuid
))
411 raise vimconn
.vimconnException("Failed create tenant {}".format(tenant_name
))
413 def delete_tenant(self
, tenant_id
=None):
414 """Delete a tenant from VIM"""
415 'Returns the tenant identifier'
416 raise vimconn
.vimconnNotImplemented("Should have implemented this")
418 def get_tenant_list(self
, filter_dict
={}):
419 """Obtain tenants of VIM
420 filter_dict can contain the following keys:
421 name: filter by tenant name
422 id: filter by tenant uuid/id
424 Returns the tenant list of dictionaries:
425 [{'name':'<name>, 'id':'<id>, ...}, ...]
428 org_dict
= self
.get_org(self
.org_uuid
)
429 vdcs_dict
= org_dict
['vdcs']
434 entry
= {'name': vdcs_dict
[k
], 'id': k
}
435 # if caller didn't specify dictionary we return all tenants.
436 if filter_dict
is not None and filter_dict
:
437 filtered_entry
= entry
.copy()
438 filtered_dict
= set(entry
.keys()) - set(filter_dict
)
439 for unwanted_key
in filtered_dict
: del entry
[unwanted_key
]
440 if filter_dict
== entry
:
441 vdclist
.append(filtered_entry
)
443 vdclist
.append(entry
)
445 self
.logger
.debug("Error in get_tenant_list()")
446 self
.logger
.debug(traceback
.format_exc())
447 raise vimconn
.vimconnException("Incorrect state. {}")
451 def new_network(self
, net_name
, net_type
, ip_profile
=None, shared
=False):
452 """Adds a tenant network to VIM
454 net_type can be 'bridge','data'.'ptp'.
455 ip_profile is a dict containing the IP parameters of the network
457 Returns the network identifier"""
459 self
.logger
.debug("new_network tenant {} net_type {} ip_profile {} shared {}"
460 .format(net_name
, net_type
, ip_profile
, shared
))
466 network_uuid
= self
.create_network(network_name
=net_name
, net_type
=net_type
,
467 ip_profile
=ip_profile
, isshared
=isshared
)
468 if network_uuid
is not None:
471 raise vimconn
.vimconnUnexpectedResponse("Failed create a new network {}".format(net_name
))
473 def get_vcd_network_list(self
):
474 """ Method available organization for a logged in tenant
477 The return vca object that letter can be used to connect to vcloud direct as admin
480 self
.logger
.debug("get_vcd_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
483 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
485 if not self
.tenant_name
:
486 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
488 vdc
= vca
.get_vdc(self
.tenant_name
)
490 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}".format(self
.tenant_name
))
492 vdc_uuid
= vdc
.get_id().split(":")[3]
493 networks
= vca
.get_networks(vdc
.get_name())
496 for network
in networks
:
498 netid
= network
.get_id().split(":")
502 filter_dict
["name"] = network
.get_name()
503 filter_dict
["id"] = netid
[3]
504 filter_dict
["shared"] = network
.get_IsShared()
505 filter_dict
["tenant_id"] = vdc_uuid
506 if network
.get_status() == 1:
507 filter_dict
["admin_state_up"] = True
509 filter_dict
["admin_state_up"] = False
510 filter_dict
["status"] = "ACTIVE"
511 filter_dict
["type"] = "bridge"
512 network_list
.append(filter_dict
)
513 self
.logger
.debug("get_vcd_network_list adding entry {}".format(filter_dict
))
515 self
.logger
.debug("Error in get_vcd_network_list")
516 self
.logger
.debug(traceback
.format_exc())
519 self
.logger
.debug("get_vcd_network_list returning {}".format(network_list
))
522 def get_network_list(self
, filter_dict
={}):
523 """Obtain tenant networks of VIM
525 name: network name OR/AND
526 id: network uuid OR/AND
527 shared: boolean OR/AND
528 tenant_id: tenant OR/AND
529 admin_state_up: boolean
532 [{key : value , key : value}]
534 Returns the network list of dictionaries:
535 [{<the fields at Filter_dict plus some VIM specific>}, ...]
539 self
.logger
.debug("get_vcd_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
542 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
544 if not self
.tenant_name
:
545 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
547 vdc
= vca
.get_vdc(self
.tenant_name
)
549 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}.".format(self
.tenant_name
))
551 vdcid
= vdc
.get_id().split(":")[3]
552 networks
= vca
.get_networks(vdc
.get_name())
556 for network
in networks
:
558 net_uuid
= network
.get_id().split(":")
559 if len(net_uuid
) != 4:
562 net_uuid
= net_uuid
[3]
564 self
.logger
.debug("Adding {} to a list vcd id {} network {}".format(net_uuid
,
567 filter_entry
["name"] = network
.get_name()
568 filter_entry
["id"] = net_uuid
569 filter_entry
["shared"] = network
.get_IsShared()
570 filter_entry
["tenant_id"] = vdcid
571 if network
.get_status() == 1:
572 filter_entry
["admin_state_up"] = True
574 filter_entry
["admin_state_up"] = False
575 filter_entry
["status"] = "ACTIVE"
576 filter_entry
["type"] = "bridge"
577 filtered_entry
= filter_entry
.copy()
579 if filter_dict
is not None and filter_dict
:
580 # we remove all the key : value we don't care and match only
582 filtered_dict
= set(filter_entry
.keys()) - set(filter_dict
)
583 for unwanted_key
in filtered_dict
: del filter_entry
[unwanted_key
]
584 if filter_dict
== filter_entry
:
585 network_list
.append(filtered_entry
)
587 network_list
.append(filtered_entry
)
589 self
.logger
.debug("Error in get_vcd_network_list")
590 self
.logger
.debug(traceback
.format_exc())
592 self
.logger
.debug("Returning {}".format(network_list
))
595 def get_network(self
, net_id
):
596 """Method obtains network details of net_id VIM network
597 Return a dict with the fields at filter_dict (see get_network_list) plus some VIM specific>}, ...]"""
601 raise vimconn
.vimconnConnectionException("self.connect() is failed")
603 vdc
= vca
.get_vdc(self
.tenant_name
)
604 vdc_id
= vdc
.get_id().split(":")[3]
606 networks
= vca
.get_networks(vdc
.get_name())
610 for network
in networks
:
611 vdc_network_id
= network
.get_id().split(":")
612 if len(vdc_network_id
) == 4 and vdc_network_id
[3] == net_id
:
613 filter_dict
["name"] = network
.get_name()
614 filter_dict
["id"] = vdc_network_id
[3]
615 filter_dict
["shared"] = network
.get_IsShared()
616 filter_dict
["tenant_id"] = vdc_id
617 if network
.get_status() == 1:
618 filter_dict
["admin_state_up"] = True
620 filter_dict
["admin_state_up"] = False
621 filter_dict
["status"] = "ACTIVE"
622 filter_dict
["type"] = "bridge"
623 self
.logger
.debug("Returning {}".format(filter_dict
))
626 self
.logger
.debug("Error in get_network")
627 self
.logger
.debug(traceback
.format_exc())
631 def delete_network(self
, net_id
):
633 Method Deletes a tenant network from VIM, provide the network id.
635 Returns the network identifier or raise an exception
640 raise vimconn
.vimconnConnectionException("self.connect() for tenant {} is failed.".format(self
.tenant_name
))
642 vcd_network
= self
.get_vcd_network(network_uuid
=net_id
)
643 if vcd_network
is not None and vcd_network
:
644 if self
.delete_network_action(network_uuid
=net_id
):
647 raise vimconn
.vimconnNotFoundException("Network {} not found".format(net_id
))
649 def refresh_nets_status(self
, net_list
):
650 """Get the status of the networks
651 Params: the list of network identifiers
652 Returns a dictionary with:
653 net_id: #VIM id of this network
654 status: #Mandatory. Text with one of:
655 # DELETED (not found at vim)
656 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
657 # OTHER (Vim reported other status not understood)
658 # ERROR (VIM indicates an ERROR status)
659 # ACTIVE, INACTIVE, DOWN (admin down),
660 # BUILD (on building process)
662 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
663 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
669 raise vimconn
.vimconnConnectionException("self.connect() is failed")
675 vcd_network
= self
.get_vcd_network(network_uuid
=net
)
676 if vcd_network
is not None and vcd_network
:
677 if vcd_network
['status'] == '1':
683 errormsg
= 'Network not found.'
685 dict_entry
[net
] = {'status': status
, 'error_msg': errormsg
,
686 'vim_info': yaml
.safe_dump(vcd_network
)}
688 self
.logger
.debug("Error in refresh_nets_status")
689 self
.logger
.debug(traceback
.format_exc())
693 def get_flavor(self
, flavor_id
):
694 """Obtain flavor details from the VIM
695 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific } #TODO to concrete
697 if flavor_id
not in flavorlist
:
698 raise vimconn
.vimconnNotFoundException("Flavor not found.")
699 return flavorlist
[flavor_id
]
701 def new_flavor(self
, flavor_data
):
702 """Adds a tenant flavor to VIM
703 flavor_data contains a dictionary with information, keys:
705 ram: memory (cloud type) in MBytes
706 vpcus: cpus (cloud type)
707 extended: EPA parameters
708 - numas: #items requested in same NUMA
709 memory: number of 1G huge pages memory
710 paired-threads|cores|threads: number of paired hyperthreads, complete cores OR individual threads
711 interfaces: # passthrough(PT) or SRIOV interfaces attached to this numa
712 - name: interface name
713 dedicated: yes|no|yes:sriov; for PT, SRIOV or only one SRIOV for the physical NIC
714 bandwidth: X Gbps; requested guarantee bandwidth
715 vpci: requested virtual PCI address
719 Returns the flavor identifier"""
721 # generate a new uuid put to internal dict and return it.
722 self
.logger
.debug("Creating new flavor - flavor_data: {}".format(flavor_data
))
723 new_flavor
=flavor_data
724 ram
= flavor_data
.get(FLAVOR_RAM_KEY
, 1024)
725 cpu
= flavor_data
.get(FLAVOR_VCPUS_KEY
, 1)
726 disk
= flavor_data
.get(FLAVOR_DISK_KEY
, 1)
728 extended_flv
= flavor_data
.get("extended")
730 numas
=extended_flv
.get("numas")
733 #overwrite ram and vcpus
734 ram
= numa
['memory']*1024
735 if 'paired-threads' in numa
:
736 cpu
= numa
['paired-threads']*2
737 elif 'cores' in numa
:
739 elif 'threads' in numa
:
740 cpu
= numa
['threads']
742 new_flavor
[FLAVOR_RAM_KEY
] = ram
743 new_flavor
[FLAVOR_VCPUS_KEY
] = cpu
744 new_flavor
[FLAVOR_DISK_KEY
] = disk
745 # generate a new uuid put to internal dict and return it.
746 flavor_id
= uuid
.uuid4()
747 flavorlist
[str(flavor_id
)] = new_flavor
748 self
.logger
.debug("Created flavor - {} : {}".format(flavor_id
, new_flavor
))
750 return str(flavor_id
)
752 def delete_flavor(self
, flavor_id
):
753 """Deletes a tenant flavor from VIM identify by its id
755 Returns the used id or raise an exception
757 if flavor_id
not in flavorlist
:
758 raise vimconn
.vimconnNotFoundException("Flavor not found.")
760 flavorlist
.pop(flavor_id
, None)
763 def new_image(self
, image_dict
):
765 Adds a tenant image to VIM
767 200, image-id if the image is created
768 <0, message if there is an error
771 return self
.get_image_id_from_path(image_dict
['location'])
773 def delete_image(self
, image_id
):
780 raise vimconn
.vimconnNotImplemented("Should have implemented this")
782 def catalog_exists(self
, catalog_name
, catalogs
):
789 for catalog
in catalogs
:
790 if catalog
.name
== catalog_name
:
794 def create_vimcatalog(self
, vca
=None, catalog_name
=None):
795 """ Create new catalog entry in vCloud director.
798 vca: vCloud director.
799 catalog_name catalog that client wish to create. Note no validation done for a name.
800 Client must make sure that provide valid string representation.
802 Return (bool) True if catalog created.
806 task
= vca
.create_catalog(catalog_name
, catalog_name
)
807 result
= vca
.block_until_completed(task
)
810 catalogs
= vca
.get_catalogs()
813 return self
.catalog_exists(catalog_name
, catalogs
)
815 # noinspection PyIncorrectDocstring
816 def upload_ovf(self
, vca
=None, catalog_name
=None, image_name
=None, media_file_name
=None,
817 description
='', progress
=False, chunk_bytes
=128 * 1024):
819 Uploads a OVF file to a vCloud catalog
826 :param catalog_name: (str): The name of the catalog to upload the media.
827 :param media_file_name: (str): The name of the local media file to upload.
828 :return: (bool) True if the media file was successfully uploaded, false otherwise.
830 os
.path
.isfile(media_file_name
)
831 statinfo
= os
.stat(media_file_name
)
833 # find a catalog entry where we upload OVF.
834 # create vApp Template and check the status if vCD able to read OVF it will respond with appropirate
836 # if VCD can parse OVF we upload VMDK file
837 for catalog
in vca
.get_catalogs():
838 if catalog_name
!= catalog
.name
:
840 link
= filter(lambda link
: link
.get_type() == "application/vnd.vmware.vcloud.media+xml" and
841 link
.get_rel() == 'add', catalog
.get_Link())
842 assert len(link
) == 1
844 <UploadVAppTemplateParams name="%s" xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"><Description>%s vApp Template</Description></UploadVAppTemplateParams>
845 """ % (escape(catalog_name
), escape(description
))
846 headers
= vca
.vcloud_session
.get_vcloud_headers()
847 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml'
848 response
= Http
.post(link
[0].get_href(), headers
=headers
, data
=data
, verify
=vca
.verify
, logger
=self
.logger
)
849 if response
.status_code
== requests
.codes
.created
:
850 catalogItem
= XmlElementTree
.fromstring(response
.content
)
851 entity
= [child
for child
in catalogItem
if
852 child
.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
853 href
= entity
.get('href')
855 response
= Http
.get(href
, headers
=vca
.vcloud_session
.get_vcloud_headers(),
856 verify
=vca
.verify
, logger
=self
.logger
)
858 if response
.status_code
== requests
.codes
.ok
:
859 media
= mediaType
.parseString(response
.content
, True)
860 link
= filter(lambda link
: link
.get_rel() == 'upload:default',
861 media
.get_Files().get_File()[0].get_Link())[0]
862 headers
= vca
.vcloud_session
.get_vcloud_headers()
863 headers
['Content-Type'] = 'Content-Type text/xml'
864 response
= Http
.put(link
.get_href(),
865 data
=open(media_file_name
, 'rb'),
867 verify
=vca
.verify
, logger
=self
.logger
)
868 if response
.status_code
!= requests
.codes
.ok
:
870 "Failed create vApp template for catalog name {} and image {}".format(catalog_name
,
874 # TODO fix this with aync block
877 self
.logger
.debug("vApp template for catalog name {} and image {}".format(catalog_name
, media_file_name
))
879 # uploading VMDK file
880 # check status of OVF upload and upload remaining files.
881 response
= Http
.get(template
,
882 headers
=vca
.vcloud_session
.get_vcloud_headers(),
886 if response
.status_code
== requests
.codes
.ok
:
887 media
= mediaType
.parseString(response
.content
, True)
888 number_of_files
= len(media
.get_Files().get_File())
889 for index
in xrange(0, number_of_files
):
890 links_list
= filter(lambda link
: link
.get_rel() == 'upload:default',
891 media
.get_Files().get_File()[index
].get_Link())
892 for link
in links_list
:
893 # we skip ovf since it already uploaded.
894 if 'ovf' in link
.get_href():
896 # The OVF file and VMDK must be in a same directory
897 head
, tail
= os
.path
.split(media_file_name
)
898 file_vmdk
= head
+ '/' + link
.get_href().split("/")[-1]
899 if not os
.path
.isfile(file_vmdk
):
901 statinfo
= os
.stat(file_vmdk
)
902 if statinfo
.st_size
== 0:
904 hrefvmdk
= link
.get_href()
907 print("Uploading file: {}".format(file_vmdk
))
909 widgets
= ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
911 progress_bar
= ProgressBar(widgets
=widgets
, maxval
=statinfo
.st_size
).start()
913 bytes_transferred
= 0
914 f
= open(file_vmdk
, 'rb')
915 while bytes_transferred
< statinfo
.st_size
:
916 my_bytes
= f
.read(chunk_bytes
)
917 if len(my_bytes
) <= chunk_bytes
:
918 headers
= vca
.vcloud_session
.get_vcloud_headers()
919 headers
['Content-Range'] = 'bytes %s-%s/%s' % (
920 bytes_transferred
, len(my_bytes
) - 1, statinfo
.st_size
)
921 headers
['Content-Length'] = str(len(my_bytes
))
922 response
= Http
.put(hrefvmdk
,
928 if response
.status_code
== requests
.codes
.ok
:
929 bytes_transferred
+= len(my_bytes
)
931 progress_bar
.update(bytes_transferred
)
934 'file upload failed with error: [%s] %s' % (response
.status_code
,
941 progress_bar
.finish()
945 self
.logger
.debug("Failed retrieve vApp template for catalog name {} for OVF {}".
946 format(catalog_name
, media_file_name
))
949 self
.logger
.debug("Failed retrieve catalog name {} for OVF file {}".format(catalog_name
, media_file_name
))
952 def upload_vimimage(self
, vca
=None, catalog_name
=None, media_name
=None, medial_file_name
=None, progress
=False):
953 """Upload media file"""
954 # TODO add named parameters for readability
956 return self
.upload_ovf(vca
=vca
, catalog_name
=catalog_name
, image_name
=media_name
.split(".")[0],
957 media_file_name
=medial_file_name
, description
='medial_file_name', progress
=progress
)
959 def validate_uuid4(self
, uuid_string
=None):
960 """ Method validate correct format of UUID.
962 Return: true if string represent valid uuid
965 val
= uuid
.UUID(uuid_string
, version
=4)
970 def get_catalogid(self
, catalog_name
=None, catalogs
=None):
971 """ Method check catalog and return catalog ID in UUID format.
974 catalog_name: catalog name as string
975 catalogs: list of catalogs.
977 Return: catalogs uuid
980 for catalog
in catalogs
:
981 if catalog
.name
== catalog_name
:
982 catalog_id
= catalog
.get_id().split(":")
986 def get_catalogbyid(self
, catalog_uuid
=None, catalogs
=None):
987 """ Method check catalog and return catalog name lookup done by catalog UUID.
990 catalog_name: catalog name as string
991 catalogs: list of catalogs.
993 Return: catalogs name or None
996 if not self
.validate_uuid4(uuid_string
=catalog_uuid
):
999 for catalog
in catalogs
:
1000 catalog_id
= catalog
.get_id().split(":")[3]
1001 if catalog_id
== catalog_uuid
:
1005 def get_image_id_from_path(self
, path
=None, progress
=False):
1006 """ Method upload OVF image to vCloud director.
1008 Each OVF image represented as single catalog entry in vcloud director.
1009 The method check for existing catalog entry. The check done by file name without file extension.
1011 if given catalog name already present method will respond with existing catalog uuid otherwise
1012 it will create new catalog entry and upload OVF file to newly created catalog.
1014 If method can't create catalog entry or upload a file it will throw exception.
1016 Method accept boolean flag progress that will output progress bar. It useful method
1017 for standalone upload use case. In case to test large file upload.
1020 path: - valid path to OVF file.
1021 progress - boolean progress bar show progress bar.
1023 Return: if image uploaded correct method will provide image catalog UUID.
1025 vca
= self
.connect()
1027 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1030 raise vimconn
.vimconnException("Image path can't be None.")
1032 if not os
.path
.isfile(path
):
1033 raise vimconn
.vimconnException("Can't read file. File not found.")
1035 if not os
.access(path
, os
.R_OK
):
1036 raise vimconn
.vimconnException("Can't read file. Check file permission to read.")
1038 self
.logger
.debug("get_image_id_from_path() client requesting {} ".format(path
))
1040 dirpath
, filename
= os
.path
.split(path
)
1041 flname
, file_extension
= os
.path
.splitext(path
)
1042 if file_extension
!= '.ovf':
1043 self
.logger
.debug("Wrong file extension {} connector support only OVF container.".format(file_extension
))
1044 raise vimconn
.vimconnException("Wrong container. vCloud director supports only OVF.")
1046 catalog_name
= os
.path
.splitext(filename
)[0]
1047 catalog_md5_name
= hashlib
.md5(path
).hexdigest()
1048 self
.logger
.debug("File name {} Catalog Name {} file path {} "
1049 "vdc catalog name {}".format(filename
, catalog_name
, path
, catalog_md5_name
))
1051 catalogs
= vca
.get_catalogs()
1052 if len(catalogs
) == 0:
1053 self
.logger
.info("Creating a new catalog entry {} in vcloud director".format(catalog_name
))
1054 result
= self
.create_vimcatalog(vca
, catalog_md5_name
)
1056 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1057 result
= self
.upload_vimimage(vca
=vca
, catalog_name
=catalog_md5_name
,
1058 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1060 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_name
))
1061 return self
.get_catalogid(catalog_name
, vca
.get_catalogs())
1063 for catalog
in catalogs
:
1064 # search for existing catalog if we find same name we return ID
1065 # TODO optimize this
1066 if catalog
.name
== catalog_md5_name
:
1067 self
.logger
.debug("Found existing catalog entry for {} "
1068 "catalog id {}".format(catalog_name
,
1069 self
.get_catalogid(catalog_md5_name
, catalogs
)))
1070 return self
.get_catalogid(catalog_md5_name
, vca
.get_catalogs())
1072 # if we didn't find existing catalog we create a new one and upload image.
1073 self
.logger
.debug("Creating new catalog entry {} - {}".format(catalog_name
, catalog_md5_name
))
1074 result
= self
.create_vimcatalog(vca
, catalog_md5_name
)
1076 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1078 result
= self
.upload_vimimage(vca
=vca
, catalog_name
=catalog_md5_name
,
1079 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1081 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_md5_name
))
1083 return self
.get_catalogid(catalog_md5_name
, vca
.get_catalogs())
1085 def get_image_list(self
, filter_dict
={}):
1086 '''Obtain tenant images from VIM
1090 checksum: image checksum
1091 location: image path
1092 Returns the image list of dictionaries:
1093 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1096 vca
= self
.connect()
1098 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1101 catalogs
= vca
.get_catalogs()
1102 if len(catalogs
) == 0:
1105 for catalog
in catalogs
:
1106 catalog_uuid
= catalog
.get_id().split(":")[3]
1109 if filter_dict
.get("name") and filter_dict
["name"] != name
:
1111 if filter_dict
.get("id") and filter_dict
["id"] != catalog_uuid
:
1113 filtered_dict
["name"] = name
1114 filtered_dict
["id"] = catalog_uuid
1115 image_list
.append(filtered_dict
)
1117 self
.logger
.debug("List of already created catalog items: {}".format(image_list
))
1119 except Exception as exp
:
1120 raise vimconn
.vimconnException("Exception occured while retriving catalog items {}".format(exp
))
1122 def get_vappid(self
, vdc
=None, vapp_name
=None):
1123 """ Method takes vdc object and vApp name and returns vapp uuid or None
1126 vdc: The VDC object.
1127 vapp_name: is application vappp name identifier
1130 The return vApp name otherwise None
1132 if vdc
is None or vapp_name
is None:
1134 # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
1136 refs
= filter(lambda ref
: ref
.name
== vapp_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1137 vdc
.ResourceEntities
.ResourceEntity
)
1139 return refs
[0].href
.split("vapp")[1][1:]
1140 except Exception as e
:
1141 self
.logger
.exception(e
)
1145 def check_vapp(self
, vdc
=None, vapp_uuid
=None):
1146 """ Method Method returns True or False if vapp deployed in vCloud director
1149 vca: Connector to VCA
1150 vdc: The VDC object.
1151 vappid: vappid is application identifier
1154 The return True if vApp deployed
1159 refs
= filter(lambda ref
:
1160 ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1161 vdc
.ResourceEntities
.ResourceEntity
)
1163 vappid
= ref
.href
.split("vapp")[1][1:]
1164 # find vapp with respected vapp uuid
1165 if vappid
== vapp_uuid
:
1167 except Exception as e
:
1168 self
.logger
.exception(e
)
1172 def get_namebyvappid(self
, vca
=None, vdc
=None, vapp_uuid
=None):
1173 """Method returns vApp name from vCD and lookup done by vapp_id.
1176 vca: Connector to VCA
1177 vdc: The VDC object.
1178 vapp_uuid: vappid is application identifier
1181 The return vApp name otherwise None
1185 refs
= filter(lambda ref
: ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1186 vdc
.ResourceEntities
.ResourceEntity
)
1188 # we care only about UUID the rest doesn't matter
1189 vappid
= ref
.href
.split("vapp")[1][1:]
1190 if vappid
== vapp_uuid
:
1191 response
= Http
.get(ref
.href
, headers
=vca
.vcloud_session
.get_vcloud_headers(), verify
=vca
.verify
,
1193 tree
= XmlElementTree
.fromstring(response
.content
)
1194 return tree
.attrib
['name']
1195 except Exception as e
:
1196 self
.logger
.exception(e
)
1200 def new_vminstance(self
, name
=None, description
="", start
=False, image_id
=None, flavor_id
=None, net_list
={},
1201 cloud_config
=None, disk_list
=None):
1202 """Adds a VM instance to VIM
1204 start: indicates if VM must start or boot in pause mode. Ignored
1205 image_id,flavor_id: image and flavor uuid
1206 net_list: list of interfaces, each one is a dictionary with:
1208 net_id: network uuid to connect
1209 vpci: virtual vcpi to assign
1210 model: interface model, virtio, e2000, ...
1212 use: 'data', 'bridge', 'mgmt'
1213 type: 'virtual', 'PF', 'VF', 'VFnotShared'
1214 vim_id: filled/added by this function
1215 cloud_config: can be a text script to be passed directly to cloud-init,
1216 or an object to inject users and ssh keys with format:
1217 key-pairs: [] list of keys to install to the default user
1218 users: [{ name, key-pairs: []}] list of users to add with their key-pair
1219 #TODO ip, security groups
1220 Returns >=0, the instance identifier
1224 self
.logger
.info("Creating new instance for entry {}".format(name
))
1225 self
.logger
.debug("desc {} boot {} image_id: {} flavor_id: {} net_list: {} cloud_config {}".
1226 format(description
, start
, image_id
, flavor_id
, net_list
, cloud_config
))
1227 vca
= self
.connect()
1229 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1231 #new vm name = vmname + tenant_id + uuid
1232 new_vm_name
= [name
, '-', str(uuid
.uuid4())]
1233 vmname_andid
= ''.join(new_vm_name
)
1235 # if vm already deployed we return existing uuid
1236 # vapp_uuid = self.get_vappid(vca.get_vdc(self.tenant_name), name)
1237 # if vapp_uuid is not None:
1240 # we check for presence of VDC, Catalog entry and Flavor.
1241 vdc
= vca
.get_vdc(self
.tenant_name
)
1243 raise vimconn
.vimconnNotFoundException(
1244 "new_vminstance(): Failed create vApp {}: (Failed retrieve VDC information)".format(name
))
1245 catalogs
= vca
.get_catalogs()
1246 if catalogs
is None:
1247 raise vimconn
.vimconnNotFoundException(
1248 "new_vminstance(): Failed create vApp {}: (Failed retrieve catalogs list)".format(name
))
1250 catalog_hash_name
= self
.get_catalogbyid(catalog_uuid
=image_id
, catalogs
=catalogs
)
1251 if catalog_hash_name
:
1252 self
.logger
.info("Found catalog entry {} for image id {}".format(catalog_hash_name
, image_id
))
1254 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1255 "(Failed retrieve catalog information {})".format(name
, image_id
))
1258 # Set vCPU and Memory based on flavor.
1263 pci_devices_info
= []
1264 if flavor_id
is not None:
1265 if flavor_id
not in flavorlist
:
1266 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1267 "Failed retrieve flavor information "
1268 "flavor id {}".format(name
, flavor_id
))
1271 flavor
= flavorlist
[flavor_id
]
1272 vm_cpus
= flavor
[FLAVOR_VCPUS_KEY
]
1273 vm_memory
= flavor
[FLAVOR_RAM_KEY
]
1274 vm_disk
= flavor
[FLAVOR_DISK_KEY
]
1275 extended
= flavor
.get("extended", None)
1277 numas
=extended
.get("numas", None)
1280 for interface
in numa
.get("interfaces",() ):
1281 if interface
["dedicated"].strip()=="yes":
1282 pci_devices_info
.append(interface
)
1284 raise vimconn
.vimconnException("Corrupted flavor. {}".format(flavor_id
))
1286 # image upload creates template name as catalog name space Template.
1287 templateName
= self
.get_catalogbyid(catalog_uuid
=image_id
, catalogs
=catalogs
)
1292 # client must provide at least one entry in net_list if not we report error
1293 #If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
1294 #If no mgmt, then the 1st NN in netlist is considered as primary net.
1296 primary_netname
= None
1297 network_mode
= 'bridged'
1298 if net_list
is not None and len(net_list
) > 0:
1299 for net
in net_list
:
1300 if 'use' in net
and net
['use'] == 'mgmt':
1302 if primary_net
is None:
1303 primary_net
= net_list
[0]
1306 primary_net_id
= primary_net
['net_id']
1307 network_dict
= self
.get_vcd_network(network_uuid
=primary_net_id
)
1308 if 'name' in network_dict
:
1309 primary_netname
= network_dict
['name']
1312 raise vimconn
.vimconnException("Corrupted flavor. {}".format(primary_net
))
1314 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed network list is empty.".format(name
))
1316 # use: 'data', 'bridge', 'mgmt'
1317 # create vApp. Set vcpu and ram based on flavor id.
1318 vapptask
= vca
.create_vapp(self
.tenant_name
, vmname_andid
, templateName
,
1319 self
.get_catalogbyid(image_id
, catalogs
),
1320 network_name
=None, # None while creating vapp
1321 network_mode
=network_mode
,
1322 vm_name
=vmname_andid
,
1323 vm_cpus
=vm_cpus
, # can be None if flavor is None
1324 vm_memory
=vm_memory
) # can be None if flavor is None
1326 if vapptask
is None or vapptask
is False:
1327 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): failed deploy vApp {}".format(vmname_andid
))
1328 if type(vapptask
) is VappTask
:
1329 vca
.block_until_completed(vapptask
)
1331 # we should have now vapp in undeployed state.
1332 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vmname_andid
)
1333 vapp_uuid
= self
.get_vappid(vca
.get_vdc(self
.tenant_name
), vmname_andid
)
1335 raise vimconn
.vimconnUnexpectedResponse(
1336 "new_vminstance(): Failed failed retrieve vApp {} after we deployed".format(
1339 #Add PCI passthrough configrations
1340 PCI_devices_status
= False
1343 if len(pci_devices_info
) > 0:
1344 self
.logger
.info("Need to add PCI devices {} into VM {}".format(pci_devices_info
,
1346 PCI_devices_status
, vm_obj
, vcenter_conect
= self
.add_pci_devices(vapp_uuid
,
1349 if PCI_devices_status
:
1350 self
.logger
.info("Added PCI devives {} to VM {}".format(
1355 self
.logger
.info("Fail to add PCI devives {} to VM {}".format(
1361 #Assuming there is only one disk in ovf and fast provisioning in organization vDC is disabled
1362 result
= self
.modify_vm_disk(vapp_uuid
, vm_disk
)
1364 self
.logger
.debug("Modified Disk size of VM {} ".format(vmname_andid
))
1366 # add NICs & connect to networks in netlist
1368 self
.logger
.info("Request to connect VM to a network: {}".format(net_list
))
1370 primary_nic_index
= 0
1371 for net
in net_list
:
1372 # openmano uses network id in UUID format.
1373 # vCloud Director need a name so we do reverse operation from provided UUID we lookup a name
1374 # [{'use': 'bridge', 'net_id': '527d4bf7-566a-41e7-a9e7-ca3cdd9cef4f', 'type': 'virtual',
1375 # 'vpci': '0000:00:11.0', 'name': 'eth0'}]
1377 if 'net_id' not in net
:
1380 interface_net_id
= net
['net_id']
1381 interface_net_name
= self
.get_network_name_by_id(network_uuid
=interface_net_id
)
1382 interface_network_mode
= net
['use']
1384 if interface_network_mode
== 'mgmt':
1385 primary_nic_index
= nicIndex
1387 """- POOL (A static IP address is allocated automatically from a pool of addresses.)
1388 - DHCP (The IP address is obtained from a DHCP service.)
1389 - MANUAL (The IP address is assigned manually in the IpAddress element.)
1390 - NONE (No IP addressing mode specified.)"""
1392 if primary_netname
is not None:
1393 nets
= filter(lambda n
: n
.name
== interface_net_name
, vca
.get_networks(self
.tenant_name
))
1395 self
.logger
.info("new_vminstance(): Found requested network: {}".format(nets
[0].name
))
1396 task
= vapp
.connect_to_network(nets
[0].name
, nets
[0].href
)
1397 if type(task
) is GenericTask
:
1398 vca
.block_until_completed(task
)
1399 # connect network to VM - with all DHCP by default
1400 self
.logger
.info("new_vminstance(): Connecting VM to a network {}".format(nets
[0].name
))
1401 task
= vapp
.connect_vms(nets
[0].name
,
1402 connection_index
=nicIndex
,
1403 connections_primary_index
=primary_nic_index
,
1404 ip_allocation_mode
='DHCP')
1405 if type(task
) is GenericTask
:
1406 vca
.block_until_completed(task
)
1409 # it might be a case if specific mandatory entry in dict is empty
1410 self
.logger
.debug("Key error {}".format(KeyError.message
))
1411 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed create new vm instance {}".format(name
))
1413 # deploy and power on vm
1414 self
.logger
.debug("new_vminstance(): Deploying vApp {} ".format(name
))
1415 deploytask
= vapp
.deploy(powerOn
=False)
1416 if type(deploytask
) is GenericTask
:
1417 vca
.block_until_completed(deploytask
)
1419 # If VM has PCI devices reserve memory for VM
1420 if PCI_devices_status
and vm_obj
and vcenter_conect
:
1421 memReserve
= vm_obj
.config
.hardware
.memoryMB
1422 spec
= vim
.vm
.ConfigSpec()
1423 spec
.memoryAllocation
= vim
.ResourceAllocationInfo(reservation
=memReserve
)
1424 task
= vm_obj
.ReconfigVM_Task(spec
=spec
)
1426 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
1427 self
.logger
.info("Reserved memmoery {} MB for "\
1428 "VM VM status: {}".format(str(memReserve
),result
))
1430 self
.logger
.info("Fail to reserved memmoery {} to VM {}".format(
1431 str(memReserve
),str(vm_obj
)))
1433 self
.logger
.debug("new_vminstance(): power on vApp {} ".format(name
))
1434 poweron_task
= vapp
.poweron()
1435 if type(poweron_task
) is GenericTask
:
1436 vca
.block_until_completed(poweron_task
)
1438 # check if vApp deployed and if that the case return vApp UUID otherwise -1
1441 while wait_time
<= MAX_WAIT_TIME
:
1442 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vmname_andid
)
1443 if vapp
and vapp
.me
.deployed
:
1444 vapp_uuid
= self
.get_vappid(vca
.get_vdc(self
.tenant_name
), vmname_andid
)
1447 self
.logger
.debug("new_vminstance(): Wait for vApp {} to deploy".format(name
))
1448 time
.sleep(INTERVAL_TIME
)
1450 wait_time
+=INTERVAL_TIME
1452 if vapp_uuid
is not None:
1455 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed create new vm instance {}".format(name
))
1459 ## based on current discussion
1463 # created: '2016-09-08T11:51:58'
1464 # description: simple-instance.linux1.1
1465 # flavor: ddc6776e-75a9-11e6-ad5f-0800273e724c
1466 # hostId: e836c036-74e7-11e6-b249-0800273e724c
1467 # image: dde30fe6-75a9-11e6-ad5f-0800273e724c
1472 def get_vminstance(self
, vim_vm_uuid
=None):
1473 """Returns the VM instance information from VIM"""
1475 self
.logger
.debug("Client requesting vm instance {} ".format(vim_vm_uuid
))
1476 vca
= self
.connect()
1478 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1480 vdc
= vca
.get_vdc(self
.tenant_name
)
1482 raise vimconn
.vimconnConnectionException(
1483 "Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
1485 vm_info_dict
= self
.get_vapp_details_rest(vapp_uuid
=vim_vm_uuid
)
1486 if not vm_info_dict
:
1487 self
.logger
.debug("get_vminstance(): Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
1488 raise vimconn
.vimconnNotFoundException("Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
1490 status_key
= vm_info_dict
['status']
1493 vm_dict
= {'created': vm_info_dict
['created'],
1494 'description': vm_info_dict
['name'],
1495 'status': vcdStatusCode2manoFormat
[int(status_key
)],
1496 'hostId': vm_info_dict
['vmuuid'],
1498 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
1500 if 'interfaces' in vm_info_dict
:
1501 vm_dict
['interfaces'] = vm_info_dict
['interfaces']
1503 vm_dict
['interfaces'] = []
1505 vm_dict
= {'created': '',
1507 'status': vcdStatusCode2manoFormat
[int(-1)],
1508 'hostId': vm_info_dict
['vmuuid'],
1509 'error_msg': "Inconsistency state",
1510 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
1514 def delete_vminstance(self
, vm__vim_uuid
):
1515 """Method poweroff and remove VM instance from vcloud director network.
1518 vm__vim_uuid: VM UUID
1521 Returns the instance identifier
1524 self
.logger
.debug("Client requesting delete vm instance {} ".format(vm__vim_uuid
))
1525 vca
= self
.connect()
1527 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1529 vdc
= vca
.get_vdc(self
.tenant_name
)
1531 self
.logger
.debug("delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
1533 raise vimconn
.vimconnException(
1534 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
1537 vapp_name
= self
.get_namebyvappid(vca
, vdc
, vm__vim_uuid
)
1538 if vapp_name
is None:
1539 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1540 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
1542 self
.logger
.info("Deleting vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
1544 # Delete vApp and wait for status change if task executed and vApp is None.
1545 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
)
1548 if vapp
.me
.deployed
:
1549 self
.logger
.info("Powering off vApp {}".format(vapp_name
))
1553 while wait_time
<= MAX_WAIT_TIME
:
1554 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
)
1556 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1557 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
1559 power_off_task
= vapp
.poweroff()
1560 if type(power_off_task
) is GenericTask
:
1561 result
= vca
.block_until_completed(power_off_task
)
1566 self
.logger
.info("Wait for vApp {} to power off".format(vapp_name
))
1567 time
.sleep(INTERVAL_TIME
)
1569 wait_time
+=INTERVAL_TIME
1571 self
.logger
.debug("delete_vminstance(): Failed to power off VM instance {} ".format(vm__vim_uuid
))
1573 self
.logger
.info("delete_vminstance(): Powered off VM instance {} ".format(vm__vim_uuid
))
1576 self
.logger
.info("Undeploy vApp {}".format(vapp_name
))
1579 while wait_time
<= MAX_WAIT_TIME
:
1580 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
)
1582 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1583 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
1584 undeploy_task
= vapp
.undeploy(action
='powerOff')
1586 if type(undeploy_task
) is GenericTask
:
1587 result
= vca
.block_until_completed(undeploy_task
)
1592 self
.logger
.debug("Wait for vApp {} to undeploy".format(vapp_name
))
1593 time
.sleep(INTERVAL_TIME
)
1595 wait_time
+=INTERVAL_TIME
1598 self
.logger
.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid
))
1601 self
.logger
.info("Start deletion of vApp {} ".format(vapp_name
))
1602 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
)
1604 if vapp
is not None:
1608 while wait_time
<= MAX_WAIT_TIME
:
1609 vapp
= vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
)
1611 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1612 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
1614 delete_task
= vapp
.delete()
1616 if type(delete_task
) is GenericTask
:
1617 vca
.block_until_completed(delete_task
)
1618 result
= vca
.block_until_completed(delete_task
)
1622 self
.logger
.debug("Wait for vApp {} to delete".format(vapp_name
))
1623 time
.sleep(INTERVAL_TIME
)
1625 wait_time
+=INTERVAL_TIME
1628 self
.logger
.debug("delete_vminstance(): Failed delete uuid {} ".format(vm__vim_uuid
))
1631 self
.logger
.debug(traceback
.format_exc())
1632 raise vimconn
.vimconnException("delete_vminstance(): Failed delete vm instance {}".format(vm__vim_uuid
))
1634 if vca
.get_vapp(vca
.get_vdc(self
.tenant_name
), vapp_name
) is None:
1635 self
.logger
.info("Deleted vm instance {} sccessfully".format(vm__vim_uuid
))
1638 raise vimconn
.vimconnException("delete_vminstance(): Failed delete vm instance {}".format(vm__vim_uuid
))
1640 def refresh_vms_status(self
, vm_list
):
1641 """Get the status of the virtual machines and their interfaces/ports
1642 Params: the list of VM identifiers
1643 Returns a dictionary with:
1644 vm_id: #VIM id of this Virtual Machine
1645 status: #Mandatory. Text with one of:
1646 # DELETED (not found at vim)
1647 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1648 # OTHER (Vim reported other status not understood)
1649 # ERROR (VIM indicates an ERROR status)
1650 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1651 # CREATING (on building process), ERROR
1652 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1654 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1655 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1657 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1658 mac_address: #Text format XX:XX:XX:XX:XX:XX
1659 vim_net_id: #network id where this interface is connected
1660 vim_interface_id: #interface/port VIM id
1661 ip_address: #null, or text with IPv4, IPv6 address
1664 self
.logger
.debug("Client requesting refresh vm status for {} ".format(vm_list
))
1667 rheaders
= {'Content-Type': 'application/xml'}
1670 resp
= requests
.get(self
.nsx_manager
+ '/api/4.0/edges/edge-2/dhcp/leaseInfo',
1671 auth
= (self
.nsx_user
, self
.nsx_password
),
1672 verify
= False, headers
= rheaders
)
1674 if resp
.status_code
== requests
.codes
.ok
:
1675 dhcp_leases
= XmlElementTree
.fromstring(resp
.text
)
1676 for child
in dhcp_leases
:
1677 if child
.tag
== 'dhcpLeaseInfo':
1678 dhcpLeaseInfo
= child
1679 for leaseInfo
in dhcpLeaseInfo
:
1680 for elem
in leaseInfo
:
1681 if (elem
.tag
)=='macAddress':
1682 mac_addr
= elem
.text
1683 if (elem
.tag
)=='ipAddress':
1685 if (mac_addr
) is not None:
1686 mac_ip_addr
[mac_addr
]= ip_addr
1687 self
.logger
.debug("NSX Manager DHCP Lease info: mac_ip_addr : {}".format(mac_ip_addr
))
1689 self
.logger
.debug("Error occurred while getting DHCP lease info from NSX Manager: {}".format(resp
.content
))
1691 self
.logger
.debug("Error in response from NSX Manager {}".format(KeyError.message
))
1692 self
.logger
.debug(traceback
.format_exc())
1694 vca
= self
.connect()
1696 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1698 vdc
= vca
.get_vdc(self
.tenant_name
)
1700 raise vimconn
.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
1703 for vmuuid
in vm_list
:
1704 vmname
= self
.get_namebyvappid(vca
, vdc
, vmuuid
)
1705 if vmname
is not None:
1707 the_vapp
= vca
.get_vapp(vdc
, vmname
)
1708 vm_info
= the_vapp
.get_vms_details()
1709 vm_status
= vm_info
[0]['status']
1710 vm_pci_details
= self
.get_vm_pci_details(vmuuid
)
1711 vm_info
[0].update(vm_pci_details
)
1713 vm_dict
= {'status': vcdStatusCode2manoFormat
[the_vapp
.me
.get_status()],
1714 'error_msg': vcdStatusCode2manoFormat
[the_vapp
.me
.get_status()],
1715 'vim_info': yaml
.safe_dump(vm_info
), 'interfaces': []}
1719 vm_app_networks
= the_vapp
.get_vms_network_info()
1720 for vapp_network
in vm_app_networks
:
1721 for vm_network
in vapp_network
:
1722 if vm_network
['name'] == vmname
:
1723 #Assign IP Address based on MAC Address in NSX DHCP lease info
1724 for mac_adres
,ip_adres
in mac_ip_addr
.iteritems():
1725 if mac_adres
== vm_network
['mac']:
1726 vm_network
['ip']=ip_adres
1727 interface
= {"mac_address": vm_network
['mac'],
1728 "vim_net_id": self
.get_network_id_by_name(vm_network
['network_name']),
1729 "vim_interface_id": self
.get_network_id_by_name(vm_network
['network_name']),
1730 'ip_address': vm_network
['ip']}
1731 # interface['vim_info'] = yaml.safe_dump(vm_network)
1732 vm_dict
["interfaces"].append(interface
)
1733 # add a vm to vm dict
1734 vms_dict
.setdefault(vmuuid
, vm_dict
)
1736 self
.logger
.debug("Error in respond {}".format(KeyError.message
))
1737 self
.logger
.debug(traceback
.format_exc())
1741 def action_vminstance(self
, vm__vim_uuid
=None, action_dict
=None):
1742 """Send and action over a VM instance from VIM
1743 Returns the vm_id if the action was successfully sent to the VIM"""
1745 self
.logger
.debug("Received action for vm {} and action dict {}".format(vm__vim_uuid
, action_dict
))
1746 if vm__vim_uuid
is None or action_dict
is None:
1747 raise vimconn
.vimconnException("Invalid request. VM id or action is None.")
1749 vca
= self
.connect()
1751 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1753 vdc
= vca
.get_vdc(self
.tenant_name
)
1755 return -1, "Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
)
1757 vapp_name
= self
.get_namebyvappid(vca
, vdc
, vm__vim_uuid
)
1758 if vapp_name
is None:
1759 self
.logger
.debug("action_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1760 raise vimconn
.vimconnException("Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
1762 self
.logger
.info("Action_vminstance vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
1765 the_vapp
= vca
.get_vapp(vdc
, vapp_name
)
1766 # TODO fix all status
1767 if "start" in action_dict
:
1768 vm_info
= the_vapp
.get_vms_details()
1769 vm_status
= vm_info
[0]['status']
1770 self
.logger
.info("Power on vApp: vm_status:{} {}".format(type(vm_status
),vm_status
))
1771 if vm_status
== "Suspended" or vm_status
== "Powered off":
1772 power_on_task
= the_vapp
.poweron()
1773 if power_on_task
is not None and type(power_on_task
) is GenericTask
:
1774 result
= vca
.block_until_completed(power_on_task
)
1776 self
.logger
.info("action_vminstance: Powered on vApp: {}".format(vapp_name
))
1778 self
.logger
.info("action_vminstance: Failed to power on vApp: {}".format(vapp_name
))
1780 self
.logger
.info("action_vminstance: Wait for vApp {} to power on".format(vapp_name
))
1781 elif "rebuild" in action_dict
:
1782 self
.logger
.info("action_vminstance: Rebuilding vApp: {}".format(vapp_name
))
1783 power_on_task
= the_vapp
.deploy(powerOn
=True)
1784 if type(power_on_task
) is GenericTask
:
1785 result
= vca
.block_until_completed(power_on_task
)
1787 self
.logger
.info("action_vminstance: Rebuilt vApp: {}".format(vapp_name
))
1789 self
.logger
.info("action_vminstance: Failed to rebuild vApp: {}".format(vapp_name
))
1791 self
.logger
.info("action_vminstance: Wait for vApp rebuild {} to power on".format(vapp_name
))
1792 elif "pause" in action_dict
:
1795 elif "resume" in action_dict
:
1798 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
1799 power_off_task
= the_vapp
.undeploy(action
='powerOff')
1800 if type(power_off_task
) is GenericTask
:
1801 result
= vca
.block_until_completed(power_off_task
)
1803 self
.logger
.info("action_vminstance: Powered off vApp: {}".format(vapp_name
))
1805 self
.logger
.info("action_vminstance: Failed to power off vApp: {}".format(vapp_name
))
1807 self
.logger
.info("action_vminstance: Wait for vApp {} to power off".format(vapp_name
))
1808 elif "forceOff" in action_dict
:
1810 elif "terminate" in action_dict
:
1812 # elif "createImage" in action_dict:
1813 # server.create_image()
1819 def get_vminstance_console(self
, vm_id
, console_type
="vnc"):
1821 Get a console for the virtual machine
1823 vm_id: uuid of the VM
1824 console_type, can be:
1825 "novnc" (by default), "xvpvnc" for VNC types,
1826 "rdp-html5" for RDP types, "spice-html5" for SPICE types
1827 Returns dict with the console parameters:
1828 protocol: ssh, ftp, http, https, ...
1829 server: usually ip address
1830 port: the http, ssh, ... port
1831 suffix: extra text, e.g. the http path and query string
1833 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1835 # NOT USED METHODS in current version
1837 def host_vim2gui(self
, host
, server_dict
):
1838 """Transform host dictionary from VIM format to GUI format,
1839 and append to the server_dict
1841 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1843 def get_hosts_info(self
):
1844 """Get the information of deployed hosts
1845 Returns the hosts content"""
1846 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1848 def get_hosts(self
, vim_tenant
):
1849 """Get the hosts and deployed instances
1850 Returns the hosts content"""
1851 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1853 def get_processor_rankings(self
):
1854 """Get the processor rankings in the VIM database"""
1855 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1857 def new_host(self
, host_data
):
1858 """Adds a new host to VIM"""
1859 '''Returns status code of the VIM response'''
1860 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1862 def new_external_port(self
, port_data
):
1863 """Adds a external port to VIM"""
1864 '''Returns the port identifier'''
1865 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1867 def new_external_network(self
, net_name
, net_type
):
1868 """Adds a external network to VIM (shared)"""
1869 '''Returns the network identifier'''
1870 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1872 def connect_port_network(self
, port_id
, network_id
, admin
=False):
1873 """Connects a external port to a network"""
1874 '''Returns status code of the VIM response'''
1875 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1877 def new_vminstancefromJSON(self
, vm_data
):
1878 """Adds a VM instance to VIM"""
1879 '''Returns the instance identifier'''
1880 raise vimconn
.vimconnNotImplemented("Should have implemented this")
1882 def get_network_name_by_id(self
, network_uuid
=None):
1883 """Method gets vcloud director network named based on supplied uuid.
1886 network_uuid: network_id
1889 The return network name.
1892 vca
= self
.connect()
1894 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1896 if not network_uuid
:
1900 org_dict
= self
.get_org(self
.org_uuid
)
1901 if 'networks' in org_dict
:
1902 org_network_dict
= org_dict
['networks']
1903 for net_uuid
in org_network_dict
:
1904 if net_uuid
== network_uuid
:
1905 return org_network_dict
[net_uuid
]
1907 self
.logger
.debug("Exception in get_network_name_by_id")
1908 self
.logger
.debug(traceback
.format_exc())
1912 def get_network_id_by_name(self
, network_name
=None):
1913 """Method gets vcloud director network uuid based on supplied name.
1916 network_name: network_name
1918 The return network uuid.
1919 network_uuid: network_id
1922 vca
= self
.connect()
1924 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
1926 if not network_name
:
1927 self
.logger
.debug("get_network_id_by_name() : Network name is empty")
1931 org_dict
= self
.get_org(self
.org_uuid
)
1932 if org_dict
and 'networks' in org_dict
:
1933 org_network_dict
= org_dict
['networks']
1934 for net_uuid
,net_name
in org_network_dict
.iteritems():
1935 if net_name
== network_name
:
1938 except KeyError as exp
:
1939 self
.logger
.debug("get_network_id_by_name() : KeyError- {} ".format(exp
))
1943 def list_org_action(self
):
1945 Method leverages vCloud director and query for available organization for particular user
1948 vca - is active VCA connection.
1949 vdc_name - is a vdc name that will be used to query vms action
1952 The return XML respond
1955 vca
= self
.connect()
1957 raise vimconn
.vimconnConnectionException("self.connect() is failed")
1959 url_list
= [vca
.host
, '/api/org']
1960 vm_list_rest_call
= ''.join(url_list
)
1962 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
1963 response
= Http
.get(url
=vm_list_rest_call
,
1964 headers
=vca
.vcloud_session
.get_vcloud_headers(),
1967 if response
.status_code
== requests
.codes
.ok
:
1968 return response
.content
1972 def get_org_action(self
, org_uuid
=None):
1974 Method leverages vCloud director and retrieve available object fdr organization.
1977 vca - is active VCA connection.
1978 vdc_name - is a vdc name that will be used to query vms action
1981 The return XML respond
1984 vca
= self
.connect()
1986 raise vimconn
.vimconnConnectionException("self.connect() is failed")
1988 if org_uuid
is None:
1991 url_list
= [vca
.host
, '/api/org/', org_uuid
]
1992 vm_list_rest_call
= ''.join(url_list
)
1994 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
1995 response
= Http
.get(url
=vm_list_rest_call
,
1996 headers
=vca
.vcloud_session
.get_vcloud_headers(),
1999 if response
.status_code
== requests
.codes
.ok
:
2000 return response
.content
2004 def get_org(self
, org_uuid
=None):
2006 Method retrieves available organization in vCloud Director
2009 org_uuid - is a organization uuid.
2012 The return dictionary with following key
2013 "network" - for network list under the org
2014 "catalogs" - for network list under the org
2015 "vdcs" - for vdc list under org
2019 vca
= self
.connect()
2021 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2023 if org_uuid
is None:
2026 content
= self
.get_org_action(org_uuid
=org_uuid
)
2031 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2032 for child
in vm_list_xmlroot
:
2033 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.vdc+xml':
2034 vdc_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2035 org_dict
['vdcs'] = vdc_list
2036 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.orgNetwork+xml':
2037 network_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2038 org_dict
['networks'] = network_list
2039 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.catalog+xml':
2040 catalog_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2041 org_dict
['catalogs'] = catalog_list
2047 def get_org_list(self
):
2049 Method retrieves available organization in vCloud Director
2052 vca - is active VCA connection.
2055 The return dictionary and key for each entry VDC UUID
2059 vca
= self
.connect()
2061 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2063 content
= self
.list_org_action()
2065 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2066 for vm_xml
in vm_list_xmlroot
:
2067 if vm_xml
.tag
.split("}")[1] == 'Org':
2068 org_uuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2069 org_dict
[org_uuid
[0]] = vm_xml
.attrib
['name']
2075 def vms_view_action(self
, vdc_name
=None):
2076 """ Method leverages vCloud director vms query call
2079 vca - is active VCA connection.
2080 vdc_name - is a vdc name that will be used to query vms action
2083 The return XML respond
2085 vca
= self
.connect()
2086 if vdc_name
is None:
2089 url_list
= [vca
.host
, '/api/vms/query']
2090 vm_list_rest_call
= ''.join(url_list
)
2092 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2093 refs
= filter(lambda ref
: ref
.name
== vdc_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vdc+xml',
2094 vca
.vcloud_session
.organization
.Link
)
2096 response
= Http
.get(url
=vm_list_rest_call
,
2097 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2100 if response
.status_code
== requests
.codes
.ok
:
2101 return response
.content
2105 def get_vapp_list(self
, vdc_name
=None):
2107 Method retrieves vApp list deployed vCloud director and returns a dictionary
2108 contains a list of all vapp deployed for queried VDC.
2109 The key for a dictionary is vApp UUID
2113 vca - is active VCA connection.
2114 vdc_name - is a vdc name that will be used to query vms action
2117 The return dictionary and key for each entry vapp UUID
2121 if vdc_name
is None:
2124 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2126 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2127 for vm_xml
in vm_list_xmlroot
:
2128 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
2129 if vm_xml
.attrib
['isVAppTemplate'] == 'true':
2130 rawuuid
= vm_xml
.attrib
['container'].split('/')[-1:]
2131 if 'vappTemplate-' in rawuuid
[0]:
2132 # vm in format vappTemplate-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
2133 # vm and use raw UUID as key
2134 vapp_dict
[rawuuid
[0][13:]] = vm_xml
.attrib
2140 def get_vm_list(self
, vdc_name
=None):
2142 Method retrieves VM's list deployed vCloud director. It returns a dictionary
2143 contains a list of all VM's deployed for queried VDC.
2144 The key for a dictionary is VM UUID
2148 vca - is active VCA connection.
2149 vdc_name - is a vdc name that will be used to query vms action
2152 The return dictionary and key for each entry vapp UUID
2156 if vdc_name
is None:
2159 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2161 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2162 for vm_xml
in vm_list_xmlroot
:
2163 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
2164 if vm_xml
.attrib
['isVAppTemplate'] == 'false':
2165 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2166 if 'vm-' in rawuuid
[0]:
2167 # vm in format vm-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
2168 # vm and use raw UUID as key
2169 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2175 def get_vapp(self
, vdc_name
=None, vapp_name
=None, isuuid
=False):
2177 Method retrieves VM deployed vCloud director. It returns VM attribute as dictionary
2178 contains a list of all VM's deployed for queried VDC.
2179 The key for a dictionary is VM UUID
2183 vca - is active VCA connection.
2184 vdc_name - is a vdc name that will be used to query vms action
2187 The return dictionary and key for each entry vapp UUID
2190 vca
= self
.connect()
2192 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2194 if vdc_name
is None:
2197 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2199 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2200 for vm_xml
in vm_list_xmlroot
:
2201 if vm_xml
.tag
.split("}")[1] == 'VMRecord' and vm_xml
.attrib
['isVAppTemplate'] == 'false':
2202 # lookup done by UUID
2204 if vapp_name
in vm_xml
.attrib
['container']:
2205 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2206 if 'vm-' in rawuuid
[0]:
2207 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2209 # lookup done by Name
2211 if vapp_name
in vm_xml
.attrib
['name']:
2212 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2213 if 'vm-' in rawuuid
[0]:
2214 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2221 def get_network_action(self
, network_uuid
=None):
2223 Method leverages vCloud director and query network based on network uuid
2226 vca - is active VCA connection.
2227 network_uuid - is a network uuid
2230 The return XML respond
2233 vca
= self
.connect()
2235 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2237 if network_uuid
is None:
2240 url_list
= [vca
.host
, '/api/network/', network_uuid
]
2241 vm_list_rest_call
= ''.join(url_list
)
2243 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2244 response
= Http
.get(url
=vm_list_rest_call
,
2245 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2248 if response
.status_code
== requests
.codes
.ok
:
2249 return response
.content
2253 def get_vcd_network(self
, network_uuid
=None):
2255 Method retrieves available network from vCloud Director
2258 network_uuid - is VCD network UUID
2260 Each element serialized as key : value pair
2262 Following keys available for access. network_configuration['Gateway'}
2266 <IsInherited>true</IsInherited>
2267 <Gateway>172.16.252.100</Gateway>
2268 <Netmask>255.255.255.0</Netmask>
2269 <Dns1>172.16.254.201</Dns1>
2270 <Dns2>172.16.254.202</Dns2>
2271 <DnsSuffix>vmwarelab.edu</DnsSuffix>
2272 <IsEnabled>true</IsEnabled>
2275 <StartAddress>172.16.252.1</StartAddress>
2276 <EndAddress>172.16.252.99</EndAddress>
2281 <FenceMode>bridged</FenceMode>
2284 The return dictionary and key for each entry vapp UUID
2287 network_configuration
= {}
2288 if network_uuid
is None:
2291 content
= self
.get_network_action(network_uuid
=network_uuid
)
2293 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2295 network_configuration
['status'] = vm_list_xmlroot
.get("status")
2296 network_configuration
['name'] = vm_list_xmlroot
.get("name")
2297 network_configuration
['uuid'] = vm_list_xmlroot
.get("id").split(":")[3]
2299 for child
in vm_list_xmlroot
:
2300 if child
.tag
.split("}")[1] == 'IsShared':
2301 network_configuration
['isShared'] = child
.text
.strip()
2302 if child
.tag
.split("}")[1] == 'Configuration':
2303 for configuration
in child
.iter():
2304 tagKey
= configuration
.tag
.split("}")[1].strip()
2306 network_configuration
[tagKey
] = configuration
.text
.strip()
2307 return network_configuration
2311 return network_configuration
2313 def delete_network_action(self
, network_uuid
=None):
2315 Method delete given network from vCloud director
2318 network_uuid - is a network uuid that client wish to delete
2321 The return None or XML respond or false
2324 vca
= self
.connect_as_admin()
2326 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2327 if network_uuid
is None:
2330 url_list
= [vca
.host
, '/api/admin/network/', network_uuid
]
2331 vm_list_rest_call
= ''.join(url_list
)
2333 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2334 response
= Http
.delete(url
=vm_list_rest_call
,
2335 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2339 if response
.status_code
== 202:
2344 def create_network(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
2345 ip_profile
=None, isshared
='true'):
2347 Method create network in vCloud director
2350 network_name - is network name to be created.
2351 net_type - can be 'bridge','data','ptp','mgmt'.
2352 ip_profile is a dict containing the IP parameters of the network
2353 isshared - is a boolean
2354 parent_network_uuid - is parent provider vdc network that will be used for mapping.
2355 It optional attribute. by default if no parent network indicate the first available will be used.
2358 The return network uuid or return None
2361 new_network_name
= [network_name
, '-', str(uuid
.uuid4())]
2362 content
= self
.create_network_rest(network_name
=''.join(new_network_name
),
2363 ip_profile
=ip_profile
,
2365 parent_network_uuid
=parent_network_uuid
,
2368 self
.logger
.debug("Failed create network {}.".format(network_name
))
2372 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2373 vcd_uuid
= vm_list_xmlroot
.get('id').split(":")
2374 if len(vcd_uuid
) == 4:
2375 self
.logger
.info("Create new network name: {} uuid: {}".format(network_name
, vcd_uuid
[3]))
2378 self
.logger
.debug("Failed create network {}".format(network_name
))
2381 def create_network_rest(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
2382 ip_profile
=None, isshared
='true'):
2384 Method create network in vCloud director
2387 network_name - is network name to be created.
2388 net_type - can be 'bridge','data','ptp','mgmt'.
2389 ip_profile is a dict containing the IP parameters of the network
2390 isshared - is a boolean
2391 parent_network_uuid - is parent provider vdc network that will be used for mapping.
2392 It optional attribute. by default if no parent network indicate the first available will be used.
2395 The return network uuid or return None
2398 vca
= self
.connect_as_admin()
2400 raise vimconn
.vimconnConnectionException("self.connect() is failed.")
2401 if network_name
is None:
2404 url_list
= [vca
.host
, '/api/admin/vdc/', self
.tenant_id
]
2405 vm_list_rest_call
= ''.join(url_list
)
2406 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2407 response
= Http
.get(url
=vm_list_rest_call
,
2408 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2412 provider_network
= None
2413 available_networks
= None
2414 add_vdc_rest_url
= None
2416 if response
.status_code
!= requests
.codes
.ok
:
2417 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
2418 response
.status_code
))
2422 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
2423 for child
in vm_list_xmlroot
:
2424 if child
.tag
.split("}")[1] == 'ProviderVdcReference':
2425 provider_network
= child
.attrib
.get('href')
2426 # application/vnd.vmware.admin.providervdc+xml
2427 if child
.tag
.split("}")[1] == 'Link':
2428 if child
.attrib
.get('type') == 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' \
2429 and child
.attrib
.get('rel') == 'add':
2430 add_vdc_rest_url
= child
.attrib
.get('href')
2432 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
2433 self
.logger
.debug("Respond body {}".format(response
.content
))
2436 # find pvdc provided available network
2437 response
= Http
.get(url
=provider_network
,
2438 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2441 if response
.status_code
!= requests
.codes
.ok
:
2442 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
2443 response
.status_code
))
2446 # available_networks.split("/")[-1]
2448 if parent_network_uuid
is None:
2450 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
2451 for child
in vm_list_xmlroot
.iter():
2452 if child
.tag
.split("}")[1] == 'AvailableNetworks':
2453 for networks
in child
.iter():
2454 # application/vnd.vmware.admin.network+xml
2455 if networks
.attrib
.get('href') is not None:
2456 available_networks
= networks
.attrib
.get('href')
2461 #Configure IP profile of the network
2462 ip_profile
= ip_profile
if ip_profile
is not None else DEFAULT_IP_PROFILE
2464 gateway_address
=ip_profile
['gateway_address']
2465 dhcp_count
=int(ip_profile
['dhcp_count'])
2466 subnet_address
=self
.convert_cidr_to_netmask(ip_profile
['subnet_address'])
2468 if ip_profile
['dhcp_enabled']==True:
2471 dhcp_enabled
='false'
2472 dhcp_start_address
=ip_profile
['dhcp_start_address']
2474 #derive dhcp_end_address from dhcp_start_address & dhcp_count
2475 end_ip_int
= int(netaddr
.IPAddress(dhcp_start_address
))
2476 end_ip_int
+= dhcp_count
- 1
2477 dhcp_end_address
= str(netaddr
.IPAddress(end_ip_int
))
2479 ip_version
=ip_profile
['ip_version']
2480 dns_address
=ip_profile
['dns_address']
2482 # either use client provided UUID or search for a first available
2483 # if both are not defined we return none
2484 if parent_network_uuid
is not None:
2485 url_list
= [vca
.host
, '/api/admin/network/', parent_network_uuid
]
2486 add_vdc_rest_url
= ''.join(url_list
)
2489 fence_mode
="isolated"
2491 is_inherited
='false'
2492 data
= """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
2493 <Description>Openmano created</Description>
2497 <IsInherited>{1:s}</IsInherited>
2498 <Gateway>{2:s}</Gateway>
2499 <Netmask>{3:s}</Netmask>
2501 <IsEnabled>{5:s}</IsEnabled>
2504 <StartAddress>{6:s}</StartAddress>
2505 <EndAddress>{7:s}</EndAddress>
2510 <FenceMode>{8:s}</FenceMode>
2512 <IsShared>{9:s}</IsShared>
2513 </OrgVdcNetwork> """.format(escape(network_name
), is_inherited
, gateway_address
,
2514 subnet_address
, dns_address
, dhcp_enabled
,
2515 dhcp_start_address
, dhcp_end_address
, fence_mode
, isshared
)
2518 fence_mode
="bridged"
2519 is_inherited
='false'
2520 data
= """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
2521 <Description>Openmano created</Description>
2525 <IsInherited>{1:s}</IsInherited>
2526 <Gateway>{2:s}</Gateway>
2527 <Netmask>{3:s}</Netmask>
2529 <IsEnabled>{5:s}</IsEnabled>
2532 <StartAddress>{6:s}</StartAddress>
2533 <EndAddress>{7:s}</EndAddress>
2538 <ParentNetwork href="{8:s}"/>
2539 <FenceMode>{9:s}</FenceMode>
2541 <IsShared>{10:s}</IsShared>
2542 </OrgVdcNetwork> """.format(escape(network_name
), is_inherited
, gateway_address
,
2543 subnet_address
, dns_address
, dhcp_enabled
,
2544 dhcp_start_address
, dhcp_end_address
, available_networks
,
2545 fence_mode
, isshared
)
2547 headers
= vca
.vcloud_session
.get_vcloud_headers()
2548 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'
2550 response
= Http
.post(url
=add_vdc_rest_url
,
2556 if response
.status_code
!= 201:
2557 self
.logger
.debug("Create Network POST REST API call failed. Return status code {}"
2558 .format(response
.status_code
))
2560 network
= networkType
.parseString(response
.content
, True)
2561 create_nw_task
= network
.get_Tasks().get_Task()[0]
2563 # if we all ok we respond with content after network creation completes
2564 # otherwise by default return None
2565 if create_nw_task
is not None:
2566 self
.logger
.debug("Create Network REST : Waiting for Nw creation complete")
2567 status
= vca
.block_until_completed(create_nw_task
)
2569 return response
.content
2571 self
.logger
.debug("create_network_rest task failed. Network Create response : {}"
2572 .format(response
.content
))
2573 except Exception as exp
:
2574 self
.logger
.debug("create_network_rest : Exception : {} ".format(exp
))
2578 def convert_cidr_to_netmask(self
, cidr_ip
=None):
2580 Method sets convert CIDR netmask address to normal IP format
2582 cidr_ip : CIDR IP address
2584 netmask : Converted netmask
2586 if cidr_ip
is not None:
2588 network
, net_bits
= cidr_ip
.split('/')
2589 netmask
= socket
.inet_ntoa(struct
.pack(">I", (0xffffffff << (32 - int(net_bits
))) & 0xffffffff))
2595 def get_provider_rest(self
, vca
=None):
2597 Method gets provider vdc view from vcloud director
2600 network_name - is network name to be created.
2601 parent_network_uuid - is parent provider vdc network that will be used for mapping.
2602 It optional attribute. by default if no parent network indicate the first available will be used.
2605 The return xml content of respond or None
2608 url_list
= [vca
.host
, '/api/admin']
2609 response
= Http
.get(url
=''.join(url_list
),
2610 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2614 if response
.status_code
== requests
.codes
.ok
:
2615 return response
.content
2618 def create_vdc(self
, vdc_name
=None):
2622 xml_content
= self
.create_vdc_from_tmpl_rest(vdc_name
=vdc_name
)
2623 if xml_content
is not None:
2625 task_resp_xmlroot
= XmlElementTree
.fromstring(xml_content
)
2626 for child
in task_resp_xmlroot
:
2627 if child
.tag
.split("}")[1] == 'Owner':
2628 vdc_id
= child
.attrib
.get('href').split("/")[-1]
2629 vdc_dict
[vdc_id
] = task_resp_xmlroot
.get('href')
2632 self
.logger
.debug("Respond body {}".format(xml_content
))
2636 def create_vdc_from_tmpl_rest(self
, vdc_name
=None):
2638 Method create vdc in vCloud director based on VDC template.
2639 it uses pre-defined template that must be named openmano
2642 vdc_name - name of a new vdc.
2645 The return xml content of respond or None
2648 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
2649 vca
= self
.connect()
2651 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2652 if vdc_name
is None:
2655 url_list
= [vca
.host
, '/api/vdcTemplates']
2656 vm_list_rest_call
= ''.join(url_list
)
2657 response
= Http
.get(url
=vm_list_rest_call
,
2658 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2662 # container url to a template
2663 vdc_template_ref
= None
2665 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
2666 for child
in vm_list_xmlroot
:
2667 # application/vnd.vmware.admin.providervdc+xml
2668 # we need find a template from witch we instantiate VDC
2669 if child
.tag
.split("}")[1] == 'VdcTemplate':
2670 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.vdcTemplate+xml' and child
.attrib
.get(
2671 'name') == 'openmano':
2672 vdc_template_ref
= child
.attrib
.get('href')
2674 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
2675 self
.logger
.debug("Respond body {}".format(response
.content
))
2678 # if we didn't found required pre defined template we return None
2679 if vdc_template_ref
is None:
2684 url_list
= [vca
.host
, '/api/org/', self
.org_uuid
, '/action/instantiate']
2685 vm_list_rest_call
= ''.join(url_list
)
2686 data
= """<InstantiateVdcTemplateParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
2687 <Source href="{1:s}"></Source>
2688 <Description>opnemano</Description>
2689 </InstantiateVdcTemplateParams>""".format(vdc_name
, vdc_template_ref
)
2690 headers
= vca
.vcloud_session
.get_vcloud_headers()
2691 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml'
2692 response
= Http
.post(url
=vm_list_rest_call
, headers
=headers
, data
=data
, verify
=vca
.verify
,
2694 # if we all ok we respond with content otherwise by default None
2695 if response
.status_code
>= 200 and response
.status_code
< 300:
2696 return response
.content
2699 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
2700 self
.logger
.debug("Respond body {}".format(response
.content
))
2704 def create_vdc_rest(self
, vdc_name
=None):
2706 Method create network in vCloud director
2709 network_name - is network name to be created.
2710 parent_network_uuid - is parent provider vdc network that will be used for mapping.
2711 It optional attribute. by default if no parent network indicate the first available will be used.
2714 The return network uuid or return None
2717 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
2719 vca
= self
.connect_as_admin()
2721 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2722 if vdc_name
is None:
2725 url_list
= [vca
.host
, '/api/admin/org/', self
.org_uuid
]
2726 vm_list_rest_call
= ''.join(url_list
)
2727 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2728 response
= Http
.get(url
=vm_list_rest_call
,
2729 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2733 provider_vdc_ref
= None
2734 add_vdc_rest_url
= None
2735 available_networks
= None
2737 if response
.status_code
!= requests
.codes
.ok
:
2738 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
2739 response
.status_code
))
2743 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
2744 for child
in vm_list_xmlroot
:
2745 # application/vnd.vmware.admin.providervdc+xml
2746 if child
.tag
.split("}")[1] == 'Link':
2747 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.createVdcParams+xml' \
2748 and child
.attrib
.get('rel') == 'add':
2749 add_vdc_rest_url
= child
.attrib
.get('href')
2751 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
2752 self
.logger
.debug("Respond body {}".format(response
.content
))
2755 response
= self
.get_provider_rest(vca
=vca
)
2757 vm_list_xmlroot
= XmlElementTree
.fromstring(response
)
2758 for child
in vm_list_xmlroot
:
2759 if child
.tag
.split("}")[1] == 'ProviderVdcReferences':
2760 for sub_child
in child
:
2761 provider_vdc_ref
= sub_child
.attrib
.get('href')
2763 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
2764 self
.logger
.debug("Respond body {}".format(response
))
2767 if add_vdc_rest_url
is not None and provider_vdc_ref
is not None:
2768 data
= """ <CreateVdcParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5"><Description>{1:s}</Description>
2769 <AllocationModel>ReservationPool</AllocationModel>
2770 <ComputeCapacity><Cpu><Units>MHz</Units><Allocated>2048</Allocated><Limit>2048</Limit></Cpu>
2771 <Memory><Units>MB</Units><Allocated>2048</Allocated><Limit>2048</Limit></Memory>
2772 </ComputeCapacity><NicQuota>0</NicQuota><NetworkQuota>100</NetworkQuota>
2773 <VdcStorageProfile><Enabled>true</Enabled><Units>MB</Units><Limit>20480</Limit><Default>true</Default></VdcStorageProfile>
2774 <ProviderVdcReference
2775 name="Main Provider"
2777 <UsesFastProvisioning>true</UsesFastProvisioning></CreateVdcParams>""".format(escape(vdc_name
),
2781 headers
= vca
.vcloud_session
.get_vcloud_headers()
2782 headers
['Content-Type'] = 'application/vnd.vmware.admin.createVdcParams+xml'
2783 response
= Http
.post(url
=add_vdc_rest_url
, headers
=headers
, data
=data
, verify
=vca
.verify
,
2786 # if we all ok we respond with content otherwise by default None
2787 if response
.status_code
== 201:
2788 return response
.content
2791 def get_vapp_details_rest(self
, vapp_uuid
=None, need_admin_access
=False):
2793 Method retrieve vapp detail from vCloud director
2796 vapp_uuid - is vapp identifier.
2799 The return network uuid or return None
2805 if need_admin_access
:
2806 vca
= self
.connect_as_admin()
2808 vca
= self
.connect()
2811 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2812 if vapp_uuid
is None:
2815 url_list
= [vca
.host
, '/api/vApp/vapp-', vapp_uuid
]
2816 get_vapp_restcall
= ''.join(url_list
)
2818 if vca
.vcloud_session
and vca
.vcloud_session
.organization
:
2819 response
= Http
.get(url
=get_vapp_restcall
,
2820 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2824 if response
.status_code
!= requests
.codes
.ok
:
2825 self
.logger
.debug("REST API call {} failed. Return status code {}".format(get_vapp_restcall
,
2826 response
.status_code
))
2827 return parsed_respond
2830 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
2831 parsed_respond
['ovfDescriptorUploaded'] = xmlroot_respond
.attrib
['ovfDescriptorUploaded']
2833 namespaces
= {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
2834 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
2835 'vmw': 'http://www.vmware.com/schema/ovf',
2836 'vm': 'http://www.vmware.com/vcloud/v1.5',
2837 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
2838 "vmext":"http://www.vmware.com/vcloud/extension/v1.5",
2839 "xmlns":"http://www.vmware.com/vcloud/v1.5"
2842 created_section
= xmlroot_respond
.find('vm:DateCreated', namespaces
)
2843 if created_section
is not None:
2844 parsed_respond
['created'] = created_section
.text
2846 network_section
= xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig', namespaces
)
2847 if network_section
is not None and 'networkName' in network_section
.attrib
:
2848 parsed_respond
['networkname'] = network_section
.attrib
['networkName']
2850 ipscopes_section
= \
2851 xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig/vm:Configuration/vm:IpScopes',
2853 if ipscopes_section
is not None:
2854 for ipscope
in ipscopes_section
:
2855 for scope
in ipscope
:
2856 tag_key
= scope
.tag
.split("}")[1]
2857 if tag_key
== 'IpRanges':
2858 ip_ranges
= scope
.getchildren()
2859 for ipblock
in ip_ranges
:
2860 for block
in ipblock
:
2861 parsed_respond
[block
.tag
.split("}")[1]] = block
.text
2863 parsed_respond
[tag_key
] = scope
.text
2865 # parse children section for other attrib
2866 children_section
= xmlroot_respond
.find('vm:Children/', namespaces
)
2867 if children_section
is not None:
2868 parsed_respond
['name'] = children_section
.attrib
['name']
2869 parsed_respond
['nestedHypervisorEnabled'] = children_section
.attrib
['nestedHypervisorEnabled'] \
2870 if "nestedHypervisorEnabled" in children_section
.attrib
else None
2871 parsed_respond
['deployed'] = children_section
.attrib
['deployed']
2872 parsed_respond
['status'] = children_section
.attrib
['status']
2873 parsed_respond
['vmuuid'] = children_section
.attrib
['id'].split(":")[-1]
2874 network_adapter
= children_section
.find('vm:NetworkConnectionSection', namespaces
)
2876 for adapters
in network_adapter
:
2877 adapter_key
= adapters
.tag
.split("}")[1]
2878 if adapter_key
== 'PrimaryNetworkConnectionIndex':
2879 parsed_respond
['primarynetwork'] = adapters
.text
2880 if adapter_key
== 'NetworkConnection':
2882 if 'network' in adapters
.attrib
:
2883 vnic
['network'] = adapters
.attrib
['network']
2884 for adapter
in adapters
:
2885 setting_key
= adapter
.tag
.split("}")[1]
2886 vnic
[setting_key
] = adapter
.text
2887 nic_list
.append(vnic
)
2889 for link
in children_section
:
2890 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
2891 if link
.attrib
['rel'] == 'screen:acquireTicket':
2892 parsed_respond
['acquireTicket'] = link
.attrib
2893 if link
.attrib
['rel'] == 'screen:acquireMksTicket':
2894 parsed_respond
['acquireMksTicket'] = link
.attrib
2896 parsed_respond
['interfaces'] = nic_list
2897 vCloud_extension_section
= children_section
.find('xmlns:VCloudExtension', namespaces
)
2898 if vCloud_extension_section
is not None:
2899 vm_vcenter_info
= {}
2900 vim_info
= vCloud_extension_section
.find('vmext:VmVimInfo', namespaces
)
2901 vmext
= vim_info
.find('vmext:VmVimObjectRef', namespaces
)
2902 if vmext
is not None:
2903 vm_vcenter_info
["vm_moref_id"] = vmext
.find('vmext:MoRef', namespaces
).text
2904 vm_vcenter_info
["vim_server_href"] = vmext
.find('vmext:VimServerRef', namespaces
).attrib
['href']
2905 parsed_respond
["vm_vcenter_info"]= vm_vcenter_info
2907 virtual_hardware_section
= children_section
.find('ovf:VirtualHardwareSection', namespaces
)
2908 vm_virtual_hardware_info
= {}
2909 if virtual_hardware_section
is not None:
2910 for item
in virtual_hardware_section
.iterfind('ovf:Item',namespaces
):
2911 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
2912 disk_size
= item
.find("rasd:HostResource" ,namespaces
2913 ).attrib
["{"+namespaces
['vm']+"}capacity"]
2915 vm_virtual_hardware_info
["disk_size"]= disk_size
2918 for link
in virtual_hardware_section
:
2919 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
2920 if link
.attrib
['rel'] == 'edit' and link
.attrib
['href'].endswith("/disks"):
2921 vm_virtual_hardware_info
["disk_edit_href"] = link
.attrib
['href']
2924 parsed_respond
["vm_virtual_hardware"]= vm_virtual_hardware_info
2925 except Exception as exp
:
2926 self
.logger
.info("Error occurred calling rest api for getting vApp details {}".format(exp
))
2927 return parsed_respond
2929 def acuire_console(self
, vm_uuid
=None):
2931 vca
= self
.connect()
2933 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2937 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2938 vm_dict
= self
.get_vapp_details_rest(self
, vapp_uuid
=vm_uuid
)
2939 console_dict
= vm_dict
['acquireTicket']
2940 console_rest_call
= console_dict
['href']
2942 response
= Http
.post(url
=console_rest_call
,
2943 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2947 if response
.status_code
== requests
.codes
.ok
:
2948 return response
.content
2952 def modify_vm_disk(self
, vapp_uuid
, flavor_disk
):
2954 Method retrieve vm disk details
2957 vapp_uuid - is vapp identifier.
2958 flavor_disk - disk size as specified in VNFD (flavor)
2961 The return network uuid or return None
2965 #Flavor disk is in GB convert it into MB
2966 flavor_disk
= int(flavor_disk
) * 1024
2967 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
2969 vm_name
= vm_details
["name"]
2970 self
.logger
.info("VM: {} flavor_disk :{}".format(vm_name
, flavor_disk
))
2972 if vm_details
and "vm_virtual_hardware" in vm_details
:
2973 vm_disk
= int(vm_details
["vm_virtual_hardware"]["disk_size"])
2974 disk_edit_href
= vm_details
["vm_virtual_hardware"]["disk_edit_href"]
2976 self
.logger
.info("VM: {} VM_disk :{}".format(vm_name
, vm_disk
))
2978 if flavor_disk
> vm_disk
:
2979 status
= self
.modify_vm_disk_rest(disk_edit_href
,flavor_disk
)
2980 self
.logger
.info("Modify disk of VM {} from {} to {} MB".format(vm_name
,
2981 vm_disk
, flavor_disk
))
2984 self
.logger
.info("No need to modify disk of VM {}".format(vm_name
))
2987 except Exception as exp
:
2988 self
.logger
.info("Error occurred while modifing disk size {}".format(exp
))
2991 def modify_vm_disk_rest(self
, disk_href
, disk_size
):
2993 Method retrieve modify vm disk size
2996 disk_href - vCD API URL to GET and PUT disk data
2997 disk_size - disk size as specified in VNFD (flavor)
3000 The return network uuid or return None
3002 vca
= self
.connect()
3004 raise vimconn
.vimconnConnectionException("self.connect() is failed")
3005 if disk_href
is None or disk_size
is None:
3008 if vca
.vcloud_session
and vca
.vcloud_session
.organization
:
3009 response
= Http
.get(url
=disk_href
,
3010 headers
=vca
.vcloud_session
.get_vcloud_headers(),
3014 if response
.status_code
!= requests
.codes
.ok
:
3015 self
.logger
.debug("GET REST API call {} failed. Return status code {}".format(disk_href
,
3016 response
.status_code
))
3019 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
3020 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
3021 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
3023 for item
in lxmlroot_respond
.iterfind('xmlns:Item',namespaces
):
3024 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
3025 disk_item
= item
.find("rasd:HostResource" ,namespaces
)
3026 if disk_item
is not None:
3027 disk_item
.attrib
["{"+namespaces
['xmlns']+"}capacity"] = str(disk_size
)
3030 data
= lxmlElementTree
.tostring(lxmlroot_respond
, encoding
='utf8', method
='xml',
3031 xml_declaration
=True)
3033 #Send PUT request to modify disk size
3034 headers
= vca
.vcloud_session
.get_vcloud_headers()
3035 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
3037 response
= Http
.put(url
=disk_href
,
3040 verify
=vca
.verify
, logger
=self
.logger
)
3042 if response
.status_code
!= 202:
3043 self
.logger
.debug("PUT REST API call {} failed. Return status code {}".format(disk_href
,
3044 response
.status_code
))
3046 modify_disk_task
= taskType
.parseString(response
.content
, True)
3047 if type(modify_disk_task
) is GenericTask
:
3048 status
= vca
.block_until_completed(modify_disk_task
)
3053 except Exception as exp
:
3054 self
.logger
.info("Error occurred calling rest api for modifing disk size {}".format(exp
))
3057 def add_pci_devices(self
, vapp_uuid
, pci_devices
, vmname_andid
):
3059 Method to attach pci devices to VM
3062 vapp_uuid - uuid of vApp/VM
3063 pci_devices - pci devices infromation as specified in VNFD (flavor)
3066 The status of add pci device task , vm object and
3067 vcenter_conect object
3070 vcenter_conect
= None
3071 self
.logger
.info("Add pci devices {} into vApp {}".format(pci_devices
, vapp_uuid
))
3072 #Assuming password of vCenter user is same as password of vCloud user
3073 vm_moref_id
, vm_vcenter_host
, vm_vcenter_username
, vm_vcenter_port
= self
.get_vcenter_info_rest(vapp_uuid
)
3074 self
.logger
.info("vm_moref_id, {} vm_vcenter_host {} vm_vcenter_username{} "\
3075 "vm_vcenter_port{}".format(
3076 vm_moref_id
, vm_vcenter_host
,
3077 vm_vcenter_username
, vm_vcenter_port
))
3078 if vm_moref_id
and vm_vcenter_host
and vm_vcenter_username
:
3080 if hasattr(ssl
, '_create_unverified_context'):
3081 context
= ssl
._create
_unverified
_context
()
3083 no_of_pci_devices
= len(pci_devices
)
3084 if no_of_pci_devices
> 0:
3085 vcenter_conect
= SmartConnect(host
=vm_vcenter_host
, user
=vm_vcenter_username
,
3086 pwd
=self
.passwd
, port
=int(vm_vcenter_port
) ,
3088 atexit
.register(Disconnect
, vcenter_conect
)
3089 content
= vcenter_conect
.RetrieveContent()
3091 #Get VM and its host
3092 host_obj
, vm_obj
= self
.get_vm_obj(content
,vm_moref_id
)
3093 self
.logger
.info("VM {} is currently on host {}".format(vm_obj
, host_obj
))
3094 if host_obj
and vm_obj
:
3095 #get PCI devies from host on which vapp is currently installed
3096 avilable_pci_devices
= self
.get_pci_devices(host_obj
, no_of_pci_devices
)
3098 if avilable_pci_devices
is None:
3099 #find other hosts with active pci devices
3100 new_host_obj
, avilable_pci_devices
= self
.get_host_and_PCIdevices(
3105 if new_host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
3106 #Migrate vm to the host where PCI devices are availble
3107 self
.logger
.info("Relocate VM {} on new host {}".format(vm_obj
, new_host_obj
))
3108 task
= self
.relocate_vm(new_host_obj
, vm_obj
)
3109 if task
is not None:
3110 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
3111 self
.logger
.info("Migrate VM status: {}".format(result
))
3112 host_obj
= new_host_obj
3114 self
.logger
.info("Fail to migrate VM : {}".format(result
))
3115 raise vimconn
.vimconnNotFoundException(
3116 "Fail to migrate VM : {} to host {}".format(
3121 if host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
3122 #Add PCI devices one by one
3123 for pci_device
in avilable_pci_devices
:
3124 task
= self
.add_pci_to_vm(host_obj
, vm_obj
, pci_device
)
3126 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
3128 self
.logger
.info("Added PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
3130 self
.logger
.info("Fail to add PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
3131 return True, vm_obj
, vcenter_conect
3133 self
.logger
.error("Currently there is no host with"\
3134 " {} number of avaialble PCI devices required for VM {}".format(
3138 raise vimconn
.vimconnNotFoundException(
3139 "Currently there is no host with {} "\
3140 "number of avaialble PCI devices required for VM {}".format(
3144 self
.logger
.debug("No infromation about PCI devices {} ",pci_devices
)
3146 except vmodl
.MethodFault
as error
:
3147 self
.logger
.error("Error occurred while adding PCI devices {} ",error
)
3148 return None, vm_obj
, vcenter_conect
3150 def get_vm_obj(self
, content
, mob_id
):
3152 Method to get the vsphere VM object associated with a given morf ID
3154 vapp_uuid - uuid of vApp/VM
3155 content - vCenter content object
3156 mob_id - mob_id of VM
3164 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
3165 [vim
.VirtualMachine
], True
3167 for vm
in container
.view
:
3168 mobID
= vm
._GetMoId
()
3171 host_obj
= vm_obj
.runtime
.host
3173 except Exception as exp
:
3174 self
.logger
.error("Error occurred while finding VM object : {}".format(exp
))
3175 return host_obj
, vm_obj
3177 def get_pci_devices(self
, host
, need_devices
):
3179 Method to get the details of pci devices on given host
3181 host - vSphere host object
3182 need_devices - number of pci devices needed on host
3185 array of pci devices
3189 used_devices_ids
= []
3193 pciPassthruInfo
= host
.config
.pciPassthruInfo
3194 pciDevies
= host
.hardware
.pciDevice
3196 for pci_status
in pciPassthruInfo
:
3197 if pci_status
.passthruActive
:
3198 for device
in pciDevies
:
3199 if device
.id == pci_status
.id:
3200 all_device_ids
.append(device
.id)
3201 all_devices
.append(device
)
3203 #check if devices are in use
3204 avalible_devices
= all_devices
3206 if vm
.runtime
.powerState
== vim
.VirtualMachinePowerState
.poweredOn
:
3207 vm_devices
= vm
.config
.hardware
.device
3208 for device
in vm_devices
:
3209 if type(device
) is vim
.vm
.device
.VirtualPCIPassthrough
:
3210 if device
.backing
.id in all_device_ids
:
3211 for use_device
in avalible_devices
:
3212 if use_device
.id == device
.backing
.id:
3213 avalible_devices
.remove(use_device
)
3214 used_devices_ids
.append(device
.backing
.id)
3215 self
.logger
.debug("Device {} from devices {}"\
3216 "is in use".format(device
.backing
.id,
3219 if len(avalible_devices
) < need_devices
:
3220 self
.logger
.debug("Host {} don't have {} number of active devices".format(host
,
3222 self
.logger
.debug("found only {} devives {}".format(len(avalible_devices
),
3226 required_devices
= avalible_devices
[:need_devices
]
3227 self
.logger
.info("Found {} PCI devivces on host {} but required only {}".format(
3228 len(avalible_devices
),
3231 self
.logger
.info("Retruning {} devices as {}".format(need_devices
,
3233 return required_devices
3235 except Exception as exp
:
3236 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host
))
3240 def get_host_and_PCIdevices(self
, content
, need_devices
):
3242 Method to get the details of pci devices infromation on all hosts
3245 content - vSphere host object
3246 need_devices - number of pci devices needed on host
3249 array of pci devices and host object
3252 pci_device_objs
= None
3255 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
3256 [vim
.HostSystem
], True)
3257 for host
in container
.view
:
3258 devices
= self
.get_pci_devices(host
, need_devices
)
3261 pci_device_objs
= devices
3263 except Exception as exp
:
3264 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host_obj
))
3266 return host_obj
,pci_device_objs
3268 def relocate_vm(self
, dest_host
, vm
) :
3270 Method to get the relocate VM to new host
3273 dest_host - vSphere host object
3274 vm - vSphere VM object
3281 relocate_spec
= vim
.vm
.RelocateSpec(host
=dest_host
)
3282 task
= vm
.Relocate(relocate_spec
)
3283 self
.logger
.info("Migrating {} to destination host {}".format(vm
, dest_host
))
3284 except Exception as exp
:
3285 self
.logger
.error("Error occurred while relocate VM {} to new host {}: {}".format(
3286 dest_host
, vm
, exp
))
3289 def wait_for_vcenter_task(self
, task
, actionName
='job', hideResult
=False):
3291 Waits and provides updates on a vSphere task
3293 while task
.info
.state
== vim
.TaskInfo
.State
.running
:
3296 if task
.info
.state
== vim
.TaskInfo
.State
.success
:
3297 if task
.info
.result
is not None and not hideResult
:
3298 self
.logger
.info('{} completed successfully, result: {}'.format(
3302 self
.logger
.info('Task {} completed successfully.'.format(actionName
))
3304 self
.logger
.error('{} did not complete successfully: {} '.format(
3309 return task
.info
.result
3311 def add_pci_to_vm(self
,host_object
, vm_object
, host_pci_dev
):
3313 Method to add pci device in given VM
3316 host_object - vSphere host object
3317 vm_object - vSphere VM object
3318 host_pci_dev - host_pci_dev must be one of the devices from the
3319 host_object.hardware.pciDevice list
3320 which is configured as a PCI passthrough device
3326 if vm_object
and host_object
and host_pci_dev
:
3328 #Add PCI device to VM
3329 pci_passthroughs
= vm_object
.environmentBrowser
.QueryConfigTarget(host
=None).pciPassthrough
3330 systemid_by_pciid
= {item
.pciDevice
.id: item
.systemId
for item
in pci_passthroughs
}
3332 if host_pci_dev
.id not in systemid_by_pciid
:
3333 self
.logger
.error("Device {} is not a passthrough device ".format(host_pci_dev
))
3336 deviceId
= hex(host_pci_dev
.deviceId
% 2**16).lstrip('0x')
3337 backing
= vim
.VirtualPCIPassthroughDeviceBackingInfo(deviceId
=deviceId
,
3339 systemId
=systemid_by_pciid
[host_pci_dev
.id],
3340 vendorId
=host_pci_dev
.vendorId
,
3341 deviceName
=host_pci_dev
.deviceName
)
3343 hba_object
= vim
.VirtualPCIPassthrough(key
=-100, backing
=backing
)
3345 new_device_config
= vim
.VirtualDeviceConfigSpec(device
=hba_object
)
3346 new_device_config
.operation
= "add"
3347 vmConfigSpec
= vim
.vm
.ConfigSpec()
3348 vmConfigSpec
.deviceChange
= [new_device_config
]
3350 task
= vm_object
.ReconfigVM_Task(spec
=vmConfigSpec
)
3351 self
.logger
.info("Adding PCI device {} into VM {} from host {} ".format(
3352 host_pci_dev
, vm_object
, host_object
)
3354 except Exception as exp
:
3355 self
.logger
.error("Error occurred while adding pci devive {} to VM {}: {}".format(
3361 def get_vcenter_info_rest(self
, vapp_uuid
):
3363 https://192.169.241.105/api/admin/extension/vimServer/cc82baf9-9f80-4468-bfe9-ce42b3f9dde5
3364 Method to get details of vCenter
3367 vapp_uuid - uuid of vApp or VM
3370 Moref Id of VM and deails of vCenter
3374 vm_vcenter_username
= None
3375 vm_vcenter_port
= None
3377 vm_details
= self
.get_vapp_details_rest(vapp_uuid
, need_admin_access
=True)
3378 if vm_details
and "vm_vcenter_info" in vm_details
:
3379 vm_moref_id
= vm_details
["vm_vcenter_info"]["vm_moref_id"]
3380 vim_server_href
= vm_details
["vm_vcenter_info"]["vim_server_href"]
3383 vca
= self
.connect_as_admin()
3385 raise vimconn
.vimconnConnectionException("self.connect() is failed")
3386 if vim_server_href
is None:
3387 self
.logger
.error("No url to get vcenter details")
3389 if vca
.vcloud_session
and vca
.vcloud_session
.organization
:
3390 response
= Http
.get(url
=vim_server_href
,
3391 headers
=vca
.vcloud_session
.get_vcloud_headers(),
3395 if response
.status_code
!= requests
.codes
.ok
:
3396 self
.logger
.debug("GET REST API call {} failed. Return status code {}".format(vim_server_href
,
3397 response
.status_code
))
3399 namespaces
={"vmext":"http://www.vmware.com/vcloud/extension/v1.5",
3400 "vcloud":"http://www.vmware.com/vcloud/v1.5"
3402 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
3403 vm_vcenter_username
= xmlroot_respond
.find('vmext:Username', namespaces
).text
3404 vcenter_url
= xmlroot_respond
.find('vmext:Url', namespaces
).text
3405 vm_vcenter_port
= vcenter_url
.split(":")[2]
3406 vm_vcenter
= vcenter_url
.split(":")[1].split("//")[1]
3408 except Exception as exp
:
3409 self
.logger
.info("Error occurred calling rest api for vcenter information {}".format(exp
))
3411 return vm_moref_id
, vm_vcenter
, vm_vcenter_username
, vm_vcenter_port
3414 def get_vm_pci_details(self
, vmuuid
):
3416 Method to get VM PCI device details from vCenter
3419 vm_obj - vSphere VM object
3422 dict of PCI devives attached to VM
3425 vm_pci_devices_info
= {}
3427 vm_moref_id
, vm_vcenter_host
, vm_vcenter_username
, vm_vcenter_port
= self
.get_vcenter_info_rest(vmuuid
)
3428 if vm_moref_id
and vm_vcenter_host
and vm_vcenter_username
:
3430 if hasattr(ssl
, '_create_unverified_context'):
3431 context
= ssl
._create
_unverified
_context
()
3432 vcenter_conect
= SmartConnect(host
=vm_vcenter_host
, user
=vm_vcenter_username
,
3433 pwd
=self
.passwd
, port
=int(vm_vcenter_port
),
3435 atexit
.register(Disconnect
, vcenter_conect
)
3436 content
= vcenter_conect
.RetrieveContent()
3438 #Get VM and its host
3439 host_obj
, vm_obj
= self
.get_vm_obj(content
,vm_moref_id
)
3440 for device
in vm_obj
.config
.hardware
.device
:
3441 if type(device
) == vim
.vm
.device
.VirtualPCIPassthrough
:
3442 device_details
={'devide_id':device
.backing
.id,
3443 'pciSlotNumber':device
.slotInfo
.pciSlotNumber
3445 vm_pci_devices_info
[device
.deviceInfo
.label
] = device_details
3446 except Exception as exp
:
3447 self
.logger
.info("Error occurred while getting PCI devices infromationn"\
3448 " for VM {} : {}".format(vm_obj
,exp
))
3449 return vm_pci_devices_info