code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if logger is None: logger = _output._DEFAULT_LOGGER logged_dict = self._freeze(action=action) logger.write(logged_dict, self._serializer)
def write(self, logger=None, action=None)
Write the message to the given logger. This will additionally include a timestamp, the action context if any, and any other fields. Byte field names will be converted to Unicode. @type logger: L{eliot.ILogger} or C{None} indicating the default one. @param action: The L{Action...
10.724088
12.845403
0.834858
return self._logged_dict.discard(TIMESTAMP_FIELD).discard( TASK_UUID_FIELD ).discard(TASK_LEVEL_FIELD)
def contents(self)
A C{PMap}, the message contents without Eliot metadata.
25.814898
17.500523
1.475093
# 1. Create top-level Eliot Action: with start_action(action_type="dask:compute"): # In order to reduce logging verbosity, add logging to the already # optimized graph: optimized = optimize(*args, optimizations=[_add_logging]) return compute(*optimized, optimize_graph=False)
def compute_with_trace(*args)
Do Dask compute(), but with added Eliot tracing. Dask is a graph of tasks, but Eliot logs trees. So we need to emulate a graph using a tree. We do this by making Eliot action for each task, but having it list the tasks it depends on. We use the following algorithm: 1. Create a top-level act...
19.325293
16.998943
1.136853
ctx = current_action() result = {} # Use topological sort to ensure Eliot actions are in logical order of # execution in Dask: keys = toposort(dsk) # Give each key a string name. Some keys are just aliases to other # keys, so make sure we have underlying key available. Later on might ...
def _add_logging(dsk, ignore=None)
Add logging to a Dask graph. @param dsk: The Dask graph. @return: New Dask graph.
4.801069
4.915076
0.976805
task = self if ( node.end_message and node.start_message and (len(node.children) == node.end_message.task_level.level[-1] - 2)): # Possibly this action is complete, make sure all sub-actions # are complete: completed = True ...
def _insert_action(self, node)
Add a L{WrittenAction} to the tree. Parent actions will be created as necessary. @param child: A L{WrittenAction} to add to the tree. @return: Updated L{Task}.
6.933105
6.655313
1.04174
task_level = child.task_level if task_level.parent() is None: return self parent = self._nodes.get(task_level.parent()) if parent is None: parent = WrittenAction( task_level=task_level.parent(), task_uuid=child.task_uuid) parent =...
def _ensure_node_parents(self, child)
Ensure the node (WrittenAction/WrittenMessage) is referenced by parent nodes. Parent actions will be created as necessary. @param child: A L{WrittenMessage} or L{WrittenAction} which is being added to the tree. @return: Updated L{Task}.
5.113942
4.228316
1.209451
is_action = message_dict.get(ACTION_TYPE_FIELD) is not None written_message = WrittenMessage.from_dict(message_dict) if is_action: action_level = written_message.task_level.parent() action = self._nodes.get(action_level) if action is None: ...
def add(self, message_dict)
Update the L{Task} with a dictionary containing a serialized Eliot message. @param message_dict: Dictionary whose task UUID matches this one. @return: Updated L{Task}.
5.654791
5.67719
0.996055
uuid = message_dict[TASK_UUID_FIELD] if uuid in self._tasks: task = self._tasks[uuid] else: task = Task() task = task.add(message_dict) if task.is_complete(): parser = self.transform(["_tasks", uuid], discard) return [task]...
def add(self, message_dict)
Update the L{Parser} with a dictionary containing a serialized Eliot message. @param message_dict: Dictionary of serialized Eliot message. @return: Tuple of (list of completed L{Task} instances, updated L{Parser}).
5.221684
4.542236
1.149584
parser = Parser() for message_dict in iterable: completed, parser = parser.add(message_dict) for task in completed: yield task for task in parser.incomplete_tasks(): yield task
def parse_stream(cls, iterable)
Parse a stream of messages into a stream of L{Task} instances. :param iterable: An iterable of serialized Eliot message dictionaries. :return: An iterable of parsed L{Task} instances. Remaining incomplete L{Task} will be returned when the input stream is exhausted.
6.955818
6.859456
1.014048
@wraps(original) def wrapper(*a, **kw): # Keep track of whether the next value to deliver to the generator is # a non-exception or an exception. ok = True # Keep track of the next value to deliver to the generator. value_in = None # Create the generator wit...
def eliot_friendly_generator_function(original)
Decorate a generator function so that the Eliot action context is preserved across ``yield`` expressions.
10.089929
9.88744
1.020479
previous_generator = self._current_generator try: self._current_generator = generator yield finally: self._current_generator = previous_generator
def in_generator(self, generator)
Context manager: set the given generator as the current generator.
2.985222
2.208507
1.351692
# The function uses printf formatting, so we need to quote # percentages. fields = [ _ffi.new( "char[]", key.encode("ascii") + b'=' + value.replace(b"%", b"%%")) for key, value in kwargs.items()] fields.append(_ffi.NULL) result = _journald.sd_journal_send(*fields) ...
def sd_journal_send(**kwargs)
Send a message to the journald log. @param kwargs: Mapping between field names to values, both as bytes. @raise IOError: If the operation failed.
6.624836
6.118663
1.082726
f = eliot_friendly_generator_function(original) if debug: f.debug = True return inlineCallbacks(f)
def inline_callbacks(original, debug=False)
Decorate a function like ``inlineCallbacks`` would but in a more Eliot-friendly way. Use it just like ``inlineCallbacks`` but where you want Eliot action contexts to Do The Right Thing inside the decorated function.
9.184617
9.065399
1.013151
if self._finishAdded: raise AlreadyFinished() if errback is None: errback = _passthrough def callbackWithContext(*args, **kwargs): return self._action.run(callback, *args, **kwargs) def errbackWithContext(*args, **kwargs): retur...
def addCallbacks( self, callback, errback=None, callbackArgs=None, callbackKeywords=None, errbackArgs=None, errbackKeywords=None )
Add a pair of callbacks that will be run in the context of an eliot action. @return: C{self} @rtype: L{DeferredContext} @raises AlreadyFinished: L{DeferredContext.addActionFinish} has been called. This indicates a programmer error.
3.02251
2.679873
1.127856
return self.addCallbacks( callback, _passthrough, callbackArgs=args, callbackKeywords=kw)
def addCallback(self, callback, *args, **kw)
Add a success callback that will be run in the context of an eliot action. @return: C{self} @rtype: L{DeferredContext} @raises AlreadyFinished: L{DeferredContext.addActionFinish} has been called. This indicates a programmer error.
11.948473
14.993332
0.796919
return self.addCallbacks( _passthrough, errback, errbackArgs=args, errbackKeywords=kw)
def addErrback(self, errback, *args, **kw)
Add a failure callback that will be run in the context of an eliot action. @return: C{self} @rtype: L{DeferredContext} @raises AlreadyFinished: L{DeferredContext.addActionFinish} has been called. This indicates a programmer error.
7.453278
11.489022
0.64873
return self.addCallbacks(callback, callback, args, kw, args, kw)
def addBoth(self, callback, *args, **kw)
Add a single callback as both success and failure callbacks. @return: C{self} @rtype: L{DeferredContext} @raises AlreadyFinished: L{DeferredContext.addActionFinish} has been called. This indicates a programmer error.
10.49527
16.065908
0.653263
if self._finishAdded: raise AlreadyFinished() self._finishAdded = True def done(result): if isinstance(result, Failure): exception = result.value else: exception = None self._action.finish(exception) ...
def addActionFinish(self)
Indicates all callbacks that should run within the action's context have been added, and that the action should therefore finish once those callbacks have fired. @return: The wrapped L{Deferred}. @raises AlreadyFinished: L{DeferredContext.addActionFinish} has been called pr...
4.45383
3.348752
1.329997
if isinstance(s, bytes): s = s.decode("utf-8") return pyjson.loads(s)
def _loads(s)
Support decoding bytes.
3.383763
3.140387
1.077499
class WithBytes(cls): def default(self, o): if isinstance(o, bytes): warnings.warn( "Eliot will soon stop supporting encoding bytes in JSON" " on Python 3", DeprecationWarning ) return o.decod...
def _dumps(obj, cls=pyjson.JSONEncoder)
Encode to bytes, and presume bytes in inputs are UTF-8 encoded strings.
4.830066
4.230116
1.141828
module = ModuleType(name) if PY3: import importlib.util spec = importlib.util.find_spec(original_module.__name__) source = spec.loader.get_code(original_module.__name__) else: if getattr(sys, "frozen", False): raise NotImplementedError("Can't load modules on ...
def load_module(name, original_module)
Load a copy of a module, distinct from what you'd get if you imported it directly. @param str name: The name of the new module. @param original_module: The original module we're recreating. @return: A new, distinct module.
2.492134
2.748242
0.90681
msg = TRACEBACK_MESSAGE( reason=exception, traceback=traceback, exception=typ) msg = msg.bind( **_error_extraction.get_fields_for_exception(logger, exception)) msg.write(logger)
def _writeTracebackMessage(logger, typ, exception, traceback)
Write a traceback to the log. @param typ: The class of the exception. @param exception: The L{Exception} instance. @param traceback: The traceback, a C{str}.
11.636283
15.795986
0.736661
try: module = load_module(str("_traceback_no_io"), traceback) except NotImplementedError: # Can't fix the I/O problem, oh well: return traceback class FakeLineCache(object): def checkcache(self, *args, **kwargs): None def getline(self, *args, **kwar...
def _get_traceback_no_io()
Return a version of L{traceback} that doesn't do I/O.
5.789858
5.162529
1.121516
if exc_info is None: exc_info = sys.exc_info() typ, exception, tb = exc_info traceback = "".join(_traceback_no_io.format_exception(typ, exception, tb)) _writeTracebackMessage(logger, typ, exception, traceback)
def write_traceback(logger=None, exc_info=None)
Write the latest traceback to the log. This should be used inside an C{except} block. For example: try: dostuff() except: write_traceback(logger) Or you can pass the result of C{sys.exc_info()} to the C{exc_info} parameter.
4.520791
5.138185
0.879842
# Failure.getBriefTraceback does not include source code, so does not do # I/O. _writeTracebackMessage( logger, failure.value.__class__, failure.value, failure.getBriefTraceback())
def writeFailure(failure, logger=None)
Write a L{twisted.python.failure.Failure} to the log. This is for situations where you got an unexpected exception and want to log a traceback. For example, if you have C{Deferred} that might error, you'll want to wrap it with a L{eliot.twisted.DeferredContext} and then add C{writeFailure} as the error...
12.871943
16.172787
0.795901
@wraps(f) def exclusively_f(self, *a, **kw): with self._lock: return f(self, *a, **kw) return exclusively_f
def exclusively(f)
Decorate a function to make it thread-safe by serializing invocations using a per-instance lock.
2.515979
2.344613
1.073089
Logger._destinations.add( FileDestination(file=output_file, encoder=encoder) )
def to_file(output_file, encoder=EliotJSONEncoder)
Add a destination that writes a JSON message per line to the given file. @param output_file: A file-like object.
13.370914
15.294628
0.874223
message.update(self._globalFields) errors = [] for dest in self._destinations: try: dest(message) except: errors.append(sys.exc_info()) if errors: raise _DestinationsSendError(errors)
def send(self, message)
Deliver a message to all destinations. The passed in message might be mutated. @param message: A message dictionary that can be serialized to JSON. @type message: L{dict}
5.429167
4.88987
1.110289
buffered_messages = None if not self._any_added: # These are first set of messages added, so we need to clear # BufferingDestination: self._any_added = True buffered_messages = self._destinations[0].messages self._destinations = [] ...
def add(self, *destinations)
Adds new destinations. A destination should never ever throw an exception. Seriously. A destination should not mutate the dictionary it is given. @param destinations: A list of callables that takes message dictionaries.
5.592761
6.297053
0.888155
seconds = int(timestamp) nanoseconds = int((timestamp - seconds) * 1000000000) seconds = seconds + _OFFSET encoded = b2a_hex(struct.pack(_STRUCTURE, seconds, nanoseconds)) return "@" + encoded.decode("ascii")
def encode(timestamp)
Convert seconds since epoch to TAI64N string. @param timestamp: Seconds since UTC Unix epoch as C{float}. @return: TAI64N-encoded time, as C{unicode}.
3.763919
4.759605
0.790805
seconds, nanoseconds = struct.unpack(_STRUCTURE, a2b_hex(tai64n[1:])) seconds -= _OFFSET return seconds + (nanoseconds / 1000000000.0)
def decode(tai64n)
Convert TAI64N string to seconds since epoch. Note that dates before 2013 may not decode accurately due to leap second issues. If you need correct decoding for earlier dates you can try the tai64n package available from PyPI (U{https://pypi.python.org/pypi/tai64n}). @param tai64n: TAI64N-encoded time,...
4.50694
5.837479
0.77207
parent = current_action() if parent is None: return startTask(logger, action_type, _serializers, **fields) else: action = parent.child(logger, action_type, _serializers) action._start(fields) return action
def start_action(logger=None, action_type="", _serializers=None, **fields)
Create a child L{Action}, figuring out the parent L{Action} from execution context, and log the start message. You can use the result as a Python context manager, or use the L{Action.finish} API to explicitly finish it. with start_action(logger, "yourapp:subsystem:dosomething", ...
4.072813
4.572304
0.890757
action = Action( logger, unicode(uuid4()), TaskLevel(level=[]), action_type, _serializers) action._start(fields) return action
def startTask(logger=None, action_type=u"", _serializers=None, **fields)
Like L{action}, but creates a new top-level L{Action} with no parent. @param logger: The L{eliot.ILogger} to which to write messages, or C{None} to use the default one. @param action_type: The type of this action, e.g. C{"yourapp:subsystem:dosomething"}. @param _serializers: Either a L{el...
11.258749
15.814016
0.711947
action = current_action() if action is None: return f task_id = action.serialize_task_id() called = threading.Lock() def restore_eliot_context(*args, **kwargs): # Make sure the function has not already been called: if not called.acquire(False): raise TooMany...
def preserve_context(f)
Package up the given function with the current Eliot context, and then restore context and call given function when the resulting callable is run. This allows continuing the action context within a different thread. The result should only be used once, since it relies on L{Action.serialize_task_id} who...
5.611426
4.177554
1.343232
if wrapped_function is None: return partial(log_call, action_type=action_type, include_args=include_args, include_result=include_result) if action_type is None: if PY3: action_type = "{}.{}".format(wrapped_function.__module__, ...
def log_call( wrapped_function=None, action_type=None, include_args=None, include_result=True )
Decorator/decorator factory that logs inputs and the return result. If used with inputs (i.e. as a decorator factory), it accepts the following parameters: @param action_type: The action type to use. If not given the function name will be used. @param include_args: If given, should be a list ...
2.293233
2.428467
0.944313
return cls(level=[int(i) for i in string.split("/") if i])
def fromString(cls, string)
Convert a serialized Unicode string to a L{TaskLevel}. @param string: Output of L{TaskLevel.toString}. @return: L{TaskLevel} parsed from the string.
9.733485
15.997089
0.608454
new_level = self._level[:] new_level.append(1) return TaskLevel(level=new_level)
def child(self)
Return a child of this L{TaskLevel}. @return: L{TaskLevel} which is the first child of this one.
8.980303
6.102938
1.471472
return "{}@{}".format( self._identification[TASK_UUID_FIELD], self._nextTaskLevel().toString()).encode("ascii")
def serialize_task_id(self)
Create a unique identifier for the current location within the task. The format is C{b"<task_uuid>@<task_level>"}. @return: L{bytes} encoding the current location within the task.
32.912109
19.292295
1.705972
if task_id is _TASK_ID_NOT_SUPPLIED: raise RuntimeError("You must supply a task_id keyword argument.") if isinstance(task_id, bytes): task_id = task_id.decode("ascii") uuid, task_level = task_id.split("@") action = cls( logger, uuid, TaskLevel...
def continue_task(cls, logger=None, task_id=_TASK_ID_NOT_SUPPLIED)
Start a new action which is part of a serialized task. @param logger: The L{eliot.ILogger} to which to write messages, or C{None} if the default one should be used. @param task_id: A serialized task identifier, the output of L{Action.serialize_task_id}, either ASCII-encoded byt...
5.211517
4.977252
1.047067
if not self._last_child: self._last_child = self._task_level.child() else: self._last_child = self._last_child.next_sibling() return self._last_child
def _nextTaskLevel(self)
Return the next C{task_level} for messages within this action. Called whenever a message is logged within the context of an action. @return: The message's C{task_level}.
3.747533
3.957352
0.94698
fields[ACTION_STATUS_FIELD] = STARTED_STATUS fields.update(self._identification) if self._serializers is None: serializer = None else: serializer = self._serializers.start Message(fields, serializer).write(self._logger, self)
def _start(self, fields)
Log the start message. The action identification fields, and any additional given fields, will be logged. In general you shouldn't call this yourself, instead using a C{with} block or L{Action.finish}.
8.074701
7.990559
1.01053
if self._finished: return self._finished = True serializer = None if exception is None: fields = self._successFields fields[ACTION_STATUS_FIELD] = SUCCEEDED_STATUS if self._serializers is not None: serializer = self...
def finish(self, exception=None)
Log the finish message. The action identification fields, and any additional given fields, will be logged. In general you shouldn't call this yourself, instead using a C{with} block or L{Action.finish}. @param exception: C{None}, in which case the fields added with ...
4.081604
3.563407
1.145422
newLevel = self._nextTaskLevel() return self.__class__( logger, self._identification[TASK_UUID_FIELD], newLevel, action_type, serializers)
def child(self, logger, action_type, serializers=None)
Create a child L{Action}. Rather than calling this directly, you can use L{start_action} to create child L{Action} using the execution context. @param logger: The L{eliot.ILogger} to which to write messages. @param action_type: The type of this action, e.g. C{"...
17.754925
21.93195
0.809546
parent = _ACTION_CONTEXT.set(self) try: return f(*args, **kwargs) finally: _ACTION_CONTEXT.reset(parent)
def run(self, f, *args, **kwargs)
Run the given function with this L{Action} as its execution context.
4.45381
3.734905
1.192483
parent = _ACTION_CONTEXT.set(self) try: yield self finally: _ACTION_CONTEXT.reset(parent)
def context(self)
Create a context manager that ensures code runs within action's context. The action does NOT finish when the context is exited.
7.031489
5.019198
1.400919
actual_message = [ message for message in [start_message, end_message] + list(children) if message][0] action = cls( task_level=actual_message.task_level.parent(), task_uuid=actual_message.task_uuid, ) if start_message: ...
def from_messages( cls, start_message=None, children=pvector(), end_message=None)
Create a C{WrittenAction} from C{WrittenMessage}s and other C{WrittenAction}s. @param WrittenMessage start_message: A message that has C{ACTION_STATUS_FIELD}, C{ACTION_TYPE_FIELD}, and a C{task_level} that ends in C{1}, or C{None} if unavailable. @param children: An iter...
3.386942
3.126003
1.083474
if self.start_message: return self.start_message.contents[ACTION_TYPE_FIELD] elif self.end_message: return self.end_message.contents[ACTION_TYPE_FIELD] else: return None
def action_type(self)
The type of this action, e.g. C{"yourapp:subsystem:dosomething"}.
3.325342
3.169979
1.049011
message = self.end_message if self.end_message else self.start_message if message: return message.contents[ACTION_STATUS_FIELD] else: return None
def status(self)
One of C{STARTED_STATUS}, C{SUCCEEDED_STATUS}, C{FAILED_STATUS} or C{None}.
8.309662
7.674372
1.082781
return pvector( sorted(self._children.values(), key=lambda m: m.task_level))
def children(self)
The list of child messages and actions sorted by task level, excluding the start and end messages.
20.09561
9.241248
2.174556
if message.task_uuid != self.task_uuid: raise WrongTask(self, message) if not message.task_level.parent() == self.task_level: raise WrongTaskLevel(self, message)
def _validate_message(self, message)
Is C{message} a valid direct child of this action? @param message: Either a C{WrittenAction} or a C{WrittenMessage}. @raise WrongTask: If C{message} has a C{task_uuid} that differs from the action's C{task_uuid}. @raise WrongTaskLevel: If C{message} has a C{task_level} that means ...
5.359382
2.899322
1.848495
self._validate_message(message) level = message.task_level return self.transform(('_children', level), message)
def _add_child(self, message)
Return a new action with C{message} added as a child. Assumes C{message} is not an end message. @param message: Either a C{WrittenAction} or a C{WrittenMessage}. @raise WrongTask: If C{message} has a C{task_uuid} that differs from the action's C{task_uuid}. @raise WrongTas...
16.586815
14.195672
1.168442
if start_message.contents.get( ACTION_STATUS_FIELD, None) != STARTED_STATUS: raise InvalidStartMessage.wrong_status(start_message) if start_message.task_level.level[-1] != 1: raise InvalidStartMessage.wrong_task_level(start_message) return self.set(st...
def _start(self, start_message)
Start this action given its start message. @param WrittenMessage start_message: A start message that has the same level as this action. @raise InvalidStartMessage: If C{start_message} does not have a C{ACTION_STATUS_FIELD} of C{STARTED_STATUS}, or if it has a C{task...
6.306466
3.640591
1.732264
action_type = end_message.contents.get(ACTION_TYPE_FIELD, None) if self.action_type not in (None, action_type): raise WrongActionType(self, end_message) self._validate_message(end_message) status = end_message.contents.get(ACTION_STATUS_FIELD, None) if status...
def _end(self, end_message)
End this action with C{end_message}. Assumes that the action has not already been ended. @param WrittenMessage end_message: An end message that has the same level as this action. @raise WrongTask: If C{end_message} has a C{task_uuid} that differs from the action's C{ta...
3.624475
2.957437
1.225546
return list(fields) + [ Field.forTypes(key, [value], "") for key, value in keys.items()]
def fields(*fields, **keys)
Factory for for L{MessageType} and L{ActionType} field definitions. @param *fields: A L{tuple} of L{Field} instances. @param **keys: A L{dict} mapping key names to the expected type of the field's values. @return: A L{list} of L{Field} instances.
16.939919
16.171051
1.047546
# Make sure the input serializes: self._serializer(input) # Use extra validator, if given: if self._extraValidator is not None: self._extraValidator(input)
def validate(self, input)
Validate the given input value against this L{Field} definition. @param input: An input value supposedly serializable by this L{Field}. @raises ValidationError: If the value is not serializable or fails to be validated by the additional validator.
8.288252
7.558833
1.096499
def validate(checked): if checked != value: raise ValidationError( checked, "Field %r must be %r" % (key, value)) return klass(key, lambda _: value, description, validate)
def forValue(klass, key, value, description)
Create a L{Field} that can only have a single value. @param key: The name of the field, the key which refers to it, e.g. C{"path"}. @param value: The allowed value for the field. @param description: A description of what this field contains. @type description: C{unicode} ...
8.218225
7.857154
1.045954
fixedClasses = [] for k in classes: if k is None: k = type(None) if k not in _JSON_TYPES: raise TypeError("%s is not JSON-encodeable" % (k, )) fixedClasses.append(k) fixedClasses = tuple(fixedClasses) def valid...
def forTypes(klass, key, classes, description, extraValidator=None)
Create a L{Field} that must be an instance of a given set of types. @param key: The name of the field, the key which refers to it, e.g. C{"path"}. @ivar classes: A C{list} of allowed Python classes for this field's values. Supported classes are C{unicode}, C{int}, C{float}, ...
3.595631
3.798825
0.946511
for key, field in self.fields.items(): message[key] = field.serialize(message[key])
def serialize(self, message)
Serialize the given message in-place, converting inputs to outputs. We do this in-place for performance reasons. There are more fields in a message than there are L{Field} objects because of the timestamp, task_level and task_uuid fields. By only iterating over our L{Fields} we therefor...
4.005794
3.958652
1.011908
for key, field in self.fields.items(): if key not in message: raise ValidationError(message, "Field %r is missing" % (key, )) field.validate(message[key]) if self.allow_additional_fields: return # Otherwise, additional fields are not ...
def validate(self, message)
Validate the given message. @param message: A C{dict}. @raises ValidationError: If the message has the wrong fields or one of its field values fail validation.
3.422501
3.389597
1.009707
return self._startTask( logger, self.action_type, self._serializers, **fields)
def as_task(self, logger=None, **fields)
Start a new L{eliot.Action} of this type as a task (i.e. top-level action) with the given start fields. See L{ActionType.__call__} for example of usage. @param logger: A L{eliot.ILogger} provider to which the action's messages will be written, or C{None} to use the default one. ...
25.888268
18.637207
1.389064
skip = { TIMESTAMP_FIELD, TASK_UUID_FIELD, TASK_LEVEL_FIELD, MESSAGE_TYPE_FIELD, ACTION_TYPE_FIELD, ACTION_STATUS_FIELD} def add_field(previous, key, value): value = unicode(pprint.pformat(value, width=40)).replace( "\\n", "\n ").replace("\\t", "\t") # Reindent ...
def pretty_format(message)
Convert a message dictionary into a human-readable string. @param message: Message to parse, as dictionary. @return: Unicode string.
4.535707
4.665163
0.97225
if argv[1:]: stdout.write(_CLI_HELP) raise SystemExit() for line in stdin: try: message = loads(line) except ValueError: stdout.write("Not JSON: {}\n\n".format(line.rstrip(b"\n"))) continue if REQUIRED_FIELDS - set(message.keys()):...
def _main()
Command-line program that reads in JSON from stdin and writes out pretty-printed messages to stdout.
3.979185
3.558946
1.11808
for klass in getmro(exception.__class__): if klass in self.registry: extractor = self.registry[klass] try: return extractor(exception) except: from ._traceback import write_traceback ...
def get_fields_for_exception(self, logger, exception)
Given an exception instance, return fields to add to the failed action message. @param logger: ``ILogger`` currently being used. @param exception: An exception instance. @return: Dictionary with fields to include.
4.858817
6.386713
0.76077
if len(sys.argv) != 2: sys.stderr.write(USAGE) return 1 EliotFilter(sys.argv[1], sys.stdin, sys.stdout).run() return 0
def main(sys=sys)
Run the program. Accept arguments from L{sys.argv}, read from L{sys.stdin}, write to L{sys.stdout}. @param sys: An object with same interface and defaulting to the L{sys} module.
3.803963
4.617553
0.823805
for line in self.incoming: message = loads(line) result = self._evaluate(message) if result is self._SKIP: continue self.output.write(dumps(result, cls=_DatetimeJSONEncoder) + b"\n")
def run(self)
For each incoming message, decode the JSON, evaluate expression, encode as JSON and write that to the output file.
7.585958
5.231143
1.450153
return eval( self.code, globals(), { "J": message, "timedelta": timedelta, "datetime": datetime, "SKIP": self._SKIP})
def _evaluate(self, message)
Evaluate the expression with the given Python object in its locals. @param message: A decoded JSON input. @return: The resulting object.
11.420539
16.653357
0.68578
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in filter(None, response): if not isinstance(chunk, six.binary_type): raise ValueError('WSGI Applications must yield bytes') self.write(chunk) ...
def respond(self)
Process the current request. From :pep:`333`: The start_response callable must not actually transmit the response headers. Instead, it must store them for the server or gateway to transmit only after the first iteration of the application return value that yield...
4.543427
4.269062
1.064268
# "The application may call start_response more than once, # if and only if the exc_info argument is provided." if self.started_response and not exc_info: raise AssertionError( 'WSGI start_response called a second ' 'time with no exc_info.', ...
def start_response(self, status, headers, exc_info=None)
WSGI callable to begin the HTTP response.
3.226419
3.170394
1.017671
if six.PY2: return status if not isinstance(status, str): raise TypeError('WSGI response status is not of type str.') return status.encode('ISO-8859-1')
def _encode_status(status)
Cast status to bytes representation of current Python version. According to :pep:`3333`, when using Python 3, the response status and headers must be bytes masquerading as unicode; that is, they must be of type "str" but are restricted to code points in the "latin-1" set.
5.242324
5.00786
1.046819
if not self.started_response: raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if rbo is not None and chunklen > rbo: if not self.req.sent_headers: # Whew. We can send a...
def write(self, chunk)
WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).
5.245959
4.970997
1.055313
req = self.req req_conn = req.conn env = { # set a non-standard environ entry so the WSGI app can know what # the *real* server protocol is (and what features to support). # See http://www.faqs.org/rfcs/rfc2145.html. 'ACTUAL_SERVER_PROTOCO...
def get_environ(self)
Return a new environ dict targeting the given wsgi.version.
2.73719
2.68636
1.018922
req = self.req env_10 = super(Gateway_u0, self).get_environ() env = dict(map(self._decode_key, env_10.items())) # Request-URI enc = env.setdefault(six.u('wsgi.url_encoding'), six.u('utf-8')) try: env['PATH_INFO'] = req.path.decode(enc) en...
def get_environ(self)
Return a new environ dict targeting the given wsgi.version.
3.960975
3.817457
1.037595
self._checkClosed() if isinstance(b, str): raise TypeError("can't write str to binary stream") with self._write_lock: self._write_buf.extend(b) self._flush_unlocked() return len(b)
def write(self, b)
Write bytes to buffer.
4.502594
4.117326
1.093572
bytes_sent = 0 data_mv = memoryview(data) payload_size = len(data_mv) while bytes_sent < payload_size: try: bytes_sent += self.send( data_mv[bytes_sent:bytes_sent + SOCK_WRITE_BLOCKSIZE], ) except socket...
def write(self, data)
Sendall for non-blocking sockets.
3.443176
3.131214
1.09963
bytes_sent = self._sock.send(extract_bytes(data)) self.bytes_written += bytes_sent return bytes_sent
def send(self, data)
Send some part of message to the socket.
4.973326
4.848267
1.025795
if self._wbuf: buffer = ''.join(self._wbuf) self._wbuf = [] self.write(buffer)
def flush(self)
Write all data from buffer to socket and reset write buffer.
4.031678
3.173224
1.270531
while True: try: data = self._sock.recv(size) self.bytes_read += len(data) return data except socket.error as e: what = ( e.args[0] not in errors.socket_errors_nonblocking and...
def recv(self, size)
Receive message of a size from the socket.
3.442234
3.474253
0.990784
# try and match for an IP/hostname and port match = six.moves.urllib.parse.urlparse('//{}'.format(bind_addr_string)) try: addr = match.hostname port = match.port if addr is not None or port is not None: return TCPSocket(addr, port) except ValueError: pass...
def parse_wsgi_bind_location(bind_addr_string)
Convert bind address string to a BindLocation.
4.134988
4.316801
0.957883
parser = argparse.ArgumentParser( description='Start an instance of the Cheroot WSGI/HTTP server.', ) for arg, spec in _arg_spec.items(): parser.add_argument(arg, **spec) raw_args = parser.parse_args() # ensure cwd in sys.path '' in sys.path or sys.path.insert(0, '') #...
def main()
Create a new Cheroot instance with arguments from the command line.
6.319944
5.437027
1.16239
mod_path, _, app_path = full_path.partition(':') app = getattr(import_module(mod_path), app_path or 'application') with contextlib.suppress(TypeError): if issubclass(app, server.Gateway): return GatewayYo(app) return cls(app)
def resolve(cls, full_path)
Read WSGI app/Gateway path string and import application module.
7.161651
5.983304
1.196939
args = { arg: value for arg, value in vars(parsed_args).items() if not arg.startswith('_') and value is not None } args.update(vars(self)) return args
def server_args(self, parsed_args)
Return keyword args for Server class.
2.599664
2.379899
1.092342
server_args = vars(self) server_args['bind_addr'] = parsed_args['bind_addr'] if parsed_args.max is not None: server_args['maxthreads'] = parsed_args.max if parsed_args.numthreads is not None: server_args['minthreads'] = parsed_args.numthreads retu...
def server(self, parsed_args)
Server.
3.033664
3.160071
0.959999
missing_attr = set([None, ]) unique_nums = set(getattr(errno, k, None) for k in errnames) return list(unique_nums - missing_attr)
def plat_specific_errors(*errnames)
Return error numbers for all errors in errnames on this platform. The 'errno' module contains different global constants depending on the specific platform (OS). This function will return the list of numeric values for a given list of potential names.
9.267467
7.017629
1.320598
if len(msgs) < 1: raise TypeError( '_assert_ssl_exc_contains() requires ' 'at least one message to be passed.', ) err_msg_lower = str(exc).lower() return any(m.lower() in err_msg_lower for m in msgs)
def _assert_ssl_exc_contains(exc, *msgs)
Check whether SSL exception contains either of messages provided.
3.671055
3.337768
1.099853
EMPTY_RESULT = None, {} try: s = self.context.wrap_socket( sock, do_handshake_on_connect=True, server_side=True, ) except ssl.SSLError as ex: if ex.errno == ssl.SSL_ERROR_EOF: # This is almost certainly due to the cherr...
def wrap(self, sock)
Wrap and return the given socket, plus WSGI environ entries.
7.101833
6.873
1.033295
cipher = sock.cipher() ssl_environ = { 'wsgi.url_scheme': 'https', 'HTTPS': 'on', 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0], # SSL_VERSION_INTERFACE string The mod_ssl program version # SSL_VERSION_LIBRARY s...
def get_environ(self, sock)
Create WSGI environ entries to be merged into each request.
4.470537
4.300089
1.039638
if not cert_value: return {} env = {} for rdn in cert_value: for attr_name, val in rdn: attr_code = self.CERT_KEY_TO_LDAP_CODE.get(attr_name) if attr_code: env['%s_%s' % (env_prefix, attr_code)] = val r...
def env_dn_dict(self, env_prefix, cert_value)
Return a dict of WSGI environment variables for a client cert DN. E.g. SSL_CLIENT_S_DN_CN, SSL_CLIENT_S_DN_C, etc. See SSL_CLIENT_S_DN_x509 at https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#envvars.
3.524536
3.511512
1.003709
cls = StreamReader if 'r' in mode else StreamWriter return cls(sock, mode, bufsize)
def makefile(self, sock, mode='r', bufsize=DEFAULT_BUFFER_SIZE)
Return socket file object.
5.505921
4.723416
1.165665
start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: # Sleep and try again. This is dangerous, because it means # the rest of the stack has no way of differentiating # ...
def _safe_call(self, is_reader, call, *args, **kwargs)
Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets).
4.413847
4.27006
1.033673
return self._safe_call( True, super(SSLFileobjectMixin, self).recv, size, )
def recv(self, size)
Receive message of a size from the socket.
16.954901
17.10552
0.991195
return self._safe_call( True, super(SSLFileobjectMixin, self).readline, size, )
def readline(self, size=-1)
Receive message of a size from the socket. Matches the following interface: https://docs.python.org/3/library/io.html#io.IOBase.readline
15.615944
17.849268
0.874879
return self._safe_call( False, super(SSLFileobjectMixin, self).sendall, *args, **kwargs )
def sendall(self, *args, **kwargs)
Send whole message to the socket.
9.598629
9.26928
1.035531
return self._safe_call( False, super(SSLFileobjectMixin, self).send, *args, **kwargs )
def send(self, *args, **kwargs)
Send some part of message to the socket.
10.832246
10.261118
1.055659
if self.context is None: self.context = self.get_context() conn = SSLConnection(self.context, sock) self._environ = self.get_environ() return conn
def bind(self, sock)
Wrap and return the given socket.
5.001397
4.915887
1.017395
# See https://code.activestate.com/recipes/442473/ c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
def get_context(self)
Return an SSL.Context from self attributes.
3.057246
2.320233
1.317646
ssl_environ = { 'HTTPS': 'on', # pyOpenSSL doesn't provide access to any of these AFAICT # 'SSL_PROTOCOL': 'SSLv2', # SSL_CIPHER string The cipher specification name # SSL_VERSION_INTERFACE string The mod_ssl program version ...
def get_environ(self)
Return WSGI environ entries to be merged into each request.
4.257505
4.176702
1.019346
cls = ( SSLFileobjectStreamReader if 'r' in mode else SSLFileobjectStreamWriter ) if SSL and isinstance(sock, ssl_conn_type): wrapped_socket = cls(sock, mode, bufsize) wrapped_socket.ssl_timeout = sock.gettimeout() ...
def makefile(self, sock, mode='r', bufsize=-1)
Return socket file object.
9.177682
8.931345
1.027581
if isinstance(mv, memoryview): return mv.tobytes() if six.PY3 else bytes(mv) if isinstance(mv, bytes): return mv raise ValueError
def extract_bytes(mv)
Retrieve bytes out of memoryview/buffer or bytes.
3.555288
2.741394
1.296891
adapter = ssl_adapters[name.lower()] if isinstance(adapter, six.string_types): last_dot = adapter.rfind('.') attr_name = adapter[last_dot + 1:] mod_path = adapter[:last_dot] try: mod = sys.modules[mod_path] if mod is None: raise KeyEr...
def get_ssl_adapter_class(name='builtin')
Return an SSL adapter class for the given name.
2.953366
2.93074
1.00772
data = self.rfile.read(size) self.bytes_read += len(data) self._check_length() return data
def read(self, size=None)
Read a chunk from rfile buffer and return it. Args: size (int): amount of data to read Returns: bytes: Chunk from rfile, limited by size if specified.
4.632311
4.948771
0.936053