queries Rackspace for details about a particular server id
506880
def get_rackspace_info(server_id,
                       region,
                       access_key_id,
                       secret_access_key,
                       username):
    
    nova = connect_to_rackspace(region, access_key_id, secret_access_key)
    server = nova.servers.get(server_id)

    data = {}
    data['id'] = server.id
    # this needs to be tackled
    data['ip_address'] = server.accessIPv4
    data['state'] = server.status
    data['region'] = region
    data['cloud_type'] = 'rackspace'
    data['username'] = username

    # find out the distribution running on the instance
    if username is not None:
        wait_for_ssh(data['ip_address'])
        with settings(host_string=username + '@' + data['ip_address']):
            data['distribution'] = linux_distribution(username,
                                                      data['ip_address'])
            data['os_release'] = os_release(username,
                                            data['ip_address'])

    data['volume'] = ''
    return data
644976
def get_rackspace_token(username, apikey):
    
    auth_params = {
        "auth": {
            "RAX-KSKEY:apiKeyCredentials": {
                "username": username,
                "apiKey": apikey,
            }
        }
    }
    response = requests.post(RS_IDENTITY_URL, json=auth_params)
    if not response.ok:
        sys.exit(RS_AUTH_ERROR.format(response.status_code, response.text))

    identity = response.json()
    return (identity['access']['token']['id'],
            identity['access']['token']['tenant']['id'])
728931
def query(method='GET', profile_dict=None, url=None, path='api/v1',
          action=None, api_key=None, service=None, params=None,
          data=None, subdomain=None, client_url=None, description=None,
          opts=None, verify_ssl=True):
    '''
    
    '''
    user_agent = 'SaltStack {0}'.format(__version__)

    if opts is None:
        opts = {}

    if isinstance(profile_dict, dict):
        creds = profile_dict
    else:
        creds = {}

    if api_key is not None:
        creds['pagerduty.api_key'] = api_key

    if service is not None:
        creds['pagerduty.service'] = service

    if subdomain is not None:
        creds['pagerduty.subdomain'] = subdomain

    if client_url is None:
        client_url = 'https://{0}.pagerduty.com'.format(
            creds['pagerduty.subdomain']
        )

    if url is None:
        url = 'https://{0}.pagerduty.com/{1}/{2}'.format(
            creds['pagerduty.subdomain'],
            path,
            action
        )

    if params is None:
        params = {}

    if data is None:
        data = {}

    data['client'] = user_agent

    # pagerduty.service is not documented.  While it makes sense to have in
    # some cases, don't force it when it is not defined.
    if 'pagerduty.service' in creds and creds['pagerduty.service'] is not None:
        data['service_key'] = creds['pagerduty.service']
    data['client_url'] = client_url
    if 'event_type' not in data:
        data['event_type'] = 'trigger'
    if 'description' not in data:
        if not description:
            data['description'] = 'SaltStack Event Triggered'
        else:
            data['description'] = description

    headers = {
        'User-Agent': user_agent,
        'Authorization': 'Token token={0}'.format(creds['pagerduty.api_key'])
    }
    if method == 'GET':
        data = {}
    else:
        headers['Content-type'] = 'application/json'

    result = salt.utils.http.query(
        url,
        method,
        params=params,
        header_dict=headers,
        data=salt.utils.json.dumps(data),
        decode=False,
        text=True,
        opts=opts,
    )

    return result['text']
955252
def request_server_info(self):
        ''' 

        '''
        if self._server_info is None:
            self._server_info = self._send_request_server_info()
        return self._server_info
1051273
def server_show_libcloud(self, uuid):
        '''
        
        '''
        server_info = self.server_show(uuid)
        server = next(six.itervalues(server_info))
        server_name = next(six.iterkeys(server_info))
        if not hasattr(self, 'password'):
            self.password = None
        ret = NovaServer(server_name, server, self.password)

        return ret
49156
def server_list_detailed(self):
        '''
        
        '''
        nt_ks = self.compute_conn
        ret = {}
        for item in nt_ks.servers.list():
            try:
                ret[item.name] = {
                    'OS-EXT-SRV-ATTR': {},
                    'OS-EXT-STS': {},
                    'accessIPv4': item.accessIPv4,
                    'accessIPv6': item.accessIPv6,
                    'addresses': item.addresses,
                    'created': item.created,
                    'flavor': {'id': item.flavor['id'],
                               'links': item.flavor['links']},
                    'hostId': item.hostId,
                    'id': item.id,
                    'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
                              'links': item.image['links'] if item.image else ''},
                    'key_name': item.key_name,
                    'links': item.links,
                    'metadata': item.metadata,
                    'name': item.name,
                    'state': item.status,
                    'tenant_id': item.tenant_id,
                    'updated': item.updated,
                    'user_id': item.user_id,
                }
            except TypeError:
                continue

            ret[item.name]['progress'] = getattr(item, 'progress', '0')

            if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
                ret[item.name]['OS-DCF'] = {
                    'diskConfig': item.__dict__['OS-DCF:diskConfig']
                }
            if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
                ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
                    item.__dict__['OS-EXT-SRV-ATTR:host']
            if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
                ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
                    item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
            if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
                ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
                    item.__dict__['OS-EXT-SRV-ATTR:instance_name']
            if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
                ret[item.name]['OS-EXT-STS']['power_state'] = \
                    item.__dict__['OS-EXT-STS:power_state']
            if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
                ret[item.name]['OS-EXT-STS']['task_state'] = \
                    item.__dict__['OS-EXT-STS:task_state']
            if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
                ret[item.name]['OS-EXT-STS']['vm_state'] = \
                    item.__dict__['OS-EXT-STS:vm_state']
            if hasattr(item.__dict__, 'security_groups'):
                ret[item.name]['security_groups'] = \
                    item.__dict__['security_groups']
        return ret
1288907
def sessions_info(self, hosts):
        
        info_by_id = {}

        for server_endpoint, dump in self.dump_by_server(hosts).items():
            server_ip, server_port = server_endpoint
            for line in dump.split("\n"):
                mat = self.IP_PORT_REGEX.match(line)
                if mat is None:
                    continue
                ip, port, sid = mat.groups()
                info_by_id[sid] = ClientInfo(sid, ip, port, server_ip, server_port)

        return info_by_id
555539
function(details, callback) {
        var self = this;

        if (typeof(details) === 'function') {
            callback = details;
            details = {};
        }

        var requestOptions = {
            uri: '/domains',
            endpoint: rackspace.Endpoints.CloudDns
        };

        requestOptions.qs = _.pick(details,
            'name');

        self.authorizedRequest(requestOptions, function(err, res, body) {
            if (err || !body.domains) {
                callback(err);
                return;
            }

            var domains = [];

            for (var i = 0; i < body.domains.length; i++) {
                domains.push(new rackspace.Domain(self, body.domains[i]));
            }

            callback(err, domains);
        });
    }
381400
def server_info(self, verbose=False):
        '''
        
        '''
        url = '{}/{}'.format(self.rest_url, 'serverinfo')
        return self.__auth_req_get(url, verbose=verbose)
594368
def get_server_id():
    '''
    
    '''
    # Provides:
    #   server_id

    if salt.utils.platform.is_proxy():
        server_id = {}
    else:
        use_crc = __opts__.get('server_id_use_crc')
        if bool(use_crc):
            id_hash = getattr(zlib, use_crc, zlib.adler32)(__opts__.get('id', '').encode()) & 0xffffffff
        else:
            log.debug('This server_id is computed not by Adler32 nor by CRC32. '
                      'Please use "server_id_use_crc" option and define algorithm you '
                      'prefer (default "Adler32"). Starting with Sodium, the '
                      'server_id will be computed with Adler32 by default.')
            id_hash = _get_hash_by_shell()
        server_id = {'server_id': id_hash}

    return server_id
622339
def hidden(self):
        """"""
        members = [self.member_info(item["_id"]) for item in self.members()]
        result = []
        for member in members:
            if member['rsInfo'].get('hidden'):
                server_id = member['server_id']
                result.append({
                    '_id': member['_id'],
                    'host': self._servers.hostname(server_id),
                    'server_id': server_id})
        return result
875403
def destroy_rackspace(region, instance_id, access_key_id, secret_access_key):
    
    nova = connect_to_rackspace(region,
                                access_key_id,
                                secret_access_key)

    server = nova.servers.get(instance_id)
    log_yellow('deleting rackspace instance ...')
    server.delete()

    # wait for server to be deleted
    try:
        while True:
            server = nova.servers.get(server.id)
            log_yellow('waiting for deletion ...')
            sleep(5)
    except:
        pass
    log_green('The server has been deleted')
    os.unlink('data.json')
1304107
def find_server(client, address_str)
      client.cluster.servers_list.detect{ |s| s.address.to_s == address_str }
    end
931633
def tablespace_list(user=None, host=None, port=None, maintenance_db=None,
                    password=None, runas=None):
    '''
    
    '''

    ret = {}

    query = (
        'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", '
        'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" '
        'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner'
    )

    rows = __salt__['postgres.psql_query'](query, runas=runas, host=host,
                                           user=user, port=port,
                                           maintenance_db=maintenance_db,
                                           password=password)

    for row in rows:
        ret[row['Name']] = row
        ret[row['Name']].pop('Name')

    return ret
89136
def GET_namespace_names( self, path_info, namespace_id ):
        
        if not check_namespace(namespace_id):
            return self._reply_json({'error': 'Invalid namespace'}, status_code=400)

        qs_values = path_info['qs_values']
        page = qs_values.get('page', None)
        if page is None:
            log.error("Page required")
            return self._reply_json({'error': 'page= argument required'}, status_code=400)

        try:
            page = int(page)
            if page < 0:
                raise ValueError()

        except ValueError:
            log.error("Invalid page")
            return self._reply_json({'error': 'Invalid page= value'}, status_code=400)

        offset = page * 100
        count = 100

        blockstackd_url = get_blockstackd_url()
        namespace_names = blockstackd_client.get_names_in_namespace(namespace_id, offset=offset, count=count, hostport=blockstackd_url)
        if json_is_error(namespace_names):
            # error
            status_code = namespace_names.get('http_status', 502)
            return self._reply_json({'error': namespace_names['error']}, status_code=status_code)

        self._reply_json(namespace_names)
        return
273886
def _fetch_system_by_machine_id(self):
        '''
        
        '''
        machine_id = generate_machine_id()
        try:
            url = self.api_url + '/inventory/v1/hosts?insights_id=' + machine_id
            net_logger.info("GET %s", url)
            res = self.session.get(url, timeout=self.config.http_timeout)
        except (requests.ConnectionError, requests.Timeout) as e:
            logger.error(e)
            logger.error('The Insights API could not be reached.')
            return None
        try:
            if (self.handle_fail_rcs(res)):
                return None
            res_json = json.loads(res.content)
        except ValueError as e:
            logger.error(e)
            logger.error('Could not parse response body.')
            return None
        if res_json['total'] == 0:
            logger.debug('No hosts found with machine ID: %s', machine_id)
            return False
        return res_json['results']
548151
def get_server(key, server=MAIN_SERVER, servers=LOAD_SERVERS):

    

    namecoind = NamecoindClient(NAMECOIND_SERVER, NAMECOIND_PORT,
                                NAMECOIND_USER, NAMECOIND_PASSWD)

    info = namecoind.name_show(key)

    if 'address' in info:
        return check_address(info['address'], server, servers)

    response = {}
    response["registered"] = False
    response["server"] = None
    response["ismine"] = False
    return response