+ def create_config_drive_iso(self, user_data):
+ tmpdir = tempfile.mkdtemp()
+ iso_path = os.path.join(tmpdir, 'ConfigDrive.iso')
+ latest_dir = os.path.join(tmpdir, 'openstack', 'latest')
+ os.makedirs(latest_dir)
+ with open(os.path.join(latest_dir, 'meta_data.json'), 'w') as meta_file_obj, \
+ open(os.path.join(latest_dir, 'user_data'), 'w') as userdata_file_obj:
+ userdata_file_obj.write(user_data)
+ meta_file_obj.write(json.dumps({"availability_zone": "nova",
+ "launch_index": 0,
+ "name": "ConfigDrive",
+ "uuid": str(uuid.uuid4())}
+ )
+ )
+ genisoimage_cmd = 'genisoimage -J -r -V config-2 -o {iso_path} {source_dir_path}'.format(
+ iso_path=iso_path, source_dir_path=tmpdir)
+ self.logger.info('create_config_drive_iso(): Creating ISO by running command "{}"'.format(genisoimage_cmd))
+ try:
+ FNULL = open(os.devnull, 'w')
+ subprocess.check_call(genisoimage_cmd, shell=True, stdout=FNULL)
+ except subprocess.CalledProcessError as e:
+ shutil.rmtree(tmpdir, ignore_errors=True)
+ error_msg = 'create_config_drive_iso(): Exception while running genisoimage command: {}'.format(e)
+ self.logger.error(error_msg)
+ raise Exception(error_msg)
+ return iso_path
+
+ def upload_iso_to_catalog(self, catalog_id, iso_file_path):
+ if not os.path.isfile(iso_file_path):
+ error_msg = "upload_iso_to_catalog(): Given iso file is not present. Given path: {}".format(iso_file_path)
+ self.logger.error(error_msg)
+ raise Exception(error_msg)
+ iso_file_stat = os.stat(iso_file_path)
+ xml_media_elem = '''<?xml version="1.0" encoding="UTF-8"?>
+ <Media
+ xmlns="http://www.vmware.com/vcloud/v1.5"
+ name="{iso_name}"
+ size="{iso_size}"
+ imageType="iso">
+ <Description>ISO image for config-drive</Description>
+ </Media>'''.format(iso_name=os.path.basename(iso_file_path), iso_size=iso_file_stat.st_size)
+ headers = {'Accept':'application/*+xml;version=' + API_VERSION,
+ 'x-vcloud-authorization': self.client._session.headers['x-vcloud-authorization']}
+ headers['Content-Type'] = 'application/vnd.vmware.vcloud.media+xml'
+ catalog_href = self.url + '/api/catalog/' + catalog_id + '/action/upload'
+ response = self.perform_request(req_type='POST', url=catalog_href, headers=headers, data=xml_media_elem)
+
+ if response.status_code != 201:
+ error_msg = "upload_iso_to_catalog(): Failed to POST an action/upload request to {}".format(catalog_href)
+ self.logger.error(error_msg)
+ raise Exception(error_msg)
+
+ catalogItem = XmlElementTree.fromstring(response.content)
+ entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.media+xml"][0]
+ entity_href = entity.get('href')
+
+ response = self.perform_request(req_type='GET', url=entity_href, headers=headers)
+ if response.status_code != 200:
+ raise Exception("upload_iso_to_catalog(): Failed to GET entity href {}".format(entity_href))
+
+ match = re.search(r'<Files>\s+?<File.+?href="(.+?)"/>\s+?</File>\s+?</Files>', response.text, re.DOTALL)
+ if match:
+ media_upload_href = match.group(1)
+ else:
+ raise Exception('Could not parse the upload URL for the media file from the last response')
+
+ headers['Content-Type'] = 'application/octet-stream'
+ response = self.perform_request(req_type='PUT',
+ url=media_upload_href,
+ headers=headers,
+ data=open(iso_file_path, 'rb'))
+
+ if response.status_code != 200:
+ raise Exception('PUT request to "{}" failed'.format(media_upload_href))
+
+ def get_vcd_availibility_zones(self,respool_href, headers):
+ """ Method to find presence of av zone is VIM resource pool
+
+ Args:
+ respool_href - resource pool href
+ headers - header information
+
+ Returns:
+ vcd_az - list of azone present in vCD
+ """
+ vcd_az = []
+ url=respool_href
+ resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(url, resp.status_code))
+ else:
+ #Get the href to hostGroups and find provided hostGroup is present in it
+ resp_xml = XmlElementTree.fromstring(resp.content)
+ for child in resp_xml:
+ if 'VMWProviderVdcResourcePool' in child.tag:
+ for schild in child:
+ if 'Link' in schild.tag:
+ if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
+ hostGroup = schild.attrib.get('href')
+ hg_resp = self.perform_request(req_type='GET',url=hostGroup, headers=headers)
+ if hg_resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(hostGroup, hg_resp.status_code))
+ else:
+ hg_resp_xml = XmlElementTree.fromstring(hg_resp.content)
+ for hostGroup in hg_resp_xml:
+ if 'HostGroup' in hostGroup.tag:
+ #append host group name to the list
+ vcd_az.append(hostGroup.attrib.get("name"))
+ return vcd_az
+
+
+ def set_availability_zones(self):
+ """
+ Set vim availability zone
+ """
+
+ vim_availability_zones = None
+ availability_zone = None
+ if 'availability_zone' in self.config:
+ vim_availability_zones = self.config.get('availability_zone')
+ if isinstance(vim_availability_zones, str):
+ availability_zone = [vim_availability_zones]
+ elif isinstance(vim_availability_zones, list):
+ availability_zone = vim_availability_zones
+ else:
+ return availability_zone
+
+ return availability_zone
+
+
+ def get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
+ """
+ Return the availability zone to be used by the created VM.
+ returns: The VIM availability zone to be used or None
+ """
+ if availability_zone_index is None:
+ if not self.config.get('availability_zone'):
+ return None
+ elif isinstance(self.config.get('availability_zone'), str):
+ return self.config['availability_zone']
+ else:
+ return self.config['availability_zone'][0]
+
+ vim_availability_zones = self.availability_zone
+
+ # check if VIM offer enough availability zones describe in the VNFD
+ if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
+ # check if all the names of NFV AV match VIM AV names
+ match_by_index = False
+ for av in availability_zone_list:
+ if av not in vim_availability_zones:
+ match_by_index = True
+ break
+ if match_by_index:
+ self.logger.debug("Required Availability zone or Host Group not found in VIM config")
+ self.logger.debug("Input Availability zone list: {}".format(availability_zone_list))
+ self.logger.debug("VIM configured Availability zones: {}".format(vim_availability_zones))
+ self.logger.debug("VIM Availability zones will be used by index")
+ return vim_availability_zones[availability_zone_index]
+ else:
+ return availability_zone_list[availability_zone_index]
+ else:
+ raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
+
+
+ def create_vm_to_host_affinity_rule(self, addrule_href, vmgrpname, hostgrpname, polarity, headers):
+ """ Method to create VM to Host Affinity rule in vCD
+
+ Args:
+ addrule_href - href to make a POST request
+ vmgrpname - name of the VM group created
+ hostgrpnmae - name of the host group created earlier
+ polarity - Affinity or Anti-affinity (default: Affinity)
+ headers - headers to make REST call
+
+ Returns:
+ True- if rule is created
+ False- Failed to create rule due to some error
+
+ """
+ task_status = False
+ rule_name = polarity + "_" + vmgrpname
+ payload = """<?xml version="1.0" encoding="UTF-8"?>
+ <vmext:VMWVmHostAffinityRule
+ xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5"
+ xmlns:vcloud="http://www.vmware.com/vcloud/v1.5"
+ type="application/vnd.vmware.admin.vmwVmHostAffinityRule+xml">
+ <vcloud:Name>{}</vcloud:Name>
+ <vcloud:IsEnabled>true</vcloud:IsEnabled>
+ <vcloud:IsMandatory>true</vcloud:IsMandatory>
+ <vcloud:Polarity>{}</vcloud:Polarity>
+ <vmext:HostGroupName>{}</vmext:HostGroupName>
+ <vmext:VmGroupName>{}</vmext:VmGroupName>
+ </vmext:VMWVmHostAffinityRule>""".format(rule_name, polarity, hostgrpname, vmgrpname)
+
+ resp = self.perform_request(req_type='POST',url=addrule_href, headers=headers, data=payload)
+
+ if resp.status_code != requests.codes.accepted:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(addrule_href, resp.status_code))
+ task_status = False
+ return task_status
+ else:
+ affinity_task = self.get_task_from_response(resp.content)
+ self.logger.debug ("affinity_task: {}".format(affinity_task))
+ if affinity_task is None or affinity_task is False:
+ raise vimconn.vimconnUnexpectedResponse("failed to find affinity task")
+ # wait for task to complete
+ result = self.client.get_task_monitor().wait_for_success(task=affinity_task)
+ if result.get('status') == 'success':
+ self.logger.debug("Successfully created affinity rule {}".format(rule_name))
+ return True
+ else:
+ raise vimconn.vimconnUnexpectedResponse(
+ "failed to create affinity rule {}".format(rule_name))
+
+
+ def get_add_rule_reference (self, respool_href, headers):
+ """ This method finds href to add vm to host affinity rule to vCD
+
+ Args:
+ respool_href- href to resource pool
+ headers- header information to make REST call
+
+ Returns:
+ None - if no valid href to add rule found or
+ addrule_href - href to add vm to host affinity rule of resource pool
+ """
+ addrule_href = None
+ resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(respool_href, resp.status_code))
+ else:
+
+ resp_xml = XmlElementTree.fromstring(resp.content)
+ for child in resp_xml:
+ if 'VMWProviderVdcResourcePool' in child.tag:
+ for schild in child:
+ if 'Link' in schild.tag:
+ if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwVmHostAffinityRule+xml" and \
+ schild.attrib.get('rel') == "add":
+ addrule_href = schild.attrib.get('href')
+ break
+
+ return addrule_href
+
+
+ def add_vm_to_vmgroup(self, vm_uuid, vmGroupNameURL, vmGroup_name, headers):
+ """ Method to add deployed VM to newly created VM Group.
+ This is required to create VM to Host affinity in vCD
+
+ Args:
+ vm_uuid- newly created vm uuid
+ vmGroupNameURL- URL to VM Group name
+ vmGroup_name- Name of VM group created
+ headers- Headers for REST request
+
+ Returns:
+ True- if VM added to VM group successfully
+ False- if any error encounter
+ """
+
+ addvm_resp = self.perform_request(req_type='GET',url=vmGroupNameURL, headers=headers)#, data=payload)
+
+ if addvm_resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call to get VM Group Name url {} failed. Return status code {}"\
+ .format(vmGroupNameURL, addvm_resp.status_code))
+ return False
+ else:
+ resp_xml = XmlElementTree.fromstring(addvm_resp.content)
+ for child in resp_xml:
+ if child.tag.split('}')[1] == 'Link':
+ if child.attrib.get("rel") == "addVms":
+ addvmtogrpURL = child.attrib.get("href")
+
+ #Get vm details
+ url_list = [self.url, '/api/vApp/vm-',vm_uuid]
+ vmdetailsURL = ''.join(url_list)
+
+ resp = self.perform_request(req_type='GET',url=vmdetailsURL, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(vmdetailsURL, resp.status_code))
+ return False
+
+ #Parse VM details
+ resp_xml = XmlElementTree.fromstring(resp.content)
+ if resp_xml.tag.split('}')[1] == "Vm":
+ vm_id = resp_xml.attrib.get("id")
+ vm_name = resp_xml.attrib.get("name")
+ vm_href = resp_xml.attrib.get("href")
+ #print vm_id, vm_name, vm_href
+ #Add VM into VMgroup
+ payload = """<?xml version="1.0" encoding="UTF-8"?>\
+ <ns2:Vms xmlns:ns2="http://www.vmware.com/vcloud/v1.5" \
+ xmlns="http://www.vmware.com/vcloud/versions" \
+ xmlns:ns3="http://schemas.dmtf.org/ovf/envelope/1" \
+ xmlns:ns4="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" \
+ xmlns:ns5="http://schemas.dmtf.org/wbem/wscim/1/common" \
+ xmlns:ns6="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" \
+ 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">\
+ <ns2:VmReference href="{}" id="{}" name="{}" \
+ type="application/vnd.vmware.vcloud.vm+xml" />\
+ </ns2:Vms>""".format(vm_href, vm_id, vm_name)
+
+ addvmtogrp_resp = self.perform_request(req_type='POST',url=addvmtogrpURL, headers=headers, data=payload)
+
+ if addvmtogrp_resp.status_code != requests.codes.accepted:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(addvmtogrpURL, addvmtogrp_resp.status_code))
+ return False
+ else:
+ self.logger.debug ("Done adding VM {} to VMgroup {}".format(vm_name, vmGroup_name))
+ return True
+
+
+ def create_vmgroup(self, vmgroup_name, vmgroup_href, headers):
+ """Method to create a VM group in vCD
+
+ Args:
+ vmgroup_name : Name of VM group to be created
+ vmgroup_href : href for vmgroup
+ headers- Headers for REST request
+ """
+ #POST to add URL with required data
+ vmgroup_status = False
+ payload = """<VMWVmGroup xmlns="http://www.vmware.com/vcloud/extension/v1.5" \
+ xmlns:vcloud_v1.5="http://www.vmware.com/vcloud/v1.5" name="{}">\
+ <vmCount>1</vmCount>\
+ </VMWVmGroup>""".format(vmgroup_name)
+ resp = self.perform_request(req_type='POST',url=vmgroup_href, headers=headers, data=payload)
+
+ if resp.status_code != requests.codes.accepted:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(vmgroup_href, resp.status_code))
+ return vmgroup_status
+ else:
+ vmgroup_task = self.get_task_from_response(resp.content)
+ if vmgroup_task is None or vmgroup_task is False:
+ raise vimconn.vimconnUnexpectedResponse(
+ "create_vmgroup(): failed to create VM group {}".format(vmgroup_name))
+
+ # wait for task to complete
+ result = self.client.get_task_monitor().wait_for_success(task=vmgroup_task)
+
+ if result.get('status') == 'success':
+ self.logger.debug("create_vmgroup(): Successfully created VM group {}".format(vmgroup_name))
+ #time.sleep(10)
+ vmgroup_status = True
+ return vmgroup_status
+ else:
+ raise vimconn.vimconnUnexpectedResponse(\
+ "create_vmgroup(): failed to create VM group {}".format(vmgroup_name))
+
+
+ def find_vmgroup_reference(self, url, headers):
+ """ Method to create a new VMGroup which is required to add created VM
+ Args:
+ url- resource pool href
+ headers- header information
+
+ Returns:
+ returns href to VM group to create VM group
+ """
+ #Perform GET on resource pool to find 'add' link to create VMGroup
+ #https://vcd-ip/api/admin/extension/providervdc/<providervdc id>/resourcePools
+ vmgrp_href = None
+ resp = self.perform_request(req_type='GET',url=url, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(url, resp.status_code))
+ else:
+ #Get the href to add vmGroup to vCD
+ resp_xml = XmlElementTree.fromstring(resp.content)
+ for child in resp_xml:
+ if 'VMWProviderVdcResourcePool' in child.tag:
+ for schild in child:
+ if 'Link' in schild.tag:
+ #Find href with type VMGroup and rel with add
+ if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwVmGroupType+xml"\
+ and schild.attrib.get('rel') == "add":
+ vmgrp_href = schild.attrib.get('href')
+ return vmgrp_href
+
+
+ def check_availibility_zone(self, az, respool_href, headers):
+ """ Method to verify requested av zone is present or not in provided
+ resource pool
+
+ Args:
+ az - name of hostgroup (availibility_zone)
+ respool_href - Resource Pool href
+ headers - Headers to make REST call
+ Returns:
+ az_found - True if availibility_zone is found else False
+ """
+ az_found = False
+ headers['Accept']='application/*+xml;version=27.0'
+ resp = self.perform_request(req_type='GET',url=respool_href, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(respool_href, resp.status_code))
+ else:
+ #Get the href to hostGroups and find provided hostGroup is present in it
+ resp_xml = XmlElementTree.fromstring(resp.content)
+
+ for child in resp_xml:
+ if 'VMWProviderVdcResourcePool' in child.tag:
+ for schild in child:
+ if 'Link' in schild.tag:
+ if schild.attrib.get('type') == "application/vnd.vmware.admin.vmwHostGroupsType+xml":
+ hostGroup_href = schild.attrib.get('href')
+ hg_resp = self.perform_request(req_type='GET',url=hostGroup_href, headers=headers)
+ if hg_resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}".format(hostGroup_href, hg_resp.status_code))
+ else:
+ hg_resp_xml = XmlElementTree.fromstring(hg_resp.content)
+ for hostGroup in hg_resp_xml:
+ if 'HostGroup' in hostGroup.tag:
+ if hostGroup.attrib.get("name") == az:
+ az_found = True
+ break
+ return az_found
+
+
+ def get_pvdc_for_org(self, org_vdc, headers):
+ """ This method gets provider vdc references from organisation
+
+ Args:
+ org_vdc - name of the organisation VDC to find pvdc
+ headers - headers to make REST call
+
+ Returns:
+ None - if no pvdc href found else
+ pvdc_href - href to pvdc
+ """
+
+ #Get provider VDC references from vCD
+ pvdc_href = None
+ #url = '<vcd url>/api/admin/extension/providerVdcReferences'
+ url_list = [self.url, '/api/admin/extension/providerVdcReferences']
+ url = ''.join(url_list)
+
+ response = self.perform_request(req_type='GET',url=url, headers=headers)
+ if response.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}"\
+ .format(url, response.status_code))
+ else:
+ xmlroot_response = XmlElementTree.fromstring(response.content)
+ for child in xmlroot_response:
+ if 'ProviderVdcReference' in child.tag:
+ pvdc_href = child.attrib.get('href')
+ #Get vdcReferences to find org
+ pvdc_resp = self.perform_request(req_type='GET',url=pvdc_href, headers=headers)
+ if pvdc_resp.status_code != requests.codes.ok:
+ raise vimconn.vimconnException("REST API call {} failed. "\
+ "Return status code {}"\
+ .format(url, pvdc_resp.status_code))
+
+ pvdc_resp_xml = XmlElementTree.fromstring(pvdc_resp.content)
+ for child in pvdc_resp_xml:
+ if 'Link' in child.tag:
+ if child.attrib.get('type') == "application/vnd.vmware.admin.vdcReferences+xml":
+ vdc_href = child.attrib.get('href')
+
+ #Check if provided org is present in vdc
+ vdc_resp = self.perform_request(req_type='GET',
+ url=vdc_href,
+ headers=headers)
+ if vdc_resp.status_code != requests.codes.ok:
+ raise vimconn.vimconnException("REST API call {} failed. "\
+ "Return status code {}"\
+ .format(url, vdc_resp.status_code))
+ vdc_resp_xml = XmlElementTree.fromstring(vdc_resp.content)
+ for child in vdc_resp_xml:
+ if 'VdcReference' in child.tag:
+ if child.attrib.get('name') == org_vdc:
+ return pvdc_href
+
+
+ def get_resource_pool_details(self, pvdc_href, headers):
+ """ Method to get resource pool information.
+ Host groups are property of resource group.
+ To get host groups, we need to GET details of resource pool.
+
+ Args:
+ pvdc_href: href to pvdc details
+ headers: headers
+
+ Returns:
+ respool_href - Returns href link reference to resource pool
+ """
+ respool_href = None
+ resp = self.perform_request(req_type='GET',url=pvdc_href, headers=headers)
+
+ if resp.status_code != requests.codes.ok:
+ self.logger.debug ("REST API call {} failed. Return status code {}"\
+ .format(pvdc_href, resp.status_code))
+ else:
+ respool_resp_xml = XmlElementTree.fromstring(resp.content)
+ for child in respool_resp_xml:
+ if 'Link' in child.tag:
+ if child.attrib.get('type') == "application/vnd.vmware.admin.vmwProviderVdcResourcePoolSet+xml":
+ respool_href = child.attrib.get("href")
+ break
+ return respool_href
+
+
+ def log_message(self, msg):
+ """
+ Method to log error messages related to Affinity rule creation
+ in new_vminstance & raise Exception
+ Args :
+ msg - Error message to be logged
+
+ """
+ #get token to connect vCD as a normal user
+ self.get_token()
+ self.logger.debug(msg)
+ raise vimconn.vimconnException(msg)
+
+