当前位置: 首页>>代码示例>>Python>>正文


Python ServiceManagementService.get_hosted_service_properties方法代码示例

本文整理汇总了Python中azure.servicemanagement.ServiceManagementService.get_hosted_service_properties方法的典型用法代码示例。如果您正苦于以下问题:Python ServiceManagementService.get_hosted_service_properties方法的具体用法?Python ServiceManagementService.get_hosted_service_properties怎么用?Python ServiceManagementService.get_hosted_service_properties使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在azure.servicemanagement.ServiceManagementService的用法示例。


在下文中一共展示了ServiceManagementService.get_hosted_service_properties方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import get_hosted_service_properties [as 别名]
class AzureServicesManager:
    # Storage
    container = 'vhds'
    windows_blob_url = 'blob.core.windows.net'

    # Linux
    linux_user = 'azureuser'
    linux_pass = 'Test123#'
    location = 'West US'
    # SSH Keys

    def __init__(self, subscription_id, cert_file):
        self.subscription_id = subscription_id
        self.cert_file = cert_file
        self.sms = ServiceManagementService(self.subscription_id, self.cert_file)

    @property
    def sms(self):
         return self.sms

    def list_locations(self):
        locations = self.sms.list_locations()
        for location in locations:
            print location

    def list_images(self):
        return self.sms.list_os_images()

    @utils.resource_not_found_handler
    def get_hosted_service(self, service_name):
        resp = self.sms.get_hosted_service_properties(service_name)
        properties = resp.hosted_service_properties
        return properties.__dict__

    def delete_hosted_service(self, service_name):
        res = self.sms.check_hosted_service_name_availability(service_name)
        if not res.result:
            return

        self.sms.delete_hosted_service(service_name)

    def create_hosted_service(self, os_user, service_name=None, random=False):
        if not service_name:
            service_name = self.generate_cloud_service_name(os_user, random)

        available = False

        while not available:
            res = self.sms.check_hosted_service_name_availability(service_name)
            if not res.result:
                service_name = self.generate_cloud_service_name(os_user,
                                                                random)
            else:
                available = True

        self.sms.create_hosted_service(service_name=service_name,
                                       label=service_name,
                                       location='West US')

        return service_name

    def create_virtual_machine(self, service_name, vm_name, image_name, role_size):
        media_link = self._get_media_link(vm_name)
        # Linux VM configuration
        hostname = '-'.join((vm_name, 'host'))
        linux_config = LinuxConfigurationSet(hostname,
                                             self.linux_user,
                                             self.linux_pass,
                                             True)

        # Hard disk for the OS
        os_hd = OSVirtualHardDisk(image_name, media_link)

        # Create vm
        result = self.sms.create_virtual_machine_deployment(
            service_name=service_name,  deployment_name=vm_name,
            deployment_slot='production', label=vm_name,
            role_name=vm_name, system_config=linux_config,
            os_virtual_hard_disk=os_hd,
            role_size=role_size
        )
        request_id = result.request_id

        return {
            'request_id': request_id,
            'media_link': media_link
        }

    def delete_virtual_machine(self, service_name, vm_name):
        resp = self.sms.delete_deployment(service_name, vm_name, True)
        self.sms.wait_for_operation_status(resp.request_id)
        result = self.sms.delete_hosted_service(service_name)
        return result

    def generate_cloud_service_name(self, os_user=None, random=False):
        if random:
            return utils.generate_random_name(10)

        return '-'.join((os_user, utils.generate_random_name(6)))

#.........这里部分代码省略.........
开发者ID:graceyu08,项目名称:azure-openstack-driver,代码行数:103,代码来源:azureclient.py

示例2: AzureInventory

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import get_hosted_service_properties [as 别名]

#.........这里部分代码省略.........
        parser.add_argument('--list-images', action='store',
                            help='Get all available images.')
        parser.add_argument('--refresh-cache',
            action='store_true', default=False,
            help='Force refresh of thecache by making API requests to Azure '
                 '(default: False - use cache files)',
        )
        parser.add_argument('--host', action='store',
                            help='Get all information about an instance.')
        self.args = parser.parse_args()

    def do_api_calls_update_cache(self):
        """Do API calls, and save data in cache files."""
        self.add_cloud_services()
        self.write_to_cache(self.inventory, self.cache_path_cache)
        self.write_to_cache(self.index, self.cache_path_index)

    def add_cloud_services(self):
        """Makes an Azure API call to get the list of cloud services."""
        try:
            for cloud_service in self.sms.list_hosted_services():
                self.add_deployments(cloud_service)
        except WindowsAzureError as e:
            print("Looks like Azure's API is down:")
            print("")
            print(e)
            sys.exit(1)

    def add_deployments(self, cloud_service):
        """Makes an Azure API call to get the list of virtual machines
        associated with a cloud service.
        """
        try:
            for deployment in self.sms.get_hosted_service_properties(cloud_service.service_name,embed_detail=True).deployments.deployments:
                self.add_deployment(cloud_service, deployment)
        except WindowsAzureError as e:
            print("Looks like Azure's API is down:")
            print("")
            print(e)
            sys.exit(1)

    def add_deployment(self, cloud_service, deployment):
        """Adds a deployment to the inventory and index"""
        for role in deployment.role_instance_list.role_instances:
            try:
                # Default port 22 unless port found with name 'SSH'
                port = '22'
                for ie in role.instance_endpoints.instance_endpoints:
                    if ie.name == 'SSH':
                        port = ie.public_port
                        break
            except AttributeError as e:
                pass
            finally:
                self.add_instance(role.instance_name, deployment, port, cloud_service, role.instance_status)

    def add_instance(self, hostname, deployment, ssh_port, cloud_service, status):
        """Adds an instance to the inventory and index"""

        dest = urlparse(deployment.url).hostname

        # Add to index
        self.index[hostname] = deployment.name

        self.host_metadata[hostname] = dict(ansible_ssh_host=dest,
                                            ansible_ssh_port=int(ssh_port),
开发者ID:JaredPennella,项目名称:DevOps_Script,代码行数:70,代码来源:windows_azure.py

示例3: Deployment

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import get_hosted_service_properties [as 别名]

#.........这里部分代码省略.........
                                (self.config.getServiceBundleStorageContainer(), None)]
        for name, access in name_and_access_list:
            logger.info("Checking for existence of Blob container %s.", name)
            blob_service.create_container(name, x_ms_blob_public_access=access, fail_on_exist=False)
            access_info = 'private' if access is None else 'public {0}'.format(access)
            logger.info("Blob container %s is ready (access: %s).", name, access_info)

    def ensureStorageHasCorsConfiguration(self):
        """
        Ensures Blob storage container for bundles is configured to allow cross-origin resource sharing.
        """
        logger.info("Setting CORS rules.")
        account_name = self.config.getServiceStorageAccountName()
        account_key = self._getStorageAccountKey(account_name)

        cors_rule = CorsRule()
        cors_rule.allowed_origins = self.config.getServiceStorageCorsAllowedOrigins()
        cors_rule.allowed_methods = 'PUT'
        cors_rule.exposed_headers = '*'
        cors_rule.allowed_headers = '*'
        cors_rule.max_age_in_seconds = 1800
        cors_rules = Cors()
        cors_rules.cors_rule.append(cors_rule)
        set_storage_service_cors_properties(account_name, account_key, cors_rules)

    def _ensureServiceExists(self, service_name, affinity_group_name):
        """
        Creates the specified cloud service host if it does not exist.

        service_name: Name of the cloud service.
        affinity_group_name: Name of the affinity group (which should exists).
        """
        logger.info("Checking for existence of cloud service (name=%s).", service_name)
        if self._resource_exists(lambda: self.sms.get_hosted_service_properties(service_name)):
            logger.warn("A cloud service named %s already exists.", service_name)
        else:
            self.sms.create_hosted_service(service_name, service_name, affinity_group=affinity_group_name)
            logger.info("Created cloud service %s.", service_name)

    def _ensureServiceCertificateExists(self, service_name):
        """
        Adds certificate to the specified cloud service.

        service_name: Name of the target cloud service (which should exist).
        """
        cert_format = self.config.getServiceCertificateFormat()
        cert_algorithm = self.config.getServiceCertificateAlgorithm()
        cert_thumbprint = self.config.getServiceCertificateThumbprint()
        cert_path = self.config.getServiceCertificateFilename()
        cert_password = self.config.getServiceCertificatePassword()
        logger.info("Checking for existence of cloud service certificate for service %s.", service_name)
        get_cert = lambda: self.sms.get_service_certificate(service_name, cert_algorithm, cert_thumbprint)
        if self._resource_exists(get_cert):
            logger.info("Found expected cloud service certificate.")
        else:
            with open(cert_path, 'rb') as f:
                cert_data = base64.b64encode(f.read())
            if len(cert_data) <= 0:
                raise Exception("Detected invalid certificate data.")
            result = self.sms.add_service_certificate(service_name, cert_data, cert_format, cert_password)
            self._wait_for_operation_success(result.request_id, timeout=self.config.getAzureOperationTimeout())
            logger.info("Added service certificate.")

    def _assertOsImageExists(self, os_image_name):
        """
        Asserts that the named OS image exists.
开发者ID:prags,项目名称:codalab,代码行数:70,代码来源:__init__.py

示例4: AzureNodeDriver

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import get_hosted_service_properties [as 别名]

#.........这里部分代码省略.........
        self.subscription_id = subscription_id
        self.key_file = key_file
        self.sms = ServiceManagementService(subscription_id, key_file)

        super(AzureNodeDriver, self).__init__(
            self.subscription_id,
            self.key_file,
            secure=True,
            **kwargs)

    def list_sizes(self):
        """
        Lists all sizes from azure

        :rtype: ``list`` of :class:`NodeSize`
        """
        if self.rolesizes is None:
            # refresh rolesizes
            data = self.sms.list_role_sizes()
            self.rolesizes = [self._to_node_size(i) for i in data]
        return self.rolesizes

    def list_images(self, location=None):
        """
        Lists all sizes from azure

        :rtype: ``list`` of :class:`NodeSize`
        """
        data = self.sms.list_os_images()
        images = [self._to_image(i) for i in data]

        if location is not None:
            images = [image for image in images
                      if location in image.extra["location"]]
        return images

    def list_locations(self):
        """
        Lists all Location from azure

        :rtype: ``list`` of :class:`NodeLocation`
        """
        data = self.sms.list_locations()
        locations = [self._to_location(i) for i in data]
        return locations

    def list_virtual_net(self):
        """
        List all VirtualNetworkSites

        :rtype: ``list`` of :class:`VirtualNetwork`
        """
        data = self.sms.list_virtual_network_sites()
        virtualnets = [self._to_virtual_network(i) for i in data]
        return virtualnets

    def create_node(self,
                    name,
                    image,
                    size,
                    storage,
                    service_name,
                    vm_user,
                    vm_password,
                    location=None,
                    affinity_group=None,
                    virtual_network=None):
        """
        Create a vm deploiement request

        :rtype:  :class:`.Node`
        :return: ``Node`` Node instance on success.
        """

        try:
            self.sms.get_hosted_service_properties(service_name)
            pass
        except WindowsAzureMissingResourceError:
            # create cloud service
            if bool(location is not None) != bool(affinity_group is not None):
                raise ValueError(
                    "For ressource creation, set location or affinity_group" +
                    " not both")
            if location is not None:
                try:
                    self.sms.create_hosted_service(
                        service_name=service_name,
                        label=service_name,
                        location=location)
                    pass
                except Exception, e:
                    raise e
            else:
                try:
                    self.sms.create_hosted_service(
                        service_name=service_name,
                        label=service_name,
                        affinity_group=affinity_group)
                except Exception, e:
                    raise e
开发者ID:zhitongLBN,项目名称:Libcloud-Custom,代码行数:104,代码来源:azure_driver.py

示例5: AzureInventory

# 需要导入模块: from azure.servicemanagement import ServiceManagementService [as 别名]
# 或者: from azure.servicemanagement.ServiceManagementService import get_hosted_service_properties [as 别名]

#.........这里部分代码省略.........
    def read_environment(self):
        ''' Reads the settings from environment variables '''
        # Credentials
        if os.getenv("AZURE_SUBSCRIPTION_ID"): self.subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID")
        if os.getenv("AZURE_CERT_PATH"):       self.cert_path = os.getenv("AZURE_CERT_PATH")


    def parse_cli_args(self):
        """Command line argument processing"""
        parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Azure')
        parser.add_argument('--list', action='store_true', default=True,
                           help='List nodes (default: True)')
        parser.add_argument('--list-images', action='store',
                           help='Get all available images.')
        parser.add_argument('--refresh-cache', action='store_true', default=False,
                           help='Force refresh of cache by making API requests to Azure (default: False - use cache files)')
        self.args = parser.parse_args()

    def do_api_calls_update_cache(self):
        """Do API calls, and save data in cache files."""
        self.add_cloud_services()
        self.write_to_cache(self.inventory, self.cache_path_cache)
        self.write_to_cache(self.index, self.cache_path_index)

    def add_cloud_services(self):
        """Makes an Azure API call to get the list of cloud services."""
        try:
            for cloud_service in self.sms.list_hosted_services():
                self.add_deployments(cloud_service)
        except WindowsAzureError as e:
            print "Looks like Azure's API is down:"
            print
            print e
            sys.exit(1)

    def add_deployments(self, cloud_service):
        """Makes an Azure API call to get the list of virtual machines associated with a cloud service"""
        try:
            for deployment in self.sms.get_hosted_service_properties(cloud_service.service_name,embed_detail=True).deployments.deployments:
                if deployment.deployment_slot == "Production":
                    self.add_deployment(cloud_service, deployment)
        except WindowsAzureError as e:
            print "Looks like Azure's API is down:"
            print
            print e
            sys.exit(1)

    def add_deployment(self, cloud_service, deployment):
        """Adds a deployment to the inventory and index"""

        dest = urlparse(deployment.url).hostname

        # Add to index
        self.index[dest] = deployment.name

        # List of all azure deployments
        self.push(self.inventory, "azure", dest)

        # Inventory: Group by service name
        self.push(self.inventory, self.to_safe(cloud_service.service_name), dest)

        # Inventory: Group by region
        self.push(self.inventory, self.to_safe(cloud_service.hosted_service_properties.location), dest)

    def push(self, my_dict, key, element):
        """Pushed an element onto an array that may not have been defined in the dict."""
        if key in my_dict:
            my_dict[key].append(element);
        else:
            my_dict[key] = [element]

    def get_inventory_from_cache(self):
        """Reads the inventory from the cache file and returns it as a JSON object."""
        cache = open(self.cache_path_cache, 'r')
        json_inventory = cache.read()
        return json_inventory

    def load_index_from_cache(self):
        """Reads the index from the cache file and sets self.index."""
        cache = open(self.cache_path_index, 'r')
        json_index = cache.read()
        self.index = json.loads(json_index)

    def write_to_cache(self, data, filename):
        """Writes data in JSON format to a file."""
        json_data = self.json_format_dict(data, True)
        cache = open(filename, 'w')
        cache.write(json_data)
        cache.close()

    def to_safe(self, word):
        """Escapes any characters that would be invalid in an ansible group name."""
        return re.sub("[^A-Za-z0-9\-]", "_", word)

    def json_format_dict(self, data, pretty=False):
        """Converts a dict to a JSON object and dumps it as a formatted string."""
        if pretty:
            return json.dumps(data, sort_keys=True, indent=2)
        else:
            return json.dumps(data)
开发者ID:pintostack,项目名称:core,代码行数:104,代码来源:windows_azure.py


注:本文中的azure.servicemanagement.ServiceManagementService.get_hosted_service_properties方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。