Pull a Low State data structure from request and execute the low-data
        chunks through Salt. The low-data chunks will be updated to include the
        authorization token for the current session.
482575
def exec_lowstate(self, client=None, token=None):
        '''
        
        '''
        lowstate = cherrypy.request.lowstate

        # Release the session lock before executing any potentially
        # long-running Salt commands. This allows different threads to execute
        # Salt commands concurrently without blocking.
        if cherrypy.request.config.get('tools.sessions.on', False):
            cherrypy.session.release_lock()

        # if the lowstate loaded isn't a list, lets notify the client
        if not isinstance(lowstate, list):
            raise cherrypy.HTTPError(400, 'Lowstates must be a list')

        # Make any requested additions or modifications to each lowstate, then
        # execute each one and yield the result.
        for chunk in lowstate:
            if token:
                chunk['token'] = token

            if 'token' in chunk:
                # Make sure that auth token is hex
                try:
                    int(chunk['token'], 16)
                except (TypeError, ValueError):
                    raise cherrypy.HTTPError(401, 'Invalid token')

            if 'token' in chunk:
                # Make sure that auth token is hex
                try:
                    int(chunk['token'], 16)
                except (TypeError, ValueError):
                    raise cherrypy.HTTPError(401, 'Invalid token')

            if client:
                chunk['client'] = client

            # Make any 'arg' params a list if not already.
            # This is largely to fix a deficiency in the urlencoded format.
            if 'arg' in chunk and not isinstance(chunk['arg'], list):
                chunk['arg'] = [chunk['arg']]

            ret = self.api.run(chunk)

            # Sometimes Salt gives us a return and sometimes an iterator
            if isinstance(ret, collections.Iterator):
                for i in ret:
                    yield i
            else:
                yield ret
1332475
def clean_expired_tokens(opts):
    '''
    
    '''
    loadauth = salt.auth.LoadAuth(opts)
    for tok in loadauth.list_tokens():
        token_data = loadauth.get_tok(tok)
        if 'expire' not in token_data or token_data.get('expire', 0) < time.time():
            loadauth.rm_token(tok)
948338
def process_request(self, request):
        
        request.token = get_token(request)
        request.user = SimpleLazyObject(lambda: get_user(request))
        request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request)
895186
def run(self):
        
        states = open(self.states, 'r').read().splitlines()
        for state in states:
            url = self.build_url(state)
            log = "Downloading State < {0} > from < {1} >"
            logging.info(log.format(state, url))
            tmp = self.download(self.output, url, self.overwrite)
            self.s3.store(self.extract(tmp, self.tmp2poi(tmp)))
204127
def show_lowstate(**kwargs):
    '''
    
    '''
    __opts__['grains'] = __grains__
    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
    st_ = salt.client.ssh.state.SSHHighState(
            opts,
            __pillar__,
            __salt__,
            __context__['fileclient'])
    st_.push_active()
    chunks = st_.compile_low_chunks()
    _cleanup_slsmod_low_data(chunks)
    return chunks
807380
def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):
        
        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body
788381
def execute(query, data=None):
    
    connection = _State.connection()
    _State.new_transaction()

    if data is None:
        data = []

    result = connection.execute(query, data)

    _State.table = None
    _State.metadata = None
    try:
        del _State.table_pending
    except AttributeError:
        pass

    if not result.returns_rows:
        return {u'data': [], u'keys': []}

    return {u'data': result.fetchall(), u'keys': list(result.keys())}
727855
async function loadSession(req, getJWT) {
	const headerKey = this.jwt.headerKey.toLowerCase()

	// Get token
	let token
	if (typeof getJWT === 'function') {
		token = getJWT(req)
	} else if (req.headers && req.headers[headerKey]) {
		const parts = req.headers[headerKey].split(' ')
		if (parts.length === 2 && /^Bearer$/i.test(parts[0])) {
			token = parts[1]
		} else {
			throw new HttpError('credentials-bad-schema', 401, { message: `Format is ${headerKey}: Bearer [token]` })
		}
	}
	token = sanitizeToken(token)

	// if no token, answer directly
	if (!token) {
		throw new HttpError('credentials-required', 401)
	}

	// Verify token
	let session
	try {
		session = await cb(jsonwebtoken.verify, token, this.jwt.secret)
	} catch (err) {
		throw new HttpError('invalid-token', 401)
	}

	// Verify session.userId
	if (!session.userId) {
		throw new HttpError('session-has-no-userId', 401)
	}

	// Add session to req.session
	req.session = session
}
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
660058
def _request(method, url, content_type=None, _data=None, user=None, passwd=None):
    '''
    
    '''
    opener = _build_opener(_HTTPHandler)
    request = _Request(url, data=_data)
    if content_type:
        request.add_header('Content-Type', content_type)
    if user and passwd:
        auth_encode = '{0}:{1}'.format(user, passwd).encode('base64')[:-1]
        auth_basic = "Basic {0}".format(auth_encode)
        request.add_header('Authorization', auth_basic)
        request.add_header('Accept', 'application/json')
    request.get_method = lambda: method
    try:
        handler = opener.open(request)
    except HTTPError as exc:
        return {'error': '{0}'.format(exc)}
    return salt.utils.json.loads(handler.read())
532584
def show_highstate(**kwargs):
    '''
    
    '''
    __opts__['grains'] = __grains__
    opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
    st_ = salt.client.ssh.state.SSHHighState(
            opts,
            __pillar__,
            __salt__,
            __context__['fileclient'])
    st_.push_active()
    chunks = st_.compile_highstate()
    _cleanup_slsmod_high_data(chunks)
    return chunks
1151707
def do_update(pool,request,models):
  ""
  return {k:fkapply(models,pool,process_update,missing_update,k,v) for k,v in request.items()}
1045281
def run(self):
        '''
        
        '''
        if self.opts['chunked']:
            ret = self.run_chunked()
        else:
            ret = self.run_oldstyle()

        salt.output.display_output(
                ret,
                self.opts.get('output', 'nested'),
                self.opts)
134162
def proccess_lowstates(**kwargs):
    '''
    
    '''
    states = []
    config = _get_config(**kwargs)
    proccesser = config.get('proccesser')
    ls = __salt__['state.show_lowstate']()

    if not isinstance(ls, list):
        raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***')
    else:
        if ls:
            if not isinstance(ls[0], dict):
                raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***')

    for s in ls:
        if _blacklist_filter(s, config):
            continue
        doc = __salt__[proccesser](s, config, **kwargs)
        states.append(doc)
    return states
1294444
def call(self, low, chunks=None, running=None, retries=1):
        '''
        
        '''
        use_uptime = False
        if os.path.isfile('/proc/uptime'):
            use_uptime = True
            with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
                start_uptime = float(fp_.readline().split()[0])
        utc_start_time = datetime.datetime.utcnow()
        local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
        log.info('Running state [%s] at time %s',
            low['name'].strip() if isinstance(low['name'], six.string_types)
                else low['name'],
            local_start_time.time().isoformat()
        )
        errors = self.verify_data(low)
        if errors:
            ret = {
                'result': False,
                'name': low['name'],
                'changes': {},
                'comment': '',
                }
            for err in errors:
                ret['comment'] += '{0}\n'.format(err)
            ret['__run_num__'] = self.__run_num
            self.__run_num += 1
            format_log(ret)
            self.check_refresh(low, ret)
            return ret
        else:
            ret = {'result': False, 'name': low['name'], 'changes': {}}

        self.state_con['runas'] = low.get('runas', None)

        if low['state'] == 'cmd' and 'password' in low:
            self.state_con['runas_password'] = low['password']
        else:
            self.state_con['runas_password'] = low.get('runas_password', None)

        if not low.get('__prereq__'):
            log.info(
                'Executing state %s.%s for [%s]',
                low['state'],
                low['fun'],
                low['name'].strip() if isinstance(low['name'], six.string_types)
                    else low['name']
            )

        if 'provider' in low:
            self.load_modules(low)

        state_func_name = '{0[state]}.{0[fun]}'.format(low)
        cdata = salt.utils.args.format_call(
            self.states[state_func_name],
            low,
            initial_ret={'full': state_func_name},
            expected_extra_kws=STATE_INTERNAL_KEYWORDS
        )
        inject_globals = {
            # Pass a copy of the running dictionary, the low state chunks and
            # the current state dictionaries.
            # We pass deep copies here because we don't want any misbehaving
            # state module to change these at runtime.
            '__low__': immutabletypes.freeze(low),
            '__running__': immutabletypes.freeze(running) if running else {},
            '__instance_id__': self.instance_id,
            '__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
        }

        if '__env__' in low:
            inject_globals['__env__'] = six.text_type(low['__env__'])

        if self.inject_globals:
            inject_globals.update(self.inject_globals)

        if low.get('__prereq__'):
            test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
            sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
        try:
            # Let's get a reference to the salt environment to use within this
            # state call.
            #
            # If the state function accepts an 'env' keyword argument, it
            # allows the state to be overridden(we look for that in cdata). If
            # that's not found in cdata, we look for what we're being passed in
            # the original data, namely, the special dunder __env__. If that's
            # not found we default to 'base'
            if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
                    ('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
                ret.update(self._run_check(low))

            if not self.opts.get('lock_saltenv', False):
                # NOTE: Overriding the saltenv when lock_saltenv is blocked in
                # salt/modules/state.py, before we ever get here, but this
                # additional check keeps use of the State class outside of the
                # salt/modules/state.py from getting around this setting.
                if 'saltenv' in low:
                    inject_globals['__env__'] = six.text_type(low['saltenv'])
                elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
                    # User is using a deprecated env setting which was parsed by
                    # format_call.
                    # We check for a string type since module functions which
                    # allow setting the OS environ also make use of the "env"
                    # keyword argument, which is not a string
                    inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])

            if '__env__' not in inject_globals:
                # Let's use the default environment
                inject_globals['__env__'] = 'base'

            if '__orchestration_jid__' in low:
                inject_globals['__orchestration_jid__'] = \
                    low['__orchestration_jid__']

            if 'result' not in ret or ret['result'] is False:
                self.states.inject_globals = inject_globals
                if self.mocked:
                    ret = mock_ret(cdata)
                else:
                    # Execute the state function
                    if not low.get('__prereq__') and low.get('parallel'):
                        # run the state call in parallel, but only if not in a prereq
                        ret = self.call_parallel(cdata, low)
                    else:
                        self.format_slots(cdata)
                        if cdata['full'].split('.')[-1] == '__call__':
                            # __call__ requires OrderedDict to preserve state order
                            # kwargs are also invalid overall
                            ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
                        else:
                            ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
                self.states.inject_globals = {}
            if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
                ret.update(self._run_check_cmd(low))
        except Exception as exc:
            log.debug('An exception occurred in this state: %s', exc,
                      exc_info_on_loglevel=logging.DEBUG)
            trb = traceback.format_exc()
            # There are a number of possibilities to not have the cdata
            # populated with what we might have expected, so just be smart
            # enough to not raise another KeyError as the name is easily
            # guessable and fallback in all cases to present the real
            # exception to the user
            name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
            if not name:
                name = low.get('name', low.get('__id__'))

            ret = {
                'result': False,
                'name': name,
                'changes': {},
                'comment': 'An exception occurred in this state: {0}'.format(trb)
            }
        finally:
            if low.get('__prereq__'):
                sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test

            self.state_con.pop('runas', None)
            self.state_con.pop('runas_password', None)

        if not isinstance(ret, dict):
            return ret

        # If format_call got any warnings, let's show them to the user
        if 'warnings' in cdata:
            ret.setdefault('warnings', []).extend(cdata['warnings'])

        if 'provider' in low:
            self.load_modules()

        if low.get('__prereq__'):
            low['__prereq__'] = False
            return ret

        ret['__sls__'] = low.get('__sls__')
        ret['__run_num__'] = self.__run_num
        self.__run_num += 1
        format_log(ret)
        self.check_refresh(low, ret)
        if use_uptime:
            with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
                finish_uptime = float(fp_.readline().split()[0])
        utc_finish_time = datetime.datetime.utcnow()
        timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
        local_finish_time = utc_finish_time - timezone_delta
        local_start_time = utc_start_time - timezone_delta
        ret['start_time'] = local_start_time.time().isoformat()
        if use_uptime:
            duration = (finish_uptime - start_uptime) * 1000.0
        else:
            delta = (utc_finish_time - utc_start_time)
            # duration in milliseconds.microseconds
            duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
        ret['duration'] = duration
        ret['__id__'] = low['__id__']
        log.info(
            'Completed state [%s] at time %s (duration_in_ms=%s)',
            low['name'].strip() if isinstance(low['name'], six.string_types)
                else low['name'],
            local_finish_time.time().isoformat(),
            duration
        )
        if 'retry' in low:
            low['retry'] = self.verify_retry_data(low['retry'])
            if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
                if low['retry']['until'] != ret['result']:
                    if low['retry']['attempts'] > retries:
                        interval = low['retry']['interval']
                        if low['retry']['splay'] != 0:
                            interval = interval + random.randint(0, low['retry']['splay'])
                        log.info(
                            'State result does not match retry until value, '
                            'state will be re-run in %s seconds', interval
                        )
                        self.functions['test.sleep'](interval)
                        retry_ret = self.call(low, chunks, running, retries=retries+1)
                        orig_ret = ret
                        ret = retry_ret
                        ret['comment'] = '\n'.join(
                                [(
                                     'Attempt {0}: Returned a result of "{1}", '
                                     'with the following comment: "{2}"'.format(
                                         retries,
                                         orig_ret['result'],
                                         orig_ret['comment'])
                                 ),
                                 '' if not ret['comment'] else ret['comment']])
                        ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
                        if retries == 1:
                            ret['start_time'] = orig_ret['start_time']
            else:
                ret['comment'] = '  '.join(
                        ['' if not ret['comment'] else ret['comment'],
                         ('The state would be retried every {1} seconds '
                          '(with a splay of up to {3} seconds) '
                          'a maximum of {0} times or until a result of {2} '
                          'is returned').format(low['retry']['attempts'],
                                                low['retry']['interval'],
                                                low['retry']['until'],
                                                low['retry']['splay'])])
        return ret
552070
def _load_states(self):
        '''
        
        '''
        if self.states_loader == 'thorium':
            self.states = salt.loader.thorium(self.opts, self.functions, {})  # TODO: Add runners, proxy?
        else:
            self.states = salt.loader.states(self.opts, self.functions, self.utils,
                                             self.serializers, context=self.state_con, proxy=self.proxy)
57856
async def update(self):
        ''''''
        if self.client.session.closed:
            async with core.Client() as client:
                data = await client.request(self.url)
        else:
            data = await self.client.request(self.url)

        self.raw_data = data
        self.from_data(data)

        return self