Search is not available for this dataset
text
stringlengths
75
104k
async def stoplisten(self, vhost = None): ''' Stop listen on current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers. ''' servers = self.getservers(vhost) for s in serv...
async def startlisten(self, vhost = None): ''' Start listen on current servers :param vhost: return only servers of vhost if specified. '' to return only default servers. None for all servers. ''' servers = self.getservers(vhost) for s in se...
async def updateconfig(self): "Reload configurations, remove non-exist servers, add new servers, and leave others unchanged" exists = {} for s in self.connections: exists[(s.protocol.vhost, s.rawurl)] = s self._createServers(self, '', exists = exists) for _,v in exist...
def getconnections(self, vhost = None): "Return accepted connections, optionally filtered by vhost" if vhost is None: return list(self.managed_connections) else: return [c for c in self.managed_connections if c.protocol.vhost == vhost]
async def _dhcp_handler(self): """ Mini DHCP server, respond DHCP packets from OpenFlow """ conn = self._connection ofdef = self._connection.openflowdef l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost) dhcp_packet_matcher = OpenflowAsyn...
def return_self_updater(func): ''' Run func, but still return v. Useful for using knowledge.update with operates like append, extend, etc. e.g. return_self(lambda k,v: v.append('newobj')) ''' @functools.wraps(func) def decorator(k,v): func(k,v) return v return decorator
def date_time_string(timestamp=None): """Return the current date and time formatted for a message header.""" global _last_date_time_string _last_timestamp, _last_str = _last_date_time_string if timestamp is None: timestamp = time.time() _curr_timestamp = int(timestamp) if _curr_timestamp...
def escape_b(s, quote=True): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated.''' s = s.replace(b"&", b"&amp;") # Must be done first! s = s.replace(b"<", b"&lt;") s = s.replace(b">", b"&...
def watch_context(keys, result, reqid, container, module = 'objectdb'): """ DEPRECATED - use request_context for most use cases """ try: keys = [k for k,r in zip(keys, result) if r is not None] yield result finally: if keys: async def clearup(): tr...
def updater(f): "Decorate a function with named arguments into updater for transact" @functools.wraps(f) def wrapped_updater(keys, values): result = f(*values) return (keys[:len(result)], result) return wrapped_updater
def list_updater(*args): """ Decorate a function with named lists into updater for transact. :params \*args: parameter list sizes. -1 means all other items. None means a single item instead of a list. only one -1 is allowed. """ neg_index = [i for v,i in izip(args, itertools...
def create_new(cls, oldvalue, *args): "Raise if the old value already exists" if oldvalue is not None: raise AlreadyExistsException('%r already exists' % (oldvalue,)) return cls.create_instance(*args)
def create_from_key(cls, oldvalue, key): "Raise if the old value already exists" if oldvalue is not None: raise AlreadyExistsException('%r already exists' % (oldvalue,)) return cls.create_from_key(key)
def dump(obj, attributes = True, _refset = None): "Show full value of a data object" if _refset is None: _refset = set() if obj is None: return None elif isinstance(obj, DataObject): if id(obj) in _refset: attributes = False else: _refset.a...
async def action_handler(self): """ Call vtep controller in sequence, merge mutiple calls if possible When a bind relationship is updated, we always send all logical ports to a logicalswitch, to make sure it recovers from some failed updates (so called idempotency). When multipl...
async def update_ports(self, ports, ovsdb_ports): """ Called from main module to update port information """ new_port_names = dict((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports) new_port_ids = dict((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id']...
def list_proxy(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule, list their default values ''' proxy_dict = OrderedDict() pkg = __import__(root_package, fromlist=['_']) for imp, module, _ in walk_packages(pkg.__path__, root_pack...
def list_modules(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.server.module.Module, list their apis through apidefs ''' pkg = __import__(root_package, fromlist=['_']) module_dict = OrderedDict() _server = Server() for imp, module, _ in walk_packag...
def append(self, event, force = False): ''' Append an event to queue. The events are classified and appended to sub-queues :param event: input event :param force: if True, the event is appended even if the queue is full :returns: None if appended succes...
def block(self, event, emptyEvents = ()): ''' Return a recently popped event to queue, and block all later events until unblock. Only the sub-queue directly containing the event is blocked, so events in other queues may still be processed. It is illegal to call block and unblock...
def unblock(self, event): ''' Remove a block ''' if event not in self.blockEvents: return self.blockEvents[event].unblock(event) del self.blockEvents[event]
def unblockqueue(self, queue): ''' Remove blocked events from the queue and all subqueues. Usually used after queue clear/unblockall to prevent leak. :returns: the cleared events ''' subqueues = set() def allSubqueues(q): subqueues.add(q) ...
def unblockall(self): ''' Remove all blocks from the queue and all sub-queues ''' for q in self.queues.values(): q.unblockall() self.blockEvents.clear()
def notifyAppend(self, queue, force): ''' Internal notify for sub-queues :returns: If the append is blocked by parent, an EventMatcher is returned, None else. ''' if not force and not self.canAppend(): self.isWaited = True return self._matcher ...
def notifyBlock(self, queue, blocked): ''' Internal notify for sub-queues been blocked ''' if blocked: if self.prioritySet[-1] == queue.priority: self.prioritySet.pop() else: pindex = bisect_left(self.prioritySet, queue.priority) ...
def notifyPop(self, queue, length = 1): ''' Internal notify for sub-queues been poped :returns: List of any events generated by this pop ''' self.totalSize = self.totalSize - length ret1 = [] ret2 = [] if self.isWaited and self.canAppend(): ...
def pop(self): ''' Pop an event from the queue. The event in the queue with higher priority is popped before ones in lower priority. If there are multiple queues with the same priority, events are taken in turn from each queue. May return some queueEvents indicating that some of the queu...
def _pop(self): ''' Actual pop ''' if not self.canPop(): raise IndexError('pop from an empty or blocked queue') priority = self.prioritySet[-1] ret = self.queues[priority]._pop() self.outputStat = self.outputStat + 1 self.totalSize = self.total...
def clear(self): ''' Clear all the events in this queue, including any sub-queues. :returns: ((queueEvents,...), (queueEmptyEvents,...)) where queueEvents are QueueCanWriteEvents generated by clearing. ''' l = len(self) ret = self._clear() if self.parent ...
def _clear(self): ''' Actual clear ''' ret = ([],[]) for q in self.queues.values(): pr = q._clear() ret[0].extend(pr[0]) ret[1].extend(pr[1]) self.totalSize = 0 del self.prioritySet[:] if self.isWaited and self.canAppend...
def setPriority(self, queue, priority): ''' Set priority of a sub-queue ''' q = self.queueindex[queue] self.queues[q[0]].removeSubQueue(q[1]) newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority)) q[0] = priority newPriority.add...
def addSubQueue(self, priority, matcher, name = None, maxdefault = None, maxtotal = None, defaultQueueClass = FifoQueue): ''' add a sub queue to current queue, with a priority and a matcher :param priority: priority of this queue. Larger is higher, 0 is lowest. :param m...
def removeSubQueue(self, queue): ''' remove a sub queue from current queue. This unblock the sub-queue, retrieve all events from the queue and put them back to the parent. Call clear on the sub-queue first if the events are not needed any more. :param q...
def ensure_keys(walk, *keys): """ Use walk to try to retrieve all keys """ all_retrieved = True for k in keys: try: walk(k) except WalkKeyNotRetrieved: all_retrieved = False return all_retrieved
def list_config(root_package = 'vlcp'): ''' Walk through all the sub modules, find subclasses of vlcp.config.Configurable, list their available configurations through _default_ prefix ''' pkg = __import__(root_package, fromlist=['_']) return_dict = OrderedDict() for imp, module, _ in walk_pa...
def http(container = None): "wrap a WSGI-style class method to a HTTPRequest event handler" def decorator(func): @functools.wraps(func) def handler(self, event): return _handler(self if container is None else container, event, lambda env: func(self, env)) return handler r...
def statichttp(container = None): "wrap a WSGI-style function to a HTTPRequest event handler" def decorator(func): @functools.wraps(func) def handler(event): return _handler(container, event, func) if hasattr(func, '__self__'): handler.__self__ = func.__self__ ...
def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.status = status self.disabledeflate = di...
def header(self, key, value, replace = True): "Send a new header" if hasattr(key, 'encode'): key = key.encode('ascii') if hasattr(value, 'encode'): value = value.encode(self.encoding) if replace: self.sent_headers = [(k,v) for k,v in self.sent_headers ...
def rawheader(self, kv, replace = True): """ Add a header with "<Header>: Value" string """ if hasattr(kv, 'encode'): kv = kv.encode(self.encoding) k,v = kv.split(b':', 1) self.header(k, v.strip(), replace)
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): """ Add a new cookie """ newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if max_age is not None:...
def bufferoutput(self): """ Buffer the whole output until write EOF or flushed. """ new_stream = Stream(writebufferlimit=None) if self._sendHeaders: # An extra copy self.container.subroutine(new_stream.copy_to(self.outputstream, self.container, buffering=F...
async def rewrite(self, path, method = None, keepresponse = True): "Rewrite this request to another processor. Must be called before header sent" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') if getattr(self.event, 'rewritedepth', 0...
async def redirect(self, path, status = 302): """ Redirect this request with 3xx status """ location = urljoin(urlunsplit((b'https' if self.https else b'http', self.host, ...
def nl2br(self, text): """ Replace \'\n\' with \'<br/>\\n\' """ if isinstance(text, bytes): return text.replace(b'\n', b'<br/>\n') else: return text.replace('\n', '<br/>\n')
def escape(self, text, quote = True): """ Escape special characters in HTML """ if isinstance(text, bytes): return escape_b(text, quote) else: return escape(text, quote)
async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []): """ Show default error response """ if showerror is None: showerror = self.showerrorinfo if self._sendHeaders: if showerror: typ, exc, tb...
async def write(self, data, eof = False, buffering = True): """ Write output to current output stream """ if not self.outputstream: self.outputstream = Stream() self._startResponse() elif (not buffering or eof) and not self._sendHeaders: self._...
async def writelines(self, lines, eof = False, buffering = True): """ Write lines to current output stream """ for l in lines: await self.write(l, False, buffering) if eof: await self.write(b'', eof, buffering)
def output(self, stream, disabletransferencoding = None): """ Set output stream and send response immediately """ if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.outputstream = stream try: cont...
def outputdata(self, data): """ Send output with fixed length data """ if not isinstance(data, bytes): data = str(data).encode(self.encoding) self.output(MemoryStream(data))
async def close(self): """ Close this request, send all data. You can still run other operations in the handler. """ if not self._sendHeaders: self._startResponse() if self.inputstream is not None: self.inputstream.close(self.connection.scheduler) ...
async def parseform(self, limit = 67108864, tostr = True, safename = True): ''' Parse form-data with multipart/form-data or application/x-www-form-urlencoded In Python3, the keys of form and files are unicode, but values are bytes If the key ends with '[]', it is considered to be a list:...
async def sessionstart(self): "Start session. Must start service.utils.session.Session to use this method" if not hasattr(self, 'session') or not self.session: self.session, setcookies = await call_api(self.container, 'session', 'start', {'cookies':self.rawcookie}) for nc in setc...
async def sessiondestroy(self): """ Destroy current session. The session object is discarded and can no longer be used in other requests. """ if hasattr(self, 'session') and self.session: setcookies = await call_api(self.container, 'session', 'destroy', {'sessionid':self.sess...
def basicauth(self, realm = b'all', nofail = False): "Try to get the basic authorize info, return (username, password) if succeeded, return 401 otherwise" if b'authorization' in self.headerdict: auth = self.headerdict[b'authorization'] auth_pair = auth.split(b' ', 1) ...
def basicauthfail(self, realm = b'all'): """ Return 401 for authentication failure. This will end the handler. """ if not isinstance(realm, bytes): realm = realm.encode('ascii') self.start_response(401, [(b'WWW-Authenticate', b'Basic realm="' + realm + b'"')]) ...
def getrealpath(self, root, path): ''' Return the real path on disk from the query path, from a root path. The input path from URL might be absolute '/abc', or point to parent '../test', or even with UNC or drive '\\test\abc', 'c:\test.abc', which creates security issues when acc...
def argstostr(self): "Query string arguments are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)." self.args = dict((k, self._tostr(v)) for k,v in self.args.items()) return self.args
def cookietostr(self): "Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)." self.cookies = dict((k, (v.decode(self.encoding) if not isinstance(v, str) else v)) for k,v in self.cookies.items()) return self.cookies
async def createcsrf(self, csrfarg = '_csrf'): """ Create a anti-CSRF token in the session """ await self.sessionstart() if not csrfarg in self.session.vars: self.session.vars[csrfarg] = uuid.uuid4().hex
def outputjson(self, obj): """ Serialize `obj` with JSON and output to the client """ self.header('Content-Type', 'application/json') self.outputdata(json.dumps(obj).encode('ascii'))
def routeevent(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']): ''' Route specified path to a routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routinemetho...
def route(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']): ''' Route specified path to a WSGI-styled routine factory :param path: path to match, can be a regular expression :param routinemethod: factory function routi...
def routeargs(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'POST'], tostr = True, matchargs = (), fileargs=(), queryargs=(), cookieargs=(), sessionargs=(), csrfcheck = False, csrfarg = '_csrf', formlimit = 67108864): ''' Convenien...
def expand(cls, match, expand): """ If use expand directly, the url-decoded context will be decoded again, which create a security issue. Hack expand to quote the text before expanding """ return re._expand(match.re, cls._EncodedMatch(match), expand)
def rewrite(self, path, expand, newmethod = None, host = None, vhost = None, method = [b'GET', b'HEAD'], keepquery = True): "Automatically rewrite a request to another location" async def func(env): newpath = self.expand(env.path_match, expand) if keepquery and getattr(env, 'quer...
def routeargs(path, host = None, vhost = None, method = [b'POST'], **kwargs): "For extra arguments, see Dispatcher.routeargs. They must be specified by keyword arguments" def decorator(func): func.routemode = 'routeargs' func.route_path = path func.route_host = host ...
def _close_generator(g): """ PyPy 3 generator has a bug that calling `close` caused memory leak. Before it is fixed, use `throw` instead """ if isinstance(g, generatorwrapper): g.close() elif _get_frame(g) is not None: try: g.throw(GeneratorExit_) except (Stop...
def Routine(coroutine, scheduler, asyncStart = True, container = None, manualStart = False, daemon = False): """ This wraps a normal coroutine to become a VLCP routine. Usually you do not need to call this yourself; `container.start` and `container.subroutine` calls this automatically. """ def run()...
def registerHandler(self, matcher, handler): ''' Register self to scheduler ''' self.handlers[matcher] = handler self.scheduler.register((matcher,), self) self._setDaemon()
def registerAllHandlers(self, handlerDict): ''' Register self to scheduler ''' self.handlers.update(handlerDict) if hasattr(handlerDict, 'keys'): self.scheduler.register(handlerDict.keys(), self) else: self.scheduler.register(tuple(h[0] for h in ha...
def start(self, asyncStart = False): """ Start `container.main` as the main routine. :param asyncStart: if True, start the routine in background. By default, the routine starts in foreground, which means it is executed to the first `...
def subroutine(self, iterator, asyncStart = True, name = None, daemon = False): """ Start extra routines in this container. :param iterator: A coroutine object i.e the return value of an async method `my_routine()` :param asyncStart: if False, start the routine in foreg...
async def wait_for_send(self, event, *, until=None): ''' Send an event to the main event queue. Can call without delegate. :param until: if the callback returns True, stop sending and return :return: the last True value the callback returns, or None ''' ...
async def wait_with_timeout(self, timeout, *matchers): """ Wait for multiple event matchers, or until timeout. :param timeout: a timeout value :param \*matchers: event matchers :return: (is_timeout, event, matcher). When is_timeout = True, event = match...
async def execute_with_timeout(self, timeout, subprocess): """ Execute a subprocess with timeout. If time limit exceeds, the subprocess is terminated, and `is_timeout` is set to True; otherwise the `is_timeout` is set to False. You can uses `execute_with_timeout` with other help...
async def with_exception(self, subprocess, *matchers): """ Monitoring event matchers while executing a subprocess. If events are matched before the subprocess ends, the subprocess is terminated and a RoutineException is raised. """ def _callback(event, matcher): raise...
def with_callback(self, subprocess, callback, *matchers, intercept_callback = None): """ Monitoring event matchers while executing a subprocess. `callback(event, matcher)` is called each time an event is matched by any event matchers. If the callback raises an exception, the subprocess is termin...
async def wait_for_all(self, *matchers, eventlist = None, eventdict = None, callback = None): """ Wait until each matcher matches an event. When this coroutine method returns, `eventlist` is set to the list of events in the arriving order (may not be the same as the matchers); `eventdict...
async def wait_for_all_to_process(self, *matchers, eventlist = None, eventdict = None, callback = None): """ Similar to `waitForAll`, but set `canignore=True` for these events. This ensures blocking events are processed correctly. """ d...
async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers """ matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None] while matcher...
def syscall_noreturn(self, func): ''' Call a syscall method. A syscall method is executed outside of any routines, directly in the scheduler loop, which gives it chances to directly operate the event loop. See :py:method::`vlcp.event.core.Scheduler.syscall`. ''' matcher =...
async def syscall(self, func, ignoreException = False): """ Call a syscall method and retrieve its return value """ ev = await self.syscall_noreturn(func) if hasattr(ev, 'exception'): if ignoreException: return else: raise e...
async def delegate(self, subprocess, forceclose = False): ''' Run a subprocess without container support Many subprocess assume itself running in a specified container, it uses container reference like self.events. Calling the subprocess in other containers will fail. ...
async def end_delegate(self, delegate_matcher, routine = None, forceclose = False): """ Retrieve a begin_delegate result. Must be called immediately after begin_delegate before any other `await`, or the result might be lost. Do not use this method without thinking. Always use `R...
def begin_delegate(self, subprocess): ''' Start the delegate routine, but do not wait for result, instead returns a (matcher, routine) tuple. Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time). This is NOT a coroutine method. WARNING: th...
def begin_delegate_other(self, subprocess, container, retnames = ('',)): ''' DEPRECATED Start the delegate routine, but do not wait for result, instead returns a (matcher routine) tuple. Useful for advanced delegates (e.g. delegate multiple subprocesses in the same time). This is NOT a c...
async def delegate_other(self, subprocess, container, retnames = ('',), forceclose = False): ''' DEPRECATED Another format of delegate allows delegate a subprocess in another container, and get some returning values the subprocess is actually running in 'container'. :: ret =...
async def execute_all_with_names(self, subprocesses, container = None, retnames = ('',), forceclose = True): ''' DEPRECATED Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param container: if specified, run ...
async def execute_all(self, subprocesses, forceclose=True): ''' Execute all subprocesses and get the return values. :param subprocesses: sequence of subroutines (coroutines) :param forceclose: force close the routines on exit, so all the subprocesses are terminated ...
def get_container(cls, scheduler): """ Create temporary instance for helper functions """ if scheduler in cls._container_cache: return cls._container_cache[scheduler] else: c = cls(scheduler) cls._container_cache[scheduler] = c retu...
def depend(*args): """ Decorator to declare dependencies to other modules. Recommended usage is:: import other_module @depend(other_module.ModuleClass) class MyModule(Module): ... :param \*args: depended module classes. """ def decfunc(cls): ...
def api(func, container = None, criteria = None): ''' Return an API def for a generic function :param func: a function or bounded method :param container: if None, this is used as a synchronous method, the return value of the method is used for the return value. If not No...
def proxy(name, default = None): """ Create a proxy module. A proxy module has a default implementation, but can be redirected to other implementations with configurations. Other modules can depend on proxy modules. """ proxymodule = _ProxyMetaClass(name, (_ProxyModule,), {'_default': default}) ...
async def send_api(container, targetname, name, params = {}): """ Send API and discard the result """ handle = object() apiEvent = ModuleAPICall(handle, targetname, name, params = params) await container.wait_for_send(apiEvent)
async def call_api(container, targetname, name, params = {}, timeout = 120.0): """ Call module API `targetname/name` with parameters. :param targetname: module targetname. Usually the lower-cased name of the module class, or 'public' for public APIs. :param name: method ...
async def batch_call_api(container, apis, timeout = 120.0): """ DEPRECATED - use execute_all instead """ apiHandles = [(object(), api) for api in apis] apiEvents = [ModuleAPICall(handle, targetname, name, params = params) for handle, (targetname, name, params) in apiHandles] api...
def registerAPIs(self, apidefs): ''' API definition is in format: `(name, handler, container, discoverinfo)` if the handler is a generator, container should be specified handler should accept two arguments:: def handler(name, params): ... ...
def registerAPI(self, name, handler, container = None, discoverinfo = None, criteria = None): """ Append new API to this handler """ self.handler.registerHandler(*self._createHandler(name, handler, container, criteria)) if discoverinfo is None: self.discoverinfo[name]...