Beispiel #1
0
 def delete_catalog(self, catalog_name):
     admin_url = None
     if not self.vcloud_session or not self.vcloud_session.organization: return False
     if 'ondemand' == self.service_type:
         refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.admin.organization+xml',
                              self.vcloud_session.organization.Link)
         if len(refs) == 1:
             admin_url = refs[0].href
     else:
         refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.admin.catalog+xml',
                              self.vcloud_session.organization.Link)
         if len(refs) == 1:
             admin_url = refs[0].href[:refs[0].href.rindex('/')]
     if admin_url:
         self.response = Http.get(admin_url, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             adminOrg = vCloudEntities.parseString(self.response.content, True)
             if adminOrg and adminOrg.Catalogs and adminOrg.Catalogs.CatalogReference:
                 catRefs = filter(lambda ref: ref.name == catalog_name and ref.type_ == 'application/vnd.vmware.admin.catalog+xml',
                                         adminOrg.Catalogs.CatalogReference)
                 if len(catRefs) == 1:
                     self.response = Http.delete(catRefs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                     if self.response.status_code == requests.codes.no_content:
                         return True
     return False
Beispiel #2
0
 def get_instances(self):
     self.response = Http.get(self.host + "/api/sc/instances", headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger)
     if self.response.history and self.response.history[-1]:
         self.response = Http.get(self.response.history[-1].headers['location'], headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         return json.loads(self.response.content)['instances']
     else:
         return None
Beispiel #3
0
 def get_plans(self):
     headers = self._get_vcloud_headers()
     headers['Accept'] = "application/json;version=%s;class=com.vmware.vchs.sc.restapi.model.planlisttype" % self.version
     self.response = Http.get(self.host + "/api/sc/plans", headers=headers, verify=self.verify, logger=self.logger)
     if self.response.history and self.response.history[-1]:
         self.response = Http.get(self.response.history[-1].headers['location'], headers=headers, verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         return json.loads(self.response.content)['plans']
     else:
         return None
Beispiel #4
0
    def create_vapp(self, vdc_name, vapp_name, template_name, catalog_name,
                    network_name=None, network_mode='bridged', vm_name=None,
                    vm_cpus=None, vm_memory=None, deploy='false',
                    poweron='false'):
        self.vdc = self.get_vdc(vdc_name)
        if not self.vcloud_session or not self.vcloud_session.organization or not self.vdc:
            #"Select an organization and datacenter first"
            return False
        if '' == vm_name: vm_name = None
        catalogs = filter(lambda link: catalog_name == link.get_name() and link.get_type() == "application/vnd.vmware.vcloud.catalog+xml",
                                 self.vcloud_session.organization.get_Link())
        if len(catalogs) == 1:
            self.response = Http.get(catalogs[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.ok:
                catalog = catalogType.parseString(self.response.content, True)
                catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == template_name, catalog.get_CatalogItems().get_CatalogItem())
                if len(catalog_items) == 1:
                    self.response = Http.get(catalog_items[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                    # use ElementTree instead because none of the types inside resources (not even catalogItemType) is able to parse the response correctly
                    catalogItem = ET.fromstring(self.response.content)
                    entity = [child for child in catalogItem if child.get("type") == "application/vnd.vmware.vcloud.vAppTemplate+xml"][0]
                    vm_href = None
                    if vm_name:
                        self.response = Http.get(entity.get('href'), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                        if self.response.status_code == requests.codes.ok:
                            vAppTemplate = ET.fromstring(self.response.content)
                            for vm in vAppTemplate.iter('{http://www.vmware.com/vcloud/v1.5}Vm'):
                                vm_href = vm.get('href')
                    template_params = self._create_instantiateVAppTemplateParams(
                        vapp_name, entity.get("href"), vm_name=vm_name,
                        vm_href=vm_href, vm_cpus=vm_cpus, vm_memory=vm_memory,
                        deploy=deploy, power=poweron)

                    if network_name:
                        pass
                    output = StringIO()
                    template_params.export(output,
                        0,
                        name_ = 'InstantiateVAppTemplateParams',
                        namespacedef_ = '''xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
                                           xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"''',
                                           pretty_print = False)
                    body = '<?xml version="1.0" encoding="UTF-8"?>' + \
                            output.getvalue().replace('class:', 'rasd:')\
                                             .replace(' xmlns:vmw="http://www.vmware.com/vcloud/v1.5"', '')\
                                             .replace('vmw:', 'rasd:')\
                                             .replace('Info>', "ovf:Info>")
                    content_type = "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml"
                    link = filter(lambda link: link.get_type() == content_type, self.vdc.get_Link())
                    self.response = Http.post(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, data=body, logger=self.logger)
                    if self.response.status_code == requests.codes.created:
                        vApp = vAppType.parseString(self.response.content, True)
                        task = vApp.get_Tasks().get_Task()[0]
                        return task
        return False
Beispiel #5
0
 def get_gateways(self, vdc_name):
     gateways = []
     vdc = self.get_vdc(vdc_name)
     if not vdc: return gateways
     link = filter(lambda link: link.get_rel() == "edgeGateways", vdc.get_Link())
     self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         queryResultRecords = queryRecordViewType.parseString(self.response.content, True)
         if queryResultRecords.get_Record():
             for edgeGatewayRecord in queryResultRecords.get_Record():
                 self.response = Http.get(edgeGatewayRecord.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                 if self.response.status_code == requests.codes.ok:
                     gateway = Gateway(networkType.parseString(self.response.content, True), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, log=self.log)
                     gateways.append(gateway)
     return gateways
Beispiel #6
0
 def get_media(self, catalog_name, media_name):
     refs = filter(lambda ref: ref.name == catalog_name and ref.type_ == 'application/vnd.vmware.vcloud.catalog+xml', self.vcloud_session.organization.Link)
     if len(refs) == 1:
         self.response = Http.get(refs[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             catalog = catalogType.parseString(self.response.content, True)
             catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == media_name, catalog.get_CatalogItems().get_CatalogItem())
             if len(catalog_items) == 1:
                 self.response = Http.get(catalog_items[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                 # print self.response.content
                 if self.response.status_code == requests.codes.ok:
                     doc = self.parsexml_(self.response.content)
                     for element in doc._children:
                         if element.tag == '{http://www.vmware.com/vcloud/v1.5}Entity':
                             return element.attrib
Beispiel #7
0
 def block_until_completed(self, task):
     progress = task.get_Progress()
     status = task.get_status()
     rnd = 0
     while status != "success":
         if status == "error":
             error = task.get_Error()
             Log.error(self.logger, "task error, major=%s, minor=%s, message=%s" % (error.get_majorErrorCode(), error.get_minorErrorCode(), error.get_message()))
             return False
         else:
             # some task doesn't not report progress
             if progress:
                 pass
             else:
                 rnd += 1
             time.sleep(1)
             self.response = Http.get(task.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
             if self.response.status_code == requests.codes.ok:
                 task = taskType.parseString(self.response.content, True)
                 progress = task.get_Progress()
                 status = task.get_status()
             else:
                 Log.error(self.logger, "can't get task")
                 return False
     return True
Beispiel #8
0
 def get_vapp(self, vdc, vapp_name):
     refs = filter(lambda ref: ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml', vdc.ResourceEntities.ResourceEntity)
     if len(refs) == 1:
         self.response = Http.get(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             vapp = VAPP(vAppType.parseString(self.response.content, True), self.vcloud_session.get_vcloud_headers(), self.verify, self.log)
             return vapp
Beispiel #9
0
 def get_vdc_references(self, serviceId):
     serviceReferences = filter(lambda serviceReference: serviceReference.get_serviceId() == serviceId, self.services.get_Service())
     if len(serviceReferences) == 0:
         return []
     self.response = Http.get(serviceReferences[0].get_href(), headers=self._get_vcloud_headers(), verify=self.verify, logger=self.logger)
     vdcs = vchsType.parseString(self.response.content, True)
     return vdcs.get_VdcRef()
Beispiel #10
0
 def set_syslog_conf(self, syslog_server_ip):
     headers = self.headers
     headers['Accept'] = 'application/*+xml;version=5.11'
     headers['Content-Type'] = 'application/vnd.vmware.vcloud.SyslogSettings+xml;version=5.11'
     # content_type = "application/vnd.vmware.vcloud.SyslogSettings+xml"
     body = ''
     if '' == syslog_server_ip:
         body = """
         <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
               <TenantSyslogServerSettings>
               </TenantSyslogServerSettings>
           </SyslogServerSettings>
                 """
     else:
         body = """
         <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
             <TenantSyslogServerSettings>
                 <SyslogServerIp>%s</SyslogServerIp>
             </TenantSyslogServerSettings>
         </SyslogServerSettings>
         """ % syslog_server_ip
     # '<SyslogServerSettings><TenantSyslogServerSettings><SyslogServerIp>%s</SyslogServerIp></TenantSyslogServerSettings></SyslogServerSettings>' % syslog_server_ip
     # link = filter(lambda link: link.get_type() == content_type, self.me.get_Link())
     self.response = Http.post(self.me.href+'/action/configureSyslogServerSettings', data=body, headers=headers, verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.accepted:
         task = taskType.parseString(self.response.content, True)
         return task
Beispiel #11
0
    def _upload(self, tar_file_obj,
                blueprint_id,
                application_file_name=None):
        query_params = {}
        if application_file_name is not None:
            query_params['application_file_name'] = \
                urllib.quote(application_file_name)

        def file_gen():
            buffer_size = 8192
            while True:
                read_bytes = tar_file_obj.read(buffer_size)
                yield read_bytes
                if len(read_bytes) < buffer_size:
                    return

        uri = '/blueprints/{0}'.format(blueprint_id)
        url = '{0}{1}'.format(self.score.url, uri)
        headers = self.score.get_headers()
        self.score.response = Http.put(url, headers=headers, params=query_params, data=file_gen(), verify=self.score.verify, logger=self.logger)

        if self.score.response.status_code != 201:
            raise Exception(self.score.response.status_code)
            
        return self.score.response.json()        
Beispiel #12
0
    def disconnect_from_network(self, network_name):
        """
        Disconnect the vApp from an existing virtual network in the VDC.

        :param network_name: (str): The name of the virtual network.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """

        networkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in networkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        found = -1
        for index, networkConfig in enumerate(networkConfigSection.get_NetworkConfig()):
            if networkConfig.get_networkName() == network_name:
                found = index
        if found != -1:
            networkConfigSection.NetworkConfig.pop(found)
            output = StringIO()
            networkConfigSection.export(output,
                0,
                name_ = 'NetworkConfigSection',
                namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                pretty_print = True)
            body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
            self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
Beispiel #13
0
    def connect_to_network(self, network_name, network_href, fence_mode='bridged'):
        """
        Connect the vApp to an existing virtual network in the VDC.

        :param network_name: (str): The name of the virtual network.
        :param network_href: (str): A uri that points to the network resource.
        :param fence_mode: (str, optional):
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """
        vApp_NetworkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in vApp_NetworkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        for networkConfig in vApp_NetworkConfigSection.get_NetworkConfig():
            if networkConfig.get_networkName() == network_name:
                task = TaskType()
                task.set_status("success")
                task.set_Progress("100")
                return task
        networkConfigSection = VAPP.create_networkConfigSection(network_name, network_href, fence_mode, vApp_NetworkConfigSection)
        output = StringIO()
        networkConfigSection.export(output,
            0,
            name_ = 'NetworkConfigSection',
            namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
            pretty_print = True)
        body = output.getvalue().\
            replace('Info msgid=""', "ovf:Info").replace("Info", "ovf:Info").replace(":vmw", "").replace("vmw:","")\
            .replace("RetainNetovf", "ovf").replace("ovf:InfoAcrossDeployments","RetainNetInfoAcrossDeployments")
        self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            return taskType.parseString(self.response.content, True)
Beispiel #14
0
 def list(self, deployment_id):
     params = {'deployment_id': deployment_id}
     self.score.response = Http.get(self.score.url + '/executions', headers=self.score.get_headers(), params=params,  verify=self.score.verify, logger=self.logger)
     if self.score.response.status_code == requests.codes.ok:
         return json.loads(self.score.response.content)
     else:
         Log.error(self.logger, 'list executions returned %s' % self.score.response.status_code)
Beispiel #15
0
 def connect_vms(self, network_name, connection_index,
                 connections_primary_index=None, ip_allocation_mode='DHCP',
                 mac_address=None, ip_address=None):
     children = self.me.get_Children()
     if children:
         vms = children.get_Vm()
         for vm in vms:
             new_connection = self._create_networkConnection(
                 network_name, connection_index, ip_allocation_mode,
                 mac_address, ip_address)
             networkConnectionSection = [section for section in vm.get_Section() if isinstance(section, NetworkConnectionSectionType)][0]
             self._modify_networkConnectionSection(
                 networkConnectionSection,
                 new_connection,
                 connections_primary_index)
             output = StringIO()
             networkConnectionSection.export(output,
                 0,
                 name_ = 'NetworkConnectionSection',
                 namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                 pretty_print = False)
             body=output.getvalue().replace("vmw:Info", "ovf:Info")
             self.response = Http.put(vm.get_href() + "/networkConnectionSection/", data=body, headers=self.headers, verify=self.verify, logger=self.logger)
             if self.response.status_code == requests.codes.accepted:
                 return taskType.parseString(self.response.content, True)
Beispiel #16
0
 def _get_services(self):
     headers = {}
     headers["x-vchs-authorization"] = self.token
     headers["Accept"] = "application/xml;version=" + self.version
     response = Http.get(self.host + "/api/vchs/services", headers=headers, verify=self.verify, logger=self.logger)
     if response.status_code == requests.codes.ok:
         return serviceType.parseString(response.content, True)
Beispiel #17
0
 def get_disks(self, vdc_name):
     vdc = self.get_vdc(vdc_name)
     links = self.get_diskRefs(vdc)
     disks = []
     for link in links:
         response = Http.get(link.get_href(), headers = self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         disk = self._parse_disk(response.content)
         vms = []
         content_type = "application/vnd.vmware.vcloud.vms+xml"
         response = Http.get(link.get_href()+'/attachedVms', headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         # print response.content
         listofvms = vmsType.parseString(response.content, True)
         for vmReference in listofvms.get_VmReference():
             vms.append(vmReference)
         disks.append([disk, vms])
     return disks
Beispiel #18
0
 def get_status(self):
     self.response = Http.get(self.url + '/status',
                              headers=self.get_headers(),
                              verify=self.verify, logger=self.logger)
     Log.debug(self.logger, self.response.status_code)
     Log.debug(self.logger, self.response.content)
     return self.response.content
Beispiel #19
0
 def _get(self, href):
     response = Http.get(
         href,
         headers=self._session.vca.vcloud_session.get_vcloud_headers(),
         verify=CONF.vcloud.verify)
     if response.status_code == requests.codes.ok:
         return response
     return None
Beispiel #20
0
 def get_vdc(self, vdc_name):
     if self.vcloud_session and self.vcloud_session.organization:
         refs = filter(lambda ref: ref.name == vdc_name and ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml', self.vcloud_session.organization.Link)
         if len(refs) == 1:
             self.response = Http.get(refs[0].href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
             if self.response.status_code == requests.codes.ok:
                 # print self.response.content
                 return vdcType.parseString(self.response.content, True)
Beispiel #21
0
 def list(self):
     self.score.response = Http.get(self.score.url + '/blueprints',
                                    headers=self.score.get_headers(),
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #22
0
 def get_catalogs(self):
     links = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.catalog+xml", self.vcloud_session.organization.Link)
     catalogs = []
     for link in links:
         self.response = Http.get(link.get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             catalogs.append(catalogType.parseString(self.response.content, True))
     return catalogs
Beispiel #23
0
 def display_progress(self, task, cmd_proc=None, headers=None):
     progress = task.get_Progress()
     status = task.get_status()
     rnd = 0
     response = None
     while status != "success":
         if status == "error":
             error = task.get_Error()
             sys.stdout.write('\r' + ' ' * 120 + '\r')
             sys.stdout.flush()
             self.print_error(CommonUtils.convertPythonObjToStr(
                              error, name="Error"),
                              cmd_proc=cmd_proc)
             return None
         else:
             # some task doesn't not report progress
             if progress:
                 sys.stdout.write("\rprogress : [" + "*" *
                                  int(progress) + " " *
                                  (100 - int(progress - 1)) + "] " +
                                  str(progress) + " %")
             else:
                 sys.stdout.write("\rprogress : ")
                 if rnd % 4 == 0:
                     sys.stdout.write(
                         "[" + "*" * 25 + " " * 75 + "]")
                 elif rnd % 4 == 1:
                     sys.stdout.write(
                         "[" + " " * 25 + "*" * 25 + " " * 50 + "]")
                 elif rnd % 4 == 2:
                     sys.stdout.write(
                         "[" + " " * 50 + "*" * 25 + " " * 25 + "]")
                 elif rnd % 4 == 3:
                     sys.stdout.write(
                         "[" + " " * 75 + "*" * 25 + "]")
                 rnd += 1
             sys.stdout.flush()
             time.sleep(1)
             response = Http.get(task.get_href(), headers=headers,
                                 verify=cmd_proc.verify,
                                 logger=cmd_proc.logger)
             if response.status_code == requests.codes.ok:
                 task = parseString(response.content, True)
                 progress = task.get_Progress()
                 status = task.get_status()
             else:
                 Log.error(cmd_proc.logger, "can't get task")
                 return
     sys.stdout.write("\r" + " " * 120)
     sys.stdout.flush()
     if response is not None:
         if cmd_proc is not None and cmd_proc.json_output:
             sys.stdout.write("\r" +
                              self.task_to_json(response.content) + '\n')
         else:
             sys.stdout.write("\r" +
                              self.task_to_table(response.content) + '\n')
         sys.stdout.flush()
Beispiel #24
0
 def delete_catalog_item(self, catalog_name, item_name):
     for catalog in self.get_catalogs():
         if catalog.CatalogItems and catalog.CatalogItems.CatalogItem:
             for item in catalog.CatalogItems.CatalogItem:
                 if item_name == item.name:
                     self.response = Http.delete(item.href, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
                     if self.response.status_code == requests.codes.no_content:
                         return True
     return False
Beispiel #25
0
 def get_syslog_conf(self):
     headers = self.headers
     headers['Accept']='application/*+xml;version=5.11'
     self.response = Http.get(self.me.href, data='', headers=headers, verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         doc = ET.fromstring(self.response.content)
         for element in doc.iter('{http://www.vmware.com/vcloud/v1.5}SyslogServerIp'):
             return element.text
     return ''
Beispiel #26
0
 def get(self, deployment_id):
     self.score.response = Http.get(self.score.url +
                                    '/deployments/%s' % deployment_id,
                                    headers=self.score.get_headers(),
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #27
0
 def _put(self, href, body):
     response = Http.put(
         href,
         data=body,
         headers=self._session.vca.vcloud_session.get_vcloud_headers(),
         verify=CONF.vcloud.verify)
     if response.status_code == requests.codes.accepted:
         return taskType.parseString(response.content, True)
     return None
Beispiel #28
0
 def get_admin_network_href(self, vdc_name, network_name):
     vdc = self.get_vdc(vdc_name)
     link = filter(lambda link: link.get_rel() == "orgVdcNetworks",
                   vdc.get_Link())
     self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
     queryResultRecords = queryRecordViewType.parseString(self.response.content, True)
     if self.response.status_code == requests.codes.ok:
         for record in queryResultRecords.get_Record():
             if record.name == network_name:
                 return record.href
Beispiel #29
0
 def delete_vdc_network(self, vdc_name, network_name):
     netref = self.get_admin_network_href(vdc_name, network_name)
     if netref is None:
         return (False, 'network not found')
     self.response = Http.delete(netref, headers=self.vcloud_session.get_vcloud_headers(), verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.accepted:
         task = taskType.parseString(self.response.content, True)
         return (True, task)
     else:
         return (False, self.response.content)
Beispiel #30
0
    def customize_guest_os(self, vm_name, customization_script=None,
                           computer_name=None, admin_password=None,
                           reset_password_required=False):
        """
        Associate a customization script with a guest OS and execute the script.
        The VMware tools must be installed in the Guest OS.

        :param vm_name: (str): The name of the vm to be customized.
        :param customization_script: (str, Optional): The path to a file on the local file system containing the customization script.
        :param computer_name: (str, Optional): A new value for the the computer name. A default value for the template is used if a value is not set.
        :param admin_password: (str, Optional): A password value for the admin/root user. A password is autogenerated if a value is not supplied.
        :param reset_password_required: (bool): Force the user to reset the password on first login.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vms[0].get_Section()
                customization_section = [section for section in sections
                         if (section.__class__.__name__ ==
                             "GuestCustomizationSectionType")
                         ][0]
                customization_section.set_Enabled(True)
                customization_section.set_ResetPasswordRequired(
                    reset_password_required)
                customization_section.set_AdminAutoLogonEnabled(False)
                customization_section.set_AdminAutoLogonCount(0)
                if customization_script:
                    customization_section.set_CustomizationScript(
                        customization_script)
                if computer_name:
                    customization_section.set_ComputerName(computer_name)
                if admin_password:
                    customization_section.set_AdminPasswordEnabled(True)
                    customization_section.set_AdminPasswordAuto(False)
                    customization_section.set_AdminPassword(admin_password)
                output = StringIO()
                customization_section.export(output,
                    0,
                    name_ = 'GuestCustomizationSection',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.guestcustomizationsection+xml'
                self.response = Http.put(customization_section.Link[0].href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
                else:
                    Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))
Beispiel #31
0
    def delete(self, deployment_id, force_delete=False):

        self.score.response = Http.delete(
            self.score.url + '/deployments/%s' % deployment_id,
            params={"ignore_live_nodes": force_delete},
            headers=self.score.get_headers(),
            verify=self.score.verify,
            logger=self.logger)

        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content.decode('utf-8'))
Beispiel #32
0
 def get_extension(self, name):
     content_type = 'application/vnd.vmware.admin.vmwExtension+xml'
     link = filter(lambda link: link.get_type() == content_type, self.vcloud_session.get_Link())
     self.response = Http.get(link[0].get_href() + '/service/query?pageSize=' + '1024',
                              headers=self.vcloud_session.get_vcloud_headers(),
                              verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         result = queryRecordViewType.parseString(self.response.content, True)
         for t in result.get_Record():
             if name == t.get_name():
                 # return {'name': t.get_name(), 'href': t.get_href()}
                 self.response = Http.get(t.get_href(), headers=self.vcloud_session.get_vcloud_headers(),
                                          verify=self.verify, logger=self.logger)
                 if self.response.status_code == requests.codes.ok:
                     doc = ET.fromstring(self.response.content)
                     return doc
                     # print(self.response.content)
                     # return {'name': t.get_name(), 'href': t.get_href()}
         return None
     else:
         raise Exception(self.response.status_code)
Beispiel #33
0
    def disconnect_vms(self, network_name=None):
        """
        Disconnect the vm from the vapp network. 

        :param network_name: (string): The name of the vApp network. If None, then disconnect from all the networks.
        :return: (bool): True if the user was vApp was successfully deployed, False otherwise.
            
        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                Log.debug(self.logger, "child VM name=%s" % vm.get_name())
                networkConnectionSection = [
                    section for section in vm.get_Section()
                    if isinstance(section, NetworkConnectionSectionType)
                ][0]
                found = -1
                if network_name is None:
                    networkConnectionSection.set_NetworkConnection([])
                    found = 1
                else:
                    for index, networkConnection in enumerate(
                            networkConnectionSection.get_NetworkConnection()):
                        if networkConnection.get_network() == network_name:
                            found = index
                            break
                    if found != -1:
                        networkConnectionSection.NetworkConnection.pop(found)
                if found != -1:
                    output = StringIO()
                    networkConnectionSection.export(
                        output,
                        0,
                        name_='NetworkConnectionSection',
                        namespacedef_=
                        'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                        pretty_print=True)
                    body = output.getvalue().replace("vmw:Info", "ovf:Info")
                    self.response = Http.put(vm.get_href() +
                                             "/networkConnectionSection/",
                                             data=body,
                                             headers=self.headers,
                                             verify=self.verify,
                                             logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content,
                                                    True)
        task = TaskType()
        task.set_status("success")
        task.set_Progress("100")
        return task
Beispiel #34
0
    def connect_vms(self, network_name, connection_index,
                    connections_primary_index=None, ip_allocation_mode='DHCP',
                    mac_address=None, ip_address=None):
        """
        Attach vms to a virtual network.

        something helpful.

        :param network_name: (str): The network name to connect the VM to.
        :param connection_index: (str): Virtual slot number associated with this NIC. First slot number is 0.
        :param connections_primary_index: (str): Virtual slot number associated with the NIC that should be considered this \n
                  virtual machine's primary network connection. Defaults to slot 0.
        :param ip_allocation_mode: (str, optional): IP address allocation mode for this connection.

                                 * One of:

                                  - POOL (A static IP address is allocated automatically from a pool of addresses.)

                                  - DHCP (The IP address is obtained from a DHCP service.)

                                  - MANUAL (The IP address is assigned manually in the IpAddress element.)

                                  - NONE (No IP addressing mode specified.)

        :param mac_address: (str):    the MAC address associated with the NIC.
        :param ip_address: (str):     the IP address assigned to this NIC.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.


        """
        children = self.me.get_Children()
        if children:
            vms = children.get_Vm()
            for vm in vms:
                new_connection = self._create_networkConnection(
                    network_name, connection_index, ip_allocation_mode,
                    mac_address, ip_address)
                networkConnectionSection = [section for section in vm.get_Section() if isinstance(section, NetworkConnectionSectionType)][0]
                self._modify_networkConnectionSection(
                    networkConnectionSection,
                    new_connection,
                    connections_primary_index)
                output = StringIO()
                networkConnectionSection.export(output,
                    0,
                    name_ = 'NetworkConnectionSection',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                    pretty_print = True)
                body=output.getvalue().replace("vmw:Info", "ovf:Info")
                self.response = Http.put(vm.get_href() + "/networkConnectionSection/", data=body, headers=self.headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
Beispiel #35
0
 def list(self, deployment_id):
     params = {'deployment_id': deployment_id}
     self.score.response = Http.get(self.score.url + '/executions',
                                    headers=self.score.get_headers(),
                                    params=params,
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         Log.error(
             self.logger, 'list executions returned %s' %
             self.score.response.status_code)
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #36
0
 def cancel(self, execution_id, force=False):
     data = {'execution_id': execution_id, 'force': force}
     headers = self.score.get_headers()
     headers['Content-type'] = 'application/json'
     self.score.response = Http.post(self.score.url + '/executions/' +
                                     execution_id,
                                     headers=headers,
                                     data=json.dumps(data),
                                     verify=self.score.verify,
                                     logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #37
0
 def get_orgs(self):
     content_type = 'application/vnd.vmware.vcloud.orgList+xml'
     link = filter(lambda link: link.get_type() == content_type, self.vcloud_session.get_Link())
     orgs = []
     self.response = Http.get(link[0].get_href(), headers=self.vcloud_session.get_vcloud_headers(),
                              verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         organizations = organizationListType.parseString(self.response.content, True)
         for org in organizations.get_Org():
             orgs.append({'name': org.get_name(), 'href': org.get_href()})
         return orgs
     else:
         raise Exception(self.response.status_code)
Beispiel #38
0
 def get_syslog_conf(self):
     headers = self.headers
     headers['Accept'] = 'application/*+xml;version=5.11'
     self.response = Http.get(self.me.href,
                              data='',
                              headers=headers,
                              verify=self.verify,
                              logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         doc = ET.fromstring(self.response.content)
         for element in doc.iter(
                 '{http://www.vmware.com/vcloud/v1.5}SyslogServerIp'):
             return element.text
     return ''
Beispiel #39
0
    def download(self, blueprint_id, output_file=None):
        self.score.response = Http.get(self.score.url +
                                       '/blueprints/%s/archive' % blueprint_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)

        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)

        with contextlib.closing(self.score.response) as streamed_response:
            output_file = self._write_response_stream_to_file(
                streamed_response, output_file)
            return output_file
Beispiel #40
0
 def get_task(self, task_id):
     if self.vcloud_session:
         o = urlparse(self.vcloud_session.url)
         link = '%s://%s%s/%s' % (o.scheme, o.netloc, '/api/task', task_id)
         self.response = Http.get(
             link,
             headers=self.vcloud_session.get_vcloud_headers(),
             verify=self.verify,
             logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             return taskType.parseString(self.response.content, True)
         else:
             raise Exception(self.response.status_code)
     return None
Beispiel #41
0
 def login(self, password=None, token=None):
     if token:
         headers = {}
         headers["x-vcloud-authorization"] = token
         headers["Accept"] = "application/*+xml;version=" + self.version
         self.response = Http.get(self.org_url, headers=headers, verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             self.token = token
             self.organization = organizationType.parseString(self.response.content, True)
             return True
         else:
             return False
     else:
         headers = {}
         headers["Accept"] = "application/*+xml;version=" + self.version
         self.response = Http.post(self.url, headers=headers, auth=(self.username + "@" + self.org, password), verify=self.verify, logger=self.logger)
         if self.response.status_code == requests.codes.ok:
             self.token = self.response.headers["x-vcloud-authorization"]
             self.session = sessionType.parseString(self.response.content, True)
             self.org_url = filter(lambda link: link.type_ == 'application/vnd.vmware.vcloud.org+xml', self.session.Link)[0].href
             return True
         else:
             return False
Beispiel #42
0
    def execute(self, operation, http, body=None, targetVM=None):
        """
        Execute an operation against a VM as an Asychronous Task.

        :param operation: (str): The command to execute
        :param http: (str): The http operation.
        :param body: (str, optional): a body for the http request
        :param targetVM: (str, optional): The name of the VM that will be the target of the request.
        :return: (TaskType or Bool) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                Or False if the request failed, error and debug level messages are logged.

        """
        vApp = targetVM if targetVM else self.me
        link = filter(lambda link: link.get_rel() == operation, vApp.get_Link())
        if not link:
            Log.error(self.logger, "link not found; rel=%s" % operation)
            Log.debug(self.logger, "vApp href=%s, name=%s" % (vApp.get_href(), vApp.get_name()))
            return False
        else:
            if http == "post":
                headers = self.headers
                if body and body.startswith('<DeployVAppParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml'
                elif body and body.startswith('<UndeployVAppParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.undeployVAppParams+xml'
                elif body and body.startswith('<CreateSnapshotParams '):
                    headers['Content-type'] = 'application/vnd.vmware.vcloud.createSnapshotParams+xml'
                self.response = Http.post(link[0].get_href(), data=body, headers=headers, verify=self.verify, logger=self.logger)
            elif http == "put":
                self.response = Http.put(link[0].get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
            else:
                self.response = Http.delete(link[0].get_href(), headers=self.headers, verify=self.verify, logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
            else:
                Log.debug(self.logger, "failed; response status=%d, content=%s" % (self.response.status_code, self.response.text))
                return False
Beispiel #43
0
 def connect_to_network(self,
                        network_name,
                        network_href,
                        fence_mode='bridged'):
     """
     Connect the vApp to an existing virtual network in the VDC.
    
     :param network_name: (str): The name of the virtual network.
     :param network_href: (str): A uri that points to the network resource.
     :param fence_mode: (str, optional): 
     :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.
  
     """
     vApp_NetworkConfigSection = [
         section for section in self.me.get_Section()
         if section.__class__.__name__ == "NetworkConfigSectionType"
     ][0]
     link = [
         link for link in vApp_NetworkConfigSection.get_Link()
         if link.get_type() ==
         "application/vnd.vmware.vcloud.networkConfigSection+xml"
     ][0]
     networkConfigSection = VAPP.create_networkConfigSection(
         network_name, network_href, fence_mode)
     for networkConfig in vApp_NetworkConfigSection.get_NetworkConfig():
         if networkConfig.get_networkName() == network_name:
             task = TaskType()
             task.set_status("success")
             task.set_Progress("100")
             return task
         networkConfigSection.add_NetworkConfig(networkConfig)
     output = StringIO()
     networkConfigSection.export(
         output,
         0,
         name_='NetworkConfigSection',
         namespacedef_=
         'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
         pretty_print=True)
     body = output.getvalue().\
         replace('Info msgid=""', "ovf:Info").replace("Info", "ovf:Info").replace(":vmw", "").replace("vmw:","")\
         .replace("RetainNetovf", "ovf").replace("ovf:InfoAcrossDeployments","RetainNetInfoAcrossDeployments")
     self.response = Http.put(link.get_href(),
                              data=body,
                              headers=self.headers,
                              verify=self.verify,
                              logger=self.logger)
     if self.response.status_code == requests.codes.accepted:
         return taskType.parseString(self.response.content, True)
Beispiel #44
0
 def create(self, blueprint_id, deployment_id, inputs=None):
     data = {'blueprint_id': blueprint_id}
     if inputs:
         data['inputs'] = inputs
     headers = self.score.get_headers()
     headers['Content-type'] = 'application/json'
     self.score.response = Http.put(self.score.url +
                                    '/deployments/%s' % deployment_id,
                                    data=json.dumps(data),
                                    headers=headers,
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #45
0
    def modify_vm_memory(self, vm_name, new_size):
        """
        Modify the virtual Memory allocation for VM.

        :param vm_name: (str): The name of the vm to be customized.
        :param new_size: (int): The new memory allocation in MB.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        :raises: Exception: If the named VM cannot be located or another error occured.
        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vm.get_Section()
                virtualHardwareSection = filter(lambda section: section.__class__.__name__== "VirtualHardwareSection_Type", sections)[0]
                items = virtualHardwareSection.get_Item()
                memory = filter(lambda item: item.get_Description().get_valueOf_() == "Memory Size", items)[0]
                href = memory.get_anyAttributes_().get('{http://www.vmware.com/vcloud/v1.5}href')
                en = memory.get_ElementName()
                en.set_valueOf_('%s MB of memory' % new_size)
                memory.set_ElementName(en)
                vq = memory.get_VirtualQuantity()
                vq.set_valueOf_(new_size)
                memory.set_VirtualQuantity(vq)
                weight = memory.get_Weight()
                weight.set_valueOf_(str(int(new_size)*10))
                memory.set_Weight(weight)
                memory_string = CommonUtils.convertPythonObjToStr(memory, 'Memory')
                Log.debug(self.logger, "memory: \n%s" % memory_string)
                output = StringIO()
                memory.export(output,
                    0,
                    name_ = 'Item',
                    namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData"',
                    pretty_print = True)
                body = output.getvalue().\
                    replace('Info msgid=""', "ovf:Info").replace("/Info", "/ovf:Info").\
                    replace("vmw:", "").replace("class:", "rasd:").replace("ResourceType", "rasd:ResourceType")
                headers = self.headers
                headers['Content-type'] = 'application/vnd.vmware.vcloud.rasdItem+xml'
                self.response = Http.put(href, data=body, headers=headers, verify=self.verify, logger=self.logger)
                if self.response.status_code == requests.codes.accepted:
                    return taskType.parseString(self.response.content, True)
                else:
                    raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')
Beispiel #46
0
    def force_customization(self, vm_name, power_on=True):
        """
        Force the guest OS customization script to be run for a specific vm in the vApp.
        A customization script must have been previously associated with the VM
        using the pyvcloud customize_guest_os method or using the vCD console
        The VMware tools must be installed in the Guest OS.
       
        :param vm_name: (str): The name of the vm to be customized.
        :param power_on (bool): Wether to power the vm on after customization or not
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.b\n
                            if the task cannot be created a debug level log message is generated detailing the reason.
 
        """
        children = self.me.get_Children()
        if children:
            vms = [vm for vm in children.get_Vm() if vm.name == vm_name]
            if len(vms) == 1:
                sections = vms[0].get_Section()
                links = filter(lambda link: link.rel == "deploy", vms[0].Link)
                if len(links) == 1:
                    forceCustomizationValue = 'true'
                    deployVAppParams = vcloudType.DeployVAppParamsType()
                    if power_on:
                        deployVAppParams.set_powerOn('true')
                    else:
                        deployVAppParams.set_powerOn('false')
                    deployVAppParams.set_deploymentLeaseSeconds(0)
                    deployVAppParams.set_forceCustomization('true')
                    body = CommonUtils.convertPythonObjToStr(
                        deployVAppParams,
                        name="DeployVAppParams",
                        namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5"'
                    )
                    headers = self.headers
                    headers[
                        'Content-type'] = 'application/vnd.vmware.vcloud.deployVAppParams+xml'
                    self.response = Http.post(links[0].href,
                                              data=body,
                                              headers=headers,
                                              verify=self.verify,
                                              logger=self.logger)
                    if self.response.status_code == requests.codes.accepted:
                        return taskType.parseString(self.response.content,
                                                    True)
                    else:
                        Log.debug(
                            self.logger, "response status=%d, content=%s" %
                            (self.response.status_code, self.response.text))
Beispiel #47
0
 def get_extensions(self):
     content_type = 'application/vnd.vmware.admin.vmwExtension+xml'
     link = [
         link for link in self.vcloud_session.get_Link()
         if link.get_type() == content_type
     ]
     self.response = Http.get(
         link[0].get_href() + '/service/query',
         headers=self.vcloud_session.get_vcloud_headers(),
         verify=self.verify,
         logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         doc = ET.fromstring(self.response.content.decode('utf-8'))
         return doc
     else:
         raise Exception(self.response.status_code)
Beispiel #48
0
 def enable_extension(self, name, href, enabled=True):
     extension_metadata = """
     <vmext:Service xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmext="http://www.vmware.com/vcloud/extension/v1.5" name="%s">
         <vmext:Namespace>%s</vmext:Namespace>
         <vmext:Enabled>%s</vmext:Enabled>
         <vmext:RoutingKey>%s</vmext:RoutingKey>
         <vmext:Exchange>vcdext</vmext:Exchange>
     </vmext:Service>
     """ % (name, name, 'true' if enabled else 'false', name)
     self.response = Http.put(href, headers=self.vcloud_session.get_vcloud_headers(),
                              data=extension_metadata,
                              verify=self.verify, logger=self.logger)
     if self.response.status_code == requests.codes.ok:
         return self.response.content
     else:
         raise Exception(self.response.status_code)
Beispiel #49
0
 def get_tasks(self, status=statuses[0]):
     if self.vcloud_session and self.vcloud_session.organization:
         refs = filter(
             lambda ref: ref.type_ ==
             'application/vnd.vmware.vcloud.tasksList+xml',
             self.vcloud_session.organization.Link)
         if len(refs) == 1:
             self.response = Http.get(
                 refs[0].href,
                 headers=self.vcloud_session.get_vcloud_headers(),
                 verify=self.verify,
                 logger=self.logger)
             if self.response.status_code == requests.codes.ok:
                 return tasksListType.parseString(self.response.content,
                                                  True)
             else:
                 raise Exception(self.response.status_code)
     return None
Beispiel #50
0
 def save_services_configuration(self):
     edgeGatewayServiceConfiguration = self.me.get_Configuration(
     ).get_EdgeGatewayServiceConfiguration()
     body = '<?xml version="1.0" encoding="UTF-8"?>' + \
            CommonUtils.convertPythonObjToStr(self.me.get_Configuration().get_EdgeGatewayServiceConfiguration(),
                                              name='EdgeGatewayServiceConfiguration',
                                              namespacedef='xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ')
     content_type = "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml"
     link = filter(lambda link: link.get_type() == content_type,
                   self.me.get_Link())
     self.response = Http.post(link[0].get_href(),
                               data=body,
                               headers=self.headers,
                               verify=self.verify,
                               logger=self.logger)
     if self.response.status_code == requests.codes.accepted:
         task = taskType.parseString(self.response.content, True)
         return task
Beispiel #51
0
    def modify_vm_name(self, vm_index, vm_name):
        """
        Modify the name of a VM in a vApp

        :param vm_index: (int):The index of the VM in the vApp 1==first VM
        :param vm_name: (str): The new name of the VM.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request. \n
                            if the task cannot be created a debug level log message is generated detailing the reason.

        :raises: Exception: If the named VM cannot be located or another error occured.
        """
        children = self.me.get_Children()
        if children:
            assert len(children.get_Vm()) >= vm_index
            vm = children.get_Vm()[vm_index - 1]
            assert vm
            href = vm.get_href()
            vm_name_old = vm.get_name()
            Log.debug(
                self.logger, "VM name change (%s) %s -> %s" %
                (vm_index, vm_name_old, vm_name))
            vm.set_name(vm_name)
            vm.set_Section([])
            output = StringIO()
            vm.export(
                output,
                0,
                name_='Vm',
                namespacedef_=
                'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:vmw="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                pretty_print=True)
            body = output.getvalue()
            headers = self.headers
            headers['Content-type'] = 'application/vnd.vmware.vcloud.vm+xml'
            self.response = Http.post(href + '/action/reconfigureVm',
                                      data=body,
                                      headers=headers,
                                      verify=self.verify,
                                      logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
            else:
                raise Exception(self.response.status_code)
        raise Exception('can\'t find vm')
Beispiel #52
0
    def disconnect_from_network(self, network_name):
        """
        Disconnect the vApp from an existing virtual network in the VDC.
       
        :param network_name: (str): The name of the virtual network.
        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.
 
        """

        networkConfigSection = [
            section for section in self.me.get_Section()
            if section.__class__.__name__ == "NetworkConfigSectionType"
        ][0]
        link = [
            link for link in networkConfigSection.get_Link()
            if link.get_type() ==
            "application/vnd.vmware.vcloud.networkConfigSection+xml"
        ][0]
        found = -1
        for index, networkConfig in enumerate(
                networkConfigSection.get_NetworkConfig()):
            if networkConfig.get_networkName() == network_name:
                found = index
        if found != -1:
            networkConfigSection.NetworkConfig.pop(found)
            output = StringIO()
            networkConfigSection.export(
                output,
                0,
                name_='NetworkConfigSection',
                namespacedef_=
                'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
                pretty_print=True)
            body = output.getvalue().\
                    replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                    replace("/Info", "/ovf:Info")
            self.response = Http.put(link.get_href(),
                                     data=body,
                                     headers=self.headers,
                                     verify=self.verify,
                                     logger=self.logger)
            if self.response.status_code == requests.codes.accepted:
                return taskType.parseString(self.response.content, True)
Beispiel #53
0
    def deallocate_public_ip(self, ip_address):
        api_version = '5.11'
        headers = dict(self.headers)
        headers['Accept'] = 'application/*+xml;version={0}'.format(api_version)
        href = self.me.get_href() + '/action/manageExternalIpAddresses'
        body = """
        <ExternalIpAddressActionList
         xmlns="http://www.vmware.com/vcloud/networkservice/1.0">
        <Deallocation>
            <ExternalIpAddress>{0}</ExternalIpAddress>
        </Deallocation>
        </ExternalIpAddressActionList>
        """.format(ip_address)

        self.response = Http.put(href, data=body, headers=headers,
                                 verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.ok:
            task = taskType.parseString(self.response.content.decode('utf-8'), True)
            return task
Beispiel #54
0
    def _upload(self, tar_file, blueprint_id, application_file_name=None):
        query_params = {}
        if application_file_name is not None:
            query_params['application_file_name'] = (
                urllib.quote(application_file_name))

        uri = '/blueprints/{0}'.format(blueprint_id)
        url = '{0}{1}'.format(self.score.url, uri)
        headers = self.score.get_headers()
        with open(tar_file, 'rb') as f:
            self.score.response = Http.put(url,
                                           headers=headers,
                                           params=query_params,
                                           data=f,
                                           verify=self.score.verify,
                                           logger=self.logger)

        if self.score.response.status_code not in range(200, 210):
            raise exceptions.from_response(self.score.response)
        return self.score.response.json()
Beispiel #55
0
    def customize_on_next_poweron(self):
        """
        Force the guest OS customization script to be run for the first VM in the vApp.
        A customization script must have been previously associated with the VM
        using the pyvcloud customize_guest_os method or using the vCD console
        The VMware tools must be installed in the Guest OS.
       
        :return: (bool) True if the request was accepted, False otherwise. If False an error level log message is generated.

        """
        vm = self._get_vms()[0]
        link = filter(lambda link: link.get_rel() == "customizeAtNextPowerOn",
                      vm.get_Link())
        if link:
            self.response = Http.post(link[0].get_href(), data=None,
                                      headers=self.headers, logger=self.logger)
            if self.response.status_code == requests.codes.no_content:
                return True

        Log.error(self.logger, "link not found")
        return False
Beispiel #56
0
 def get(self,
         execution_id,
         from_event=0,
         batch_size=100,
         include_logs=False):
     data = {
         "execution_id": execution_id,
         "from": from_event,
         "size": batch_size,
         "include_logs": include_logs
     }
     headers = self.score.get_headers()
     headers['Content-type'] = 'application/json'
     self.score.response = Http.get(self.score.url + '/events',
                                    headers=headers,
                                    data=json.dumps(data),
                                    verify=self.score.verify,
                                    logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #57
0
    def disconnect_from_networks(self):
        """
        Disconnect the vApp from currently connected virtual networks.

        :return: (TaskType) a :class:`pyvcloud.schema.vcd.v1_5.schemas.admin.vCloudEntities.TaskType` object that can be used to monitor the request.

        """
        networkConfigSection = [section for section in self.me.get_Section() if section.__class__.__name__ == "NetworkConfigSectionType"][0]
        link = [link for link in networkConfigSection.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.networkConfigSection+xml"][0]
        networkConfigSection.NetworkConfig[:] = []
        output = StringIO()
        networkConfigSection.export(output,
            0,
            name_ = 'NetworkConfigSection',
            namespacedef_ = 'xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"',
            pretty_print = True)
        body = output.getvalue().\
                replace("vmw:", "").replace('Info xmlns:vmw="http://www.vmware.com/vcloud/v1.5" msgid=""', "ovf:Info").\
                replace("/Info", "/ovf:Info")
        self.response = Http.put(link.get_href(), data=body, headers=self.headers, verify=self.verify, logger=self.logger)
        if self.response.status_code == requests.codes.accepted:
            return taskType.parseString(self.response.content, True)
Beispiel #58
0
 def start(self,
           deployment_id,
           workflow_id,
           parameters=None,
           allow_custom_parameters=False,
           force=False):
     data = {
         'deployment_id': deployment_id,
         'workflow_id': workflow_id,
         'parameters': parameters,
         'allow_custom_parameters': allow_custom_parameters,
         'force': force,
     }
     headers = self.score.get_headers()
     headers['Content-type'] = 'application/json'
     self.score.response = Http.post(self.score.url + '/executions',
                                     headers=headers,
                                     data=json.dumps(data),
                                     verify=self.score.verify,
                                     logger=self.logger)
     if self.score.response.status_code != requests.codes.ok:
         raise exceptions.from_response(self.score.response)
     return json.loads(self.score.response.content)
Beispiel #59
0
 def set_syslog_conf(self, syslog_server_ip):
     headers = self.headers
     headers['Accept'] = 'application/*+xml;version=5.11'
     headers[
         'Content-Type'] = 'application/vnd.vmware.vcloud.SyslogSettings+xml;version=5.11'
     # content_type = "application/vnd.vmware.vcloud.SyslogSettings+xml"
     body = ''
     if '' == syslog_server_ip:
         body = """
         <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
               <TenantSyslogServerSettings>
               </TenantSyslogServerSettings>
           </SyslogServerSettings>
                 """
     else:
         body = """
         <SyslogServerSettings xmlns="http://www.vmware.com/vcloud/v1.5"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://10.160.99.94/api/v1.5/schema/master.xsd">
             <TenantSyslogServerSettings>
                 <SyslogServerIp>%s</SyslogServerIp>
             </TenantSyslogServerSettings>
         </SyslogServerSettings>
         """ % syslog_server_ip
     # '<SyslogServerSettings><TenantSyslogServerSettings><SyslogServerIp>%s</SyslogServerIp></TenantSyslogServerSettings></SyslogServerSettings>' % syslog_server_ip
     # link = filter(lambda link: link.get_type() == content_type, self.me.get_Link())
     self.response = Http.post(
         self.me.href +
         '/action/configureSyslogServerSettings',
         data=body,
         headers=headers,
         verify=self.verify,
         logger=self.logger)
     if self.response.status_code == requests.codes.accepted:
         task = taskType.parseString(self.response.content.decode('utf-8'), True)
         return task
Beispiel #60
0
 def ping(self):
     self.response = Http.get(self.host + '/appsrv/api/v1/services/mssql/',
                              headers=self.get_headers(),
                              verify=self.verify,
                              logger=self.logger)
     return self.response.status_code