Detect the cloud provider where I am running on.
183444
def detect_cloud() -> str:
    '''
    
    '''
    # NOTE: Contributions are welcome!
    # Please add other cloud providers such as Rackspace, IBM BlueMix, etc.
    if sys.platform.startswith('linux'):
        # Google Cloud Platform or Amazon AWS (hvm)
        try:
            # AWS Nitro-based instances
            mb = Path('/sys/devices/virtual/dmi/id/board_vendor').read_text().lower()
            if 'amazon' in mb:
                return 'amazon'
        except IOError:
            pass
        try:
            bios = Path('/sys/devices/virtual/dmi/id/bios_version').read_text().lower()
            if 'google' in bios:
                return 'google'
            if 'amazon' in bios:
                return 'amazon'
        except IOError:
            pass
        # Microsoft Azure
        # https://gallery.technet.microsoft.com/scriptcenter/Detect-Windows-Azure-aed06d51
        # TODO: this only works with Debian/Ubuntu instances.
        # TODO: this does not work inside containers.
        try:
            dhcp = Path('/var/lib/dhcp/dhclient.eth0.leases').read_text()
            if 'unknown-245' in dhcp:
                return 'azure'
            # alternative method is to read /var/lib/waagent/GoalState.1.xml
            # but it requires sudo privilege.
        except IOError:
            pass
    else:
        log.warning('Cloud detection is implemented for Linux only yet.')
    return None
95692
def _get_server(vm_, volumes, nics):
    '''
    
    '''
    # Apply component overrides to the size from the cloud profile config
    vm_size = _override_size(vm_)

    # Set the server availability zone from the cloud profile config
    availability_zone = config.get_cloud_config_value(
        'availability_zone', vm_, __opts__, default=None,
        search_global=False
    )

    # Assign CPU family from the cloud profile config
    cpu_family = config.get_cloud_config_value(
        'cpu_family', vm_, __opts__, default=None,
        search_global=False
    )

    # Contruct server object
    return Server(
        name=vm_['name'],
        ram=vm_size['ram'],
        availability_zone=availability_zone,
        cores=vm_size['cores'],
        cpu_family=cpu_family,
        create_volumes=volumes,
        nics=nics
    )
733420
def _get_instance(self):
        """"""
        resource = self._connect()

        try:
            instance = resource.Instance(self.running_instance_id)
        except Exception:
            raise EC2CloudException(
                'Instance with ID: {instance_id} not found.'.format(
                    instance_id=self.running_instance_id
                )
            )
        return instance
1219973
def get_security_groups(conn, vm_):
    '''
    
    '''
    securitygroup_enabled = config.get_cloud_config_value(
        'securitygroup_enabled', vm_, __opts__, default=True
    )
    if securitygroup_enabled:
        return config.get_cloud_config_value(
            'securitygroup', vm_, __opts__, default=['default']
        )
    else:
        return False
1356101
def cli(env, identifier):
    """"""
    mgr = SoftLayer.LoadBalancerManager(env.client)

    _, loadbal_id = loadbal.parse_id(identifier)

    load_balancer = mgr.get_local_lb(loadbal_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'l'
    table.align['value'] = 'l'
    table.add_row(['ID', 'local:%s' % load_balancer['id']])
    table.add_row(['IP Address', load_balancer['ipAddress']['ipAddress']])
    name = load_balancer['loadBalancerHardware'][0]['datacenter']['name']
    table.add_row(['Datacenter', name])
    table.add_row(['Connections limit', load_balancer['connectionLimit']])
    table.add_row(['Dedicated', load_balancer['dedicatedFlag']])
    table.add_row(['HA', load_balancer['highAvailabilityFlag']])
    table.add_row(['SSL Enabled', load_balancer['sslEnabledFlag']])
    table.add_row(['SSL Active', load_balancer['sslActiveFlag']])

    index0 = 1
    for virtual_server in load_balancer['virtualServers']:
        for group in virtual_server['serviceGroups']:
            service_group_table = formatting.KeyValueTable(['name', 'value'])

            table.add_row(['Service Group %s' % index0, service_group_table])
            index0 += 1

            service_group_table.add_row(['Guest ID',
                                         virtual_server['id']])
            service_group_table.add_row(['Port', virtual_server['port']])
            service_group_table.add_row(['Allocation',
                                         '%s %%' %
                                         virtual_server['allocation']])
            service_group_table.add_row(['Routing Type',
                                         '%s:%s' %
                                         (group['routingTypeId'],
                                          group['routingType']['name'])])
            service_group_table.add_row(['Routing Method',
                                         '%s:%s' %
                                         (group['routingMethodId'],
                                          group['routingMethod']['name'])])

            index1 = 1
            for service in group['services']:
                service_table = formatting.KeyValueTable(['name', 'value'])

                service_group_table.add_row(['Service %s' % index1,
                                             service_table])
                index1 += 1

                health_check = service['healthChecks'][0]
                service_table.add_row(['Service ID', service['id']])
                service_table.add_row(['IP Address',
                                       service['ipAddress']['ipAddress']])
                service_table.add_row(['Port', service['port']])
                service_table.add_row(['Health Check',
                                       '%s:%s' %
                                       (health_check['healthCheckTypeId'],
                                        health_check['type']['name'])])
                service_table.add_row(
                    ['Weight', service['groupReferences'][0]['weight']])
                service_table.add_row(['Enabled', service['enabled']])
                service_table.add_row(['Status', service['status']])

    env.fout(table)
897494
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
    """"""

    mgr = SoftLayer.LoadBalancerManager(env.client)

    loadbal_id, group_id = loadbal.parse_id(identifier)

    # check if the IP is valid
    ip_address_id = None
    if ip_address:
        ip_service = env.client['Network_Subnet_IpAddress']
        ip_record = ip_service.getByIpAddress(ip_address)
        if len(ip_record) > 0:
            ip_address_id = ip_record['id']

    mgr.add_service(loadbal_id,
                    group_id,
                    ip_address_id=ip_address_id,
                    enabled=enabled,
                    port=port,
                    weight=weight,
                    hc_type=healthcheck_type)
    env.fout('Load balancer service is being added!')
872759
def check(self, radl):
        """"""

        SIMPLE_FEATURES = {
            "outbound": (str, ["YES", "NO"]),
            "outports": (str, check_outports_format),
            "provider_id": (str, None)
        }
        self.check_simple(SIMPLE_FEATURES, radl)
720199
def _get_client():
    '''
    
    '''
    client = salt.cloud.CloudClient(
            os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud')
            )
    return client
878004
def _get_connection(self):
        """"""
        kwargs = {
            'username': self.account,
            'api_key': self.secret_key,
        }

        # Only add kwarg for servicenet if True because user could set
        # environment variable 'RACKSPACE_SERVICENET' separately.
        if self.servicenet:
            kwargs['servicenet'] = True

        if self.authurl:
            kwargs['authurl'] = self.authurl

        return cloudfiles.get_connection(**kwargs)
592937
def is_running(self, port):
        """"""
        try:
            con = self.client('localhost:%s' % port)
            con.admin.command('ping')
            return True
        except (AutoReconnect, ConnectionFailure, OperationFailure):
            # Catch OperationFailure to work around SERVER-31916.
            return False
1185686
def verify_state(self):
        """"""
        if self.state == CONNECTING:
            self.state = OPEN

            self.conn.on_open(self.conn_info)
694230
def get_location(conn, vm_):
    '''
    
    '''
    locations = conn.list_locations()
    vm_location = config.get_cloud_config_value('location', vm_, __opts__)
    if not six.PY3:
        vm_location = vm_location.encode(
            'ascii', 'salt-cloud-force-ascii'
        )

    for img in locations:
        if isinstance(img.id, six.string_types) and not six.PY3:
            img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_id = str(img.id)  # future lint: disable=blacklisted-function

        if isinstance(img.name, six.string_types) and not six.PY3:
            img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_name = str(img.name)  # future lint: disable=blacklisted-function

        if vm_location and vm_location in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        'The specified location, \'{0}\', could not be found.'.format(
            vm_location
        )
    )
164199
def cli(env, identifier, wait):
    """"""

    compute = SoftLayer.HardwareManager(env.client)
    compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
                                    'hardware')
    ready = compute.wait_for_ready(compute_id, wait)
    if ready:
        env.fout("READY")
    else:
        raise exceptions.CLIAbort("Server %s not ready" % compute_id)
1007946
def get_conn():
    '''
    
    '''
    driver = get_driver(Provider.CLOUDSTACK)

    verify_ssl_cert = config.get_cloud_config_value('verify_ssl_cert',
            get_configured_provider(),
            __opts__,
            default=True,
            search_global=False)

    if verify_ssl_cert is False:
        try:
            import libcloud.security
            libcloud.security.VERIFY_SSL_CERT = False
        except (ImportError, AttributeError):
            raise SaltCloudSystemExit(
                'Could not disable SSL certificate verification. '
                'Not loading module.'
            )

    return driver(
        key=config.get_cloud_config_value(
            'apikey', get_configured_provider(), __opts__, search_global=False
        ),
        secret=config.get_cloud_config_value(
            'secretkey', get_configured_provider(), __opts__,
            search_global=False
        ),
        secure=config.get_cloud_config_value(
            'secure', get_configured_provider(), __opts__,
            default=True, search_global=False
        ),
        host=config.get_cloud_config_value(
            'host', get_configured_provider(), __opts__, search_global=False
        ),
        path=config.get_cloud_config_value(
            'path', get_configured_provider(), __opts__, search_global=False
        ),
        port=config.get_cloud_config_value(
            'port', get_configured_provider(), __opts__,
            default=None, search_global=False
        )
    )
583889
def tracker():
    """"""
    application = mmi.tracker.app()
    application.listen(22222)
    logger.info('serving at port 22222')
    tornado.ioloop.IOLoop.instance().start()
851022
def lookup_providers(self, lookup):
        '''
        
        '''
        if lookup is None:
            lookup = 'all'
        if lookup == 'all':
            providers = set()
            for alias, drivers in six.iteritems(self.opts['providers']):
                for driver in drivers:
                    providers.add((alias, driver))

            if not providers:
                raise SaltCloudSystemExit(
                    'There are no cloud providers configured.'
                )

            return providers

        if ':' in lookup:
            alias, driver = lookup.split(':')
            if alias not in self.opts['providers'] or \
                    driver not in self.opts['providers'][alias]:
                raise SaltCloudSystemExit(
                    'No cloud providers matched \'{0}\'. Available: {1}'.format(
                        lookup, ', '.join(self.get_configured_providers())
                    )
                )

        providers = set()
        for alias, drivers in six.iteritems(self.opts['providers']):
            for driver in drivers:
                if lookup in (alias, driver):
                    providers.add((alias, driver))

        if not providers:
            raise SaltCloudSystemExit(
                'No cloud providers matched \'{0}\'. '
                'Available selections: {1}'.format(
                    lookup, ', '.join(self.get_configured_providers())
                )
            )
        return providers
602260
def _find_usage_cloudtrail(self):
        """"""

        trail_list = self.conn.describe_trails()['trailList']
        trail_count = len(trail_list) if trail_list else 0

        for trail in trail_list:
            data_resource_count = 0
            if self.conn._client_config.region_name == trail['HomeRegion']:
                response = self.conn.get_event_selectors(
                    TrailName=trail['Name']
                )
                event_selectors = response['EventSelectors']
                for event_selector in event_selectors:
                    data_resource_count += len(
                        event_selector.get('DataResources', [])
                    )
                self.limits['Event Selectors Per Trail']._add_current_usage(
                    len(event_selectors),
                    aws_type='AWS::CloudTrail::EventSelector',
                    resource_id=trail['Name']
                )
                self.limits['Data Resources Per Trail']._add_current_usage(
                    data_resource_count,
                    aws_type='AWS::CloudTrail::DataResource',
                    resource_id=trail['Name']
                )
            else:
                logger.debug(
                    'Ignoring event selectors and data resources for '
                    'CloudTrail %s in non-home region' % trail['Name']
                )
        self.limits['Trails Per Region']._add_current_usage(
            trail_count,
            aws_type=self.aws_type
        )