Determine the GCE authorization settings and return a
        libcloud driver.
161468
def get_gce_driver(self):
        
        # Attempt to get GCE params from a configuration file, if one
        # exists.
        secrets_path = self.config.get('gce', 'libcloud_secrets')
        secrets_found = False
        try:
            import secrets
            args = list(getattr(secrets, 'GCE_PARAMS', []))
            kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {})
            secrets_found = True
        except:
            pass

        if not secrets_found and secrets_path:
            if not secrets_path.endswith('secrets.py'):
                err = "Must specify libcloud secrets file as "
                err += "/absolute/path/to/secrets.py"
                sys.exit(err)
            sys.path.append(os.path.dirname(secrets_path))
            try:
                import secrets
                args = list(getattr(secrets, 'GCE_PARAMS', []))
                kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {})
                secrets_found = True
            except:
                pass
        if not secrets_found:
            args = [
                self.config.get('gce','gce_service_account_email_address'),
                self.config.get('gce','gce_service_account_pem_file_path')
            ]
            kwargs = {'project': self.config.get('gce', 'gce_project_id')}

        # If the appropriate environment variables are set, they override
        # other configuration; process those into our args and kwargs.
        args[0] = os.environ.get('GCE_EMAIL', args[0])
        args[1] = os.environ.get('GCE_PEM_FILE_PATH', args[1])
        kwargs['project'] = os.environ.get('GCE_PROJECT', kwargs['project'])

        # Retrieve and return the GCE driver.
        gce = get_driver(Provider.GCE)(*args, **kwargs)
        gce.connection.user_agent_append(
            '%s/%s' % (USER_AGENT_PRODUCT, USER_AGENT_VERSION),
        )
        return gce
1251332
def _get_gdcmconv():
    
    gdcmconv_executable = settings.gdcmconv_path
    if gdcmconv_executable is None:
        gdcmconv_executable = _which('gdcmconv')
    if gdcmconv_executable is None:
        gdcmconv_executable = _which('gdcmconv.exe')

    if gdcmconv_executable is None:
        raise ConversionError('GDCMCONV_NOT_FOUND')

    return gdcmconv_executable
979278
def cli(env, identifier, passwords, price):
    """"""

    hardware = SoftLayer.HardwareManager(env.client)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
    result = hardware.get_hardware(hardware_id)
    result = utils.NestedDict(result)

    operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {}
    memory = formatting.gb(result.get('memoryCapacity', 0))
    owner = None
    if utils.lookup(result, 'billingItem') != []:
        owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username')

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier'] or formatting.blank()])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row(['status', result['hardwareStatus']['status']])
    table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()])
    table.add_row(['cores', result['processorPhysicalCoreAmount']])
    table.add_row(['memory', memory])
    table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()])
    table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()])
    table.add_row(['ipmi_ip', result['networkManagementIpAddress'] or formatting.blank()])
    table.add_row(['os', operating_system.get('name') or formatting.blank()])
    table.add_row(['os_version', operating_system.get('version') or formatting.blank()])
    table.add_row(['created', result['provisionDate'] or formatting.blank()])
    table.add_row(['owner', owner or formatting.blank()])

    vlan_table = formatting.Table(['type', 'number', 'id'])
    for vlan in result['networkVlans']:
        vlan_table.add_row([vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])

    table.add_row(['vlans', vlan_table])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0

        price_table = formatting.Table(['Item', 'Recurring Price'])
        price_table.add_row(['Total', total_price])

        for item in utils.lookup(result, 'billingItem', 'children') or []:
            price_table.add_row([item['description'], item['nextInvoiceTotalRecurringAmount']])

        table.add_row(['prices', price_table])

    if passwords:
        pass_table = formatting.Table(['username', 'password'])
        for item in result['operatingSystem']['passwords']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['users', pass_table])

        pass_table = formatting.Table(['ipmi_username', 'password'])
        for item in result['remoteManagementAccounts']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['remote users', pass_table])

    table.add_row(['tags', formatting.tags(result['tagReferences'])])

    env.fout(table)
1351183
def vm_configured(name, vm_name, cpu, memory, image, version, interfaces,
                  disks, scsi_devices, serial_ports, datacenter, datastore,
                  placement, cd_dvd_drives=None, sata_controllers=None,
                  advanced_configs=None, template=None, tools=True,
                  power_on=False, deploy=False):
    '''
    
    '''
    result = {'name': name,
              'result': None,
              'changes': {},
              'comment': ''}

    log.trace('Validating virtual machine configuration')
    schema = ESXVirtualMachineConfigSchema.serialize()
    log.trace('schema = %s', schema)
    try:
        jsonschema.validate({'vm_name': vm_name,
                             'cpu': cpu,
                             'memory': memory,
                             'image': image,
                             'version': version,
                             'interfaces': interfaces,
                             'disks': disks,
                             'scsi_devices': scsi_devices,
                             'serial_ports': serial_ports,
                             'cd_dvd_drives': cd_dvd_drives,
                             'sata_controllers': sata_controllers,
                             'datacenter': datacenter,
                             'datastore': datastore,
                             'placement': placement,
                             'template': template,
                             'tools': tools,
                             'power_on': power_on,
                             'deploy': deploy}, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise salt.exceptions.InvalidConfigError(exc)

    service_instance = __salt__['vsphere.get_service_instance_via_proxy']()
    try:
        __salt__['vsphere.get_vm'](vm_name, vm_properties=['name'],
                                   service_instance=service_instance)
    except salt.exceptions.VMwareObjectRetrievalError:
        vm_file = __salt__['vsphere.get_vm_config_file'](
            vm_name, datacenter,
            placement, datastore,
            service_instance=service_instance)
        if vm_file:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be registered.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            result = vm_registered(vm_name, datacenter, placement,
                                   vm_file, power_on=power_on)
            return result
        else:
            if __opts__['test']:
                result.update({'comment': 'The virtual machine {0}'
                                          ' will be created.'.format(vm_name)})
                __salt__['vsphere.disconnect'](service_instance)
                return result
            if template:
                result = vm_cloned(name)
            else:
                result = vm_created(name, vm_name, cpu, memory, image, version,
                                    interfaces, disks, scsi_devices,
                                    serial_ports, datacenter, datastore,
                                    placement, cd_dvd_drives=cd_dvd_drives,
                                    advanced_configs=advanced_configs,
                                    power_on=power_on)
            return result

    result = vm_updated(name, vm_name, cpu, memory, image, version,
                        interfaces, disks, scsi_devices,
                        serial_ports, datacenter, datastore,
                        cd_dvd_drives=cd_dvd_drives,
                        sata_controllers=sata_controllers,
                        advanced_configs=advanced_configs,
                        power_on=power_on)
    __salt__['vsphere.disconnect'](service_instance)

    log.trace(result)
    return result
951585
def create_gce_image(zone,
                     project,
                     instance_name,
                     name,
                     description):
    

    disk_name = instance_name
    try:
        down_gce(instance_name=instance_name, project=project, zone=zone)
    except HttpError as e:
        if e.resp.status == 404:
            log_yellow("the instance {} is already down".format(instance_name))
        else:
            raise e

    body = {
        "rawDisk": {},
        "name": name,
        "sourceDisk": "projects/{}/zones/{}/disks/{}".format(
            project, zone, disk_name
        ),
        "description": description
    }
    compute = _get_gce_compute()
    gce_wait_until_done(
        compute.images().insert(project=project, body=body).execute()
    )
    return name
62853
def credentials_delegated(self):
        
        return self._gss_flags & sspicon.ISC_REQ_DELEGATE and (
            self._gss_srv_ctxt_status or self._gss_flags
        )
447548
def get_persistent_address(instance):
    """"""
    if instance.cloud == 'aws':
        client = boto3.client('ec2', instance.region)
        try:
            client.describe_addresses(PublicIps=[instance.ip_address])
            return instance.ip_address
        except botocore.client.ClientError as exc:
            if exc.response.get('Error', {}).get('Code') != 'InvalidAddress.NotFound':
                raise
            # Address is not public
            return None
    if instance.cloud == 'gcp':
        credentials = GoogleCredentials.get_application_default()
        compute = discovery.build('compute', 'v1', credentials=credentials)
        try:
            return compute.addresses().get(address=instance.name, project=instance.project, region=instance.region).execute()['address']
        except errors.HttpError as exc:
            if 'was not found' in str(exc):
                return None
            raise
    raise ValueError('Unknown cloud %s' % instance.cloud)
1098119
def _verify(vm_):
    '''
    
    '''
    log.info('Verifying credentials for %s', vm_['name'])

    win_installer = config.get_cloud_config_value(
        'win_installer', vm_, __opts__)

    if win_installer:

        log.debug('Testing Windows authentication method for %s', vm_['name'])

        if not HAS_IMPACKET:
            log.error('Impacket library not found')
            return False

        # Test Windows connection
        kwargs = {
            'host': vm_['ssh_host'],
            'username': config.get_cloud_config_value(
                'win_username', vm_, __opts__, default='Administrator'),
            'password': config.get_cloud_config_value(
                'win_password', vm_, __opts__, default='')
        }

        # Test SMB connection
        try:
            log.debug('Testing SMB protocol for %s', vm_['name'])
            if __utils__['smb.get_conn'](**kwargs) is False:
                return False
        except (smbSessionError, smb3SessionError) as exc:
            log.error('Exception: %s', exc)
            return False

        # Test WinRM connection
        use_winrm = config.get_cloud_config_value(
            'use_winrm', vm_, __opts__, default=False)

        if use_winrm:
            log.debug('WinRM protocol requested for %s', vm_['name'])
            if not HAS_WINRM:
                log.error('WinRM library not found')
                return False

            kwargs['port'] = config.get_cloud_config_value(
                'winrm_port', vm_, __opts__, default=5986)
            kwargs['timeout'] = 10

            try:
                log.debug('Testing WinRM protocol for %s', vm_['name'])
                return __utils__['cloud.wait_for_winrm'](**kwargs) is not None
            except (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
                    ProxyError, RetryError, InvalidSchema, WinRMTransportError) as exc:
                log.error('Exception: %s', exc)
                return False

        return True

    else:

        log.debug('Testing SSH authentication method for %s', vm_['name'])

        # Test SSH connection
        kwargs = {
            'host': vm_['ssh_host'],
            'port': config.get_cloud_config_value(
                'ssh_port', vm_, __opts__, default=22
            ),
            'username': config.get_cloud_config_value(
                'ssh_username', vm_, __opts__, default='root'
            ),
            'password': config.get_cloud_config_value(
                'password', vm_, __opts__, search_global=False
            ),
            'key_filename': config.get_cloud_config_value(
                'key_filename', vm_, __opts__, search_global=False,
                default=config.get_cloud_config_value(
                    'ssh_keyfile', vm_, __opts__, search_global=False,
                    default=None
                )
            ),
            'gateway': vm_.get('gateway', None),
            'maxtries': 1
        }

        log.debug('Testing SSH protocol for %s', vm_['name'])
        try:
            return __utils__['cloud.wait_for_passwd'](**kwargs) is True
        except SaltCloudException as exc:
            log.error('Exception: %s', exc)
            return False
631029
def get_driver(self, name, version):
        
        user_credentials = self.get_user_credentials()  # get credentials
        return discovery.build(
            name, version,
            http=self.authenticate(user_credentials)
        )
446065
def _build_credentials_tuple(mech, source, user, passwd, extra):
    
    user = _unicode(user) if user is not None else None
    password = passwd if passwd is None else _unicode(passwd)
    if mech == 'GSSAPI':
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, password, props)
    elif mech == 'MONGODB-X509':
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None)
    else:
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(mech, source, user, password, None)
1267075
def get_storage_credentials(key, read_only=False):
    """"""
    if read_only:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
    else:
        scopes = ['https://www.googleapis.com/auth/devstorage.read_write']

    credentials = service_account.Credentials.from_service_account_info(key)
    
    scoped_credentials = credentials.with_scopes(scopes)
    
    return scoped_credentials
1121290
def get_configured_provider():
    '''
    
    '''
    return config.is_provider_configured(
        opts=__opts__,
        provider=__active_provider_name__ or __virtualname__,
        aliases=__virtual_aliases__,
        required_keys=('personal_access_token',)
    )
1179227
def _initialize_metadata_service(cls):
        
        if cls.inited:
            return

        instance_id = cls.get_attribute('instance/id')

        if instance_id is not None:
            cls.is_running = True

            _GCP_METADATA_MAP['instance_id'] = instance_id

            # fetch attributes from metadata request
            for attribute_key, attribute_uri in _GCE_ATTRIBUTES.items():
                if attribute_key not in _GCP_METADATA_MAP:
                    attribute_value = cls.get_attribute(attribute_uri)
                    if attribute_value is not None:  # pragma: NO COVER
                        _GCP_METADATA_MAP[attribute_key] = attribute_value

        cls.inited = True
517778
def auth_from_hass_config(path=None, **kwargs):
    """"""
    if path is None:
        path = config.find_hass_config()

    return Auth(os.path.join(path, ".storage/auth"), **kwargs)
394209
def create_client(self) -> "google.cloud.storage.Client":
        
        # Client should be imported here because grpc starts threads during import
        # and if you call fork after that, a child process will be hang during exit
        from google.cloud.storage import Client
        if self.credentials:
            client = Client.from_service_account_json(self.credentials)
        else:
            client = Client()
        return client
186049
def get_drive_api():
    
    settings = Settings()

    if settings.credentials:
        return get_drive_api_from_file(settings.credentials_path)

    if settings.client_secrets:
        return get_drive_api_from_client_secrets(settings.client_secrets_path)
964252
def _get_gcloud_sdk_credentials():
    """"""
    from google.auth import _cloud_sdk

    # Check if application default credentials exist.
    credentials_filename = (
        _cloud_sdk.get_application_default_credentials_path())

    if not os.path.isfile(credentials_filename):
        return None, None

    credentials, project_id = _load_credentials_from_file(
        credentials_filename)

    if not project_id:
        project_id = _cloud_sdk.get_project_id()

    return credentials, project_id