Return a keystone session object
356171
def get_keystone_session(self, keystone_ip, username, password,
                             api_version=False, admin_port=False,
                             user_domain_name=None, domain_name=None,
                             project_domain_name=None, project_name=None):
        """"""
        ep = self.get_keystone_endpoint(keystone_ip,
                                        api_version=api_version,
                                        admin_port=admin_port)
        if api_version == 2:
            auth = v2.Password(
                username=username,
                password=password,
                tenant_name=project_name,
                auth_url=ep
            )
            sess = keystone_session.Session(auth=auth)
        else:
            auth = v3.Password(
                user_domain_name=user_domain_name,
                username=username,
                password=password,
                domain_name=domain_name,
                project_domain_name=project_domain_name,
                project_name=project_name,
                auth_url=ep
            )
            sess = keystone_session.Session(auth=auth)
        return (sess, auth)
1350959
def query(self, session=None):
        ''''''
        if session is None or session.router is not self.router:
            session = self.session()
        return session.query(self.model)
985295
def resource(*args, loop=None, **kwargs):
    
    return _get_default_session(loop=loop).resource(*args, **kwargs)
980509
def _get_client(region, key, keyid, profile):
    '''
    
    '''
    session = _get_session(region, key, keyid, profile)
    if not session:
        log.error("Failed to get datapipeline client.")
        return None

    return session.client('datapipeline')
789709
def sessions(status, access_key, id_only, all):
    '''
    
    '''
    fields = [
        ('Session ID', 'sess_id'),
    ]
    with Session() as session:
        if is_admin(session):
            fields.append(('Owner', 'access_key'))
    if not id_only:
        fields.extend([
            ('Image', 'image'),
            ('Tag', 'tag'),
            ('Created At', 'created_at',),
            ('Terminated At', 'terminated_at'),
            ('Status', 'status'),
            ('Occupied Resource', 'occupied_slots'),
            ('Used Memory (MiB)', 'mem_cur_bytes'),
            ('Max Used Memory (MiB)', 'mem_max_bytes'),
            ('CPU Using (%)', 'cpu_using'),
        ])
        if is_legacy_server():
            del fields[2]

    def execute_paginated_query(limit, offset):
        q = '''
        query($limit:Int!, $offset:Int!, $ak:String, $status:String) {
          compute_session_list(
              limit:$limit, offset:$offset, access_key:$ak, status:$status) {
            items { $fields }
            total_count
          }
        }'''
        q = textwrap.dedent(q).strip()
        q = q.replace('$fields', ' '.join(item[1] for item in fields))
        v = {
            'limit': limit,
            'offset': offset,
            'status': status if status != 'ALL' else None,
            'ak': access_key,
        }
        try:
            resp = session.Admin.query(q, v)
        except Exception as e:
            print_error(e)
            sys.exit(1)
        return resp['compute_session_list']

    def round_mem(items):
        for item in items:
            if 'mem_cur_bytes' in item:
                item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1)
            if 'mem_max_bytes' in item:
                item['mem_max_bytes'] = round(item['mem_max_bytes'] / 2 ** 20, 1)
        return items

    def _generate_paginated_results(interval):
        offset = 0
        is_first = True
        total_count = -1
        while True:
            limit = (interval if is_first else
                    min(interval, total_count - offset))
            try:
                result = execute_paginated_query(limit, offset)
            except Exception as e:
                print_error(e)
                sys.exit(1)
            offset += interval
            total_count = result['total_count']
            items = result['items']
            items = round_mem(items)

            if id_only:
                yield '\n'.join([item['sess_id'] for item in items]) + '\n'
            else:
                table = tabulate([item.values() for item in items],
                                    headers=(item[0] for item in fields))
                if not is_first:
                    table_rows = table.split('\n')
                    table = '\n'.join(table_rows[2:])
                yield table + '\n'

            if is_first:
                is_first = False
            if not offset < total_count:
                break

    with Session() as session:
        paginating_interval = 10
        if all:
            click.echo_via_pager(_generate_paginated_results(paginating_interval))
        else:
            result = execute_paginated_query(paginating_interval, offset=0)
            total_count = result['total_count']
            if total_count == 0:
                print('There are no compute sessions currently {0}.'
                      .format(status.lower()))
                return
            items = result['items']
            items = round_mem(items)
            if id_only:
                for item in items:
                    print(item['sess_id'])
            else:
                print(tabulate([item.values() for item in items],
                                headers=(item[0] for item in fields)))
            if total_count > paginating_interval:
                print("More sessions can be displayed by using --all option.")
1215774
def __init_keystone_session_v3(self, check=False):
        
        try:
            # may fail on Python 2.6?
            from keystoneauth1.identity import v3 as keystone_v3
        except ImportError:
            log.warning("Cannot load Keystone API v3 library.")
            return None
        auth = keystone_v3.Password(
            auth_url=self._os_auth_url,
            username=self._os_username,
            password=self._os_password,
            user_domain_name=self._os_user_domain_name,
            project_domain_name=self._os_project_domain_name,
            project_name=self._os_tenant_name,
        )
        sess = keystoneauth1.session.Session(auth=auth, verify=self._os_cacert)
        if check:
            log.debug("Checking that Keystone API v3 session works...")
            try:
                # if session is invalid, the following will raise some exception
                nova = nova_client.Client(self._compute_api_version, session=sess)
                nova.flavors.list()
            except keystoneauth1.exceptions.NotFound as err:
                log.warning("Creating Keystone v3 session failed: %s", err)
                return None
            except keystoneauth1.exceptions.ClientException as err:
                log.error("OpenStack server rejected request (likely configuration error?): %s", err)
                return None  # FIXME: should we be raising an error instead?
        # if we got to this point, v3 session is valid
        log.info("Using Keystone API v3 session to authenticate to OpenStack")
        return sess
1179348
private Session getSession(boolean isSingleton) {
		final MailAccount mailAccount = this.mailAccount;
		Authenticator authenticator = null;
		if (mailAccount.isAuth()) {
			authenticator = new UserPassAuthenticator(mailAccount.getUser(), mailAccount.getPass());
		}

		return isSingleton ? Session.getDefaultInstance(mailAccount.getSmtpProps(), authenticator) //
				: Session.getInstance(mailAccount.getSmtpProps(), authenticator);
	}
203270
def _auth(profile=None, api_version=2, **connection_args):
    '''
    
    '''
    __utils__['versions.warn_until'](
        'Neon',
        (
            'The glance module has been deprecated and will be removed in {version}.  '
            'Please update to using the glanceng module'
        ),
    )

    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 = get('region')
    ks_endpoint = get('endpoint', 'http://127.0.0.1:9292/')
    g_endpoint_url = __salt__['keystone.endpoint_get']('glance', profile)
    # The trailing 'v2' causes URLs like thise one:
    # http://127.0.0.1:9292/v2/v1/images
    g_endpoint_url = re.sub('/v2', '', g_endpoint_url['internalurl'])

    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 Glance API v1')
    elif password:
        # Can't use the admin-token anyway
        kwargs = {'username': user,
                  'password': password,
                  'tenant_id': tenant_id,
                  'auth_url': auth_url,
                  'endpoint_url': g_endpoint_url,
                  'region_name': region,
                  '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,
                  'endpoint_url': g_endpoint_url}
    else:
        raise SaltInvocationError('No credentials to authenticate with.')

    if HAS_KEYSTONE:
        log.debug('Calling keystoneclient.v2_0.client.Client(%s, **%s)',
                  ks_endpoint, kwargs)
        keystone = kstone.Client(**kwargs)
        kwargs['token'] = keystone.get_token(keystone.session)
        # 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')
        log.debug('Calling glanceclient.client.Client(%s, %s, **%s)',
                  api_version, g_endpoint_url, kwargs)
        # may raise exc.HTTPUnauthorized, exc.HTTPNotFound
        # but we deal with those elsewhere
        return client.Client(api_version, g_endpoint_url, **kwargs)
    else:
        raise NotImplementedError(
            "Can't retrieve a auth_token without keystone")
462662
def new_session_callback(fuzzer, edge, resp):
    '''
    
    '''
    fuzzer.logger.info('session is: %s' % hexlify(resp[1:3]).decode())
    fuzzer.target.session_data['session_id'] = resp[1:3]
896800
def get_current_session(request, hproPk):
    """"""

    retour = {}

    base_key = 'plugit_' + str(hproPk) + '_'

    for key, value in request.session.iteritems():
        if key.startswith(base_key):
            retour[key[len(base_key):]] = value

    return retour
364743
def _get_session(self, session):
        

        if not session:
            logger.debug('(SESSION_CREATE) User: %s' % self._user)
            s = requests.Session()
            s.auth = HTTPBasicAuth(self._user, self._password)
        else:
            logger.debug('(SESSION_CREATE) Object: %s' % session)
            s = session

        s.headers.update(
            {
                'content-type': 'application/json',
                'accept': 'application/json',
                'User-Agent': 'pysnow/%s' % pysnow.__version__
            }
        )

        return s
35188
def _auth(profile=None):
    '''
    
    '''
    if profile:
        credentials = __salt__['config.option'](profile)
        user = credentials['keystone.user']
        password = credentials.get('keystone.password', None)
        tenant = credentials['keystone.tenant']
        auth_url = credentials['keystone.auth_url']
        auth_version = credentials.get('keystone.auth_version', 2)
        region_name = credentials.get('keystone.region_name', None)
        api_key = credentials.get('keystone.api_key', None)
        os_auth_system = credentials.get('keystone.os_auth_system', None)
    else:
        user = __salt__['config.option']('keystone.user')
        password = __salt__['config.option']('keystone.password', None)
        tenant = __salt__['config.option']('keystone.tenant')
        auth_url = __salt__['config.option']('keystone.auth_url')
        auth_version = __salt__['config.option']('keystone.auth_version', 2)
        region_name = __salt__['config.option']('keystone.region_name')
        api_key = __salt__['config.option']('keystone.api_key')
        os_auth_system = __salt__['config.option']('keystone.os_auth_system')
    kwargs = {
        'user': user,
        'password': password,
        'key': api_key,
        'tenant_name': tenant,
        'auth_url': auth_url,
        'auth_version': auth_version,
        'region_name': region_name
    }

    return suos.SaltSwift(**kwargs)
878678
def do_get_session(self, session_key):
        
        session_id = session_key.session_id
        msg = ("do_get_session: Attempting to retrieve session with key " +
               str(session_id))
        logger.debug(msg)

        session = self._retrieve_session(session_key)

        if (session is not None):
            self.validate(session, session_key)

        return session
1260900
def get_session(ec=None, create=True):
    
    
    ec = ec or __default_engine__
    if isinstance(ec, (str, unicode)):
        session = engine_manager[ec].session(create=True)
    elif isinstance(ec, Session):
        session = ec
    else:
        raise Error("Connection %r should be existed engine name or Session object" % ec)
    return session
1331792
def defaultSessionFactory(env={}, usePTY=False, *args, **kwargs):
    
    return SSHSession(env, usePTY, *args, **kwargs)
616748
def session(self) -> BaseFileWriterSession:
        ''''''
        return self.session_class(
            self._path_namer,
            self._file_continuing,
            self._headers_included,
            self._local_timestamping,
            self._adjust_extension,
            self._content_disposition,
            self._trust_server_names,
        )
1190148
def get(schema=None, key=None, user=None, **kwargs):
    '''
    

    '''
    _gsession = _GSettings(user=user, schema=schema, key=key)
    return _gsession._get()