Set up heat credentials, returns
    `heatclient.client.Client`. Optional parameter
    "api_version" defaults to 1.

    Only intended to be used within heat-enabled modules
548135
def _auth(profile=None, api_version=1, **connection_args):
    '''
    
    '''

    if profile:
        prefix = profile + ':keystone.'
    else:
        prefix = 'keystone.'

    def get(key, default=None):
        '''
        Checks connection_args, then salt-minion config,
        falls back to specified default value.
        '''
        return connection_args.get('connection_' + key,
                                   __salt__['config.get'](prefix + key, default))

    user = get('user', 'admin')
    password = get('password', None)
    tenant = get('tenant', 'admin')
    tenant_id = get('tenant_id')
    auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')
    insecure = get('insecure', False)
    admin_token = get('token')
    region_name = get('region_name', None)

    if admin_token and api_version != 1 and not password:
        # If we had a password we could just
        # ignore the admin-token and move on...
        raise SaltInvocationError('Only can use keystone admin token ' +
                                  'with Heat API v1')
    elif password:
        # Can't use the admin-token anyway
        kwargs = {'username': user,
                  'password': password,
                  'tenant_id': tenant_id,
                  'auth_url': auth_url,
                  'region_name': region_name,
                  'tenant_name': tenant}
        # 'insecure' keyword not supported by all v2.0 keystone clients
        #   this ensures it's only passed in when defined
        if insecure:
            kwargs['insecure'] = True
    elif api_version == 1 and admin_token:
        kwargs = {'token': admin_token,
                  'auth_url': auth_url}
    else:
        raise SaltInvocationError('No credentials to authenticate with.')

    token = __salt__['keystone.token_get'](profile)
    kwargs['token'] = token['id']
    # This doesn't realy prevent the password to show up
    # in the minion log as keystoneclient.session is
    # logging it anyway when in debug-mode
    kwargs.pop('password')
    try:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['url']
    except KeyError:
        heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl']
    heat_endpoint = heat_endpoint % token
    log.debug('Calling heatclient.client.Client(%s, %s, **%s)',
              api_version, heat_endpoint, kwargs)
    # may raise exc.HTTPUnauthorized, exc.HTTPNotFound
    # but we deal with those elsewhere
    return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs)
594318
def set_up_api_connection
      logger.info "connecting to rabbitmq HTTP API (#{api_config.sanitized_uri})"

      with_authentication_error_handler do
        with_connection_error_handler do
          @api_client = CarrotTop.new(host: api_config.host, port: api_config.port,
                                      user: api_config.username, password: api_config.password,
                                      ssl: api_config.ssl)
          @api_client.exchanges
        end
      end
    end
1056371
def generate_api_key(self):
        
        endpoint = '/'.join((self.server_url, '_api', 'v2', 'api_keys'))
        resp = self.r_session.post(endpoint)
        resp.raise_for_status()
        return response_to_json_dict(resp)
522824
def setup(cls, client_id, client_secret):
        
        cls.client_id = client_id
        cls.client_secret = client_secret
426637
def api_version(self):
        
        # Lean on the cache first.
        if self._api_version is not None:
            return self._api_version

        # We don't have a cache. Build it.
        self._api_version = self._introspect_api_version(
            self.session.core_session,
            self.service_name
        )
        return self._api_version
1186739
def initialize_api(args):
  
  global api
  api = ApiResource(server_host=args.hostname, server_port=args.port,
                    username=args.username, password=args.password,
                    version=args.api_version, use_tls=args.use_tls)
103844
def set_credentials(self, username, password=None, region=None,
            tenant_id=None, authenticate=False):
        
        self.api_key = None
        super(RaxIdentity, self).set_credentials(username, password=password,
                region=region, tenant_id=tenant_id, authenticate=authenticate)
967842
def create_api_key(awsclient, api_name, api_key_name):
    
    _sleep()
    client_api = awsclient.get_client('apigateway')
    print('create api key: %s' % api_key_name)

    response = client_api.create_api_key(
        name=api_key_name,
        description='Created for ' + api_name,
        enabled=True
    )

    #print(json2table(response))

    print('Add this api key \'%s\' to your api.conf' % response['id'])
    return response['id']
1062119
def _get_config(**api_opts):
    '''
    
    '''
    config = {
        'api_sslverify': True,
        'api_url': 'https://INFOBLOX/wapi/v1.2.1',
        'api_user': '',
        'api_key': '',
    }
    if '__salt__' in globals():
        config_key = '{0}.config'.format(__virtualname__)
        config.update(__salt__['config.get'](config_key, {}))
    # pylint: disable=C0201
    for k in set(config.keys()) & set(api_opts.keys()):
        config[k] = api_opts[k]
    return config
1310745
def set_http_connection_options(conn, opts)
      # Authentication
      unless uri.user.to_s.empty?
        conn.force_basic_auth = true
        conn.set_auth(uri.to_s, uri.user, uri.password)
      end

      # SSL Certificate option mapping
      if opts.include?(:verify_ssl)
        conn.ssl_config.verify_mode = opts[:verify_ssl] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
      end
      conn.ssl_config.client_cert = opts[:ssl_client_cert] if opts.include?(:ssl_client_cert)
      conn.ssl_config.client_key  = opts[:ssl_client_key]  if opts.include?(:ssl_client_key)
      conn.ssl_config.set_trust_ca(opts[:ssl_ca_file]) if opts.include?(:ssl_ca_file)

      # Timeout options
      conn.receive_timeout = opts[:timeout] if opts.include?(:timeout)
      conn.connect_timeout = opts[:open_timeout] if opts.include?(:open_timeout)
      conn.send_timeout    = opts[:read_timeout] if opts.include?(:read_timeout)
    end
975001
def setup_kojiclient(profile):
    
    opts = koji.read_config(profile)
    for k, v in opts.iteritems():
        opts[k] = os.path.expanduser(v) if type(v) is str else v
    kojiclient = koji.ClientSession(opts['server'], opts=opts)
    kojiclient.ssl_login(opts['cert'], None, opts['serverca'])
    return kojiclient
742954
def get_api_client():
    """"""
    with _api_lock:
        global _api_client
        if not _api_client:
            conf_file = os.path.join(os.environ.get("HOME"),
                                     ".python-grid5000.yaml")
            _api_client = Client.from_yaml(conf_file)

        return _api_client
146182
def available_api_versions(base_url, timeout=10, verify=True):
    
    try:
        r = requests.get('%s/api' % base_url, timeout=timeout,
                         verify=verify)  # no session required
        
        if r.status_code == 200:
            j = json.loads(r.text)
            versions = []
            for version in j['version']:
                versions.append(version['rel'])
            return versions
        
        raise SMCConnectionError(
            'Invalid status received while getting entry points from SMC. '
            'Status code received %s. Reason: %s' % (r.status_code, r.reason))

    except requests.exceptions.RequestException as e:
        raise SMCConnectionError(e)
402651
def get_settings(options = {}, request_options = {})
      options['getVersion'] = 2 if !options[:getVersion] && !options['getVersion']
      client.get(Protocol.settings_uri(name, options).to_s, :read, request_options)
    end
164881
def version(user=None, host=None, port=None, maintenance_db=None,
            password=None, runas=None):
    '''
    
    '''
    query = 'SELECT setting FROM pg_catalog.pg_settings ' \
            'WHERE name = \'server_version\''
    cmd = _psql_cmd('-c', query,
                    '-t',
                    host=host,
                    user=user,
                    port=port,
                    maintenance_db=maintenance_db,
                    password=password)
    ret = _run_psql(
        cmd, runas=runas, password=password, host=host, port=port, user=user)

    for line in salt.utils.itertools.split(ret['stdout'], '\n'):
        # Just return the first line
        return line
533825
def setup_apiv2():
    
    # setup PyQt api to version 2
    if sys.version_info[0] == 2:
        logging.getLogger(__name__).debug(
            'setting up SIP API to version 2')
        import sip
        try:
            sip.setapi("QString", 2)
            sip.setapi("QVariant", 2)
        except ValueError:
            logging.getLogger(__name__).critical(
                "failed to set up sip api to version 2 for PyQt4")
            raise ImportError('PyQt4')
184071
def Initialize(api_key, api_secret, api_host="localhost", api_port=443, api_ssl=True, asyncblock=False, timeout=10, req_method="get"):
    
    config = Config()

    if api_ssl:
        proto = "https"
    else:
        proto = "http"
    api_url = "%s://%s:%s/client/api" % (proto, api_host, api_port)
    if os.access(os.path.expanduser("~") , os.W_OK):
        d = os.path.expanduser("~")
    else:
        d = tempfile.gettempdir()
    cache_file = os.getenv('MOLNCTRL_CACHE') or '.molnctrl_cache'
    if os.path.exists(os.path.join(d, cache_file)):
        apicache = pickle.load(open( os.path.join(d, cache_file), "rb" ))
    else:
        method = {'description': u'lists all available apis on the server, provided by the Api Discovery plugin',
            'isasync': False,
            'name': u'listApis',
            'params': [{'description': u'API name',
            'length': 255,
            'name': u'name',
            'related': [],
            'required': False,
            'type': u'string'}],
            'related': [],
            'requiredparams': []}
        _create_api_method(CSApi, "list_apis", method)
        c = CSApi(api_url, api_key, api_secret, asyncblock)
        apicache = cachemaker.monkeycache(c.list_apis())
        pickle.dump(apicache, open(os.path.join(d, cache_file), "wb"))

    for verb, methods in six.iteritems(apicache):
        if isinstance(methods, dict):
            for method in six.iterkeys(methods):
                _create_api_method(CSApi, "%s_%s" % (verb, method), methods[method])
    return CSApi(api_url, api_key, api_secret, asyncblock, timeout, req_method)