Return a GCE libcloud network object with matching name
193253
def __get_network(conn, vm_):
    '''
    
    '''
    network = config.get_cloud_config_value(
        'network', vm_, __opts__,
        default='default', search_global=False)
    return conn.ex_get_network(network)
1217402
def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID,
               provider=config.DEFAULT_PROVIDER):

    """"""

    if hasattr(config, 'get_driver'):
        logger.debug('get_driver %s' % config.get_driver)
        return config.get_driver()
    else:
        logger.debug('get_driver {0}@{1}'.format(userid, provider))
        return libcloud.compute.providers.get_driver(
            config.PROVIDERS[provider])(userid, secret_key)
316065
def connect_to_cloudfiles(region=None, public=None):
    """"""
    if public is None:
        is_public = not bool(get_setting("use_servicenet"))
    else:
        is_public = public
    ret = _create_client(ep_name="object_store", region=region,
            public=is_public)
    if ret:
        # Add CDN endpoints, if available
        region = _safe_region(region)
        ret.cdn_management_url = _get_service_endpoint(None, "object_cdn",
                region, public=is_public)
    return ret
214509
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}):
    """"""
    if libname not in _libcache:
        _libcache[libname] = windll.LoadLibrary(libname)
    func = getattr(_libcache[libname], funcname)
    func.argtypes = argtypes
    func.restype = restype
    return func
1121561
def get_subnetid(vm_):
    '''
    
    '''
    subnetid = config.get_cloud_config_value(
        'subnetid', vm_, __opts__, search_global=False
    )
    if subnetid:
        return subnetid

    subnetname = config.get_cloud_config_value(
        'subnetname', vm_, __opts__, search_global=False
    )
    if subnetname:
        return _get_subnetname_id(subnetname)
    return None
57561
def name_url(provider, cloud, method_name):
    
    snake_parts = method_name.split('_')
    if len(snake_parts) <= 1:
        return False

    # Convention for libcloud is ex_ are extended methods
    if snake_parts[0] == 'ex':
        extra = True
        method_name = method_name.replace('ex_', '', 1)
    else:
        extra = False
    snake_parts = method_name.split('_')
    # Try to semantically match the method name to a REST action
    if snake_parts[0] in get_sem_verbs:
        method = 'GET'
        for verb in get_sem_verbs:
            method_name = method_name.replace('%s_' % verb, '', 1)
    elif snake_parts[0] in delete_sem_verbs:
        method = 'DELETE'
    elif snake_parts[0] in put_sem_verbs:
        method = 'PUT'
    else:
        method = 'POST'

    uri = '/%s/%s/%s%s' % (provider,
                           cloud,
                           'extensions/' if extra else '',
                           method_name)
    return (method, uri)
1065202
def get_dependencies():
    '''
    
    '''
    if LIBCLOUD_IMPORT_ERROR:
        log.error("Failure when importing LibCloud: ", exc_info=LIBCLOUD_IMPORT_ERROR)
        log.error("Note: The libcloud dependency is called 'apache-libcloud' on PyPi/pip.")
    return config.check_driver_dependencies(
        __virtualname__,
        {'libcloud': HAS_LIBCLOUD}
    )
800487
def get_node(conn, name):
    '''
    
    '''
    datacenter_id = get_datacenter_id()

    for item in conn.list_servers(datacenter_id)['items']:
        if item['properties']['name'] == name:
            node = {'id': item['id']}
            node.update(item['properties'])
            return node
761250
def network_show(self, name):
        '''
        
        '''
        nt_ks = self.compute_conn
        net_list = nt_ks.networks.list()
        return self._network_show(name, net_list)
248792
def show_network(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_network function must be called with -f or --function.'
        )
    if not kwargs or 'name' not in kwargs:
        log.error(
            'Must specify name of network.'
        )
        return False

    conn = get_conn()
    return _expand_item(conn.ex_get_network(kwargs['name']))
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
805932
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )
    try:
        node = list_nodes_full('function')[name]
    except KeyError:
        log.debug('Failed to get data for node \'%s\'', name)
        node = {}

    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)

    return node
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
    )
679882
def subnet_get(auth=None, **kwargs):
    '''
    

    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.get_subnet(**kwargs)
1186986
def key_pair_name(i, region, project_id, ssh_user):
    """"""
    key_name = "{}_gcp_{}_{}_{}".format(RAY, region, project_id, ssh_user, i)
    return key_name
1179652
def get_datacenter(content, obj):
    '''
    
    '''
    datacenters = content.rootFolder.childEntity
    for d in datacenters:
        dch = get_all(content, d, type(obj))
        if dch is not None and obj in dch:
            return d
960795
def request_instance(vm_):
    '''
    
    '''
    if not GCE_VM_NAME_REGEX.match(vm_['name']):
        raise SaltCloudSystemExit(
            'VM names must start with a letter, only contain letters, numbers, or dashes '
            'and cannot end in a dash.'
        )

    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'gce',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'create instance',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    conn = get_conn()

    kwargs = {
        'name': vm_['name'],
        'size': __get_size(conn, vm_),
        'image': __get_image(conn, vm_),
        'location': __get_location(conn, vm_),
        'ex_network': __get_network(conn, vm_),
        'ex_subnetwork': __get_subnetwork(vm_),
        'ex_tags': __get_tags(vm_),
        'ex_metadata': __get_metadata(vm_),
    }
    external_ip = config.get_cloud_config_value(
        'external_ip', vm_, __opts__, default='ephemeral'
    )

    if external_ip.lower() == 'ephemeral':
        external_ip = 'ephemeral'
        vm_['external_ip'] = external_ip
    elif external_ip == 'None':
        external_ip = None
        vm_['external_ip'] = external_ip
    else:
        region = __get_region(conn, vm_)
        external_ip = __create_orget_address(conn, external_ip, region)
        vm_['external_ip'] = {
            'name': external_ip.name,
            'address': external_ip.address,
            'region': external_ip.region.name
        }
    kwargs['external_ip'] = external_ip

    if LIBCLOUD_VERSION_INFO > (0, 15, 1):

        kwargs.update({
            'ex_disk_type': config.get_cloud_config_value(
                'ex_disk_type', vm_, __opts__, default='pd-standard'),
            'ex_disk_auto_delete': config.get_cloud_config_value(
                'ex_disk_auto_delete', vm_, __opts__, default=True),
            'ex_disks_gce_struct': config.get_cloud_config_value(
                'ex_disks_gce_struct', vm_, __opts__, default=None),
            'ex_service_accounts': config.get_cloud_config_value(
                'ex_service_accounts', vm_, __opts__, default=None),
            'ex_can_ip_forward': config.get_cloud_config_value(
                'ip_forwarding', vm_, __opts__, default=False),
            'ex_preemptible': config.get_cloud_config_value(
                'preemptible', vm_, __opts__, default=False)
        })
        if kwargs.get('ex_disk_type') not in ('pd-standard', 'pd-ssd'):
            raise SaltCloudSystemExit(
                'The value of \'ex_disk_type\' needs to be one of: '
                '\'pd-standard\', \'pd-ssd\''
            )

    # GCE accelerator options are only supported as of libcloud >= 2.3.0
    # and Python 3+ is required so that libcloud will detect a type of
    # 'string' rather than 'unicode'
    if LIBCLOUD_VERSION_INFO >= (2, 3, 0) and isinstance(u'test', str):

        kwargs.update({
            'ex_accelerator_type': config.get_cloud_config_value(
                'ex_accelerator_type', vm_, __opts__, default=None),
            'ex_accelerator_count': config.get_cloud_config_value(
                'ex_accelerator_count', vm_, __opts__, default=None)
        })
        if kwargs.get('ex_accelerator_type'):
            log.warning(
                'An accelerator is being attached to this instance, '
                'the ex_on_host_maintenance setting is being set to '
                '\'TERMINATE\' as a result'
            )
            kwargs.update({
                'ex_on_host_maintenance': 'TERMINATE'
            })

    log.info(
        'Creating GCE instance %s in %s',
        vm_['name'], kwargs['location'].name
    )
    log.debug('Create instance kwargs %s', kwargs)

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    try:
        node_data = conn.create_node(**kwargs)
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s on GCE\n\n'
            'The following exception was thrown by libcloud when trying to '
            'run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )

    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args={'volumes': volumes},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'node': node_data
            },
            call='action'
        )

    try:
        node_dict = show_instance(node_data['name'], 'action')
    except TypeError:
        # node_data is a libcloud Node which is unsubscriptable
        node_dict = show_instance(node_data.name, 'action')

    return node_dict, node_data