1 # -*- coding: utf-8 -*-
4 # Copyright 2016-2017 VMware Inc.
5 # This file is part of ETSI OSM
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
12 # http://www.apache.org/licenses/LICENSE-2.0
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact: osslegalrouting@vmware.com
25 vimconn_vmware implementation an Abstract class in order to interact with VMware vCloud Director.
28 from progressbar
import Percentage
, Bar
, ETA
, FileTransferSpeed
, ProgressBar
38 from pyVmomi
import vim
, vmodl
39 from pyVim
.connect
import SmartConnect
, Disconnect
41 from xml
.etree
import ElementTree
as XmlElementTree
42 from lxml
import etree
as lxmlElementTree
45 from pyvcloud
.vcd
.client
import BasicLoginCredentials
,Client
,VcdTaskException
46 from pyvcloud
.vcd
.vdc
import VDC
47 from pyvcloud
.vcd
.org
import Org
49 from pyvcloud
.vcd
.vapp
import VApp
50 from xml
.sax
.saxutils
import escape
64 # global variable for vcd connector type
65 STANDALONE
= 'standalone'
67 # key for flavor dicts
68 FLAVOR_RAM_KEY
= 'ram'
69 FLAVOR_VCPUS_KEY
= 'vcpus'
70 FLAVOR_DISK_KEY
= 'disk'
71 DEFAULT_IP_PROFILE
= {'dhcp_count':50,
75 # global variable for wait time
81 __author__
= "Mustafa Bayramov, Arpita Kate, Sachin Bhangare, Prakash Kasar"
82 __date__
= "$09-Mar-2018 11:09:29$"
85 # -1: "Could not be created",
91 # 5: "Waiting for user input",
93 # 7: "Unrecognized state",
95 # 9: "Inconsistent state",
96 # 10: "Children do not all have the same status",
97 # 11: "Upload initiated, OVF descriptor pending",
98 # 12: "Upload initiated, copying contents",
99 # 13: "Upload initiated , disk contents pending",
100 # 14: "Upload has been quarantined",
101 # 15: "Upload quarantine period has expired"
103 # mapping vCD status to MANO
104 vcdStatusCode2manoFormat
= {4: 'ACTIVE',
113 netStatus2manoFormat
= {'ACTIVE': 'ACTIVE', 'PAUSED': 'PAUSED', 'INACTIVE': 'INACTIVE', 'BUILD': 'BUILD',
114 'ERROR': 'ERROR', 'DELETED': 'DELETED'
117 class vimconnector(vimconn
.vimconnector
):
118 # dict used to store flavor in memory
121 def __init__(self
, uuid
=None, name
=None, tenant_id
=None, tenant_name
=None,
122 url
=None, url_admin
=None, user
=None, passwd
=None, log_level
=None, config
={}, persistent_info
={}):
124 Constructor create vmware connector to vCloud director.
126 By default construct doesn't validate connection state. So client can create object with None arguments.
127 If client specified username , password and host and VDC name. Connector initialize other missing attributes.
129 a) It initialize organization UUID
130 b) Initialize tenant_id/vdc ID. (This information derived from tenant name)
133 uuid - is organization uuid.
134 name - is organization name that must be presented in vCloud director.
135 tenant_id - is VDC uuid it must be presented in vCloud director
136 tenant_name - is VDC name.
137 url - is hostname or ip address of vCloud director
138 url_admin - same as above.
139 user - is user that administrator for organization. Caller must make sure that
140 username has right privileges.
142 password - is password for a user.
144 VMware connector also requires PVDC administrative privileges and separate account.
145 This variables must be passed via config argument dict contains keys
147 dict['admin_username']
148 dict['admin_password']
149 config - Provide NSX and vCenter information
155 vimconn
.vimconnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
,
156 url_admin
, user
, passwd
, log_level
, config
)
158 self
.logger
= logging
.getLogger('openmano.vim.vmware')
159 self
.logger
.setLevel(10)
160 self
.persistent_info
= persistent_info
165 self
.url_admin
= url_admin
166 self
.tenant_id
= tenant_id
167 self
.tenant_name
= tenant_name
171 self
.admin_password
= None
172 self
.admin_user
= None
174 self
.nsx_manager
= None
176 self
.nsx_password
= None
178 # Disable warnings from self-signed certificates.
179 requests
.packages
.urllib3
.disable_warnings()
181 if tenant_name
is not None:
182 orgnameandtenant
= tenant_name
.split(":")
183 if len(orgnameandtenant
) == 2:
184 self
.tenant_name
= orgnameandtenant
[1]
185 self
.org_name
= orgnameandtenant
[0]
187 self
.tenant_name
= tenant_name
188 if "orgname" in config
:
189 self
.org_name
= config
['orgname']
192 self
.logger
.setLevel(getattr(logging
, log_level
))
195 self
.admin_user
= config
['admin_username']
196 self
.admin_password
= config
['admin_password']
198 raise vimconn
.vimconnException(message
="Error admin username or admin password is empty.")
201 self
.nsx_manager
= config
['nsx_manager']
202 self
.nsx_user
= config
['nsx_user']
203 self
.nsx_password
= config
['nsx_password']
205 raise vimconn
.vimconnException(message
="Error: nsx manager or nsx user or nsx password is empty in Config")
207 self
.vcenter_ip
= config
.get("vcenter_ip", None)
208 self
.vcenter_port
= config
.get("vcenter_port", None)
209 self
.vcenter_user
= config
.get("vcenter_user", None)
210 self
.vcenter_password
= config
.get("vcenter_password", None)
212 # ############# Stub code for SRIOV #################
214 # self.dvs_name = config['dv_switch_name']
216 # raise vimconn.vimconnException(message="Error: distributed virtaul switch name is empty in Config")
218 # self.vlanID_range = config.get("vlanID_range", None)
224 raise vimconn
.vimconnException('url param can not be NoneType')
226 if not self
.url_admin
: # try to use normal url
227 self
.url_admin
= self
.url
229 logging
.debug("UUID: {} name: {} tenant_id: {} tenant name {}".format(self
.id, self
.org_name
,
230 self
.tenant_id
, self
.tenant_name
))
231 logging
.debug("vcd url {} vcd username: {} vcd password: {}".format(self
.url
, self
.user
, self
.passwd
))
232 logging
.debug("vcd admin username {} vcd admin passowrd {}".format(self
.admin_user
, self
.admin_password
))
234 # initialize organization
235 if self
.user
is not None and self
.passwd
is not None and self
.url
:
236 self
.init_organization()
238 def __getitem__(self
, index
):
241 if index
== 'tenant_id':
242 return self
.tenant_id
243 if index
== 'tenant_name':
244 return self
.tenant_name
247 elif index
== 'org_name':
249 elif index
== 'org_uuid':
251 elif index
== 'user':
253 elif index
== 'passwd':
257 elif index
== 'url_admin':
258 return self
.url_admin
259 elif index
== "config":
262 raise KeyError("Invalid key '%s'" % str(index
))
264 def __setitem__(self
, index
, value
):
267 if index
== 'tenant_id':
268 self
.tenant_id
= value
269 if index
== 'tenant_name':
270 self
.tenant_name
= value
273 elif index
== 'org_name':
274 self
.org_name
= value
275 elif index
== 'org_uuid':
276 self
.org_uuid
= value
277 elif index
== 'user':
279 elif index
== 'passwd':
283 elif index
== 'url_admin':
284 self
.url_admin
= value
286 raise KeyError("Invalid key '%s'" % str(index
))
288 def connect_as_admin(self
):
289 """ Method connect as pvdc admin user to vCloud director.
290 There are certain action that can be done only by provider vdc admin user.
291 Organization creation / provider network creation etc.
294 The return client object that latter can be used to connect to vcloud director as admin for provider vdc
297 self
.logger
.debug("Logging into vCD {} as admin.".format(self
.org_name
))
302 client_as_admin
= Client(host
, verify_ssl_certs
=False)
303 client_as_admin
.set_credentials(BasicLoginCredentials(self
.admin_user
, org
, self
.admin_password
))
304 except Exception as e
:
305 raise vimconn
.vimconnException(
306 "Can't connect to a vCloud director as: {} with exception {}".format(self
.admin_user
, e
))
308 return client_as_admin
311 """ Method connect as normal user to vCloud director.
314 The return client object that latter can be used to connect to vCloud director as admin for VDC
318 self
.logger
.debug("Logging into vCD {} as {} to datacenter {}.".format(self
.org_name
,
322 client
= Client(host
, verify_ssl_certs
=False)
323 client
.set_credentials(BasicLoginCredentials(self
.user
, self
.org_name
, self
.passwd
))
325 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director org: "
326 "{} as user: {}".format(self
.org_name
, self
.user
))
330 def init_organization(self
):
331 """ Method initialize organization UUID and VDC parameters.
333 At bare minimum client must provide organization name that present in vCloud director and VDC.
335 The VDC - UUID ( tenant_id) will be initialized at the run time if client didn't call constructor.
336 The Org - UUID will be initialized at the run time if data center present in vCloud director.
339 The return vca object that letter can be used to connect to vcloud direct as admin
341 client
= self
.connect()
343 raise vimconn
.vimconnConnectionException("Failed to connect vCD.")
347 if self
.org_uuid
is None:
348 org_list
= client
.get_org_list()
349 for org
in org_list
.Org
:
350 # we set org UUID at the init phase but we can do it only when we have valid credential.
351 if org
.get('name') == self
.org_name
:
352 self
.org_uuid
= org
.get('href').split('/')[-1]
353 self
.logger
.debug("Setting organization UUID {}".format(self
.org_uuid
))
356 raise vimconn
.vimconnException("Vcloud director organization {} not found".format(self
.org_name
))
358 # if well good we require for org details
359 org_details_dict
= self
.get_org(org_uuid
=self
.org_uuid
)
361 # we have two case if we want to initialize VDC ID or VDC name at run time
362 # tenant_name provided but no tenant id
363 if self
.tenant_id
is None and self
.tenant_name
is not None and 'vdcs' in org_details_dict
:
364 vdcs_dict
= org_details_dict
['vdcs']
365 for vdc
in vdcs_dict
:
366 if vdcs_dict
[vdc
] == self
.tenant_name
:
368 self
.logger
.debug("Setting vdc uuid {} for organization UUID {}".format(self
.tenant_id
,
372 raise vimconn
.vimconnException("Tenant name indicated but not present in vcloud director.")
373 # case two we have tenant_id but we don't have tenant name so we find and set it.
374 if self
.tenant_id
is not None and self
.tenant_name
is None and 'vdcs' in org_details_dict
:
375 vdcs_dict
= org_details_dict
['vdcs']
376 for vdc
in vdcs_dict
:
377 if vdc
== self
.tenant_id
:
378 self
.tenant_name
= vdcs_dict
[vdc
]
379 self
.logger
.debug("Setting vdc uuid {} for organization UUID {}".format(self
.tenant_id
,
383 raise vimconn
.vimconnException("Tenant id indicated but not present in vcloud director")
384 self
.logger
.debug("Setting organization uuid {}".format(self
.org_uuid
))
386 self
.logger
.debug("Failed initialize organization UUID for org {}".format(self
.org_name
))
387 self
.logger
.debug(traceback
.format_exc())
390 def new_tenant(self
, tenant_name
=None, tenant_description
=None):
391 """ Method adds a new tenant to VIM with this name.
392 This action requires access to create VDC action in vCloud director.
395 tenant_name is tenant_name to be created.
396 tenant_description not used for this call
399 returns the tenant identifier in UUID format.
400 If action is failed method will throw vimconn.vimconnException method
402 vdc_task
= self
.create_vdc(vdc_name
=tenant_name
)
403 if vdc_task
is not None:
404 vdc_uuid
, value
= vdc_task
.popitem()
405 self
.logger
.info("Created new vdc {} and uuid: {}".format(tenant_name
, vdc_uuid
))
408 raise vimconn
.vimconnException("Failed create tenant {}".format(tenant_name
))
410 def delete_tenant(self
, tenant_id
=None):
411 """ Delete a tenant from VIM
413 tenant_id is tenant_id to be deleted.
416 returns the tenant identifier in UUID format.
417 If action is failed method will throw exception
419 vca
= self
.connect_as_admin()
421 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
423 if tenant_id
is not None:
426 url_list
= [self
.url
, '/api/vdc/', tenant_id
]
427 orgvdc_herf
= ''.join(url_list
)
429 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
430 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
431 response
= self
.perform_request(req_type
='GET',
435 if response
.status_code
!= requests
.codes
.ok
:
436 self
.logger
.debug("delete_tenant():GET REST API call {} failed. "\
437 "Return status code {}".format(orgvdc_herf
,
438 response
.status_code
))
439 raise vimconn
.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id
))
441 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
442 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
444 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
445 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
446 vdc_remove_href
= lxmlroot_respond
.find("xmlns:Link[@rel='remove']",namespaces
).attrib
['href']
447 vdc_remove_href
= vdc_remove_href
+ '?recursive=true&force=true'
449 response
= self
.perform_request(req_type
='DELETE',
453 if response
.status_code
== 202:
457 self
.logger
.debug("delete_tenant(): DELETE REST API call {} failed. "\
458 "Return status code {}".format(vdc_remove_href
,
459 response
.status_code
))
460 raise vimconn
.vimconnException("Fail to delete tenant with ID {}".format(tenant_id
))
462 self
.logger
.debug("delete_tenant():Incorrect tenant ID {}".format(tenant_id
))
463 raise vimconn
.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id
))
466 def get_tenant_list(self
, filter_dict
={}):
467 """Obtain tenants of VIM
468 filter_dict can contain the following keys:
469 name: filter by tenant name
470 id: filter by tenant uuid/id
472 Returns the tenant list of dictionaries:
473 [{'name':'<name>, 'id':'<id>, ...}, ...]
476 org_dict
= self
.get_org(self
.org_uuid
)
477 vdcs_dict
= org_dict
['vdcs']
482 entry
= {'name': vdcs_dict
[k
], 'id': k
}
483 # if caller didn't specify dictionary we return all tenants.
484 if filter_dict
is not None and filter_dict
:
485 filtered_entry
= entry
.copy()
486 filtered_dict
= set(entry
.keys()) - set(filter_dict
)
487 for unwanted_key
in filtered_dict
: del entry
[unwanted_key
]
488 if filter_dict
== entry
:
489 vdclist
.append(filtered_entry
)
491 vdclist
.append(entry
)
493 self
.logger
.debug("Error in get_tenant_list()")
494 self
.logger
.debug(traceback
.format_exc())
495 raise vimconn
.vimconnException("Incorrect state. {}")
499 def new_network(self
, net_name
, net_type
, ip_profile
=None, shared
=False):
500 """Adds a tenant network to VIM
502 net_type can be 'bridge','data'.'ptp'.
503 ip_profile is a dict containing the IP parameters of the network
505 Returns the network identifier"""
507 self
.logger
.debug("new_network tenant {} net_type {} ip_profile {} shared {}"
508 .format(net_name
, net_type
, ip_profile
, shared
))
514 # ############# Stub code for SRIOV #################
515 # if net_type == "data" or net_type == "ptp":
516 # if self.config.get('dv_switch_name') == None:
517 # raise vimconn.vimconnConflictException("You must provide 'dv_switch_name' at config value")
518 # network_uuid = self.create_dvPort_group(net_name)
520 network_uuid
= self
.create_network(network_name
=net_name
, net_type
=net_type
,
521 ip_profile
=ip_profile
, isshared
=isshared
)
522 if network_uuid
is not None:
525 raise vimconn
.vimconnUnexpectedResponse("Failed create a new network {}".format(net_name
))
527 def get_vcd_network_list(self
):
528 """ Method available organization for a logged in tenant
531 The return vca object that letter can be used to connect to vcloud direct as admin
534 self
.logger
.debug("get_vcd_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
536 if not self
.tenant_name
:
537 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
539 org
, vdc
= self
.get_vdc_details()
541 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}".format(self
.tenant_name
))
543 vdc_uuid
= vdc
.get('id').split(":")[3]
544 if self
.client
._session
:
545 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
546 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
547 response
= self
.perform_request(req_type
='GET',
550 if response
.status_code
!= 200:
551 self
.logger
.error("Failed to get vdc content")
552 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
554 content
= XmlElementTree
.fromstring(response
.content
)
559 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
561 response
= self
.perform_request(req_type
='GET',
565 if response
.status_code
!= 200:
566 self
.logger
.error("Failed to get network content")
567 raise vimconn
.vimconnNotFoundException("Failed to get network content")
569 net_details
= XmlElementTree
.fromstring(response
.content
)
572 net_uuid
= net_details
.get('id').split(":")
573 if len(net_uuid
) != 4:
576 net_uuid
= net_uuid
[3]
578 self
.logger
.debug("Adding {} to a list vcd id {} network {}".format(net_uuid
,
580 net_details
.get('name')))
581 filter_dict
["name"] = net_details
.get('name')
582 filter_dict
["id"] = net_uuid
583 if [i
.text
for i
in net_details
if i
.tag
.split('}')[-1] == 'IsShared'][0] == 'true':
587 filter_dict
["shared"] = shared
588 filter_dict
["tenant_id"] = vdc_uuid
589 if int(net_details
.get('status')) == 1:
590 filter_dict
["admin_state_up"] = True
592 filter_dict
["admin_state_up"] = False
593 filter_dict
["status"] = "ACTIVE"
594 filter_dict
["type"] = "bridge"
595 network_list
.append(filter_dict
)
596 self
.logger
.debug("get_vcd_network_list adding entry {}".format(filter_dict
))
598 self
.logger
.debug("Error in get_vcd_network_list", exc_info
=True)
601 self
.logger
.debug("get_vcd_network_list returning {}".format(network_list
))
604 def get_network_list(self
, filter_dict
={}):
605 """Obtain tenant networks of VIM
607 name: network name OR/AND
608 id: network uuid OR/AND
609 shared: boolean OR/AND
610 tenant_id: tenant OR/AND
611 admin_state_up: boolean
614 [{key : value , key : value}]
616 Returns the network list of dictionaries:
617 [{<the fields at Filter_dict plus some VIM specific>}, ...]
621 self
.logger
.debug("get_network_list(): retrieving network list for vcd {}".format(self
.tenant_name
))
623 if not self
.tenant_name
:
624 raise vimconn
.vimconnConnectionException("Tenant name is empty.")
626 org
, vdc
= self
.get_vdc_details()
628 raise vimconn
.vimconnConnectionException("Can't retrieve information for a VDC {}.".format(self
.tenant_name
))
631 vdcid
= vdc
.get('id').split(":")[3]
633 if self
.client
._session
:
634 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
635 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
636 response
= self
.perform_request(req_type
='GET',
639 if response
.status_code
!= 200:
640 self
.logger
.error("Failed to get vdc content")
641 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
643 content
= XmlElementTree
.fromstring(response
.content
)
647 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
649 response
= self
.perform_request(req_type
='GET',
653 if response
.status_code
!= 200:
654 self
.logger
.error("Failed to get network content")
655 raise vimconn
.vimconnNotFoundException("Failed to get network content")
657 net_details
= XmlElementTree
.fromstring(response
.content
)
660 net_uuid
= net_details
.get('id').split(":")
661 if len(net_uuid
) != 4:
664 net_uuid
= net_uuid
[3]
666 self
.logger
.debug("Adding {} to a list vcd id {} network {}".format(net_uuid
,
668 net_details
.get('name')))
669 filter_entry
["name"] = net_details
.get('name')
670 filter_entry
["id"] = net_uuid
671 if [i
.text
for i
in net_details
if i
.tag
.split('}')[-1] == 'IsShared'][0] == 'true':
675 filter_entry
["shared"] = shared
676 filter_entry
["tenant_id"] = vdcid
677 if int(net_details
.get('status')) == 1:
678 filter_entry
["admin_state_up"] = True
680 filter_entry
["admin_state_up"] = False
681 filter_entry
["status"] = "ACTIVE"
682 filter_entry
["type"] = "bridge"
683 filtered_entry
= filter_entry
.copy()
685 if filter_dict
is not None and filter_dict
:
686 # we remove all the key : value we don't care and match only
688 filtered_dict
= set(filter_entry
.keys()) - set(filter_dict
)
689 for unwanted_key
in filtered_dict
: del filter_entry
[unwanted_key
]
690 if filter_dict
== filter_entry
:
691 network_list
.append(filtered_entry
)
693 network_list
.append(filtered_entry
)
694 except Exception as e
:
695 self
.logger
.debug("Error in get_network_list",exc_info
=True)
696 if isinstance(e
, vimconn
.vimconnException
):
699 raise vimconn
.vimconnNotFoundException("Failed : Networks list not found {} ".format(e
))
701 self
.logger
.debug("Returning {}".format(network_list
))
704 def get_network(self
, net_id
):
705 """Method obtains network details of net_id VIM network
706 Return a dict with the fields at filter_dict (see get_network_list) plus some VIM specific>}, ...]"""
709 org
, vdc
= self
.get_vdc_details()
710 vdc_id
= vdc
.get('id').split(":")[3]
711 if self
.client
._session
:
712 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
713 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
714 response
= self
.perform_request(req_type
='GET',
717 if response
.status_code
!= 200:
718 self
.logger
.error("Failed to get vdc content")
719 raise vimconn
.vimconnNotFoundException("Failed to get vdc content")
721 content
= XmlElementTree
.fromstring(response
.content
)
726 if item
.tag
.split('}')[-1] == 'AvailableNetworks':
728 response
= self
.perform_request(req_type
='GET',
732 if response
.status_code
!= 200:
733 self
.logger
.error("Failed to get network content")
734 raise vimconn
.vimconnNotFoundException("Failed to get network content")
736 net_details
= XmlElementTree
.fromstring(response
.content
)
738 vdc_network_id
= net_details
.get('id').split(":")
739 if len(vdc_network_id
) == 4 and vdc_network_id
[3] == net_id
:
740 filter_dict
["name"] = net_details
.get('name')
741 filter_dict
["id"] = vdc_network_id
[3]
742 if [i
.text
for i
in net_details
if i
.tag
.split('}')[-1] == 'IsShared'][0] == 'true':
746 filter_dict
["shared"] = shared
747 filter_dict
["tenant_id"] = vdc_id
748 if int(net_details
.get('status')) == 1:
749 filter_dict
["admin_state_up"] = True
751 filter_dict
["admin_state_up"] = False
752 filter_dict
["status"] = "ACTIVE"
753 filter_dict
["type"] = "bridge"
754 self
.logger
.debug("Returning {}".format(filter_dict
))
757 raise vimconn
.vimconnNotFoundException("Network {} not found".format(net_id
))
758 except Exception as e
:
759 self
.logger
.debug("Error in get_network")
760 self
.logger
.debug(traceback
.format_exc())
761 if isinstance(e
, vimconn
.vimconnException
):
764 raise vimconn
.vimconnNotFoundException("Failed : Network not found {} ".format(e
))
768 def delete_network(self
, net_id
):
770 Method Deletes a tenant network from VIM, provide the network id.
772 Returns the network identifier or raise an exception
775 # ############# Stub code for SRIOV #################
776 # dvport_group = self.get_dvport_group(net_id)
779 # status = self.destroy_dvport_group(net_id)
781 # # Remove vlanID from persistent info
782 # if net_id in self.persistent_info["used_vlanIDs"]:
783 # del self.persistent_info["used_vlanIDs"][net_id]
787 vcd_network
= self
.get_vcd_network(network_uuid
=net_id
)
788 if vcd_network
is not None and vcd_network
:
789 if self
.delete_network_action(network_uuid
=net_id
):
792 raise vimconn
.vimconnNotFoundException("Network {} not found".format(net_id
))
794 def refresh_nets_status(self
, net_list
):
795 """Get the status of the networks
796 Params: the list of network identifiers
797 Returns a dictionary with:
798 net_id: #VIM id of this network
799 status: #Mandatory. Text with one of:
800 # DELETED (not found at vim)
801 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
802 # OTHER (Vim reported other status not understood)
803 # ERROR (VIM indicates an ERROR status)
804 # ACTIVE, INACTIVE, DOWN (admin down),
805 # BUILD (on building process)
807 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
808 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
816 vcd_network
= self
.get_vcd_network(network_uuid
=net
)
817 if vcd_network
is not None and vcd_network
:
818 if vcd_network
['status'] == '1':
824 errormsg
= 'Network not found.'
826 dict_entry
[net
] = {'status': status
, 'error_msg': errormsg
,
827 'vim_info': yaml
.safe_dump(vcd_network
)}
829 self
.logger
.debug("Error in refresh_nets_status")
830 self
.logger
.debug(traceback
.format_exc())
834 def get_flavor(self
, flavor_id
):
835 """Obtain flavor details from the VIM
836 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific } #TODO to concrete
838 if flavor_id
not in vimconnector
.flavorlist
:
839 raise vimconn
.vimconnNotFoundException("Flavor not found.")
840 return vimconnector
.flavorlist
[flavor_id
]
842 def new_flavor(self
, flavor_data
):
843 """Adds a tenant flavor to VIM
844 flavor_data contains a dictionary with information, keys:
846 ram: memory (cloud type) in MBytes
847 vpcus: cpus (cloud type)
848 extended: EPA parameters
849 - numas: #items requested in same NUMA
850 memory: number of 1G huge pages memory
851 paired-threads|cores|threads: number of paired hyperthreads, complete cores OR individual threads
852 interfaces: # passthrough(PT) or SRIOV interfaces attached to this numa
853 - name: interface name
854 dedicated: yes|no|yes:sriov; for PT, SRIOV or only one SRIOV for the physical NIC
855 bandwidth: X Gbps; requested guarantee bandwidth
856 vpci: requested virtual PCI address
860 Returns the flavor identifier"""
862 # generate a new uuid put to internal dict and return it.
863 self
.logger
.debug("Creating new flavor - flavor_data: {}".format(flavor_data
))
864 new_flavor
=flavor_data
865 ram
= flavor_data
.get(FLAVOR_RAM_KEY
, 1024)
866 cpu
= flavor_data
.get(FLAVOR_VCPUS_KEY
, 1)
867 disk
= flavor_data
.get(FLAVOR_DISK_KEY
, 0)
869 if not isinstance(ram
, int):
870 raise vimconn
.vimconnException("Non-integer value for ram")
871 elif not isinstance(cpu
, int):
872 raise vimconn
.vimconnException("Non-integer value for cpu")
873 elif not isinstance(disk
, int):
874 raise vimconn
.vimconnException("Non-integer value for disk")
876 extended_flv
= flavor_data
.get("extended")
878 numas
=extended_flv
.get("numas")
881 #overwrite ram and vcpus
882 ram
= numa
['memory']*1024
883 if 'paired-threads' in numa
:
884 cpu
= numa
['paired-threads']*2
885 elif 'cores' in numa
:
887 elif 'threads' in numa
:
888 cpu
= numa
['threads']
890 new_flavor
[FLAVOR_RAM_KEY
] = ram
891 new_flavor
[FLAVOR_VCPUS_KEY
] = cpu
892 new_flavor
[FLAVOR_DISK_KEY
] = disk
893 # generate a new uuid put to internal dict and return it.
894 flavor_id
= uuid
.uuid4()
895 vimconnector
.flavorlist
[str(flavor_id
)] = new_flavor
896 self
.logger
.debug("Created flavor - {} : {}".format(flavor_id
, new_flavor
))
898 return str(flavor_id
)
900 def delete_flavor(self
, flavor_id
):
901 """Deletes a tenant flavor from VIM identify by its id
903 Returns the used id or raise an exception
905 if flavor_id
not in vimconnector
.flavorlist
:
906 raise vimconn
.vimconnNotFoundException("Flavor not found.")
908 vimconnector
.flavorlist
.pop(flavor_id
, None)
911 def new_image(self
, image_dict
):
913 Adds a tenant image to VIM
915 200, image-id if the image is created
916 <0, message if there is an error
919 return self
.get_image_id_from_path(image_dict
['location'])
921 def delete_image(self
, image_id
):
923 Deletes a tenant image from VIM
925 image_id is ID of Image to be deleted
927 returns the image identifier in UUID format or raises an exception on error
929 conn
= self
.connect_as_admin()
931 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
932 # Get Catalog details
933 url_list
= [self
.url
, '/api/catalog/', image_id
]
934 catalog_herf
= ''.join(url_list
)
936 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
937 'x-vcloud-authorization': conn
._session
.headers
['x-vcloud-authorization']}
939 response
= self
.perform_request(req_type
='GET',
943 if response
.status_code
!= requests
.codes
.ok
:
944 self
.logger
.debug("delete_image():GET REST API call {} failed. "\
945 "Return status code {}".format(catalog_herf
,
946 response
.status_code
))
947 raise vimconn
.vimconnNotFoundException("Fail to get image {}".format(image_id
))
949 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
950 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
952 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
953 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
955 catalogItems_section
= lxmlroot_respond
.find("xmlns:CatalogItems",namespaces
)
956 catalogItems
= catalogItems_section
.iterfind("xmlns:CatalogItem",namespaces
)
957 for catalogItem
in catalogItems
:
958 catalogItem_href
= catalogItem
.attrib
['href']
960 response
= self
.perform_request(req_type
='GET',
961 url
=catalogItem_href
,
964 if response
.status_code
!= requests
.codes
.ok
:
965 self
.logger
.debug("delete_image():GET REST API call {} failed. "\
966 "Return status code {}".format(catalog_herf
,
967 response
.status_code
))
968 raise vimconn
.vimconnNotFoundException("Fail to get catalogItem {} for catalog {}".format(
972 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
973 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
975 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
976 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
977 catalogitem_remove_href
= lxmlroot_respond
.find("xmlns:Link[@rel='remove']",namespaces
).attrib
['href']
980 response
= self
.perform_request(req_type
='DELETE',
981 url
=catalogitem_remove_href
,
983 if response
.status_code
== requests
.codes
.no_content
:
984 self
.logger
.debug("Deleted Catalog item {}".format(catalogItem
))
986 raise vimconn
.vimconnException("Fail to delete Catalog Item {}".format(catalogItem
))
989 url_list
= [self
.url
, '/api/admin/catalog/', image_id
]
990 catalog_remove_herf
= ''.join(url_list
)
991 response
= self
.perform_request(req_type
='DELETE',
992 url
=catalog_remove_herf
,
995 if response
.status_code
== requests
.codes
.no_content
:
996 self
.logger
.debug("Deleted Catalog {}".format(image_id
))
999 raise vimconn
.vimconnException("Fail to delete Catalog {}".format(image_id
))
1002 def catalog_exists(self
, catalog_name
, catalogs
):
1005 :param catalog_name:
1009 for catalog
in catalogs
:
1010 if catalog
['name'] == catalog_name
:
1014 def create_vimcatalog(self
, vca
=None, catalog_name
=None):
1015 """ Create new catalog entry in vCloud director.
1018 vca: vCloud director.
1019 catalog_name catalog that client wish to create. Note no validation done for a name.
1020 Client must make sure that provide valid string representation.
1022 Return (bool) True if catalog created.
1026 result
= vca
.create_catalog(catalog_name
, catalog_name
)
1027 if result
is not None:
1029 catalogs
= vca
.list_catalogs()
1032 return self
.catalog_exists(catalog_name
, catalogs
)
1034 # noinspection PyIncorrectDocstring
1035 def upload_ovf(self
, vca
=None, catalog_name
=None, image_name
=None, media_file_name
=None,
1036 description
='', progress
=False, chunk_bytes
=128 * 1024):
1038 Uploads a OVF file to a vCloud catalog
1045 :param catalog_name: (str): The name of the catalog to upload the media.
1046 :param media_file_name: (str): The name of the local media file to upload.
1047 :return: (bool) True if the media file was successfully uploaded, false otherwise.
1049 os
.path
.isfile(media_file_name
)
1050 statinfo
= os
.stat(media_file_name
)
1052 # find a catalog entry where we upload OVF.
1053 # create vApp Template and check the status if vCD able to read OVF it will respond with appropirate
1055 # if VCD can parse OVF we upload VMDK file
1057 for catalog
in vca
.list_catalogs():
1058 if catalog_name
!= catalog
['name']:
1060 catalog_href
= "{}/api/catalog/{}/action/upload".format(self
.url
, catalog
['id'])
1062 <UploadVAppTemplateParams name="{}" xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"><Description>{} vApp Template</Description></UploadVAppTemplateParams>
1063 """.format(catalog_name
, description
)
1066 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
1067 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
1068 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml'
1070 response
= self
.perform_request(req_type
='POST',
1075 if response
.status_code
== requests
.codes
.created
:
1076 catalogItem
= XmlElementTree
.fromstring(response
.content
)
1077 entity
= [child
for child
in catalogItem
if
1078 child
.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
1079 href
= entity
.get('href')
1082 response
= self
.perform_request(req_type
='GET',
1086 if response
.status_code
== requests
.codes
.ok
:
1087 headers
['Content-Type'] = 'Content-Type text/xml'
1088 result
= re
.search('rel="upload:default"\shref="(.*?\/descriptor.ovf)"',response
.content
)
1090 transfer_href
= result
.group(1)
1092 response
= self
.perform_request(req_type
='PUT',
1095 data
=open(media_file_name
, 'rb'))
1096 if response
.status_code
!= requests
.codes
.ok
:
1098 "Failed create vApp template for catalog name {} and image {}".format(catalog_name
,
1102 # TODO fix this with aync block
1105 self
.logger
.debug("vApp template for catalog name {} and image {}".format(catalog_name
, media_file_name
))
1107 # uploading VMDK file
1108 # check status of OVF upload and upload remaining files.
1109 response
= self
.perform_request(req_type
='GET',
1113 if response
.status_code
== requests
.codes
.ok
:
1114 result
= re
.search('rel="upload:default"\s*href="(.*?vmdk)"',response
.content
)
1116 link_href
= result
.group(1)
1117 # we skip ovf since it already uploaded.
1118 if 'ovf' in link_href
:
1120 # The OVF file and VMDK must be in a same directory
1121 head
, tail
= os
.path
.split(media_file_name
)
1122 file_vmdk
= head
+ '/' + link_href
.split("/")[-1]
1123 if not os
.path
.isfile(file_vmdk
):
1125 statinfo
= os
.stat(file_vmdk
)
1126 if statinfo
.st_size
== 0:
1128 hrefvmdk
= link_href
1131 widgets
= ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
1132 FileTransferSpeed()]
1133 progress_bar
= ProgressBar(widgets
=widgets
, maxval
=statinfo
.st_size
).start()
1135 bytes_transferred
= 0
1136 f
= open(file_vmdk
, 'rb')
1137 while bytes_transferred
< statinfo
.st_size
:
1138 my_bytes
= f
.read(chunk_bytes
)
1139 if len(my_bytes
) <= chunk_bytes
:
1140 headers
['Content-Range'] = 'bytes %s-%s/%s' % (
1141 bytes_transferred
, len(my_bytes
) - 1, statinfo
.st_size
)
1142 headers
['Content-Length'] = str(len(my_bytes
))
1143 response
= requests
.put(url
=hrefvmdk
,
1147 if response
.status_code
== requests
.codes
.ok
:
1148 bytes_transferred
+= len(my_bytes
)
1150 progress_bar
.update(bytes_transferred
)
1153 'file upload failed with error: [%s] %s' % (response
.status_code
,
1160 progress_bar
.finish()
1164 self
.logger
.debug("Failed retrieve vApp template for catalog name {} for OVF {}".
1165 format(catalog_name
, media_file_name
))
1167 except Exception as exp
:
1168 self
.logger
.debug("Failed while uploading OVF to catalog {} for OVF file {} with Exception {}"
1169 .format(catalog_name
,media_file_name
, exp
))
1170 raise vimconn
.vimconnException(
1171 "Failed while uploading OVF to catalog {} for OVF file {} with Exception {}"
1172 .format(catalog_name
,media_file_name
, exp
))
1174 self
.logger
.debug("Failed retrieve catalog name {} for OVF file {}".format(catalog_name
, media_file_name
))
1177 def upload_vimimage(self
, vca
=None, catalog_name
=None, media_name
=None, medial_file_name
=None, progress
=False):
1178 """Upload media file"""
1179 # TODO add named parameters for readability
1181 return self
.upload_ovf(vca
=vca
, catalog_name
=catalog_name
, image_name
=media_name
.split(".")[0],
1182 media_file_name
=medial_file_name
, description
='medial_file_name', progress
=progress
)
1184 def validate_uuid4(self
, uuid_string
=None):
1185 """ Method validate correct format of UUID.
1187 Return: true if string represent valid uuid
1190 val
= uuid
.UUID(uuid_string
, version
=4)
1195 def get_catalogid(self
, catalog_name
=None, catalogs
=None):
1196 """ Method check catalog and return catalog ID in UUID format.
1199 catalog_name: catalog name as string
1200 catalogs: list of catalogs.
1202 Return: catalogs uuid
1205 for catalog
in catalogs
:
1206 if catalog
['name'] == catalog_name
:
1207 catalog_id
= catalog
['id']
1211 def get_catalogbyid(self
, catalog_uuid
=None, catalogs
=None):
1212 """ Method check catalog and return catalog name lookup done by catalog UUID.
1215 catalog_name: catalog name as string
1216 catalogs: list of catalogs.
1218 Return: catalogs name or None
1221 if not self
.validate_uuid4(uuid_string
=catalog_uuid
):
1224 for catalog
in catalogs
:
1225 catalog_id
= catalog
.get('id')
1226 if catalog_id
== catalog_uuid
:
1227 return catalog
.get('name')
1230 def get_catalog_obj(self
, catalog_uuid
=None, catalogs
=None):
1231 """ Method check catalog and return catalog name lookup done by catalog UUID.
1234 catalog_name: catalog name as string
1235 catalogs: list of catalogs.
1237 Return: catalogs name or None
1240 if not self
.validate_uuid4(uuid_string
=catalog_uuid
):
1243 for catalog
in catalogs
:
1244 catalog_id
= catalog
.get('id')
1245 if catalog_id
== catalog_uuid
:
1249 def get_image_id_from_path(self
, path
=None, progress
=False):
1250 """ Method upload OVF image to vCloud director.
1252 Each OVF image represented as single catalog entry in vcloud director.
1253 The method check for existing catalog entry. The check done by file name without file extension.
1255 if given catalog name already present method will respond with existing catalog uuid otherwise
1256 it will create new catalog entry and upload OVF file to newly created catalog.
1258 If method can't create catalog entry or upload a file it will throw exception.
1260 Method accept boolean flag progress that will output progress bar. It useful method
1261 for standalone upload use case. In case to test large file upload.
1264 path: - valid path to OVF file.
1265 progress - boolean progress bar show progress bar.
1267 Return: if image uploaded correct method will provide image catalog UUID.
1271 raise vimconn
.vimconnException("Image path can't be None.")
1273 if not os
.path
.isfile(path
):
1274 raise vimconn
.vimconnException("Can't read file. File not found.")
1276 if not os
.access(path
, os
.R_OK
):
1277 raise vimconn
.vimconnException("Can't read file. Check file permission to read.")
1279 self
.logger
.debug("get_image_id_from_path() client requesting {} ".format(path
))
1281 dirpath
, filename
= os
.path
.split(path
)
1282 flname
, file_extension
= os
.path
.splitext(path
)
1283 if file_extension
!= '.ovf':
1284 self
.logger
.debug("Wrong file extension {} connector support only OVF container.".format(file_extension
))
1285 raise vimconn
.vimconnException("Wrong container. vCloud director supports only OVF.")
1287 catalog_name
= os
.path
.splitext(filename
)[0]
1288 catalog_md5_name
= hashlib
.md5(path
).hexdigest()
1289 self
.logger
.debug("File name {} Catalog Name {} file path {} "
1290 "vdc catalog name {}".format(filename
, catalog_name
, path
, catalog_md5_name
))
1293 org
,vdc
= self
.get_vdc_details()
1294 catalogs
= org
.list_catalogs()
1295 except Exception as exp
:
1296 self
.logger
.debug("Failed get catalogs() with Exception {} ".format(exp
))
1297 raise vimconn
.vimconnException("Failed get catalogs() with Exception {} ".format(exp
))
1299 if len(catalogs
) == 0:
1300 self
.logger
.info("Creating a new catalog entry {} in vcloud director".format(catalog_name
))
1301 result
= self
.create_vimcatalog(org
, catalog_md5_name
)
1303 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1305 result
= self
.upload_vimimage(vca
=org
, catalog_name
=catalog_md5_name
,
1306 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1308 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_name
))
1309 return self
.get_catalogid(catalog_name
, catalogs
)
1311 for catalog
in catalogs
:
1312 # search for existing catalog if we find same name we return ID
1313 # TODO optimize this
1314 if catalog
['name'] == catalog_md5_name
:
1315 self
.logger
.debug("Found existing catalog entry for {} "
1316 "catalog id {}".format(catalog_name
,
1317 self
.get_catalogid(catalog_md5_name
, catalogs
)))
1318 return self
.get_catalogid(catalog_md5_name
, catalogs
)
1320 # if we didn't find existing catalog we create a new one and upload image.
1321 self
.logger
.debug("Creating new catalog entry {} - {}".format(catalog_name
, catalog_md5_name
))
1322 result
= self
.create_vimcatalog(org
, catalog_md5_name
)
1324 raise vimconn
.vimconnException("Failed create new catalog {} ".format(catalog_md5_name
))
1326 result
= self
.upload_vimimage(vca
=org
, catalog_name
=catalog_md5_name
,
1327 media_name
=filename
, medial_file_name
=path
, progress
=progress
)
1329 raise vimconn
.vimconnException("Failed create vApp template for catalog {} ".format(catalog_md5_name
))
1331 return self
.get_catalogid(catalog_md5_name
, org
.list_catalogs())
1333 def get_image_list(self
, filter_dict
={}):
1334 '''Obtain tenant images from VIM
1338 checksum: image checksum
1339 location: image path
1340 Returns the image list of dictionaries:
1341 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1346 org
, vdc
= self
.get_vdc_details()
1348 catalogs
= org
.list_catalogs()
1349 if len(catalogs
) == 0:
1352 for catalog
in catalogs
:
1353 catalog_uuid
= catalog
.get('id')
1354 name
= catalog
.get('name')
1356 if filter_dict
.get("name") and filter_dict
["name"] != name
:
1358 if filter_dict
.get("id") and filter_dict
["id"] != catalog_uuid
:
1360 filtered_dict
["name"] = name
1361 filtered_dict
["id"] = catalog_uuid
1362 image_list
.append(filtered_dict
)
1364 self
.logger
.debug("List of already created catalog items: {}".format(image_list
))
1366 except Exception as exp
:
1367 raise vimconn
.vimconnException("Exception occured while retriving catalog items {}".format(exp
))
1369 def get_vappid(self
, vdc
=None, vapp_name
=None):
1370 """ Method takes vdc object and vApp name and returns vapp uuid or None
1373 vdc: The VDC object.
1374 vapp_name: is application vappp name identifier
1377 The return vApp name otherwise None
1379 if vdc
is None or vapp_name
is None:
1381 # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
1383 refs
= filter(lambda ref
: ref
.name
== vapp_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1384 vdc
.ResourceEntities
.ResourceEntity
)
1386 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1387 # if ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1389 return refs
[0].href
.split("vapp")[1][1:]
1390 except Exception as e
:
1391 self
.logger
.exception(e
)
1395 def check_vapp(self
, vdc
=None, vapp_uuid
=None):
1396 """ Method Method returns True or False if vapp deployed in vCloud director
1399 vca: Connector to VCA
1400 vdc: The VDC object.
1401 vappid: vappid is application identifier
1404 The return True if vApp deployed
1409 refs
= filter(lambda ref
:
1410 ref
.type_
== 'application/vnd.vmware.vcloud.vApp+xml',
1411 vdc
.ResourceEntities
.ResourceEntity
)
1413 #refs = [ref for ref in vdc.ResourceEntities.ResourceEntity\
1414 # if ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
1416 vappid
= ref
.href
.split("vapp")[1][1:]
1417 # find vapp with respected vapp uuid
1418 if vappid
== vapp_uuid
:
1420 except Exception as e
:
1421 self
.logger
.exception(e
)
1425 def get_namebyvappid(self
, vapp_uuid
=None):
1426 """Method returns vApp name from vCD and lookup done by vapp_id.
1429 vapp_uuid: vappid is application identifier
1432 The return vApp name otherwise None
1435 if self
.client
and vapp_uuid
:
1436 vapp_call
= "{}/api/vApp/vapp-{}".format(self
.url
, vapp_uuid
)
1437 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
1438 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
1440 response
= self
.perform_request(req_type
='GET',
1443 #Retry login if session expired & retry sending request
1444 if response
.status_code
== 403:
1445 response
= self
.retry_rest('GET', vapp_call
)
1447 tree
= XmlElementTree
.fromstring(response
.content
)
1448 return tree
.attrib
['name']
1449 except Exception as e
:
1450 self
.logger
.exception(e
)
1454 def new_vminstance(self
, name
=None, description
="", start
=False, image_id
=None, flavor_id
=None, net_list
=[],
1455 cloud_config
=None, disk_list
=None, availability_zone_index
=None, availability_zone_list
=None):
1456 """Adds a VM instance to VIM
1458 'start': (boolean) indicates if VM must start or created in pause mode.
1459 'image_id','flavor_id': image and flavor VIM id to use for the VM
1460 'net_list': list of interfaces, each one is a dictionary with:
1461 'name': (optional) name for the interface.
1462 'net_id': VIM network id where this interface must be connect to. Mandatory for type==virtual
1463 'vpci': (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM capabilities
1464 'model': (optional and only have sense for type==virtual) interface model: virtio, e2000, ...
1465 'mac_address': (optional) mac address to assign to this interface
1466 #TODO: CHECK if an optional 'vlan' parameter is needed for VIMs when type if VF and net_id is not provided,
1467 the VLAN tag to be used. In case net_id is provided, the internal network vlan is used for tagging VF
1468 'type': (mandatory) can be one of:
1469 'virtual', in this case always connected to a network of type 'net_type=bridge'
1470 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a data/ptp network ot it
1471 can created unconnected
1472 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
1473 'VFnotShared'(SRIOV without VLAN tag) same as PF for network connectivity. VF where no other VFs
1474 are allocated on the same physical NIC
1475 'bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
1476 'port_security': (optional) If False it must avoid any traffic filtering at this interface. If missing
1477 or True, it must apply the default VIM behaviour
1478 After execution the method will add the key:
1479 'vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
1480 interface. 'net_list' is modified
1481 'cloud_config': (optional) dictionary with:
1482 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1483 'users': (optional) list of users to be inserted, each item is a dict with:
1484 'name': (mandatory) user name,
1485 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1486 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
1487 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
1488 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1489 'dest': (mandatory) string with the destination absolute path
1490 'encoding': (optional, by default text). Can be one of:
1491 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1492 'content' (mandatory): string with the content of the file
1493 'permissions': (optional) string with file permissions, typically octal notation '0644'
1494 'owner': (optional) file owner, string with the format 'owner:group'
1495 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1496 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1497 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1498 'size': (mandatory) string with the size of the disk in GB
1499 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1500 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1501 availability_zone_index is None
1502 Returns a tuple with the instance identifier and created_items or raises an exception on error
1503 created_items can be None or a dictionary where this method can include key-values that will be passed to
1504 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1505 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1508 self
.logger
.info("Creating new instance for entry {}".format(name
))
1509 self
.logger
.debug("desc {} boot {} image_id: {} flavor_id: {} net_list: {} cloud_config {} disk_list {}".format(
1510 description
, start
, image_id
, flavor_id
, net_list
, cloud_config
, disk_list
))
1512 #new vm name = vmname + tenant_id + uuid
1513 new_vm_name
= [name
, '-', str(uuid
.uuid4())]
1514 vmname_andid
= ''.join(new_vm_name
)
1516 for net
in net_list
:
1517 if net
['type'] == "SR-IOV" or net
['type'] == "PCI-PASSTHROUGH":
1518 raise vimconn
.vimconnNotSupportedException(
1519 "Current vCD version does not support type : {}".format(net
['type']))
1521 if len(net_list
) > 10:
1522 raise vimconn
.vimconnNotSupportedException(
1523 "The VM hardware versions 7 and above support upto 10 NICs only")
1525 # if vm already deployed we return existing uuid
1526 # we check for presence of VDC, Catalog entry and Flavor.
1527 org
, vdc
= self
.get_vdc_details()
1529 raise vimconn
.vimconnNotFoundException(
1530 "new_vminstance(): Failed create vApp {}: (Failed retrieve VDC information)".format(name
))
1531 catalogs
= org
.list_catalogs()
1532 if catalogs
is None:
1533 #Retry once, if failed by refreshing token
1535 org
= Org(self
.client
, resource
=self
.client
.get_org())
1536 catalogs
= org
.list_catalogs()
1537 if catalogs
is None:
1538 raise vimconn
.vimconnNotFoundException(
1539 "new_vminstance(): Failed create vApp {}: (Failed retrieve catalogs list)".format(name
))
1541 catalog_hash_name
= self
.get_catalogbyid(catalog_uuid
=image_id
, catalogs
=catalogs
)
1542 if catalog_hash_name
:
1543 self
.logger
.info("Found catalog entry {} for image id {}".format(catalog_hash_name
, image_id
))
1545 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1546 "(Failed retrieve catalog information {})".format(name
, image_id
))
1549 # Set vCPU and Memory based on flavor.
1555 if flavor_id
is not None:
1556 if flavor_id
not in vimconnector
.flavorlist
:
1557 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed create vApp {}: "
1558 "Failed retrieve flavor information "
1559 "flavor id {}".format(name
, flavor_id
))
1562 flavor
= vimconnector
.flavorlist
[flavor_id
]
1563 vm_cpus
= flavor
[FLAVOR_VCPUS_KEY
]
1564 vm_memory
= flavor
[FLAVOR_RAM_KEY
]
1565 vm_disk
= flavor
[FLAVOR_DISK_KEY
]
1566 extended
= flavor
.get("extended", None)
1568 numas
=extended
.get("numas", None)
1570 except Exception as exp
:
1571 raise vimconn
.vimconnException("Corrupted flavor. {}.Exception: {}".format(flavor_id
, exp
))
1573 # image upload creates template name as catalog name space Template.
1574 templateName
= self
.get_catalogbyid(catalog_uuid
=image_id
, catalogs
=catalogs
)
1579 # client must provide at least one entry in net_list if not we report error
1580 #If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
1581 #If no mgmt, then the 1st NN in netlist is considered as primary net.
1583 primary_netname
= None
1584 network_mode
= 'bridged'
1585 if net_list
is not None and len(net_list
) > 0:
1586 for net
in net_list
:
1587 if 'use' in net
and net
['use'] == 'mgmt' and not primary_net
:
1589 if primary_net
is None:
1590 primary_net
= net_list
[0]
1593 primary_net_id
= primary_net
['net_id']
1594 network_dict
= self
.get_vcd_network(network_uuid
=primary_net_id
)
1595 if 'name' in network_dict
:
1596 primary_netname
= network_dict
['name']
1599 raise vimconn
.vimconnException("Corrupted flavor. {}".format(primary_net
))
1601 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed network list is empty.".format(name
))
1603 # use: 'data', 'bridge', 'mgmt'
1604 # create vApp. Set vcpu and ram based on flavor id.
1606 vdc_obj
= VDC(self
.client
, resource
=org
.get_vdc(self
.tenant_name
))
1608 raise vimconn
.vimconnNotFoundException("new_vminstance(): Failed to get VDC object")
1611 items
= org
.get_catalog_item(catalog_hash_name
, catalog_hash_name
)
1612 catalog_items
= [items
.attrib
]
1614 if len(catalog_items
) == 1:
1616 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
1617 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
1619 response
= self
.perform_request(req_type
='GET',
1620 url
=catalog_items
[0].get('href'),
1622 catalogItem
= XmlElementTree
.fromstring(response
.content
)
1623 entity
= [child
for child
in catalogItem
if child
.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
1624 vapp_tempalte_href
= entity
.get("href")
1626 response
= self
.perform_request(req_type
='GET',
1627 url
=vapp_tempalte_href
,
1629 if response
.status_code
!= requests
.codes
.ok
:
1630 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vapp_tempalte_href
,
1631 response
.status_code
))
1633 result
= (response
.content
).replace("\n"," ")
1635 src
= re
.search('<Vm goldMaster="false"\sstatus="\d+"\sname="(.*?)"\s'
1636 'id="(\w+:\w+:vm:.*?)"\shref="(.*?)"\s'
1637 'type="application/vnd\.vmware\.vcloud\.vm\+xml',result
)
1639 vm_name
= src
.group(1)
1640 vm_id
= src
.group(2)
1641 vm_href
= src
.group(3)
1643 cpus
= re
.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',result
).group(1)
1644 memory_mb
= re
.search('<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>',result
).group(1)
1645 cores
= re
.search('<vmw:CoresPerSocket ovf:required.*?>(\d+)</vmw:CoresPerSocket>',result
).group(1)
1647 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'
1648 vdc_id
= vdc
.get('id').split(':')[-1]
1649 instantiate_vapp_href
= "{}/api/vdc/{}/action/instantiateVAppTemplate".format(self
.url
,
1651 data
= """<?xml version="1.0" encoding="UTF-8"?>
1652 <InstantiateVAppTemplateParams
1653 xmlns="http://www.vmware.com/vcloud/v1.5"
1657 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1658 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1">
1659 <Description>Vapp instantiation</Description>
1660 <InstantiationParams>
1661 <NetworkConfigSection>
1662 <ovf:Info>Configuration parameters for logical networks</ovf:Info>
1663 <NetworkConfig networkName="None">
1665 <ParentNetwork href=""/>
1666 <FenceMode>bridged</FenceMode>
1669 </NetworkConfigSection>
1670 <LeaseSettingsSection
1671 type="application/vnd.vmware.vcloud.leaseSettingsSection+xml">
1672 <ovf:Info>Lease Settings</ovf:Info>
1673 <StorageLeaseInSeconds>172800</StorageLeaseInSeconds>
1674 <StorageLeaseExpiration>2014-04-25T08:08:16.438-07:00</StorageLeaseExpiration>
1675 </LeaseSettingsSection>
1676 </InstantiationParams>
1679 <Source href="{}" id="{}" name="{}"
1680 type="application/vnd.vmware.vcloud.vm+xml"/>
1682 <NeedsCustomization>false</NeedsCustomization>
1684 <InstantiationParams>
1685 <NetworkConnectionSection>
1686 <ovf:Info>Specifies the available VM network connections</ovf:Info>
1687 <NetworkConnection network="{}">
1688 <NetworkConnectionIndex>0</NetworkConnectionIndex>
1689 <IsConnected>true</IsConnected>
1690 <IpAddressAllocationMode>DHCP</IpAddressAllocationMode>
1691 </NetworkConnection>
1692 </NetworkConnectionSection><ovf:VirtualHardwareSection>
1693 <ovf:Info>Virtual hardware requirements</ovf:Info>
1694 <ovf:Item xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"
1695 xmlns:vmw="http://www.vmware.com/schema/ovf">
1696 <rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
1697 <rasd:Description>Number of Virtual CPUs</rasd:Description>
1698 <rasd:ElementName xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">{cpu} virtual CPU(s)</rasd:ElementName>
1699 <rasd:InstanceID>4</rasd:InstanceID>
1700 <rasd:Reservation>0</rasd:Reservation>
1701 <rasd:ResourceType>3</rasd:ResourceType>
1702 <rasd:VirtualQuantity xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="int">{cpu}</rasd:VirtualQuantity>
1703 <rasd:Weight>0</rasd:Weight>
1704 <vmw:CoresPerSocket ovf:required="false">{core}</vmw:CoresPerSocket>
1705 </ovf:Item><ovf:Item xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData">
1706 <rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
1707 <rasd:Description>Memory Size</rasd:Description>
1708 <rasd:ElementName xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">{memory} MB of memory</rasd:ElementName>
1709 <rasd:InstanceID>5</rasd:InstanceID>
1710 <rasd:Reservation>0</rasd:Reservation>
1711 <rasd:ResourceType>4</rasd:ResourceType>
1712 <rasd:VirtualQuantity xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="int">{memory}</rasd:VirtualQuantity>
1713 <rasd:Weight>0</rasd:Weight>
1715 </ovf:VirtualHardwareSection>
1716 </InstantiationParams>
1718 <AllEULAsAccepted>false</AllEULAsAccepted>
1719 </InstantiateVAppTemplateParams>""".format(vmname_andid
,
1729 response
= self
.perform_request(req_type
='POST',
1730 url
=instantiate_vapp_href
,
1734 if response
.status_code
!= 201:
1735 self
.logger
.error("REST call {} failed reason : {}"\
1736 "status code : {}".format(instantiate_vapp_href
,
1738 response
.status_code
))
1739 raise vimconn
.vimconnException("new_vminstance(): Failed to create"\
1740 "vAapp {}".format(vmname_andid
))
1742 vapptask
= self
.get_task_from_response(response
.content
)
1744 if vapptask
is None and retry
==1:
1745 self
.get_token() # Retry getting token
1750 if vapptask
is None or vapptask
is False:
1751 raise vimconn
.vimconnUnexpectedResponse(
1752 "new_vminstance(): failed to create vApp {}".format(vmname_andid
))
1754 # wait for task to complete
1755 result
= self
.client
.get_task_monitor().wait_for_success(task
=vapptask
)
1757 if result
.get('status') == 'success':
1758 self
.logger
.debug("new_vminstance(): Sucessfully created Vapp {}".format(vmname_andid
))
1760 raise vimconn
.vimconnUnexpectedResponse(
1761 "new_vminstance(): failed to create vApp {}".format(vmname_andid
))
1763 except Exception as exp
:
1764 raise vimconn
.vimconnUnexpectedResponse(
1765 "new_vminstance(): failed to create vApp {} with Exception:{}".format(vmname_andid
, exp
))
1767 # we should have now vapp in undeployed state.
1769 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
1770 vapp_resource
= vdc_obj
.get_vapp(vmname_andid
)
1771 vapp_uuid
= vapp_resource
.get('id').split(':')[-1]
1772 vapp
= VApp(self
.client
, resource
=vapp_resource
)
1774 except Exception as exp
:
1775 raise vimconn
.vimconnUnexpectedResponse(
1776 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
1777 .format(vmname_andid
, exp
))
1779 if vapp_uuid
is None:
1780 raise vimconn
.vimconnUnexpectedResponse(
1781 "new_vminstance(): Failed to retrieve vApp {} after creation".format(
1784 #Add PCI passthrough/SRIOV configrations
1786 pci_devices_info
= []
1788 reserve_memory
= False
1790 for net
in net_list
:
1791 if net
["type"] == "PF" or net
["type"] == "PCI-PASSTHROUGH":
1792 pci_devices_info
.append(net
)
1793 elif (net
["type"] == "VF" or net
["type"] == "SR-IOV" or net
["type"] == "VFnotShared") and 'net_id'in net
:
1794 sriov_net_info
.append(net
)
1797 if len(pci_devices_info
) > 0:
1798 self
.logger
.info("Need to add PCI devices {} into VM {}".format(pci_devices_info
,
1800 PCI_devices_status
, vm_obj
, vcenter_conect
= self
.add_pci_devices(vapp_uuid
,
1803 if PCI_devices_status
:
1804 self
.logger
.info("Added PCI devives {} to VM {}".format(
1808 reserve_memory
= True
1810 self
.logger
.info("Fail to add PCI devives {} to VM {}".format(
1817 #Assuming there is only one disk in ovf and fast provisioning in organization vDC is disabled
1818 result
= self
.modify_vm_disk(vapp_uuid
, vm_disk
)
1820 self
.logger
.debug("Modified Disk size of VM {} ".format(vmname_andid
))
1822 #Add new or existing disks to vApp
1824 added_existing_disk
= False
1825 for disk
in disk_list
:
1826 if 'device_type' in disk
and disk
['device_type'] == 'cdrom':
1827 image_id
= disk
['image_id']
1828 # Adding CD-ROM to VM
1829 # will revisit code once specification ready to support this feature
1830 self
.insert_media_to_vm(vapp
, image_id
)
1831 elif "image_id" in disk
and disk
["image_id"] is not None:
1832 self
.logger
.debug("Adding existing disk from image {} to vm {} ".format(
1833 disk
["image_id"] , vapp_uuid
))
1834 self
.add_existing_disk(catalogs
=catalogs
,
1835 image_id
=disk
["image_id"],
1836 size
= disk
["size"],
1837 template_name
=templateName
,
1840 added_existing_disk
= True
1842 #Wait till added existing disk gets reflected into vCD database/API
1843 if added_existing_disk
:
1845 added_existing_disk
= False
1846 self
.add_new_disk(vapp_uuid
, disk
['size'])
1849 # Assigning numa affinity setting
1851 if 'paired-threads-id' in numa
:
1852 paired_threads_id
= numa
['paired-threads-id']
1853 self
.set_numa_affinity(vapp_uuid
, paired_threads_id
)
1855 # add NICs & connect to networks in netlist
1857 self
.logger
.info("Request to connect VM to a network: {}".format(net_list
))
1859 primary_nic_index
= 0
1860 for net
in net_list
:
1861 # openmano uses network id in UUID format.
1862 # vCloud Director need a name so we do reverse operation from provided UUID we lookup a name
1863 # [{'use': 'bridge', 'net_id': '527d4bf7-566a-41e7-a9e7-ca3cdd9cef4f', 'type': 'virtual',
1864 # 'vpci': '0000:00:11.0', 'name': 'eth0'}]
1866 if 'net_id' not in net
:
1869 #Using net_id as a vim_id i.e. vim interface id, as do not have saperate vim interface id
1870 #Same will be returned in refresh_vms_status() as vim_interface_id
1871 net
['vim_id'] = net
['net_id'] # Provide the same VIM identifier as the VIM network
1873 interface_net_id
= net
['net_id']
1874 interface_net_name
= self
.get_network_name_by_id(network_uuid
=interface_net_id
)
1875 interface_network_mode
= net
['use']
1877 if interface_network_mode
== 'mgmt':
1878 primary_nic_index
= nicIndex
1880 """- POOL (A static IP address is allocated automatically from a pool of addresses.)
1881 - DHCP (The IP address is obtained from a DHCP service.)
1882 - MANUAL (The IP address is assigned manually in the IpAddress element.)
1883 - NONE (No IP addressing mode specified.)"""
1885 if primary_netname
is not None:
1886 nets
= filter(lambda n
: n
.get('name') == interface_net_name
, self
.get_network_list())
1888 #nets = [n for n in self.get_network_list() if n.get('name') == interface_net_name]
1890 self
.logger
.info("new_vminstance(): Found requested network: {}".format(nets
[0].get('name')))
1892 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
1893 vapp_resource
= vdc_obj
.get_vapp(vmname_andid
)
1894 vapp
= VApp(self
.client
, resource
=vapp_resource
)
1895 # connect network to VM - with all DHCP by default
1896 task
= vapp
.connect_org_vdc_network(nets
[0].get('name'))
1898 self
.client
.get_task_monitor().wait_for_success(task
=task
)
1900 type_list
= ('PF', 'PCI-PASSTHROUGH', 'VF', 'SR-IOV', 'VFnotShared')
1901 if 'type' in net
and net
['type'] not in type_list
:
1902 # fetching nic type from vnf
1904 if net
['model'] is not None and net
['model'].lower() == 'virtio':
1905 nic_type
= 'VMXNET3'
1907 nic_type
= net
['model']
1909 self
.logger
.info("new_vminstance(): adding network adapter "\
1910 "to a network {}".format(nets
[0].get('name')))
1911 self
.add_network_adapter_to_vms(vapp
, nets
[0].get('name'),
1917 self
.logger
.info("new_vminstance(): adding network adapter "\
1918 "to a network {}".format(nets
[0].get('name')))
1919 self
.add_network_adapter_to_vms(vapp
, nets
[0].get('name'),
1925 # cloud-init for ssh-key injection
1927 self
.cloud_init(vapp
,cloud_config
)
1929 # ############# Stub code for SRIOV #################
1931 # if len(sriov_net_info) > 0:
1932 # self.logger.info("Need to add SRIOV adapters {} into VM {}".format(sriov_net_info,
1934 # sriov_status, vm_obj, vcenter_conect = self.add_sriov(vapp_uuid,
1938 # self.logger.info("Added SRIOV {} to VM {}".format(
1942 # reserve_memory = True
1944 # self.logger.info("Fail to add SRIOV {} to VM {}".format(
1949 # If VM has PCI devices or SRIOV reserve memory for VM
1951 memReserve
= vm_obj
.config
.hardware
.memoryMB
1952 spec
= vim
.vm
.ConfigSpec()
1953 spec
.memoryAllocation
= vim
.ResourceAllocationInfo(reservation
=memReserve
)
1954 task
= vm_obj
.ReconfigVM_Task(spec
=spec
)
1956 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
1957 self
.logger
.info("Reserved memory {} MB for "
1958 "VM VM status: {}".format(str(memReserve
), result
))
1960 self
.logger
.info("Fail to reserved memory {} to VM {}".format(
1961 str(memReserve
), str(vm_obj
)))
1963 self
.logger
.debug("new_vminstance(): starting power on vApp {} ".format(vmname_andid
))
1965 vapp_id
= vapp_resource
.get('id').split(':')[-1]
1966 poweron_task
= self
.power_on_vapp(vapp_id
, vmname_andid
)
1967 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
1968 if result
.get('status') == 'success':
1969 self
.logger
.info("new_vminstance(): Successfully power on "\
1970 "vApp {}".format(vmname_andid
))
1972 self
.logger
.error("new_vminstance(): failed to power on vApp "\
1973 "{}".format(vmname_andid
))
1975 except Exception as exp
:
1976 # it might be a case if specific mandatory entry in dict is empty or some other pyVcloud exception
1977 self
.logger
.error("new_vminstance(): Failed create new vm instance {} with exception {}"
1979 raise vimconn
.vimconnException("new_vminstance(): Failed create new vm instance {} with exception {}"
1982 # check if vApp deployed and if that the case return vApp UUID otherwise -1
1985 while wait_time
<= MAX_WAIT_TIME
:
1987 vapp_resource
= vdc_obj
.get_vapp(vmname_andid
)
1988 vapp
= VApp(self
.client
, resource
=vapp_resource
)
1989 except Exception as exp
:
1990 raise vimconn
.vimconnUnexpectedResponse(
1991 "new_vminstance(): Failed to retrieve vApp {} after creation: Exception:{}"
1992 .format(vmname_andid
, exp
))
1994 #if vapp and vapp.me.deployed:
1995 if vapp
and vapp_resource
.get('deployed') == 'true':
1996 vapp_uuid
= vapp_resource
.get('id').split(':')[-1]
1999 self
.logger
.debug("new_vminstance(): Wait for vApp {} to deploy".format(name
))
2000 time
.sleep(INTERVAL_TIME
)
2002 wait_time
+=INTERVAL_TIME
2004 if vapp_uuid
is not None:
2005 return vapp_uuid
, None
2007 raise vimconn
.vimconnUnexpectedResponse("new_vminstance(): Failed create new vm instance {}".format(name
))
2011 ## based on current discussion
2015 # created: '2016-09-08T11:51:58'
2016 # description: simple-instance.linux1.1
2017 # flavor: ddc6776e-75a9-11e6-ad5f-0800273e724c
2018 # hostId: e836c036-74e7-11e6-b249-0800273e724c
2019 # image: dde30fe6-75a9-11e6-ad5f-0800273e724c
2024 def get_vminstance(self
, vim_vm_uuid
=None):
2025 """Returns the VM instance information from VIM"""
2027 self
.logger
.debug("Client requesting vm instance {} ".format(vim_vm_uuid
))
2029 org
, vdc
= self
.get_vdc_details()
2031 raise vimconn
.vimconnConnectionException(
2032 "Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2034 vm_info_dict
= self
.get_vapp_details_rest(vapp_uuid
=vim_vm_uuid
)
2035 if not vm_info_dict
:
2036 self
.logger
.debug("get_vminstance(): Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
2037 raise vimconn
.vimconnNotFoundException("Failed to get vApp name by UUID {}".format(vim_vm_uuid
))
2039 status_key
= vm_info_dict
['status']
2042 vm_dict
= {'created': vm_info_dict
['created'],
2043 'description': vm_info_dict
['name'],
2044 'status': vcdStatusCode2manoFormat
[int(status_key
)],
2045 'hostId': vm_info_dict
['vmuuid'],
2047 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
2049 if 'interfaces' in vm_info_dict
:
2050 vm_dict
['interfaces'] = vm_info_dict
['interfaces']
2052 vm_dict
['interfaces'] = []
2054 vm_dict
= {'created': '',
2056 'status': vcdStatusCode2manoFormat
[int(-1)],
2057 'hostId': vm_info_dict
['vmuuid'],
2058 'error_msg': "Inconsistency state",
2059 'vim_info': yaml
.safe_dump(vm_info_dict
), 'interfaces': []}
2063 def delete_vminstance(self
, vm__vim_uuid
, created_items
=None):
2064 """Method poweroff and remove VM instance from vcloud director network.
2067 vm__vim_uuid: VM UUID
2070 Returns the instance identifier
2073 self
.logger
.debug("Client requesting delete vm instance {} ".format(vm__vim_uuid
))
2075 org
, vdc
= self
.get_vdc_details()
2076 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2078 self
.logger
.debug("delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(
2080 raise vimconn
.vimconnException(
2081 "delete_vminstance(): Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2084 vapp_name
= self
.get_namebyvappid(vm__vim_uuid
)
2085 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2086 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2087 if vapp_name
is None:
2088 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2089 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2091 self
.logger
.info("Deleting vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
2093 # Delete vApp and wait for status change if task executed and vApp is None.
2096 if vapp_resource
.get('deployed') == 'true':
2097 self
.logger
.info("Powering off vApp {}".format(vapp_name
))
2101 while wait_time
<= MAX_WAIT_TIME
:
2102 power_off_task
= vapp
.power_off()
2103 result
= self
.client
.get_task_monitor().wait_for_success(task
=power_off_task
)
2105 if result
.get('status') == 'success':
2109 self
.logger
.info("Wait for vApp {} to power off".format(vapp_name
))
2110 time
.sleep(INTERVAL_TIME
)
2112 wait_time
+=INTERVAL_TIME
2114 self
.logger
.debug("delete_vminstance(): Failed to power off VM instance {} ".format(vm__vim_uuid
))
2116 self
.logger
.info("delete_vminstance(): Powered off VM instance {} ".format(vm__vim_uuid
))
2119 self
.logger
.info("Undeploy vApp {}".format(vapp_name
))
2122 while wait_time
<= MAX_WAIT_TIME
:
2123 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2125 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2126 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2127 undeploy_task
= vapp
.undeploy()
2129 result
= self
.client
.get_task_monitor().wait_for_success(task
=undeploy_task
)
2130 if result
.get('status') == 'success':
2134 self
.logger
.debug("Wait for vApp {} to undeploy".format(vapp_name
))
2135 time
.sleep(INTERVAL_TIME
)
2137 wait_time
+=INTERVAL_TIME
2140 self
.logger
.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid
))
2143 self
.logger
.info("Start deletion of vApp {} ".format(vapp_name
))
2145 if vapp
is not None:
2149 while wait_time
<= MAX_WAIT_TIME
:
2150 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2152 self
.logger
.debug("delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2153 return -1, "delete_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
)
2155 delete_task
= vdc_obj
.delete_vapp(vapp
.name
, force
=True)
2157 result
= self
.client
.get_task_monitor().wait_for_success(task
=delete_task
)
2158 if result
.get('status') == 'success':
2161 self
.logger
.debug("Wait for vApp {} to delete".format(vapp_name
))
2162 time
.sleep(INTERVAL_TIME
)
2164 wait_time
+=INTERVAL_TIME
2167 self
.logger
.debug("delete_vminstance(): Failed delete uuid {} ".format(vm__vim_uuid
))
2169 self
.logger
.info("Deleted vm instance {} sccessfully".format(vm__vim_uuid
))
2172 self
.logger
.debug(traceback
.format_exc())
2173 raise vimconn
.vimconnException("delete_vminstance(): Failed delete vm instance {}".format(vm__vim_uuid
))
2176 def refresh_vms_status(self
, vm_list
):
2177 """Get the status of the virtual machines and their interfaces/ports
2178 Params: the list of VM identifiers
2179 Returns a dictionary with:
2180 vm_id: #VIM id of this Virtual Machine
2181 status: #Mandatory. Text with one of:
2182 # DELETED (not found at vim)
2183 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2184 # OTHER (Vim reported other status not understood)
2185 # ERROR (VIM indicates an ERROR status)
2186 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2187 # CREATING (on building process), ERROR
2188 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2190 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2191 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2193 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2194 mac_address: #Text format XX:XX:XX:XX:XX:XX
2195 vim_net_id: #network id where this interface is connected
2196 vim_interface_id: #interface/port VIM id
2197 ip_address: #null, or text with IPv4, IPv6 address
2200 self
.logger
.debug("Client requesting refresh vm status for {} ".format(vm_list
))
2202 org
,vdc
= self
.get_vdc_details()
2204 raise vimconn
.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2208 for vmuuid
in vm_list
:
2209 vapp_name
= self
.get_namebyvappid(vmuuid
)
2210 if vapp_name
is not None:
2213 vm_pci_details
= self
.get_vm_pci_details(vmuuid
)
2214 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2215 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2216 the_vapp
= VApp(self
.client
, resource
=vapp_resource
)
2219 for vm
in the_vapp
.get_all_vms():
2220 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2221 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2222 response
= self
.perform_request(req_type
='GET',
2226 if response
.status_code
!= 200:
2227 self
.logger
.error("refresh_vms_status : REST call {} failed reason : {}"\
2228 "status code : {}".format(vm
.get('href'),
2230 response
.status_code
))
2231 raise vimconn
.vimconnException("refresh_vms_status : Failed to get "\
2233 xmlroot
= XmlElementTree
.fromstring(response
.content
)
2235 result
= response
.content
.replace("\n"," ")
2236 hdd_mb
= re
.search('vcloud:capacity="(\d+)"\svcloud:storageProfileOverrideVmDefault=',result
).group(1)
2237 vm_details
['hdd_mb'] = int(hdd_mb
) if hdd_mb
else None
2238 cpus
= re
.search('<rasd:Description>Number of Virtual CPUs</.*?>(\d+)</rasd:VirtualQuantity>',result
).group(1)
2239 vm_details
['cpus'] = int(cpus
) if cpus
else None
2240 memory_mb
= re
.search('<rasd:Description>Memory Size</.*?>(\d+)</rasd:VirtualQuantity>',result
).group(1)
2241 vm_details
['memory_mb'] = int(memory_mb
) if memory_mb
else None
2242 vm_details
['status'] = vcdStatusCode2manoFormat
[int(xmlroot
.get('status'))]
2243 vm_details
['id'] = xmlroot
.get('id')
2244 vm_details
['name'] = xmlroot
.get('name')
2245 vm_info
= [vm_details
]
2247 vm_info
[0].update(vm_pci_details
)
2249 vm_dict
= {'status': vcdStatusCode2manoFormat
[int(vapp_resource
.get('status'))],
2250 'error_msg': vcdStatusCode2manoFormat
[int(vapp_resource
.get('status'))],
2251 'vim_info': yaml
.safe_dump(vm_info
), 'interfaces': []}
2256 networks
= re
.findall('<NetworkConnection needsCustomization=.*?</NetworkConnection>',result
)
2257 for network
in networks
:
2258 mac_s
= re
.search('<MACAddress>(.*?)</MACAddress>',network
)
2259 vm_mac
= mac_s
.group(1) if mac_s
else None
2260 ip_s
= re
.search('<IpAddress>(.*?)</IpAddress>',network
)
2261 vm_ip
= ip_s
.group(1) if ip_s
else None
2264 if not nsx_edge_list
:
2265 nsx_edge_list
= self
.get_edge_details()
2266 if nsx_edge_list
is None:
2267 raise vimconn
.vimconnException("refresh_vms_status:"\
2268 "Failed to get edge details from NSX Manager")
2269 if vm_mac
is not None:
2270 vm_ip
= self
.get_ipaddr_from_NSXedge(nsx_edge_list
, vm_mac
)
2272 network_name
= vm
.NetworkConnectionSection
.NetworkConnection
.get('network')
2273 vm_net_id
= self
.get_network_id_by_name(network_name
)
2274 interface
= {"mac_address": vm_mac
,
2275 "vim_net_id": vm_net_id
,
2276 "vim_interface_id": vm_net_id
,
2277 "ip_address": vm_ip
}
2279 vm_dict
["interfaces"].append(interface
)
2281 # add a vm to vm dict
2282 vms_dict
.setdefault(vmuuid
, vm_dict
)
2283 self
.logger
.debug("refresh_vms_status : vm info {}".format(vm_dict
))
2284 except Exception as exp
:
2285 self
.logger
.debug("Error in response {}".format(exp
))
2286 self
.logger
.debug(traceback
.format_exc())
2291 def get_edge_details(self
):
2292 """Get the NSX edge list from NSX Manager
2293 Returns list of NSX edges
2296 rheaders
= {'Content-Type': 'application/xml'}
2297 nsx_api_url
= '/api/4.0/edges'
2299 self
.logger
.debug("Get edge details from NSX Manager {} {}".format(self
.nsx_manager
, nsx_api_url
))
2302 resp
= requests
.get(self
.nsx_manager
+ nsx_api_url
,
2303 auth
= (self
.nsx_user
, self
.nsx_password
),
2304 verify
= False, headers
= rheaders
)
2305 if resp
.status_code
== requests
.codes
.ok
:
2306 paged_Edge_List
= XmlElementTree
.fromstring(resp
.text
)
2307 for edge_pages
in paged_Edge_List
:
2308 if edge_pages
.tag
== 'edgePage':
2309 for edge_summary
in edge_pages
:
2310 if edge_summary
.tag
== 'pagingInfo':
2311 for element
in edge_summary
:
2312 if element
.tag
== 'totalCount' and element
.text
== '0':
2313 raise vimconn
.vimconnException("get_edge_details: No NSX edges details found: {}"
2314 .format(self
.nsx_manager
))
2316 if edge_summary
.tag
== 'edgeSummary':
2317 for element
in edge_summary
:
2318 if element
.tag
== 'id':
2319 edge_list
.append(element
.text
)
2321 raise vimconn
.vimconnException("get_edge_details: No NSX edge details found: {}"
2322 .format(self
.nsx_manager
))
2325 raise vimconn
.vimconnException("get_edge_details: "\
2326 "No NSX edge details found: {}"
2327 .format(self
.nsx_manager
))
2329 self
.logger
.debug("get_edge_details: Found NSX edges {}".format(edge_list
))
2332 self
.logger
.debug("get_edge_details: "
2333 "Failed to get NSX edge details from NSX Manager: {}"
2334 .format(resp
.content
))
2337 except Exception as exp
:
2338 self
.logger
.debug("get_edge_details: "\
2339 "Failed to get NSX edge details from NSX Manager: {}"
2341 raise vimconn
.vimconnException("get_edge_details: "\
2342 "Failed to get NSX edge details from NSX Manager: {}"
2346 def get_ipaddr_from_NSXedge(self
, nsx_edges
, mac_address
):
2347 """Get IP address details from NSX edges, using the MAC address
2348 PARAMS: nsx_edges : List of NSX edges
2349 mac_address : Find IP address corresponding to this MAC address
2350 Returns: IP address corrresponding to the provided MAC address
2354 rheaders
= {'Content-Type': 'application/xml'}
2356 self
.logger
.debug("get_ipaddr_from_NSXedge: Finding IP addr from NSX edge")
2359 for edge
in nsx_edges
:
2360 nsx_api_url
= '/api/4.0/edges/'+ edge
+'/dhcp/leaseInfo'
2362 resp
= requests
.get(self
.nsx_manager
+ nsx_api_url
,
2363 auth
= (self
.nsx_user
, self
.nsx_password
),
2364 verify
= False, headers
= rheaders
)
2366 if resp
.status_code
== requests
.codes
.ok
:
2367 dhcp_leases
= XmlElementTree
.fromstring(resp
.text
)
2368 for child
in dhcp_leases
:
2369 if child
.tag
== 'dhcpLeaseInfo':
2370 dhcpLeaseInfo
= child
2371 for leaseInfo
in dhcpLeaseInfo
:
2372 for elem
in leaseInfo
:
2373 if (elem
.tag
)=='macAddress':
2374 edge_mac_addr
= elem
.text
2375 if (elem
.tag
)=='ipAddress':
2377 if edge_mac_addr
is not None:
2378 if edge_mac_addr
== mac_address
:
2379 self
.logger
.debug("Found ip addr {} for mac {} at NSX edge {}"
2380 .format(ip_addr
, mac_address
,edge
))
2383 self
.logger
.debug("get_ipaddr_from_NSXedge: "\
2384 "Error occurred while getting DHCP lease info from NSX Manager: {}"
2385 .format(resp
.content
))
2387 self
.logger
.debug("get_ipaddr_from_NSXedge: No IP addr found in any NSX edge")
2390 except XmlElementTree
.ParseError
as Err
:
2391 self
.logger
.debug("ParseError in response from NSX Manager {}".format(Err
.message
), exc_info
=True)
2394 def action_vminstance(self
, vm__vim_uuid
=None, action_dict
=None, created_items
={}):
2395 """Send and action over a VM instance from VIM
2396 Returns the vm_id if the action was successfully sent to the VIM"""
2398 self
.logger
.debug("Received action for vm {} and action dict {}".format(vm__vim_uuid
, action_dict
))
2399 if vm__vim_uuid
is None or action_dict
is None:
2400 raise vimconn
.vimconnException("Invalid request. VM id or action is None.")
2402 org
, vdc
= self
.get_vdc_details()
2404 raise vimconn
.vimconnException("Failed to get a reference of VDC for a tenant {}".format(self
.tenant_name
))
2406 vapp_name
= self
.get_namebyvappid(vm__vim_uuid
)
2407 if vapp_name
is None:
2408 self
.logger
.debug("action_vminstance(): Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2409 raise vimconn
.vimconnException("Failed to get vm by given {} vm uuid".format(vm__vim_uuid
))
2411 self
.logger
.info("Action_vminstance vApp {} and UUID {}".format(vapp_name
, vm__vim_uuid
))
2414 vdc_obj
= VDC(self
.client
, href
=vdc
.get('href'))
2415 vapp_resource
= vdc_obj
.get_vapp(vapp_name
)
2416 vapp
= VApp(self
.client
, resource
=vapp_resource
)
2417 if "start" in action_dict
:
2418 self
.logger
.info("action_vminstance: Power on vApp: {}".format(vapp_name
))
2419 poweron_task
= self
.power_on_vapp(vm__vim_uuid
, vapp_name
)
2420 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
2421 self
.instance_actions_result("start", result
, vapp_name
)
2422 elif "rebuild" in action_dict
:
2423 self
.logger
.info("action_vminstance: Rebuild vApp: {}".format(vapp_name
))
2424 rebuild_task
= vapp
.deploy(power_on
=True)
2425 result
= self
.client
.get_task_monitor().wait_for_success(task
=rebuild_task
)
2426 self
.instance_actions_result("rebuild", result
, vapp_name
)
2427 elif "pause" in action_dict
:
2428 self
.logger
.info("action_vminstance: pause vApp: {}".format(vapp_name
))
2429 pause_task
= vapp
.undeploy(action
='suspend')
2430 result
= self
.client
.get_task_monitor().wait_for_success(task
=pause_task
)
2431 self
.instance_actions_result("pause", result
, vapp_name
)
2432 elif "resume" in action_dict
:
2433 self
.logger
.info("action_vminstance: resume vApp: {}".format(vapp_name
))
2434 poweron_task
= self
.power_on_vapp(vm__vim_uuid
, vapp_name
)
2435 result
= self
.client
.get_task_monitor().wait_for_success(task
=poweron_task
)
2436 self
.instance_actions_result("resume", result
, vapp_name
)
2437 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
2438 action_name
, value
= action_dict
.items()[0]
2440 #action_name , value = list(action_dict.items())[0]
2441 self
.logger
.info("action_vminstance: {} vApp: {}".format(action_name
, vapp_name
))
2442 shutdown_task
= vapp
.shutdown()
2443 result
= self
.client
.get_task_monitor().wait_for_success(task
=shutdown_task
)
2444 if action_name
== "shutdown":
2445 self
.instance_actions_result("shutdown", result
, vapp_name
)
2447 self
.instance_actions_result("shutoff", result
, vapp_name
)
2448 elif "forceOff" in action_dict
:
2449 result
= vapp
.undeploy(action
='powerOff')
2450 self
.instance_actions_result("forceOff", result
, vapp_name
)
2451 elif "reboot" in action_dict
:
2452 self
.logger
.info("action_vminstance: reboot vApp: {}".format(vapp_name
))
2453 reboot_task
= vapp
.reboot()
2454 self
.client
.get_task_monitor().wait_for_success(task
=reboot_task
)
2456 raise vimconn
.vimconnException("action_vminstance: Invalid action {} or action is None.".format(action_dict
))
2458 except Exception as exp
:
2459 self
.logger
.debug("action_vminstance: Failed with Exception {}".format(exp
))
2460 raise vimconn
.vimconnException("action_vminstance: Failed with Exception {}".format(exp
))
2462 def instance_actions_result(self
, action
, result
, vapp_name
):
2463 if result
.get('status') == 'success':
2464 self
.logger
.info("action_vminstance: Sucessfully {} the vApp: {}".format(action
, vapp_name
))
2466 self
.logger
.error("action_vminstance: Failed to {} vApp: {}".format(action
, vapp_name
))
2468 def get_vminstance_console(self
, vm_id
, console_type
="vnc"):
2470 Get a console for the virtual machine
2472 vm_id: uuid of the VM
2473 console_type, can be:
2474 "novnc" (by default), "xvpvnc" for VNC types,
2475 "rdp-html5" for RDP types, "spice-html5" for SPICE types
2476 Returns dict with the console parameters:
2477 protocol: ssh, ftp, http, https, ...
2478 server: usually ip address
2479 port: the http, ssh, ... port
2480 suffix: extra text, e.g. the http path and query string
2482 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2484 # NOT USED METHODS in current version
2486 def host_vim2gui(self
, host
, server_dict
):
2487 """Transform host dictionary from VIM format to GUI format,
2488 and append to the server_dict
2490 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2492 def get_hosts_info(self
):
2493 """Get the information of deployed hosts
2494 Returns the hosts content"""
2495 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2497 def get_hosts(self
, vim_tenant
):
2498 """Get the hosts and deployed instances
2499 Returns the hosts content"""
2500 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2502 def get_processor_rankings(self
):
2503 """Get the processor rankings in the VIM database"""
2504 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2506 def new_host(self
, host_data
):
2507 """Adds a new host to VIM"""
2508 '''Returns status code of the VIM response'''
2509 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2511 def new_external_port(self
, port_data
):
2512 """Adds a external port to VIM"""
2513 '''Returns the port identifier'''
2514 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2516 def new_external_network(self
, net_name
, net_type
):
2517 """Adds a external network to VIM (shared)"""
2518 '''Returns the network identifier'''
2519 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2521 def connect_port_network(self
, port_id
, network_id
, admin
=False):
2522 """Connects a external port to a network"""
2523 '''Returns status code of the VIM response'''
2524 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2526 def new_vminstancefromJSON(self
, vm_data
):
2527 """Adds a VM instance to VIM"""
2528 '''Returns the instance identifier'''
2529 raise vimconn
.vimconnNotImplemented("Should have implemented this")
2531 def get_network_name_by_id(self
, network_uuid
=None):
2532 """Method gets vcloud director network named based on supplied uuid.
2535 network_uuid: network_id
2538 The return network name.
2541 if not network_uuid
:
2545 org_dict
= self
.get_org(self
.org_uuid
)
2546 if 'networks' in org_dict
:
2547 org_network_dict
= org_dict
['networks']
2548 for net_uuid
in org_network_dict
:
2549 if net_uuid
== network_uuid
:
2550 return org_network_dict
[net_uuid
]
2552 self
.logger
.debug("Exception in get_network_name_by_id")
2553 self
.logger
.debug(traceback
.format_exc())
2557 def get_network_id_by_name(self
, network_name
=None):
2558 """Method gets vcloud director network uuid based on supplied name.
2561 network_name: network_name
2563 The return network uuid.
2564 network_uuid: network_id
2567 if not network_name
:
2568 self
.logger
.debug("get_network_id_by_name() : Network name is empty")
2572 org_dict
= self
.get_org(self
.org_uuid
)
2573 if org_dict
and 'networks' in org_dict
:
2574 org_network_dict
= org_dict
['networks']
2575 for net_uuid
,net_name
in org_network_dict
.iteritems():
2577 #for net_uuid,net_name in org_network_dict.items():
2578 if net_name
== network_name
:
2581 except KeyError as exp
:
2582 self
.logger
.debug("get_network_id_by_name() : KeyError- {} ".format(exp
))
2586 def list_org_action(self
):
2588 Method leverages vCloud director and query for available organization for particular user
2591 vca - is active VCA connection.
2592 vdc_name - is a vdc name that will be used to query vms action
2595 The return XML respond
2597 url_list
= [self
.url
, '/api/org']
2598 vm_list_rest_call
= ''.join(url_list
)
2600 if self
.client
._session
:
2601 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2602 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2604 response
= self
.perform_request(req_type
='GET',
2605 url
=vm_list_rest_call
,
2608 if response
.status_code
== 403:
2609 response
= self
.retry_rest('GET', vm_list_rest_call
)
2611 if response
.status_code
== requests
.codes
.ok
:
2612 return response
.content
2616 def get_org_action(self
, org_uuid
=None):
2618 Method leverages vCloud director and retrieve available object for organization.
2621 org_uuid - vCD organization uuid
2622 self.client - is active connection.
2625 The return XML respond
2628 if org_uuid
is None:
2631 url_list
= [self
.url
, '/api/org/', org_uuid
]
2632 vm_list_rest_call
= ''.join(url_list
)
2634 if self
.client
._session
:
2635 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2636 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2638 #response = requests.get(vm_list_rest_call, headers=headers, verify=False)
2639 response
= self
.perform_request(req_type
='GET',
2640 url
=vm_list_rest_call
,
2642 if response
.status_code
== 403:
2643 response
= self
.retry_rest('GET', vm_list_rest_call
)
2645 if response
.status_code
== requests
.codes
.ok
:
2646 return response
.content
2649 def get_org(self
, org_uuid
=None):
2651 Method retrieves available organization in vCloud Director
2654 org_uuid - is a organization uuid.
2657 The return dictionary with following key
2658 "network" - for network list under the org
2659 "catalogs" - for network list under the org
2660 "vdcs" - for vdc list under org
2665 if org_uuid
is None:
2668 content
= self
.get_org_action(org_uuid
=org_uuid
)
2673 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2674 for child
in vm_list_xmlroot
:
2675 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.vdc+xml':
2676 vdc_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2677 org_dict
['vdcs'] = vdc_list
2678 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.orgNetwork+xml':
2679 network_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2680 org_dict
['networks'] = network_list
2681 if child
.attrib
['type'] == 'application/vnd.vmware.vcloud.catalog+xml':
2682 catalog_list
[child
.attrib
['href'].split("/")[-1:][0]] = child
.attrib
['name']
2683 org_dict
['catalogs'] = catalog_list
2689 def get_org_list(self
):
2691 Method retrieves available organization in vCloud Director
2694 vca - is active VCA connection.
2697 The return dictionary and key for each entry VDC UUID
2702 content
= self
.list_org_action()
2704 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2705 for vm_xml
in vm_list_xmlroot
:
2706 if vm_xml
.tag
.split("}")[1] == 'Org':
2707 org_uuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2708 org_dict
[org_uuid
[0]] = vm_xml
.attrib
['name']
2714 def vms_view_action(self
, vdc_name
=None):
2715 """ Method leverages vCloud director vms query call
2718 vca - is active VCA connection.
2719 vdc_name - is a vdc name that will be used to query vms action
2722 The return XML respond
2724 vca
= self
.connect()
2725 if vdc_name
is None:
2728 url_list
= [vca
.host
, '/api/vms/query']
2729 vm_list_rest_call
= ''.join(url_list
)
2731 if not (not vca
.vcloud_session
or not vca
.vcloud_session
.organization
):
2732 refs
= filter(lambda ref
: ref
.name
== vdc_name
and ref
.type_
== 'application/vnd.vmware.vcloud.vdc+xml',
2733 vca
.vcloud_session
.organization
.Link
)
2735 #refs = [ref for ref in vca.vcloud_session.organization.Link if ref.name == vdc_name and\
2736 # ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml']
2738 response
= Http
.get(url
=vm_list_rest_call
,
2739 headers
=vca
.vcloud_session
.get_vcloud_headers(),
2742 if response
.status_code
== requests
.codes
.ok
:
2743 return response
.content
2747 def get_vapp_list(self
, vdc_name
=None):
2749 Method retrieves vApp list deployed vCloud director and returns a dictionary
2750 contains a list of all vapp deployed for queried VDC.
2751 The key for a dictionary is vApp UUID
2755 vca - is active VCA connection.
2756 vdc_name - is a vdc name that will be used to query vms action
2759 The return dictionary and key for each entry vapp UUID
2763 if vdc_name
is None:
2766 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2768 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2769 for vm_xml
in vm_list_xmlroot
:
2770 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
2771 if vm_xml
.attrib
['isVAppTemplate'] == 'true':
2772 rawuuid
= vm_xml
.attrib
['container'].split('/')[-1:]
2773 if 'vappTemplate-' in rawuuid
[0]:
2774 # vm in format vappTemplate-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
2775 # vm and use raw UUID as key
2776 vapp_dict
[rawuuid
[0][13:]] = vm_xml
.attrib
2782 def get_vm_list(self
, vdc_name
=None):
2784 Method retrieves VM's list deployed vCloud director. It returns a dictionary
2785 contains a list of all VM's deployed for queried VDC.
2786 The key for a dictionary is VM UUID
2790 vca - is active VCA connection.
2791 vdc_name - is a vdc name that will be used to query vms action
2794 The return dictionary and key for each entry vapp UUID
2798 if vdc_name
is None:
2801 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2803 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2804 for vm_xml
in vm_list_xmlroot
:
2805 if vm_xml
.tag
.split("}")[1] == 'VMRecord':
2806 if vm_xml
.attrib
['isVAppTemplate'] == 'false':
2807 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2808 if 'vm-' in rawuuid
[0]:
2809 # vm in format vm-e63d40e7-4ff5-4c6d-851f-96c1e4da86a5 we remove
2810 # vm and use raw UUID as key
2811 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2817 def get_vapp(self
, vdc_name
=None, vapp_name
=None, isuuid
=False):
2819 Method retrieves VM deployed vCloud director. It returns VM attribute as dictionary
2820 contains a list of all VM's deployed for queried VDC.
2821 The key for a dictionary is VM UUID
2825 vca - is active VCA connection.
2826 vdc_name - is a vdc name that will be used to query vms action
2829 The return dictionary and key for each entry vapp UUID
2832 vca
= self
.connect()
2834 raise vimconn
.vimconnConnectionException("self.connect() is failed")
2836 if vdc_name
is None:
2839 content
= self
.vms_view_action(vdc_name
=vdc_name
)
2841 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2842 for vm_xml
in vm_list_xmlroot
:
2843 if vm_xml
.tag
.split("}")[1] == 'VMRecord' and vm_xml
.attrib
['isVAppTemplate'] == 'false':
2844 # lookup done by UUID
2846 if vapp_name
in vm_xml
.attrib
['container']:
2847 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2848 if 'vm-' in rawuuid
[0]:
2849 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2851 # lookup done by Name
2853 if vapp_name
in vm_xml
.attrib
['name']:
2854 rawuuid
= vm_xml
.attrib
['href'].split('/')[-1:]
2855 if 'vm-' in rawuuid
[0]:
2856 vm_dict
[rawuuid
[0][3:]] = vm_xml
.attrib
2863 def get_network_action(self
, network_uuid
=None):
2865 Method leverages vCloud director and query network based on network uuid
2868 vca - is active VCA connection.
2869 network_uuid - is a network uuid
2872 The return XML respond
2875 if network_uuid
is None:
2878 url_list
= [self
.url
, '/api/network/', network_uuid
]
2879 vm_list_rest_call
= ''.join(url_list
)
2881 if self
.client
._session
:
2882 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2883 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
2885 response
= self
.perform_request(req_type
='GET',
2886 url
=vm_list_rest_call
,
2888 #Retry login if session expired & retry sending request
2889 if response
.status_code
== 403:
2890 response
= self
.retry_rest('GET', vm_list_rest_call
)
2892 if response
.status_code
== requests
.codes
.ok
:
2893 return response
.content
2897 def get_vcd_network(self
, network_uuid
=None):
2899 Method retrieves available network from vCloud Director
2902 network_uuid - is VCD network UUID
2904 Each element serialized as key : value pair
2906 Following keys available for access. network_configuration['Gateway'}
2910 <IsInherited>true</IsInherited>
2911 <Gateway>172.16.252.100</Gateway>
2912 <Netmask>255.255.255.0</Netmask>
2913 <Dns1>172.16.254.201</Dns1>
2914 <Dns2>172.16.254.202</Dns2>
2915 <DnsSuffix>vmwarelab.edu</DnsSuffix>
2916 <IsEnabled>true</IsEnabled>
2919 <StartAddress>172.16.252.1</StartAddress>
2920 <EndAddress>172.16.252.99</EndAddress>
2925 <FenceMode>bridged</FenceMode>
2928 The return dictionary and key for each entry vapp UUID
2931 network_configuration
= {}
2932 if network_uuid
is None:
2936 content
= self
.get_network_action(network_uuid
=network_uuid
)
2937 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
2939 network_configuration
['status'] = vm_list_xmlroot
.get("status")
2940 network_configuration
['name'] = vm_list_xmlroot
.get("name")
2941 network_configuration
['uuid'] = vm_list_xmlroot
.get("id").split(":")[3]
2943 for child
in vm_list_xmlroot
:
2944 if child
.tag
.split("}")[1] == 'IsShared':
2945 network_configuration
['isShared'] = child
.text
.strip()
2946 if child
.tag
.split("}")[1] == 'Configuration':
2947 for configuration
in child
.iter():
2948 tagKey
= configuration
.tag
.split("}")[1].strip()
2950 network_configuration
[tagKey
] = configuration
.text
.strip()
2951 return network_configuration
2952 except Exception as exp
:
2953 self
.logger
.debug("get_vcd_network: Failed with Exception {}".format(exp
))
2954 raise vimconn
.vimconnException("get_vcd_network: Failed with Exception {}".format(exp
))
2956 return network_configuration
2958 def delete_network_action(self
, network_uuid
=None):
2960 Method delete given network from vCloud director
2963 network_uuid - is a network uuid that client wish to delete
2966 The return None or XML respond or false
2968 client
= self
.connect_as_admin()
2970 raise vimconn
.vimconnConnectionException("Failed to connect vCD as admin")
2971 if network_uuid
is None:
2974 url_list
= [self
.url
, '/api/admin/network/', network_uuid
]
2975 vm_list_rest_call
= ''.join(url_list
)
2978 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
2979 'x-vcloud-authorization': client
._session
.headers
['x-vcloud-authorization']}
2980 response
= self
.perform_request(req_type
='DELETE',
2981 url
=vm_list_rest_call
,
2983 if response
.status_code
== 202:
2988 def create_network(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
2989 ip_profile
=None, isshared
='true'):
2991 Method create network in vCloud director
2994 network_name - is network name to be created.
2995 net_type - can be 'bridge','data','ptp','mgmt'.
2996 ip_profile is a dict containing the IP parameters of the network
2997 isshared - is a boolean
2998 parent_network_uuid - is parent provider vdc network that will be used for mapping.
2999 It optional attribute. by default if no parent network indicate the first available will be used.
3002 The return network uuid or return None
3005 new_network_name
= [network_name
, '-', str(uuid
.uuid4())]
3006 content
= self
.create_network_rest(network_name
=''.join(new_network_name
),
3007 ip_profile
=ip_profile
,
3009 parent_network_uuid
=parent_network_uuid
,
3012 self
.logger
.debug("Failed create network {}.".format(network_name
))
3016 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
3017 vcd_uuid
= vm_list_xmlroot
.get('id').split(":")
3018 if len(vcd_uuid
) == 4:
3019 self
.logger
.info("Created new network name: {} uuid: {}".format(network_name
, vcd_uuid
[3]))
3022 self
.logger
.debug("Failed create network {}".format(network_name
))
3025 def create_network_rest(self
, network_name
=None, net_type
='bridge', parent_network_uuid
=None,
3026 ip_profile
=None, isshared
='true'):
3028 Method create network in vCloud director
3031 network_name - is network name to be created.
3032 net_type - can be 'bridge','data','ptp','mgmt'.
3033 ip_profile is a dict containing the IP parameters of the network
3034 isshared - is a boolean
3035 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3036 It optional attribute. by default if no parent network indicate the first available will be used.
3039 The return network uuid or return None
3041 client_as_admin
= self
.connect_as_admin()
3042 if not client_as_admin
:
3043 raise vimconn
.vimconnConnectionException("Failed to connect vCD.")
3044 if network_name
is None:
3047 url_list
= [self
.url
, '/api/admin/vdc/', self
.tenant_id
]
3048 vm_list_rest_call
= ''.join(url_list
)
3050 if client_as_admin
._session
:
3051 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3052 'x-vcloud-authorization': client_as_admin
._session
.headers
['x-vcloud-authorization']}
3054 response
= self
.perform_request(req_type
='GET',
3055 url
=vm_list_rest_call
,
3058 provider_network
= None
3059 available_networks
= None
3060 add_vdc_rest_url
= None
3062 if response
.status_code
!= requests
.codes
.ok
:
3063 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3064 response
.status_code
))
3068 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3069 for child
in vm_list_xmlroot
:
3070 if child
.tag
.split("}")[1] == 'ProviderVdcReference':
3071 provider_network
= child
.attrib
.get('href')
3072 # application/vnd.vmware.admin.providervdc+xml
3073 if child
.tag
.split("}")[1] == 'Link':
3074 if child
.attrib
.get('type') == 'application/vnd.vmware.vcloud.orgVdcNetwork+xml' \
3075 and child
.attrib
.get('rel') == 'add':
3076 add_vdc_rest_url
= child
.attrib
.get('href')
3078 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3079 self
.logger
.debug("Respond body {}".format(response
.content
))
3082 # find pvdc provided available network
3083 response
= self
.perform_request(req_type
='GET',
3084 url
=provider_network
,
3086 if response
.status_code
!= requests
.codes
.ok
:
3087 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3088 response
.status_code
))
3091 if parent_network_uuid
is None:
3093 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3094 for child
in vm_list_xmlroot
.iter():
3095 if child
.tag
.split("}")[1] == 'AvailableNetworks':
3096 for networks
in child
.iter():
3097 # application/vnd.vmware.admin.network+xml
3098 if networks
.attrib
.get('href') is not None:
3099 available_networks
= networks
.attrib
.get('href')
3105 #Configure IP profile of the network
3106 ip_profile
= ip_profile
if ip_profile
is not None else DEFAULT_IP_PROFILE
3108 if 'subnet_address' not in ip_profile
or ip_profile
['subnet_address'] is None:
3109 subnet_rand
= random
.randint(0, 255)
3110 ip_base
= "192.168.{}.".format(subnet_rand
)
3111 ip_profile
['subnet_address'] = ip_base
+ "0/24"
3113 ip_base
= ip_profile
['subnet_address'].rsplit('.',1)[0] + '.'
3115 if 'gateway_address' not in ip_profile
or ip_profile
['gateway_address'] is None:
3116 ip_profile
['gateway_address']=ip_base
+ "1"
3117 if 'dhcp_count' not in ip_profile
or ip_profile
['dhcp_count'] is None:
3118 ip_profile
['dhcp_count']=DEFAULT_IP_PROFILE
['dhcp_count']
3119 if 'dhcp_enabled' not in ip_profile
or ip_profile
['dhcp_enabled'] is None:
3120 ip_profile
['dhcp_enabled']=DEFAULT_IP_PROFILE
['dhcp_enabled']
3121 if 'dhcp_start_address' not in ip_profile
or ip_profile
['dhcp_start_address'] is None:
3122 ip_profile
['dhcp_start_address']=ip_base
+ "3"
3123 if 'ip_version' not in ip_profile
or ip_profile
['ip_version'] is None:
3124 ip_profile
['ip_version']=DEFAULT_IP_PROFILE
['ip_version']
3125 if 'dns_address' not in ip_profile
or ip_profile
['dns_address'] is None:
3126 ip_profile
['dns_address']=ip_base
+ "2"
3128 gateway_address
=ip_profile
['gateway_address']
3129 dhcp_count
=int(ip_profile
['dhcp_count'])
3130 subnet_address
=self
.convert_cidr_to_netmask(ip_profile
['subnet_address'])
3132 if ip_profile
['dhcp_enabled']==True:
3135 dhcp_enabled
='false'
3136 dhcp_start_address
=ip_profile
['dhcp_start_address']
3138 #derive dhcp_end_address from dhcp_start_address & dhcp_count
3139 end_ip_int
= int(netaddr
.IPAddress(dhcp_start_address
))
3140 end_ip_int
+= dhcp_count
- 1
3141 dhcp_end_address
= str(netaddr
.IPAddress(end_ip_int
))
3143 ip_version
=ip_profile
['ip_version']
3144 dns_address
=ip_profile
['dns_address']
3145 except KeyError as exp
:
3146 self
.logger
.debug("Create Network REST: Key error {}".format(exp
))
3147 raise vimconn
.vimconnException("Create Network REST: Key error{}".format(exp
))
3149 # either use client provided UUID or search for a first available
3150 # if both are not defined we return none
3151 if parent_network_uuid
is not None:
3152 url_list
= [self
.url
, '/api/admin/network/', parent_network_uuid
]
3153 add_vdc_rest_url
= ''.join(url_list
)
3155 #Creating all networks as Direct Org VDC type networks.
3156 #Unused in case of Underlay (data/ptp) network interface.
3157 fence_mode
="bridged"
3158 is_inherited
='false'
3159 dns_list
= dns_address
.split(";")
3162 if len(dns_list
) >= 2:
3163 dns2_text
= "\n <Dns2>{}</Dns2>\n".format(dns_list
[1])
3164 data
= """ <OrgVdcNetwork name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
3165 <Description>Openmano created</Description>
3169 <IsInherited>{1:s}</IsInherited>
3170 <Gateway>{2:s}</Gateway>
3171 <Netmask>{3:s}</Netmask>
3172 <Dns1>{4:s}</Dns1>{5:s}
3173 <IsEnabled>{6:s}</IsEnabled>
3176 <StartAddress>{7:s}</StartAddress>
3177 <EndAddress>{8:s}</EndAddress>
3182 <ParentNetwork href="{9:s}"/>
3183 <FenceMode>{10:s}</FenceMode>
3185 <IsShared>{11:s}</IsShared>
3186 </OrgVdcNetwork> """.format(escape(network_name
), is_inherited
, gateway_address
,
3187 subnet_address
, dns1
, dns2_text
, dhcp_enabled
,
3188 dhcp_start_address
, dhcp_end_address
, available_networks
,
3189 fence_mode
, isshared
)
3191 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'
3193 response
= self
.perform_request(req_type
='POST',
3194 url
=add_vdc_rest_url
,
3198 if response
.status_code
!= 201:
3199 self
.logger
.debug("Create Network POST REST API call failed. Return status code {}, Response content: {}"
3200 .format(response
.status_code
,response
.content
))
3202 network_task
= self
.get_task_from_response(response
.content
)
3203 self
.logger
.debug("Create Network REST : Waiting for Network creation complete")
3205 result
= self
.client
.get_task_monitor().wait_for_success(task
=network_task
)
3206 if result
.get('status') == 'success':
3207 return response
.content
3209 self
.logger
.debug("create_network_rest task failed. Network Create response : {}"
3210 .format(response
.content
))
3211 except Exception as exp
:
3212 self
.logger
.debug("create_network_rest : Exception : {} ".format(exp
))
3216 def convert_cidr_to_netmask(self
, cidr_ip
=None):
3218 Method sets convert CIDR netmask address to normal IP format
3220 cidr_ip : CIDR IP address
3222 netmask : Converted netmask
3224 if cidr_ip
is not None:
3226 network
, net_bits
= cidr_ip
.split('/')
3227 netmask
= socket
.inet_ntoa(struct
.pack(">I", (0xffffffff << (32 - int(net_bits
))) & 0xffffffff))
3233 def get_provider_rest(self
, vca
=None):
3235 Method gets provider vdc view from vcloud director
3238 network_name - is network name to be created.
3239 parent_network_uuid - is parent provider vdc network that will be used for mapping.
3240 It optional attribute. by default if no parent network indicate the first available will be used.
3243 The return xml content of respond or None
3246 url_list
= [self
.url
, '/api/admin']
3248 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3249 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3250 response
= self
.perform_request(req_type
='GET',
3251 url
=''.join(url_list
),
3254 if response
.status_code
== requests
.codes
.ok
:
3255 return response
.content
3258 def create_vdc(self
, vdc_name
=None):
3262 xml_content
= self
.create_vdc_from_tmpl_rest(vdc_name
=vdc_name
)
3263 if xml_content
is not None:
3265 task_resp_xmlroot
= XmlElementTree
.fromstring(xml_content
)
3266 for child
in task_resp_xmlroot
:
3267 if child
.tag
.split("}")[1] == 'Owner':
3268 vdc_id
= child
.attrib
.get('href').split("/")[-1]
3269 vdc_dict
[vdc_id
] = task_resp_xmlroot
.get('href')
3272 self
.logger
.debug("Respond body {}".format(xml_content
))
3276 def create_vdc_from_tmpl_rest(self
, vdc_name
=None):
3278 Method create vdc in vCloud director based on VDC template.
3279 it uses pre-defined template.
3282 vdc_name - name of a new vdc.
3285 The return xml content of respond or None
3287 # pre-requesite atleast one vdc template should be available in vCD
3288 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
3289 vca
= self
.connect_as_admin()
3291 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
3292 if vdc_name
is None:
3295 url_list
= [self
.url
, '/api/vdcTemplates']
3296 vm_list_rest_call
= ''.join(url_list
)
3298 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3299 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
3300 response
= self
.perform_request(req_type
='GET',
3301 url
=vm_list_rest_call
,
3304 # container url to a template
3305 vdc_template_ref
= None
3307 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3308 for child
in vm_list_xmlroot
:
3309 # application/vnd.vmware.admin.providervdc+xml
3310 # we need find a template from witch we instantiate VDC
3311 if child
.tag
.split("}")[1] == 'VdcTemplate':
3312 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.vdcTemplate+xml':
3313 vdc_template_ref
= child
.attrib
.get('href')
3315 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3316 self
.logger
.debug("Respond body {}".format(response
.content
))
3319 # if we didn't found required pre defined template we return None
3320 if vdc_template_ref
is None:
3325 url_list
= [self
.url
, '/api/org/', self
.org_uuid
, '/action/instantiate']
3326 vm_list_rest_call
= ''.join(url_list
)
3327 data
= """<InstantiateVdcTemplateParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5">
3328 <Source href="{1:s}"></Source>
3329 <Description>opnemano</Description>
3330 </InstantiateVdcTemplateParams>""".format(vdc_name
, vdc_template_ref
)
3332 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.instantiateVdcTemplateParams+xml'
3334 response
= self
.perform_request(req_type
='POST',
3335 url
=vm_list_rest_call
,
3339 vdc_task
= self
.get_task_from_response(response
.content
)
3340 self
.client
.get_task_monitor().wait_for_success(task
=vdc_task
)
3342 # if we all ok we respond with content otherwise by default None
3343 if response
.status_code
>= 200 and response
.status_code
< 300:
3344 return response
.content
3347 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3348 self
.logger
.debug("Respond body {}".format(response
.content
))
3352 def create_vdc_rest(self
, vdc_name
=None):
3354 Method create network in vCloud director
3357 vdc_name - vdc name to be created
3362 self
.logger
.info("Creating new vdc {}".format(vdc_name
))
3364 vca
= self
.connect_as_admin()
3366 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
3367 if vdc_name
is None:
3370 url_list
= [self
.url
, '/api/admin/org/', self
.org_uuid
]
3371 vm_list_rest_call
= ''.join(url_list
)
3374 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3375 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3376 response
= self
.perform_request(req_type
='GET',
3377 url
=vm_list_rest_call
,
3380 provider_vdc_ref
= None
3381 add_vdc_rest_url
= None
3382 available_networks
= None
3384 if response
.status_code
!= requests
.codes
.ok
:
3385 self
.logger
.debug("REST API call {} failed. Return status code {}".format(vm_list_rest_call
,
3386 response
.status_code
))
3390 vm_list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
3391 for child
in vm_list_xmlroot
:
3392 # application/vnd.vmware.admin.providervdc+xml
3393 if child
.tag
.split("}")[1] == 'Link':
3394 if child
.attrib
.get('type') == 'application/vnd.vmware.admin.createVdcParams+xml' \
3395 and child
.attrib
.get('rel') == 'add':
3396 add_vdc_rest_url
= child
.attrib
.get('href')
3398 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3399 self
.logger
.debug("Respond body {}".format(response
.content
))
3402 response
= self
.get_provider_rest(vca
=vca
)
3404 vm_list_xmlroot
= XmlElementTree
.fromstring(response
)
3405 for child
in vm_list_xmlroot
:
3406 if child
.tag
.split("}")[1] == 'ProviderVdcReferences':
3407 for sub_child
in child
:
3408 provider_vdc_ref
= sub_child
.attrib
.get('href')
3410 self
.logger
.debug("Failed parse respond for rest api call {}".format(vm_list_rest_call
))
3411 self
.logger
.debug("Respond body {}".format(response
))
3414 if add_vdc_rest_url
is not None and provider_vdc_ref
is not None:
3415 data
= """ <CreateVdcParams name="{0:s}" xmlns="http://www.vmware.com/vcloud/v1.5"><Description>{1:s}</Description>
3416 <AllocationModel>ReservationPool</AllocationModel>
3417 <ComputeCapacity><Cpu><Units>MHz</Units><Allocated>2048</Allocated><Limit>2048</Limit></Cpu>
3418 <Memory><Units>MB</Units><Allocated>2048</Allocated><Limit>2048</Limit></Memory>
3419 </ComputeCapacity><NicQuota>0</NicQuota><NetworkQuota>100</NetworkQuota>
3420 <VdcStorageProfile><Enabled>true</Enabled><Units>MB</Units><Limit>20480</Limit><Default>true</Default></VdcStorageProfile>
3421 <ProviderVdcReference
3422 name="Main Provider"
3424 <UsesFastProvisioning>true</UsesFastProvisioning></CreateVdcParams>""".format(escape(vdc_name
),
3428 headers
['Content-Type'] = 'application/vnd.vmware.admin.createVdcParams+xml'
3430 response
= self
.perform_request(req_type
='POST',
3431 url
=add_vdc_rest_url
,
3435 # if we all ok we respond with content otherwise by default None
3436 if response
.status_code
== 201:
3437 return response
.content
3440 def get_vapp_details_rest(self
, vapp_uuid
=None, need_admin_access
=False):
3442 Method retrieve vapp detail from vCloud director
3445 vapp_uuid - is vapp identifier.
3448 The return network uuid or return None
3454 if need_admin_access
:
3455 vca
= self
.connect_as_admin()
3460 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
3461 if vapp_uuid
is None:
3464 url_list
= [self
.url
, '/api/vApp/vapp-', vapp_uuid
]
3465 get_vapp_restcall
= ''.join(url_list
)
3468 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3469 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
3470 response
= self
.perform_request(req_type
='GET',
3471 url
=get_vapp_restcall
,
3474 if response
.status_code
== 403:
3475 if need_admin_access
== False:
3476 response
= self
.retry_rest('GET', get_vapp_restcall
)
3478 if response
.status_code
!= requests
.codes
.ok
:
3479 self
.logger
.debug("REST API call {} failed. Return status code {}".format(get_vapp_restcall
,
3480 response
.status_code
))
3481 return parsed_respond
3484 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
3485 parsed_respond
['ovfDescriptorUploaded'] = xmlroot_respond
.attrib
['ovfDescriptorUploaded']
3487 namespaces
= {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
3488 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
3489 'vmw': 'http://www.vmware.com/schema/ovf',
3490 'vm': 'http://www.vmware.com/vcloud/v1.5',
3491 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
3492 "vmext":"http://www.vmware.com/vcloud/extension/v1.5",
3493 "xmlns":"http://www.vmware.com/vcloud/v1.5"
3496 created_section
= xmlroot_respond
.find('vm:DateCreated', namespaces
)
3497 if created_section
is not None:
3498 parsed_respond
['created'] = created_section
.text
3500 network_section
= xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig', namespaces
)
3501 if network_section
is not None and 'networkName' in network_section
.attrib
:
3502 parsed_respond
['networkname'] = network_section
.attrib
['networkName']
3504 ipscopes_section
= \
3505 xmlroot_respond
.find('vm:NetworkConfigSection/vm:NetworkConfig/vm:Configuration/vm:IpScopes',
3507 if ipscopes_section
is not None:
3508 for ipscope
in ipscopes_section
:
3509 for scope
in ipscope
:
3510 tag_key
= scope
.tag
.split("}")[1]
3511 if tag_key
== 'IpRanges':
3512 ip_ranges
= scope
.getchildren()
3513 for ipblock
in ip_ranges
:
3514 for block
in ipblock
:
3515 parsed_respond
[block
.tag
.split("}")[1]] = block
.text
3517 parsed_respond
[tag_key
] = scope
.text
3519 # parse children section for other attrib
3520 children_section
= xmlroot_respond
.find('vm:Children/', namespaces
)
3521 if children_section
is not None:
3522 parsed_respond
['name'] = children_section
.attrib
['name']
3523 parsed_respond
['nestedHypervisorEnabled'] = children_section
.attrib
['nestedHypervisorEnabled'] \
3524 if "nestedHypervisorEnabled" in children_section
.attrib
else None
3525 parsed_respond
['deployed'] = children_section
.attrib
['deployed']
3526 parsed_respond
['status'] = children_section
.attrib
['status']
3527 parsed_respond
['vmuuid'] = children_section
.attrib
['id'].split(":")[-1]
3528 network_adapter
= children_section
.find('vm:NetworkConnectionSection', namespaces
)
3530 for adapters
in network_adapter
:
3531 adapter_key
= adapters
.tag
.split("}")[1]
3532 if adapter_key
== 'PrimaryNetworkConnectionIndex':
3533 parsed_respond
['primarynetwork'] = adapters
.text
3534 if adapter_key
== 'NetworkConnection':
3536 if 'network' in adapters
.attrib
:
3537 vnic
['network'] = adapters
.attrib
['network']
3538 for adapter
in adapters
:
3539 setting_key
= adapter
.tag
.split("}")[1]
3540 vnic
[setting_key
] = adapter
.text
3541 nic_list
.append(vnic
)
3543 for link
in children_section
:
3544 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
3545 if link
.attrib
['rel'] == 'screen:acquireTicket':
3546 parsed_respond
['acquireTicket'] = link
.attrib
3547 if link
.attrib
['rel'] == 'screen:acquireMksTicket':
3548 parsed_respond
['acquireMksTicket'] = link
.attrib
3550 parsed_respond
['interfaces'] = nic_list
3551 vCloud_extension_section
= children_section
.find('xmlns:VCloudExtension', namespaces
)
3552 if vCloud_extension_section
is not None:
3553 vm_vcenter_info
= {}
3554 vim_info
= vCloud_extension_section
.find('vmext:VmVimInfo', namespaces
)
3555 vmext
= vim_info
.find('vmext:VmVimObjectRef', namespaces
)
3556 if vmext
is not None:
3557 vm_vcenter_info
["vm_moref_id"] = vmext
.find('vmext:MoRef', namespaces
).text
3558 parsed_respond
["vm_vcenter_info"]= vm_vcenter_info
3560 virtual_hardware_section
= children_section
.find('ovf:VirtualHardwareSection', namespaces
)
3561 vm_virtual_hardware_info
= {}
3562 if virtual_hardware_section
is not None:
3563 for item
in virtual_hardware_section
.iterfind('ovf:Item',namespaces
):
3564 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
3565 disk_size
= item
.find("rasd:HostResource" ,namespaces
3566 ).attrib
["{"+namespaces
['vm']+"}capacity"]
3568 vm_virtual_hardware_info
["disk_size"]= disk_size
3571 for link
in virtual_hardware_section
:
3572 if link
.tag
.split("}")[1] == 'Link' and 'rel' in link
.attrib
:
3573 if link
.attrib
['rel'] == 'edit' and link
.attrib
['href'].endswith("/disks"):
3574 vm_virtual_hardware_info
["disk_edit_href"] = link
.attrib
['href']
3577 parsed_respond
["vm_virtual_hardware"]= vm_virtual_hardware_info
3578 except Exception as exp
:
3579 self
.logger
.info("Error occurred calling rest api for getting vApp details {}".format(exp
))
3580 return parsed_respond
3582 def acquire_console(self
, vm_uuid
=None):
3586 if self
.client
._session
:
3587 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3588 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3589 vm_dict
= self
.get_vapp_details_rest(vapp_uuid
=vm_uuid
)
3590 console_dict
= vm_dict
['acquireTicket']
3591 console_rest_call
= console_dict
['href']
3593 response
= self
.perform_request(req_type
='POST',
3594 url
=console_rest_call
,
3597 if response
.status_code
== 403:
3598 response
= self
.retry_rest('POST', console_rest_call
)
3600 if response
.status_code
== requests
.codes
.ok
:
3601 return response
.content
3605 def modify_vm_disk(self
, vapp_uuid
, flavor_disk
):
3607 Method retrieve vm disk details
3610 vapp_uuid - is vapp identifier.
3611 flavor_disk - disk size as specified in VNFD (flavor)
3614 The return network uuid or return None
3618 #Flavor disk is in GB convert it into MB
3619 flavor_disk
= int(flavor_disk
) * 1024
3620 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
3622 vm_name
= vm_details
["name"]
3623 self
.logger
.info("VM: {} flavor_disk :{}".format(vm_name
, flavor_disk
))
3625 if vm_details
and "vm_virtual_hardware" in vm_details
:
3626 vm_disk
= int(vm_details
["vm_virtual_hardware"]["disk_size"])
3627 disk_edit_href
= vm_details
["vm_virtual_hardware"]["disk_edit_href"]
3629 self
.logger
.info("VM: {} VM_disk :{}".format(vm_name
, vm_disk
))
3631 if flavor_disk
> vm_disk
:
3632 status
= self
.modify_vm_disk_rest(disk_edit_href
,flavor_disk
)
3633 self
.logger
.info("Modify disk of VM {} from {} to {} MB".format(vm_name
,
3634 vm_disk
, flavor_disk
))
3637 self
.logger
.info("No need to modify disk of VM {}".format(vm_name
))
3640 except Exception as exp
:
3641 self
.logger
.info("Error occurred while modifing disk size {}".format(exp
))
3644 def modify_vm_disk_rest(self
, disk_href
, disk_size
):
3646 Method retrieve modify vm disk size
3649 disk_href - vCD API URL to GET and PUT disk data
3650 disk_size - disk size as specified in VNFD (flavor)
3653 The return network uuid or return None
3655 if disk_href
is None or disk_size
is None:
3658 if self
.client
._session
:
3659 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
3660 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
3661 response
= self
.perform_request(req_type
='GET',
3665 if response
.status_code
== 403:
3666 response
= self
.retry_rest('GET', disk_href
)
3668 if response
.status_code
!= requests
.codes
.ok
:
3669 self
.logger
.debug("GET REST API call {} failed. Return status code {}".format(disk_href
,
3670 response
.status_code
))
3673 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
3674 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
3676 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
3677 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
3679 for item
in lxmlroot_respond
.iterfind('xmlns:Item',namespaces
):
3680 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
3681 disk_item
= item
.find("rasd:HostResource" ,namespaces
)
3682 if disk_item
is not None:
3683 disk_item
.attrib
["{"+namespaces
['xmlns']+"}capacity"] = str(disk_size
)
3686 data
= lxmlElementTree
.tostring(lxmlroot_respond
, encoding
='utf8', method
='xml',
3687 xml_declaration
=True)
3689 #Send PUT request to modify disk size
3690 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
3692 response
= self
.perform_request(req_type
='PUT',
3696 if response
.status_code
== 403:
3697 add_headers
= {'Content-Type': headers
['Content-Type']}
3698 response
= self
.retry_rest('PUT', disk_href
, add_headers
, data
)
3700 if response
.status_code
!= 202:
3701 self
.logger
.debug("PUT REST API call {} failed. Return status code {}".format(disk_href
,
3702 response
.status_code
))
3704 modify_disk_task
= self
.get_task_from_response(response
.content
)
3705 result
= self
.client
.get_task_monitor().wait_for_success(task
=modify_disk_task
)
3706 if result
.get('status') == 'success':
3712 except Exception as exp
:
3713 self
.logger
.info("Error occurred calling rest api for modifing disk size {}".format(exp
))
3716 def add_pci_devices(self
, vapp_uuid
, pci_devices
, vmname_andid
):
3718 Method to attach pci devices to VM
3721 vapp_uuid - uuid of vApp/VM
3722 pci_devices - pci devices infromation as specified in VNFD (flavor)
3725 The status of add pci device task , vm object and
3726 vcenter_conect object
3729 self
.logger
.info("Add pci devices {} into vApp {}".format(pci_devices
, vapp_uuid
))
3730 vcenter_conect
, content
= self
.get_vcenter_content()
3731 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
3735 no_of_pci_devices
= len(pci_devices
)
3736 if no_of_pci_devices
> 0:
3737 #Get VM and its host
3738 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
3739 self
.logger
.info("VM {} is currently on host {}".format(vm_obj
, host_obj
))
3740 if host_obj
and vm_obj
:
3741 #get PCI devies from host on which vapp is currently installed
3742 avilable_pci_devices
= self
.get_pci_devices(host_obj
, no_of_pci_devices
)
3744 if avilable_pci_devices
is None:
3745 #find other hosts with active pci devices
3746 new_host_obj
, avilable_pci_devices
= self
.get_host_and_PCIdevices(
3751 if new_host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
3752 #Migrate vm to the host where PCI devices are availble
3753 self
.logger
.info("Relocate VM {} on new host {}".format(vm_obj
, new_host_obj
))
3754 task
= self
.relocate_vm(new_host_obj
, vm_obj
)
3755 if task
is not None:
3756 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
3757 self
.logger
.info("Migrate VM status: {}".format(result
))
3758 host_obj
= new_host_obj
3760 self
.logger
.info("Fail to migrate VM : {}".format(result
))
3761 raise vimconn
.vimconnNotFoundException(
3762 "Fail to migrate VM : {} to host {}".format(
3767 if host_obj
is not None and avilable_pci_devices
is not None and len(avilable_pci_devices
)> 0:
3768 #Add PCI devices one by one
3769 for pci_device
in avilable_pci_devices
:
3770 task
= self
.add_pci_to_vm(host_obj
, vm_obj
, pci_device
)
3772 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
3774 self
.logger
.info("Added PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
3776 self
.logger
.error("Fail to add PCI device {} to VM {}".format(pci_device
,str(vm_obj
)))
3777 return True, vm_obj
, vcenter_conect
3779 self
.logger
.error("Currently there is no host with"\
3780 " {} number of avaialble PCI devices required for VM {}".format(
3784 raise vimconn
.vimconnNotFoundException(
3785 "Currently there is no host with {} "\
3786 "number of avaialble PCI devices required for VM {}".format(
3790 self
.logger
.debug("No infromation about PCI devices {} ",pci_devices
)
3792 except vmodl
.MethodFault
as error
:
3793 self
.logger
.error("Error occurred while adding PCI devices {} ",error
)
3794 return None, vm_obj
, vcenter_conect
3796 def get_vm_obj(self
, content
, mob_id
):
3798 Method to get the vsphere VM object associated with a given morf ID
3800 vapp_uuid - uuid of vApp/VM
3801 content - vCenter content object
3802 mob_id - mob_id of VM
3810 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
3811 [vim
.VirtualMachine
], True
3813 for vm
in container
.view
:
3814 mobID
= vm
._GetMoId
()
3817 host_obj
= vm_obj
.runtime
.host
3819 except Exception as exp
:
3820 self
.logger
.error("Error occurred while finding VM object : {}".format(exp
))
3821 return host_obj
, vm_obj
3823 def get_pci_devices(self
, host
, need_devices
):
3825 Method to get the details of pci devices on given host
3827 host - vSphere host object
3828 need_devices - number of pci devices needed on host
3831 array of pci devices
3835 used_devices_ids
= []
3839 pciPassthruInfo
= host
.config
.pciPassthruInfo
3840 pciDevies
= host
.hardware
.pciDevice
3842 for pci_status
in pciPassthruInfo
:
3843 if pci_status
.passthruActive
:
3844 for device
in pciDevies
:
3845 if device
.id == pci_status
.id:
3846 all_device_ids
.append(device
.id)
3847 all_devices
.append(device
)
3849 #check if devices are in use
3850 avalible_devices
= all_devices
3852 if vm
.runtime
.powerState
== vim
.VirtualMachinePowerState
.poweredOn
:
3853 vm_devices
= vm
.config
.hardware
.device
3854 for device
in vm_devices
:
3855 if type(device
) is vim
.vm
.device
.VirtualPCIPassthrough
:
3856 if device
.backing
.id in all_device_ids
:
3857 for use_device
in avalible_devices
:
3858 if use_device
.id == device
.backing
.id:
3859 avalible_devices
.remove(use_device
)
3860 used_devices_ids
.append(device
.backing
.id)
3861 self
.logger
.debug("Device {} from devices {}"\
3862 "is in use".format(device
.backing
.id,
3865 if len(avalible_devices
) < need_devices
:
3866 self
.logger
.debug("Host {} don't have {} number of active devices".format(host
,
3868 self
.logger
.debug("found only {} devives {}".format(len(avalible_devices
),
3872 required_devices
= avalible_devices
[:need_devices
]
3873 self
.logger
.info("Found {} PCI devivces on host {} but required only {}".format(
3874 len(avalible_devices
),
3877 self
.logger
.info("Retruning {} devices as {}".format(need_devices
,
3879 return required_devices
3881 except Exception as exp
:
3882 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host
))
3886 def get_host_and_PCIdevices(self
, content
, need_devices
):
3888 Method to get the details of pci devices infromation on all hosts
3891 content - vSphere host object
3892 need_devices - number of pci devices needed on host
3895 array of pci devices and host object
3898 pci_device_objs
= None
3901 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
3902 [vim
.HostSystem
], True)
3903 for host
in container
.view
:
3904 devices
= self
.get_pci_devices(host
, need_devices
)
3907 pci_device_objs
= devices
3909 except Exception as exp
:
3910 self
.logger
.error("Error {} occurred while finding pci devices on host: {}".format(exp
, host_obj
))
3912 return host_obj
,pci_device_objs
3914 def relocate_vm(self
, dest_host
, vm
) :
3916 Method to get the relocate VM to new host
3919 dest_host - vSphere host object
3920 vm - vSphere VM object
3927 relocate_spec
= vim
.vm
.RelocateSpec(host
=dest_host
)
3928 task
= vm
.Relocate(relocate_spec
)
3929 self
.logger
.info("Migrating {} to destination host {}".format(vm
, dest_host
))
3930 except Exception as exp
:
3931 self
.logger
.error("Error occurred while relocate VM {} to new host {}: {}".format(
3932 dest_host
, vm
, exp
))
3935 def wait_for_vcenter_task(self
, task
, actionName
='job', hideResult
=False):
3937 Waits and provides updates on a vSphere task
3939 while task
.info
.state
== vim
.TaskInfo
.State
.running
:
3942 if task
.info
.state
== vim
.TaskInfo
.State
.success
:
3943 if task
.info
.result
is not None and not hideResult
:
3944 self
.logger
.info('{} completed successfully, result: {}'.format(
3948 self
.logger
.info('Task {} completed successfully.'.format(actionName
))
3950 self
.logger
.error('{} did not complete successfully: {} '.format(
3955 return task
.info
.result
3957 def add_pci_to_vm(self
,host_object
, vm_object
, host_pci_dev
):
3959 Method to add pci device in given VM
3962 host_object - vSphere host object
3963 vm_object - vSphere VM object
3964 host_pci_dev - host_pci_dev must be one of the devices from the
3965 host_object.hardware.pciDevice list
3966 which is configured as a PCI passthrough device
3972 if vm_object
and host_object
and host_pci_dev
:
3974 #Add PCI device to VM
3975 pci_passthroughs
= vm_object
.environmentBrowser
.QueryConfigTarget(host
=None).pciPassthrough
3976 systemid_by_pciid
= {item
.pciDevice
.id: item
.systemId
for item
in pci_passthroughs
}
3978 if host_pci_dev
.id not in systemid_by_pciid
:
3979 self
.logger
.error("Device {} is not a passthrough device ".format(host_pci_dev
))
3982 deviceId
= hex(host_pci_dev
.deviceId
% 2**16).lstrip('0x')
3983 backing
= vim
.VirtualPCIPassthroughDeviceBackingInfo(deviceId
=deviceId
,
3985 systemId
=systemid_by_pciid
[host_pci_dev
.id],
3986 vendorId
=host_pci_dev
.vendorId
,
3987 deviceName
=host_pci_dev
.deviceName
)
3989 hba_object
= vim
.VirtualPCIPassthrough(key
=-100, backing
=backing
)
3991 new_device_config
= vim
.VirtualDeviceConfigSpec(device
=hba_object
)
3992 new_device_config
.operation
= "add"
3993 vmConfigSpec
= vim
.vm
.ConfigSpec()
3994 vmConfigSpec
.deviceChange
= [new_device_config
]
3996 task
= vm_object
.ReconfigVM_Task(spec
=vmConfigSpec
)
3997 self
.logger
.info("Adding PCI device {} into VM {} from host {} ".format(
3998 host_pci_dev
, vm_object
, host_object
)
4000 except Exception as exp
:
4001 self
.logger
.error("Error occurred while adding pci devive {} to VM {}: {}".format(
4007 def get_vm_vcenter_info(self
):
4009 Method to get details of vCenter and vm
4012 vapp_uuid - uuid of vApp or VM
4015 Moref Id of VM and deails of vCenter
4017 vm_vcenter_info
= {}
4019 if self
.vcenter_ip
is not None:
4020 vm_vcenter_info
["vm_vcenter_ip"] = self
.vcenter_ip
4022 raise vimconn
.vimconnException(message
="vCenter IP is not provided."\
4023 " Please provide vCenter IP while attaching datacenter to tenant in --config")
4024 if self
.vcenter_port
is not None:
4025 vm_vcenter_info
["vm_vcenter_port"] = self
.vcenter_port
4027 raise vimconn
.vimconnException(message
="vCenter port is not provided."\
4028 " Please provide vCenter port while attaching datacenter to tenant in --config")
4029 if self
.vcenter_user
is not None:
4030 vm_vcenter_info
["vm_vcenter_user"] = self
.vcenter_user
4032 raise vimconn
.vimconnException(message
="vCenter user is not provided."\
4033 " Please provide vCenter user while attaching datacenter to tenant in --config")
4035 if self
.vcenter_password
is not None:
4036 vm_vcenter_info
["vm_vcenter_password"] = self
.vcenter_password
4038 raise vimconn
.vimconnException(message
="vCenter user password is not provided."\
4039 " Please provide vCenter user password while attaching datacenter to tenant in --config")
4041 return vm_vcenter_info
4044 def get_vm_pci_details(self
, vmuuid
):
4046 Method to get VM PCI device details from vCenter
4049 vm_obj - vSphere VM object
4052 dict of PCI devives attached to VM
4055 vm_pci_devices_info
= {}
4057 vcenter_conect
, content
= self
.get_vcenter_content()
4058 vm_moref_id
= self
.get_vm_moref_id(vmuuid
)
4060 #Get VM and its host
4062 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
4063 if host_obj
and vm_obj
:
4064 vm_pci_devices_info
["host_name"]= host_obj
.name
4065 vm_pci_devices_info
["host_ip"]= host_obj
.config
.network
.vnic
[0].spec
.ip
.ipAddress
4066 for device
in vm_obj
.config
.hardware
.device
:
4067 if type(device
) == vim
.vm
.device
.VirtualPCIPassthrough
:
4068 device_details
={'devide_id':device
.backing
.id,
4069 'pciSlotNumber':device
.slotInfo
.pciSlotNumber
,
4071 vm_pci_devices_info
[device
.deviceInfo
.label
] = device_details
4073 self
.logger
.error("Can not connect to vCenter while getting "\
4074 "PCI devices infromationn")
4075 return vm_pci_devices_info
4076 except Exception as exp
:
4077 self
.logger
.error("Error occurred while getting VM infromationn"\
4078 " for VM : {}".format(exp
))
4079 raise vimconn
.vimconnException(message
=exp
)
4081 def add_network_adapter_to_vms(self
, vapp
, network_name
, primary_nic_index
, nicIndex
, net
, nic_type
=None):
4083 Method to add network adapter type to vm
4085 network_name - name of network
4086 primary_nic_index - int value for primary nic index
4087 nicIndex - int value for nic index
4088 nic_type - specify model name to which add to vm
4097 if 'floating_ip' in net
: floating_ip
= net
['floating_ip']
4099 # Stub for ip_address feature
4100 if 'ip_address' in net
: ip_address
= net
['ip_address']
4102 if 'mac_address' in net
: mac_address
= net
['mac_address']
4105 allocation_mode
= "POOL"
4107 allocation_mode
= "MANUAL"
4109 allocation_mode
= "DHCP"
4112 for vms
in vapp
.get_all_vms():
4113 vm_id
= vms
.get('id').split(':')[-1]
4115 url_rest_call
= "{}/api/vApp/vm-{}/networkConnectionSection/".format(self
.url
, vm_id
)
4117 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4118 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4119 response
= self
.perform_request(req_type
='GET',
4123 if response
.status_code
== 403:
4124 response
= self
.retry_rest('GET', url_rest_call
)
4126 if response
.status_code
!= 200:
4127 self
.logger
.error("REST call {} failed reason : {}"\
4128 "status code : {}".format(url_rest_call
,
4130 response
.status_code
))
4131 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to get "\
4132 "network connection section")
4134 data
= response
.content
4135 data
= data
.split('<Link rel="edit"')[0]
4136 if '<PrimaryNetworkConnectionIndex>' not in data
:
4137 item
= """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
4138 <NetworkConnection network="{}">
4139 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4140 <IsConnected>true</IsConnected>
4141 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4142 </NetworkConnection>""".format(primary_nic_index
, network_name
, nicIndex
,
4144 # Stub for ip_address feature
4146 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4147 item
= item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4150 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4151 item
= item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4153 data
= data
.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item
))
4155 new_item
= """<NetworkConnection network="{}">
4156 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4157 <IsConnected>true</IsConnected>
4158 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4159 </NetworkConnection>""".format(network_name
, nicIndex
,
4161 # Stub for ip_address feature
4163 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4164 new_item
= new_item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4167 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4168 new_item
= new_item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4170 data
= data
+ new_item
+ '</NetworkConnectionSection>'
4172 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
4174 response
= self
.perform_request(req_type
='PUT',
4179 if response
.status_code
== 403:
4180 add_headers
= {'Content-Type': headers
['Content-Type']}
4181 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, data
)
4183 if response
.status_code
!= 202:
4184 self
.logger
.error("REST call {} failed reason : {}"\
4185 "status code : {} ".format(url_rest_call
,
4187 response
.status_code
))
4188 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to update "\
4189 "network connection section")
4191 nic_task
= self
.get_task_from_response(response
.content
)
4192 result
= self
.client
.get_task_monitor().wait_for_success(task
=nic_task
)
4193 if result
.get('status') == 'success':
4194 self
.logger
.info("add_network_adapter_to_vms(): VM {} conneced to "\
4195 "default NIC type".format(vm_id
))
4197 self
.logger
.error("add_network_adapter_to_vms(): VM {} failed to "\
4198 "connect NIC type".format(vm_id
))
4200 for vms
in vapp
.get_all_vms():
4201 vm_id
= vms
.get('id').split(':')[-1]
4204 url_rest_call
= "{}/api/vApp/vm-{}/networkConnectionSection/".format(self
.url
, vm_id
)
4206 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4207 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4208 response
= self
.perform_request(req_type
='GET',
4212 if response
.status_code
== 403:
4213 response
= self
.retry_rest('GET', url_rest_call
)
4215 if response
.status_code
!= 200:
4216 self
.logger
.error("REST call {} failed reason : {}"\
4217 "status code : {}".format(url_rest_call
,
4219 response
.status_code
))
4220 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to get "\
4221 "network connection section")
4222 data
= response
.content
4223 data
= data
.split('<Link rel="edit"')[0]
4224 if '<PrimaryNetworkConnectionIndex>' not in data
:
4225 item
= """<PrimaryNetworkConnectionIndex>{}</PrimaryNetworkConnectionIndex>
4226 <NetworkConnection network="{}">
4227 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4228 <IsConnected>true</IsConnected>
4229 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4230 <NetworkAdapterType>{}</NetworkAdapterType>
4231 </NetworkConnection>""".format(primary_nic_index
, network_name
, nicIndex
,
4232 allocation_mode
, nic_type
)
4233 # Stub for ip_address feature
4235 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4236 item
= item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4239 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4240 item
= item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4242 data
= data
.replace('</ovf:Info>\n','</ovf:Info>\n{}\n</NetworkConnectionSection>'.format(item
))
4244 new_item
= """<NetworkConnection network="{}">
4245 <NetworkConnectionIndex>{}</NetworkConnectionIndex>
4246 <IsConnected>true</IsConnected>
4247 <IpAddressAllocationMode>{}</IpAddressAllocationMode>
4248 <NetworkAdapterType>{}</NetworkAdapterType>
4249 </NetworkConnection>""".format(network_name
, nicIndex
,
4250 allocation_mode
, nic_type
)
4251 # Stub for ip_address feature
4253 ip_tag
= '<IpAddress>{}</IpAddress>'.format(ip_address
)
4254 new_item
= new_item
.replace('</NetworkConnectionIndex>\n','</NetworkConnectionIndex>\n{}\n'.format(ip_tag
))
4257 mac_tag
= '<MACAddress>{}</MACAddress>'.format(mac_address
)
4258 new_item
= new_item
.replace('</IsConnected>\n','</IsConnected>\n{}\n'.format(mac_tag
))
4260 data
= data
+ new_item
+ '</NetworkConnectionSection>'
4262 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.networkConnectionSection+xml'
4264 response
= self
.perform_request(req_type
='PUT',
4269 if response
.status_code
== 403:
4270 add_headers
= {'Content-Type': headers
['Content-Type']}
4271 response
= self
.retry_rest('PUT', url_rest_call
, add_headers
, data
)
4273 if response
.status_code
!= 202:
4274 self
.logger
.error("REST call {} failed reason : {}"\
4275 "status code : {}".format(url_rest_call
,
4277 response
.status_code
))
4278 raise vimconn
.vimconnException("add_network_adapter_to_vms : Failed to update "\
4279 "network connection section")
4281 nic_task
= self
.get_task_from_response(response
.content
)
4282 result
= self
.client
.get_task_monitor().wait_for_success(task
=nic_task
)
4283 if result
.get('status') == 'success':
4284 self
.logger
.info("add_network_adapter_to_vms(): VM {} "\
4285 "conneced to NIC type {}".format(vm_id
, nic_type
))
4287 self
.logger
.error("add_network_adapter_to_vms(): VM {} "\
4288 "failed to connect NIC type {}".format(vm_id
, nic_type
))
4289 except Exception as exp
:
4290 self
.logger
.error("add_network_adapter_to_vms() : exception occurred "\
4291 "while adding Network adapter")
4292 raise vimconn
.vimconnException(message
=exp
)
4295 def set_numa_affinity(self
, vmuuid
, paired_threads_id
):
4297 Method to assign numa affinity in vm configuration parammeters
4300 paired_threads_id - one or more virtual processor
4306 vcenter_conect
, content
= self
.get_vcenter_content()
4307 vm_moref_id
= self
.get_vm_moref_id(vmuuid
)
4309 host_obj
, vm_obj
= self
.get_vm_obj(content
,vm_moref_id
)
4311 config_spec
= vim
.vm
.ConfigSpec()
4312 config_spec
.extraConfig
= []
4313 opt
= vim
.option
.OptionValue()
4314 opt
.key
= 'numa.nodeAffinity'
4315 opt
.value
= str(paired_threads_id
)
4316 config_spec
.extraConfig
.append(opt
)
4317 task
= vm_obj
.ReconfigVM_Task(config_spec
)
4319 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4320 extra_config
= vm_obj
.config
.extraConfig
4322 for opts
in extra_config
:
4323 if 'numa.nodeAffinity' in opts
.key
:
4325 self
.logger
.info("set_numa_affinity: Sucessfully assign numa affinity "\
4326 "value {} for vm {}".format(opt
.value
, vm_obj
))
4330 self
.logger
.error("set_numa_affinity: Failed to assign numa affinity")
4331 except Exception as exp
:
4332 self
.logger
.error("set_numa_affinity : exception occurred while setting numa affinity "\
4333 "for VM {} : {}".format(vm_obj
, vm_moref_id
))
4334 raise vimconn
.vimconnException("set_numa_affinity : Error {} failed to assign numa "\
4335 "affinity".format(exp
))
4338 def cloud_init(self
, vapp
, cloud_config
):
4340 Method to inject ssh-key
4342 cloud_config a dictionary with:
4343 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
4344 'users': (optional) list of users to be inserted, each item is a dict with:
4345 'name': (mandatory) user name,
4346 'key-pairs': (optional) list of strings with the public key to be inserted to the user
4347 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
4348 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
4349 'config-files': (optional). List of files to be transferred. Each item is a dict with:
4350 'dest': (mandatory) string with the destination absolute path
4351 'encoding': (optional, by default text). Can be one of:
4352 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
4353 'content' (mandatory): string with the content of the file
4354 'permissions': (optional) string with file permissions, typically octal notation '0644'
4355 'owner': (optional) file owner, string with the format 'owner:group'
4356 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk
4359 if not isinstance(cloud_config
, dict):
4360 raise Exception("cloud_init : parameter cloud_config is not a dictionary")
4364 if "key-pairs" in cloud_config
:
4365 key_pairs
= cloud_config
["key-pairs"]
4367 if "users" in cloud_config
:
4368 userdata
= cloud_config
["users"]
4370 self
.logger
.debug("cloud_init : Guest os customization started..")
4371 customize_script
= self
.format_script(key_pairs
=key_pairs
, users_list
=userdata
)
4372 customize_script
= customize_script
.replace("&","&")
4373 self
.guest_customization(vapp
, customize_script
)
4375 except Exception as exp
:
4376 self
.logger
.error("cloud_init : exception occurred while injecting "\
4378 raise vimconn
.vimconnException("cloud_init : Error {} failed to inject "\
4379 "ssh-key".format(exp
))
4381 def format_script(self
, key_pairs
=[], users_list
=[]):
4382 bash_script
= """#!/bin/sh
4383 echo performing customization tasks with param $1 at `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
4384 if [ "$1" = "precustomization" ];then
4385 echo performing precustomization tasks on `date "+DATE: %Y-%m-%d - TIME: %H:%M:%S"` >> /root/customization.log
4388 keys
= "\n".join(key_pairs
)
4391 if [ ! -d /root/.ssh ];then
4393 chown root:root /root/.ssh
4394 chmod 700 /root/.ssh
4395 touch /root/.ssh/authorized_keys
4396 chown root:root /root/.ssh/authorized_keys
4397 chmod 600 /root/.ssh/authorized_keys
4398 # make centos with selinux happy
4399 which restorecon && restorecon -Rv /root/.ssh
4401 touch /root/.ssh/authorized_keys
4402 chown root:root /root/.ssh/authorized_keys
4403 chmod 600 /root/.ssh/authorized_keys
4405 echo '{key}' >> /root/.ssh/authorized_keys
4406 """.format(key
=keys
)
4408 bash_script
+= keys_data
4410 for user
in users_list
:
4411 if 'name' in user
: user_name
= user
['name']
4412 if 'key-pairs' in user
:
4413 user_keys
= "\n".join(user
['key-pairs'])
4418 useradd -d /home/{user_name} -m -g users -s /bin/bash {user_name}
4419 """.format(user_name
=user_name
)
4421 bash_script
+= add_user_name
4424 user_keys_data
= """
4425 mkdir /home/{user_name}/.ssh
4426 chown {user_name}:{user_name} /home/{user_name}/.ssh
4427 chmod 700 /home/{user_name}/.ssh
4428 touch /home/{user_name}/.ssh/authorized_keys
4429 chown {user_name}:{user_name} /home/{user_name}/.ssh/authorized_keys
4430 chmod 600 /home/{user_name}/.ssh/authorized_keys
4431 # make centos with selinux happy
4432 which restorecon && restorecon -Rv /home/{user_name}/.ssh
4433 echo '{user_key}' >> /home/{user_name}/.ssh/authorized_keys
4434 """.format(user_name
=user_name
,user_key
=user_keys
)
4436 bash_script
+= user_keys_data
4438 return bash_script
+"\n\tfi"
4440 def guest_customization(self
, vapp
, customize_script
):
4442 Method to customize guest os
4444 customize_script - Customize script to be run at first boot of VM.
4446 for vm
in vapp
.get_all_vms():
4447 vm_id
= vm
.get('id').split(':')[-1]
4448 vm_name
= vm
.get('name')
4449 vm_name
= vm_name
.replace('_','-')
4451 vm_customization_url
= "{}/api/vApp/vm-{}/guestCustomizationSection/".format(self
.url
, vm_id
)
4452 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4453 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4455 headers
['Content-Type'] = "application/vnd.vmware.vcloud.guestCustomizationSection+xml"
4457 data
= """<GuestCustomizationSection
4458 xmlns="http://www.vmware.com/vcloud/v1.5"
4459 xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
4460 ovf:required="false" href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml">
4461 <ovf:Info>Specifies Guest OS Customization Settings</ovf:Info>
4462 <Enabled>true</Enabled>
4463 <ChangeSid>false</ChangeSid>
4464 <VirtualMachineId>{}</VirtualMachineId>
4465 <JoinDomainEnabled>false</JoinDomainEnabled>
4466 <UseOrgSettings>false</UseOrgSettings>
4467 <AdminPasswordEnabled>false</AdminPasswordEnabled>
4468 <AdminPasswordAuto>true</AdminPasswordAuto>
4469 <AdminAutoLogonEnabled>false</AdminAutoLogonEnabled>
4470 <AdminAutoLogonCount>0</AdminAutoLogonCount>
4471 <ResetPasswordRequired>false</ResetPasswordRequired>
4472 <CustomizationScript>{}</CustomizationScript>
4473 <ComputerName>{}</ComputerName>
4474 <Link href="{}" type="application/vnd.vmware.vcloud.guestCustomizationSection+xml" rel="edit"/>
4475 </GuestCustomizationSection>
4476 """.format(vm_customization_url
,
4480 vm_customization_url
)
4482 response
= self
.perform_request(req_type
='PUT',
4483 url
=vm_customization_url
,
4486 if response
.status_code
== 202:
4487 guest_task
= self
.get_task_from_response(response
.content
)
4488 self
.client
.get_task_monitor().wait_for_success(task
=guest_task
)
4489 self
.logger
.info("guest_customization : customized guest os task "\
4490 "completed for VM {}".format(vm_name
))
4492 self
.logger
.error("guest_customization : task for customized guest os"\
4493 "failed for VM {}".format(vm_name
))
4494 raise vimconn
.vimconnException("guest_customization : failed to perform"\
4495 "guest os customization on VM {}".format(vm_name
))
4497 def add_new_disk(self
, vapp_uuid
, disk_size
):
4499 Method to create an empty vm disk
4502 vapp_uuid - is vapp identifier.
4503 disk_size - size of disk to be created in GB
4511 #Disk size in GB, convert it into MB
4512 if disk_size
is not None:
4513 disk_size_mb
= int(disk_size
) * 1024
4514 vm_details
= self
.get_vapp_details_rest(vapp_uuid
)
4516 if vm_details
and "vm_virtual_hardware" in vm_details
:
4517 self
.logger
.info("Adding disk to VM: {} disk size:{}GB".format(vm_details
["name"], disk_size
))
4518 disk_href
= vm_details
["vm_virtual_hardware"]["disk_edit_href"]
4519 status
= self
.add_new_disk_rest(disk_href
, disk_size_mb
)
4521 except Exception as exp
:
4522 msg
= "Error occurred while creating new disk {}.".format(exp
)
4523 self
.rollback_newvm(vapp_uuid
, msg
)
4526 self
.logger
.info("Added new disk to VM: {} disk size:{}GB".format(vm_details
["name"], disk_size
))
4528 #If failed to add disk, delete VM
4529 msg
= "add_new_disk: Failed to add new disk to {}".format(vm_details
["name"])
4530 self
.rollback_newvm(vapp_uuid
, msg
)
4533 def add_new_disk_rest(self
, disk_href
, disk_size_mb
):
4535 Retrives vApp Disks section & add new empty disk
4538 disk_href: Disk section href to addd disk
4539 disk_size_mb: Disk size in MB
4541 Returns: Status of add new disk task
4544 if self
.client
._session
:
4545 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4546 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
4547 response
= self
.perform_request(req_type
='GET',
4551 if response
.status_code
== 403:
4552 response
= self
.retry_rest('GET', disk_href
)
4554 if response
.status_code
!= requests
.codes
.ok
:
4555 self
.logger
.error("add_new_disk_rest: GET REST API call {} failed. Return status code {}"
4556 .format(disk_href
, response
.status_code
))
4559 #Find but type & max of instance IDs assigned to disks
4560 lxmlroot_respond
= lxmlElementTree
.fromstring(response
.content
)
4561 namespaces
= {prefix
:uri
for prefix
,uri
in lxmlroot_respond
.nsmap
.iteritems() if prefix
}
4563 #namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
4564 namespaces
["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
4566 for item
in lxmlroot_respond
.iterfind('xmlns:Item',namespaces
):
4567 if item
.find("rasd:Description",namespaces
).text
== "Hard disk":
4568 inst_id
= int(item
.find("rasd:InstanceID" ,namespaces
).text
)
4569 if inst_id
> instance_id
:
4570 instance_id
= inst_id
4571 disk_item
= item
.find("rasd:HostResource" ,namespaces
)
4572 bus_subtype
= disk_item
.attrib
["{"+namespaces
['xmlns']+"}busSubType"]
4573 bus_type
= disk_item
.attrib
["{"+namespaces
['xmlns']+"}busType"]
4575 instance_id
= instance_id
+ 1
4576 new_item
= """<Item>
4577 <rasd:Description>Hard disk</rasd:Description>
4578 <rasd:ElementName>New disk</rasd:ElementName>
4580 xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
4581 vcloud:capacity="{}"
4582 vcloud:busSubType="{}"
4583 vcloud:busType="{}"></rasd:HostResource>
4584 <rasd:InstanceID>{}</rasd:InstanceID>
4585 <rasd:ResourceType>17</rasd:ResourceType>
4586 </Item>""".format(disk_size_mb
, bus_subtype
, bus_type
, instance_id
)
4588 new_data
= response
.content
4589 #Add new item at the bottom
4590 new_data
= new_data
.replace('</Item>\n</RasdItemsList>', '</Item>\n{}\n</RasdItemsList>'.format(new_item
))
4592 # Send PUT request to modify virtual hardware section with new disk
4593 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.rasdItemsList+xml; charset=ISO-8859-1'
4595 response
= self
.perform_request(req_type
='PUT',
4600 if response
.status_code
== 403:
4601 add_headers
= {'Content-Type': headers
['Content-Type']}
4602 response
= self
.retry_rest('PUT', disk_href
, add_headers
, new_data
)
4604 if response
.status_code
!= 202:
4605 self
.logger
.error("PUT REST API call {} failed. Return status code {}. Response Content:{}"
4606 .format(disk_href
, response
.status_code
, response
.content
))
4608 add_disk_task
= self
.get_task_from_response(response
.content
)
4609 result
= self
.client
.get_task_monitor().wait_for_success(task
=add_disk_task
)
4610 if result
.get('status') == 'success':
4613 self
.logger
.error("Add new disk REST task failed to add {} MB disk".format(disk_size_mb
))
4615 except Exception as exp
:
4616 self
.logger
.error("Error occurred calling rest api for creating new disk {}".format(exp
))
4621 def add_existing_disk(self
, catalogs
=None, image_id
=None, size
=None, template_name
=None, vapp_uuid
=None):
4623 Method to add existing disk to vm
4625 catalogs - List of VDC catalogs
4626 image_id - Catalog ID
4627 template_name - Name of template in catalog
4628 vapp_uuid - UUID of vApp
4633 vcenter_conect
, content
= self
.get_vcenter_content()
4634 #find moref-id of vm in image
4635 catalog_vm_info
= self
.get_vapp_template_details(catalogs
=catalogs
,
4639 if catalog_vm_info
and "vm_vcenter_info" in catalog_vm_info
:
4640 if "vm_moref_id" in catalog_vm_info
["vm_vcenter_info"]:
4641 catalog_vm_moref_id
= catalog_vm_info
["vm_vcenter_info"].get("vm_moref_id", None)
4642 if catalog_vm_moref_id
:
4643 self
.logger
.info("Moref_id of VM in catalog : {}" .format(catalog_vm_moref_id
))
4644 host
, catalog_vm_obj
= self
.get_vm_obj(content
, catalog_vm_moref_id
)
4647 disk_info
= self
.find_disk(catalog_vm_obj
)
4649 exp_msg
= "No VM with image id {} found".format(image_id
)
4650 self
.rollback_newvm(vapp_uuid
, exp_msg
, exp_type
="NotFound")
4652 exp_msg
= "No Image found with image ID {} ".format(image_id
)
4653 self
.rollback_newvm(vapp_uuid
, exp_msg
, exp_type
="NotFound")
4656 self
.logger
.info("Existing disk_info : {}".format(disk_info
))
4658 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
4659 host
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
4661 status
= self
.add_disk(vcenter_conect
=vcenter_conect
,
4663 disk_info
=disk_info
,
4668 self
.logger
.info("Disk from image id {} added to {}".format(image_id
,
4672 msg
= "No disk found with image id {} to add in VM {}".format(
4675 self
.rollback_newvm(vapp_uuid
, msg
, exp_type
="NotFound")
4678 def find_disk(self
, vm_obj
):
4680 Method to find details of existing disk in VM
4682 vm_obj - vCenter object of VM
4683 image_id - Catalog ID
4685 disk_info : dict of disk details
4690 devices
= vm_obj
.config
.hardware
.device
4691 for device
in devices
:
4692 if type(device
) is vim
.vm
.device
.VirtualDisk
:
4693 if isinstance(device
.backing
,vim
.vm
.device
.VirtualDisk
.FlatVer2BackingInfo
) and hasattr(device
.backing
, 'fileName'):
4694 disk_info
["full_path"] = device
.backing
.fileName
4695 disk_info
["datastore"] = device
.backing
.datastore
4696 disk_info
["capacityKB"] = device
.capacityInKB
4698 except Exception as exp
:
4699 self
.logger
.error("find_disk() : exception occurred while "\
4700 "getting existing disk details :{}".format(exp
))
4704 def add_disk(self
, vcenter_conect
=None, vm
=None, size
=None, vapp_uuid
=None, disk_info
={}):
4706 Method to add existing disk in VM
4708 vcenter_conect - vCenter content object
4709 vm - vCenter vm object
4710 disk_info : dict of disk details
4712 status : status of add disk task
4714 datastore
= disk_info
["datastore"] if "datastore" in disk_info
else None
4715 fullpath
= disk_info
["full_path"] if "full_path" in disk_info
else None
4716 capacityKB
= disk_info
["capacityKB"] if "capacityKB" in disk_info
else None
4717 if size
is not None:
4718 #Convert size from GB to KB
4719 sizeKB
= int(size
) * 1024 * 1024
4720 #compare size of existing disk and user given size.Assign whicherver is greater
4721 self
.logger
.info("Add Existing disk : sizeKB {} , capacityKB {}".format(
4722 sizeKB
, capacityKB
))
4723 if sizeKB
> capacityKB
:
4726 if datastore
and fullpath
and capacityKB
:
4728 spec
= vim
.vm
.ConfigSpec()
4729 # get all disks on a VM, set unit_number to the next available
4731 for dev
in vm
.config
.hardware
.device
:
4732 if hasattr(dev
.backing
, 'fileName'):
4733 unit_number
= int(dev
.unitNumber
) + 1
4734 # unit_number 7 reserved for scsi controller
4735 if unit_number
== 7:
4737 if isinstance(dev
, vim
.vm
.device
.VirtualDisk
):
4738 #vim.vm.device.VirtualSCSIController
4739 controller_key
= dev
.controllerKey
4741 self
.logger
.info("Add Existing disk : unit number {} , controller key {}".format(
4742 unit_number
, controller_key
))
4745 disk_spec
= vim
.vm
.device
.VirtualDeviceSpec()
4746 disk_spec
.operation
= vim
.vm
.device
.VirtualDeviceSpec
.Operation
.add
4747 disk_spec
.device
= vim
.vm
.device
.VirtualDisk()
4748 disk_spec
.device
.backing
= \
4749 vim
.vm
.device
.VirtualDisk
.FlatVer2BackingInfo()
4750 disk_spec
.device
.backing
.thinProvisioned
= True
4751 disk_spec
.device
.backing
.diskMode
= 'persistent'
4752 disk_spec
.device
.backing
.datastore
= datastore
4753 disk_spec
.device
.backing
.fileName
= fullpath
4755 disk_spec
.device
.unitNumber
= unit_number
4756 disk_spec
.device
.capacityInKB
= capacityKB
4757 disk_spec
.device
.controllerKey
= controller_key
4758 dev_changes
.append(disk_spec
)
4759 spec
.deviceChange
= dev_changes
4760 task
= vm
.ReconfigVM_Task(spec
=spec
)
4761 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4763 except Exception as exp
:
4764 exp_msg
= "add_disk() : exception {} occurred while adding disk "\
4765 "{} to vm {}".format(exp
,
4768 self
.rollback_newvm(vapp_uuid
, exp_msg
)
4770 msg
= "add_disk() : Can not add disk to VM with disk info {} ".format(disk_info
)
4771 self
.rollback_newvm(vapp_uuid
, msg
)
4774 def get_vcenter_content(self
):
4776 Get the vsphere content object
4779 vm_vcenter_info
= self
.get_vm_vcenter_info()
4780 except Exception as exp
:
4781 self
.logger
.error("Error occurred while getting vCenter infromationn"\
4782 " for VM : {}".format(exp
))
4783 raise vimconn
.vimconnException(message
=exp
)
4786 if hasattr(ssl
, '_create_unverified_context'):
4787 context
= ssl
._create
_unverified
_context
()
4789 vcenter_conect
= SmartConnect(
4790 host
=vm_vcenter_info
["vm_vcenter_ip"],
4791 user
=vm_vcenter_info
["vm_vcenter_user"],
4792 pwd
=vm_vcenter_info
["vm_vcenter_password"],
4793 port
=int(vm_vcenter_info
["vm_vcenter_port"]),
4796 atexit
.register(Disconnect
, vcenter_conect
)
4797 content
= vcenter_conect
.RetrieveContent()
4798 return vcenter_conect
, content
4801 def get_vm_moref_id(self
, vapp_uuid
):
4803 Get the moref_id of given VM
4807 vm_details
= self
.get_vapp_details_rest(vapp_uuid
, need_admin_access
=True)
4808 if vm_details
and "vm_vcenter_info" in vm_details
:
4809 vm_moref_id
= vm_details
["vm_vcenter_info"].get("vm_moref_id", None)
4812 except Exception as exp
:
4813 self
.logger
.error("Error occurred while getting VM moref ID "\
4814 " for VM : {}".format(exp
))
4818 def get_vapp_template_details(self
, catalogs
=None, image_id
=None , template_name
=None):
4820 Method to get vApp template details
4822 catalogs - list of VDC catalogs
4823 image_id - Catalog ID to find
4824 template_name : template name in catalog
4826 parsed_respond : dict of vApp tempalte details
4828 parsed_response
= {}
4830 vca
= self
.connect_as_admin()
4832 raise vimconn
.vimconnConnectionException("Failed to connect vCD")
4835 org
, vdc
= self
.get_vdc_details()
4836 catalog
= self
.get_catalog_obj(image_id
, catalogs
)
4838 items
= org
.get_catalog_item(catalog
.get('name'), catalog
.get('name'))
4839 catalog_items
= [items
.attrib
]
4841 if len(catalog_items
) == 1:
4842 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
4843 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
4845 response
= self
.perform_request(req_type
='GET',
4846 url
=catalog_items
[0].get('href'),
4848 catalogItem
= XmlElementTree
.fromstring(response
.content
)
4849 entity
= [child
for child
in catalogItem
if child
.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
4850 vapp_tempalte_href
= entity
.get("href")
4851 #get vapp details and parse moref id
4853 namespaces
= {"vssd":"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" ,
4854 'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
4855 'vmw': 'http://www.vmware.com/schema/ovf',
4856 'vm': 'http://www.vmware.com/vcloud/v1.5',
4857 'rasd':"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData",
4858 'vmext':"http://www.vmware.com/vcloud/extension/v1.5",
4859 'xmlns':"http://www.vmware.com/vcloud/v1.5"
4863 response
= self
.perform_request(req_type
='GET',
4864 url
=vapp_tempalte_href
,
4867 if response
.status_code
!= requests
.codes
.ok
:
4868 self
.logger
.debug("REST API call {} failed. Return status code {}".format(
4869 vapp_tempalte_href
, response
.status_code
))
4872 xmlroot_respond
= XmlElementTree
.fromstring(response
.content
)
4873 children_section
= xmlroot_respond
.find('vm:Children/', namespaces
)
4874 if children_section
is not None:
4875 vCloud_extension_section
= children_section
.find('xmlns:VCloudExtension', namespaces
)
4876 if vCloud_extension_section
is not None:
4877 vm_vcenter_info
= {}
4878 vim_info
= vCloud_extension_section
.find('vmext:VmVimInfo', namespaces
)
4879 vmext
= vim_info
.find('vmext:VmVimObjectRef', namespaces
)
4880 if vmext
is not None:
4881 vm_vcenter_info
["vm_moref_id"] = vmext
.find('vmext:MoRef', namespaces
).text
4882 parsed_response
["vm_vcenter_info"]= vm_vcenter_info
4884 except Exception as exp
:
4885 self
.logger
.info("Error occurred calling rest api for getting vApp details {}".format(exp
))
4887 return parsed_response
4890 def rollback_newvm(self
, vapp_uuid
, msg
, exp_type
="Genric"):
4892 Method to delete vApp
4894 vapp_uuid - vApp UUID
4895 msg - Error message to be logged
4896 exp_type : Exception type
4901 status
= self
.delete_vminstance(vapp_uuid
)
4904 self
.logger
.error(msg
)
4905 if exp_type
== "Genric":
4906 raise vimconn
.vimconnException(msg
)
4907 elif exp_type
== "NotFound":
4908 raise vimconn
.vimconnNotFoundException(message
=msg
)
4910 def add_sriov(self
, vapp_uuid
, sriov_nets
, vmname_andid
):
4912 Method to attach SRIOV adapters to VM
4915 vapp_uuid - uuid of vApp/VM
4916 sriov_nets - SRIOV devices infromation as specified in VNFD (flavor)
4917 vmname_andid - vmname
4920 The status of add SRIOV adapter task , vm object and
4921 vcenter_conect object
4924 vcenter_conect
, content
= self
.get_vcenter_content()
4925 vm_moref_id
= self
.get_vm_moref_id(vapp_uuid
)
4929 no_of_sriov_devices
= len(sriov_nets
)
4930 if no_of_sriov_devices
> 0:
4931 #Get VM and its host
4932 host_obj
, vm_obj
= self
.get_vm_obj(content
, vm_moref_id
)
4933 self
.logger
.info("VM {} is currently on host {}".format(vm_obj
, host_obj
))
4934 if host_obj
and vm_obj
:
4935 #get SRIOV devies from host on which vapp is currently installed
4936 avilable_sriov_devices
= self
.get_sriov_devices(host_obj
,
4937 no_of_sriov_devices
,
4940 if len(avilable_sriov_devices
) == 0:
4941 #find other hosts with active pci devices
4942 new_host_obj
, avilable_sriov_devices
= self
.get_host_and_sriov_devices(
4944 no_of_sriov_devices
,
4947 if new_host_obj
is not None and len(avilable_sriov_devices
)> 0:
4948 #Migrate vm to the host where SRIOV devices are available
4949 self
.logger
.info("Relocate VM {} on new host {}".format(vm_obj
,
4951 task
= self
.relocate_vm(new_host_obj
, vm_obj
)
4952 if task
is not None:
4953 result
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4954 self
.logger
.info("Migrate VM status: {}".format(result
))
4955 host_obj
= new_host_obj
4957 self
.logger
.info("Fail to migrate VM : {}".format(result
))
4958 raise vimconn
.vimconnNotFoundException(
4959 "Fail to migrate VM : {} to host {}".format(
4964 if host_obj
is not None and avilable_sriov_devices
is not None and len(avilable_sriov_devices
)> 0:
4965 #Add SRIOV devices one by one
4966 for sriov_net
in sriov_nets
:
4967 network_name
= sriov_net
.get('net_id')
4968 dvs_portgr_name
= self
.create_dvPort_group(network_name
)
4969 if sriov_net
.get('type') == "VF" or sriov_net
.get('type') == "SR-IOV":
4970 #add vlan ID ,Modify portgroup for vlan ID
4971 self
.configure_vlanID(content
, vcenter_conect
, network_name
)
4973 task
= self
.add_sriov_to_vm(content
,
4977 avilable_sriov_devices
[0]
4980 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
4982 self
.logger
.info("Added SRIOV {} to VM {}".format(
4983 no_of_sriov_devices
,
4986 self
.logger
.error("Fail to add SRIOV {} to VM {}".format(
4987 no_of_sriov_devices
,
4989 raise vimconn
.vimconnUnexpectedResponse(
4990 "Fail to add SRIOV adapter in VM ".format(str(vm_obj
))
4992 return True, vm_obj
, vcenter_conect
4994 self
.logger
.error("Currently there is no host with"\
4995 " {} number of avaialble SRIOV "\
4996 "VFs required for VM {}".format(
4997 no_of_sriov_devices
,
5000 raise vimconn
.vimconnNotFoundException(
5001 "Currently there is no host with {} "\
5002 "number of avaialble SRIOV devices required for VM {}".format(
5003 no_of_sriov_devices
,
5006 self
.logger
.debug("No infromation about SRIOV devices {} ",sriov_nets
)
5008 except vmodl
.MethodFault
as error
:
5009 self
.logger
.error("Error occurred while adding SRIOV {} ",error
)
5010 return None, vm_obj
, vcenter_conect
5013 def get_sriov_devices(self
,host
, no_of_vfs
):
5015 Method to get the details of SRIOV devices on given host
5017 host - vSphere host object
5018 no_of_vfs - number of VFs needed on host
5021 array of SRIOV devices
5025 for device
in host
.config
.pciPassthruInfo
:
5026 if isinstance(device
,vim
.host
.SriovInfo
) and device
.sriovActive
:
5027 if device
.numVirtualFunction
>= no_of_vfs
:
5028 sriovInfo
.append(device
)
5033 def get_host_and_sriov_devices(self
, content
, no_of_vfs
):
5035 Method to get the details of SRIOV devices infromation on all hosts
5038 content - vSphere host object
5039 no_of_vfs - number of pci VFs needed on host
5042 array of SRIOV devices and host object
5045 sriov_device_objs
= None
5048 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
,
5049 [vim
.HostSystem
], True)
5050 for host
in container
.view
:
5051 devices
= self
.get_sriov_devices(host
, no_of_vfs
)
5054 sriov_device_objs
= devices
5056 except Exception as exp
:
5057 self
.logger
.error("Error {} occurred while finding SRIOV devices on host: {}".format(exp
, host_obj
))
5059 return host_obj
,sriov_device_objs
5062 def add_sriov_to_vm(self
,content
, vm_obj
, host_obj
, network_name
, sriov_device
):
5064 Method to add SRIOV adapter to vm
5067 host_obj - vSphere host object
5068 vm_obj - vSphere vm object
5069 content - vCenter content object
5070 network_name - name of distributed virtaul portgroup
5071 sriov_device - SRIOV device info
5077 vnic_label
= "sriov nic"
5079 dvs_portgr
= self
.get_dvport_group(network_name
)
5080 network_name
= dvs_portgr
.name
5081 nic
= vim
.vm
.device
.VirtualDeviceSpec()
5083 nic
.operation
= vim
.vm
.device
.VirtualDeviceSpec
.Operation
.add
5084 nic
.device
= vim
.vm
.device
.VirtualSriovEthernetCard()
5085 nic
.device
.addressType
= 'assigned'
5086 #nic.device.key = 13016
5087 nic
.device
.deviceInfo
= vim
.Description()
5088 nic
.device
.deviceInfo
.label
= vnic_label
5089 nic
.device
.deviceInfo
.summary
= network_name
5090 nic
.device
.backing
= vim
.vm
.device
.VirtualEthernetCard
.NetworkBackingInfo()
5092 nic
.device
.backing
.network
= self
.get_obj(content
, [vim
.Network
], network_name
)
5093 nic
.device
.backing
.deviceName
= network_name
5094 nic
.device
.backing
.useAutoDetect
= False
5095 nic
.device
.connectable
= vim
.vm
.device
.VirtualDevice
.ConnectInfo()
5096 nic
.device
.connectable
.startConnected
= True
5097 nic
.device
.connectable
.allowGuestControl
= True
5099 nic
.device
.sriovBacking
= vim
.vm
.device
.VirtualSriovEthernetCard
.SriovBackingInfo()
5100 nic
.device
.sriovBacking
.physicalFunctionBacking
= vim
.vm
.device
.VirtualPCIPassthrough
.DeviceBackingInfo()
5101 nic
.device
.sriovBacking
.physicalFunctionBacking
.id = sriov_device
.id
5104 vmconf
= vim
.vm
.ConfigSpec(deviceChange
=devices
)
5105 task
= vm_obj
.ReconfigVM_Task(vmconf
)
5107 except Exception as exp
:
5108 self
.logger
.error("Error {} occurred while adding SRIOV adapter in VM: {}".format(exp
, vm_obj
))
5112 def create_dvPort_group(self
, network_name
):
5114 Method to create disributed virtual portgroup
5117 network_name - name of network/portgroup
5123 new_network_name
= [network_name
, '-', str(uuid
.uuid4())]
5124 network_name
=''.join(new_network_name
)
5125 vcenter_conect
, content
= self
.get_vcenter_content()
5127 dv_switch
= self
.get_obj(content
, [vim
.DistributedVirtualSwitch
], self
.dvs_name
)
5129 dv_pg_spec
= vim
.dvs
.DistributedVirtualPortgroup
.ConfigSpec()
5130 dv_pg_spec
.name
= network_name
5132 dv_pg_spec
.type = vim
.dvs
.DistributedVirtualPortgroup
.PortgroupType
.earlyBinding
5133 dv_pg_spec
.defaultPortConfig
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VmwarePortConfigPolicy()
5134 dv_pg_spec
.defaultPortConfig
.securityPolicy
= vim
.dvs
.VmwareDistributedVirtualSwitch
.SecurityPolicy()
5135 dv_pg_spec
.defaultPortConfig
.securityPolicy
.allowPromiscuous
= vim
.BoolPolicy(value
=False)
5136 dv_pg_spec
.defaultPortConfig
.securityPolicy
.forgedTransmits
= vim
.BoolPolicy(value
=False)
5137 dv_pg_spec
.defaultPortConfig
.securityPolicy
.macChanges
= vim
.BoolPolicy(value
=False)
5139 task
= dv_switch
.AddDVPortgroup_Task([dv_pg_spec
])
5140 self
.wait_for_vcenter_task(task
, vcenter_conect
)
5142 dvPort_group
= self
.get_obj(content
, [vim
.dvs
.DistributedVirtualPortgroup
], network_name
)
5144 self
.logger
.info("Created disributed virtaul port group: {}".format(dvPort_group
))
5145 return dvPort_group
.key
5147 self
.logger
.debug("No disributed virtual switch found with name {}".format(network_name
))
5149 except Exception as exp
:
5150 self
.logger
.error("Error occurred while creating disributed virtaul port group {}"\
5151 " : {}".format(network_name
, exp
))
5154 def reconfig_portgroup(self
, content
, dvPort_group_name
, config_info
={}):
5156 Method to reconfigure disributed virtual portgroup
5159 dvPort_group_name - name of disributed virtual portgroup
5160 content - vCenter content object
5161 config_info - disributed virtual portgroup configuration
5167 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
5169 dv_pg_spec
= vim
.dvs
.DistributedVirtualPortgroup
.ConfigSpec()
5170 dv_pg_spec
.configVersion
= dvPort_group
.config
.configVersion
5171 dv_pg_spec
.defaultPortConfig
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VmwarePortConfigPolicy()
5172 if "vlanID" in config_info
:
5173 dv_pg_spec
.defaultPortConfig
.vlan
= vim
.dvs
.VmwareDistributedVirtualSwitch
.VlanIdSpec()
5174 dv_pg_spec
.defaultPortConfig
.vlan
.vlanId
= config_info
.get('vlanID')
5176 task
= dvPort_group
.ReconfigureDVPortgroup_Task(spec
=dv_pg_spec
)
5180 except Exception as exp
:
5181 self
.logger
.error("Error occurred while reconfiguraing disributed virtaul port group {}"\
5182 " : {}".format(dvPort_group_name
, exp
))
5186 def destroy_dvport_group(self
, dvPort_group_name
):
5188 Method to destroy disributed virtual portgroup
5191 network_name - name of network/portgroup
5194 True if portgroup successfully got deleted else false
5196 vcenter_conect
, content
= self
.get_vcenter_content()
5199 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
5201 task
= dvPort_group
.Destroy_Task()
5202 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5204 except vmodl
.MethodFault
as exp
:
5205 self
.logger
.error("Caught vmodl fault {} while deleting disributed virtaul port group {}".format(
5206 exp
, dvPort_group_name
))
5210 def get_dvport_group(self
, dvPort_group_name
):
5212 Method to get disributed virtual portgroup
5215 network_name - name of network/portgroup
5220 vcenter_conect
, content
= self
.get_vcenter_content()
5223 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
, [vim
.dvs
.DistributedVirtualPortgroup
], True)
5224 for item
in container
.view
:
5225 if item
.key
== dvPort_group_name
:
5229 except vmodl
.MethodFault
as exp
:
5230 self
.logger
.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
5231 exp
, dvPort_group_name
))
5234 def get_vlanID_from_dvs_portgr(self
, dvPort_group_name
):
5236 Method to get disributed virtual portgroup vlanID
5239 network_name - name of network/portgroup
5246 dvPort_group
= self
.get_dvport_group(dvPort_group_name
)
5248 vlanId
= dvPort_group
.config
.defaultPortConfig
.vlan
.vlanId
5249 except vmodl
.MethodFault
as exp
:
5250 self
.logger
.error("Caught vmodl fault {} for disributed virtaul port group {}".format(
5251 exp
, dvPort_group_name
))
5255 def configure_vlanID(self
, content
, vcenter_conect
, dvPort_group_name
):
5257 Method to configure vlanID in disributed virtual portgroup vlanID
5260 network_name - name of network/portgroup
5265 vlanID
= self
.get_vlanID_from_dvs_portgr(dvPort_group_name
)
5268 vlanID
= self
.genrate_vlanID(dvPort_group_name
)
5269 config
= {"vlanID":vlanID
}
5270 task
= self
.reconfig_portgroup(content
, dvPort_group_name
,
5273 status
= self
.wait_for_vcenter_task(task
, vcenter_conect
)
5275 self
.logger
.info("Reconfigured Port group {} for vlan ID {}".format(
5276 dvPort_group_name
,vlanID
))
5278 self
.logger
.error("Fail reconfigure portgroup {} for vlanID{}".format(
5279 dvPort_group_name
, vlanID
))
5282 def genrate_vlanID(self
, network_name
):
5284 Method to get unused vlanID
5286 network_name - name of network/portgroup
5292 if self
.config
.get('vlanID_range') == None:
5293 raise vimconn
.vimconnConflictException("You must provide a 'vlanID_range' "\
5294 "at config value before creating sriov network with vlan tag")
5295 if "used_vlanIDs" not in self
.persistent_info
:
5296 self
.persistent_info
["used_vlanIDs"] = {}
5298 used_ids
= self
.persistent_info
["used_vlanIDs"].values()
5300 #used_ids = list(self.persistent_info["used_vlanIDs"].values())
5302 for vlanID_range
in self
.config
.get('vlanID_range'):
5303 start_vlanid
, end_vlanid
= vlanID_range
.split("-")
5304 if start_vlanid
> end_vlanid
:
5305 raise vimconn
.vimconnConflictException("Invalid vlan ID range {}".format(
5308 for id in xrange(int(start_vlanid
), int(end_vlanid
) + 1):
5310 #for id in range(int(start_vlanid), int(end_vlanid) + 1):
5311 if id not in used_ids
:
5313 self
.persistent_info
["used_vlanIDs"][network_name
] = vlan_id
5316 raise vimconn
.vimconnConflictException("All Vlan IDs are in use")
5319 def get_obj(self
, content
, vimtype
, name
):
5321 Get the vsphere object associated with a given text name
5324 container
= content
.viewManager
.CreateContainerView(content
.rootFolder
, vimtype
, True)
5325 for item
in container
.view
:
5326 if item
.name
== name
:
5332 def insert_media_to_vm(self
, vapp
, image_id
):
5334 Method to insert media CD-ROM (ISO image) from catalog to vm.
5335 vapp - vapp object to get vm id
5336 Image_id - image id for cdrom to be inerted to vm
5338 # create connection object
5339 vca
= self
.connect()
5341 # fetching catalog details
5342 rest_url
= "{}/api/catalog/{}".format(self
.url
, image_id
)
5344 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5345 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
5346 response
= self
.perform_request(req_type
='GET',
5350 if response
.status_code
!= 200:
5351 self
.logger
.error("REST call {} failed reason : {}"\
5352 "status code : {}".format(url_rest_call
,
5354 response
.status_code
))
5355 raise vimconn
.vimconnException("insert_media_to_vm(): Failed to get "\
5357 # searching iso name and id
5358 iso_name
,media_id
= self
.get_media_details(vca
, response
.content
)
5360 if iso_name
and media_id
:
5361 data
="""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
5362 <ns6:MediaInsertOrEjectParams
5363 xmlns="http://www.vmware.com/vcloud/versions" xmlns:ns2="http://schemas.dmtf.org/ovf/envelope/1" xmlns:ns3="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:ns6="http://www.vmware.com/vcloud/v1.5" xmlns:ns7="http://www.vmware.com/schema/ovf" xmlns:ns8="http://schemas.dmtf.org/ovf/environment/1" xmlns:ns9="http://www.vmware.com/vcloud/extension/v1.5">
5365 type="application/vnd.vmware.vcloud.media+xml"
5367 id="urn:vcloud:media:{}"
5368 href="https://{}/api/media/{}"/>
5369 </ns6:MediaInsertOrEjectParams>""".format(iso_name
, media_id
,
5372 for vms
in vapp
.get_all_vms():
5373 vm_id
= vms
.get('id').split(':')[-1]
5375 headers
['Content-Type'] = 'application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml'
5376 rest_url
= "{}/api/vApp/vm-{}/media/action/insertMedia".format(self
.url
,vm_id
)
5378 response
= self
.perform_request(req_type
='POST',
5383 if response
.status_code
!= 202:
5384 self
.logger
.error("Failed to insert CD-ROM to vm")
5385 raise vimconn
.vimconnException("insert_media_to_vm() : Failed to insert"\
5388 task
= self
.get_task_from_response(response
.content
)
5389 result
= self
.client
.get_task_monitor().wait_for_success(task
=task
)
5390 if result
.get('status') == 'success':
5391 self
.logger
.info("insert_media_to_vm(): Sucessfully inserted media ISO"\
5392 " image to vm {}".format(vm_id
))
5394 except Exception as exp
:
5395 self
.logger
.error("insert_media_to_vm() : exception occurred "\
5396 "while inserting media CD-ROM")
5397 raise vimconn
.vimconnException(message
=exp
)
5400 def get_media_details(self
, vca
, content
):
5402 Method to get catalog item details
5403 vca - connection object
5404 content - Catalog details
5405 Return - Media name, media id
5407 cataloghref_list
= []
5410 vm_list_xmlroot
= XmlElementTree
.fromstring(content
)
5411 for child
in vm_list_xmlroot
.iter():
5412 if 'CatalogItem' in child
.tag
:
5413 cataloghref_list
.append(child
.attrib
.get('href'))
5414 if cataloghref_list
is not None:
5415 for href
in cataloghref_list
:
5417 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5418 'x-vcloud-authorization': vca
._session
.headers
['x-vcloud-authorization']}
5419 response
= self
.perform_request(req_type
='GET',
5422 if response
.status_code
!= 200:
5423 self
.logger
.error("REST call {} failed reason : {}"\
5424 "status code : {}".format(href
,
5426 response
.status_code
))
5427 raise vimconn
.vimconnException("get_media_details : Failed to get "\
5428 "catalogitem details")
5429 list_xmlroot
= XmlElementTree
.fromstring(response
.content
)
5430 for child
in list_xmlroot
.iter():
5431 if 'Entity' in child
.tag
:
5432 if 'media' in child
.attrib
.get('href'):
5433 name
= child
.attrib
.get('name')
5434 media_id
= child
.attrib
.get('href').split('/').pop()
5435 return name
,media_id
5437 self
.logger
.debug("Media name and id not found")
5439 except Exception as exp
:
5440 self
.logger
.error("get_media_details : exception occurred "\
5441 "getting media details")
5442 raise vimconn
.vimconnException(message
=exp
)
5445 def retry_rest(self
, method
, url
, add_headers
=None, data
=None):
5446 """ Method to get Token & retry respective REST request
5448 api - REST API - Can be one of 'GET' or 'PUT' or 'POST'
5449 url - request url to be used
5450 add_headers - Additional headers (optional)
5451 data - Request payload data to be passed in request
5453 response - Response of request
5460 if self
.client
._session
:
5461 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5462 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
5465 headers
.update(add_headers
)
5468 response
= self
.perform_request(req_type
='GET',
5471 elif method
== 'PUT':
5472 response
= self
.perform_request(req_type
='PUT',
5476 elif method
== 'POST':
5477 response
= self
.perform_request(req_type
='POST',
5481 elif method
== 'DELETE':
5482 response
= self
.perform_request(req_type
='DELETE',
5488 def get_token(self
):
5489 """ Generate a new token if expired
5492 The return client object that letter can be used to connect to vCloud director as admin for VDC
5495 self
.logger
.debug("Generate token for vca {} as {} to datacenter {}.".format(self
.org_name
,
5499 client
= Client(host
, verify_ssl_certs
=False)
5500 client
.set_credentials(BasicLoginCredentials(self
.user
, self
.org_name
, self
.passwd
))
5502 self
.client
= client
5505 raise vimconn
.vimconnConnectionException("Can't connect to a vCloud director org: "
5506 "{} as user: {}".format(self
.org_name
, self
.user
))
5509 raise vimconn
.vimconnConnectionException("Failed while reconnecting vCD")
5512 def get_vdc_details(self
):
5513 """ Get VDC details using pyVcloud Lib
5515 Returns org and vdc object
5517 org
= Org(self
.client
, resource
=self
.client
.get_org())
5518 vdc
= org
.get_vdc(self
.tenant_name
)
5520 #Retry once, if failed by refreshing token
5523 vdc
= org
.get_vdc(self
.tenant_name
)
5528 def perform_request(self
, req_type
, url
, headers
=None, data
=None):
5529 """Perform the POST/PUT/GET/DELETE request."""
5531 #Log REST request details
5532 self
.log_request(req_type
, url
=url
, headers
=headers
, data
=data
)
5533 # perform request and return its result
5534 if req_type
== 'GET':
5535 response
= requests
.get(url
=url
,
5538 elif req_type
== 'PUT':
5539 response
= requests
.put(url
=url
,
5543 elif req_type
== 'POST':
5544 response
= requests
.post(url
=url
,
5548 elif req_type
== 'DELETE':
5549 response
= requests
.delete(url
=url
,
5552 #Log the REST response
5553 self
.log_response(response
)
5558 def log_request(self
, req_type
, url
=None, headers
=None, data
=None):
5559 """Logs REST request details"""
5561 if req_type
is not None:
5562 self
.logger
.debug("Request type: {}".format(req_type
))
5565 self
.logger
.debug("Request url: {}".format(url
))
5567 if headers
is not None:
5568 for header
in headers
:
5569 self
.logger
.debug("Request header: {}: {}".format(header
, headers
[header
]))
5571 if data
is not None:
5572 self
.logger
.debug("Request data: {}".format(data
))
5575 def log_response(self
, response
):
5576 """Logs REST response details"""
5578 self
.logger
.debug("Response status code: {} ".format(response
.status_code
))
5581 def get_task_from_response(self
, content
):
5583 content - API response content(response.content)
5586 xmlroot
= XmlElementTree
.fromstring(content
)
5587 if xmlroot
.tag
.split('}')[1] == "Task":
5591 if ele
.tag
.split("}")[1] == "Tasks":
5597 def power_on_vapp(self
,vapp_id
, vapp_name
):
5600 vapp_name - vAapp name
5601 return - Task object
5603 headers
= {'Accept':'application/*+xml;version=' + API_VERSION
,
5604 'x-vcloud-authorization': self
.client
._session
.headers
['x-vcloud-authorization']}
5606 poweron_href
= "{}/api/vApp/vapp-{}/power/action/powerOn".format(self
.url
,
5608 response
= self
.perform_request(req_type
='POST',
5612 if response
.status_code
!= 202:
5613 self
.logger
.error("REST call {} failed reason : {}"\
5614 "status code : {} ".format(poweron_href
,
5616 response
.status_code
))
5617 raise vimconn
.vimconnException("power_on_vapp() : Failed to power on "\
5618 "vApp {}".format(vapp_name
))
5620 poweron_task
= self
.get_task_from_response(response
.content
)