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} which is the context for this message. If C{None}, the L{Action} will be deduced from the current call stack.
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 action. 2. For each entry in the dask graph, create a child with serialize_task_id. Do this in likely order of execution, so that if B depends on A the task level of B is higher than the task Ievel of A. 3. Replace each function with a wrapper that uses the corresponding task ID (with Action.continue_task), and while it's at it also records which other things this function depends on. Known issues: 1. Retries will confuse Eliot. Probably need different distributed-tree mechanism within Eliot to solve that.
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 # want to shorten them as well. def simplify(k): if isinstance(k, str): return k return "-".join(str(o) for o in k) key_names = {} for key in keys: value = dsk[key] if not callable(value) and value in keys: # It's an alias for another key: key_names[key] = key_names[value] else: key_names[key] = simplify(key) # 2. Create Eliot child Actions for each key, in topological order: key_to_action_id = { key: str(ctx.serialize_task_id(), "utf-8") for key in keys } # 3. Replace function with wrapper that logs appropriate Action: for key in keys: func = dsk[key][0] args = dsk[key][1:] if not callable(func): # This key is just an alias for another key, no need to add # logging: result[key] = dsk[key] continue wrapped_func = _RunWithEliotContext( task_id=key_to_action_id[key], func=func, key=key_names[key], dependencies=[key_names[k] for k in get_dependencies(dsk, key)], ) result[key] = (wrapped_func, ) + tuple(args) assert result.keys() == dsk.keys() return result
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 for child in node.children: if ( isinstance(child, WrittenAction) and child.task_level not in self._completed): completed = False break if completed: task = task.transform(["_completed"], lambda s: s.add(node.task_level)) task = task.transform(["_nodes", node.task_level], node) return task._ensure_node_parents(node)
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 = parent._add_child(child) return self._insert_action(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: action = WrittenAction( task_level=action_level, task_uuid=message_dict[TASK_UUID_FIELD]) if message_dict[ACTION_STATUS_FIELD] == STARTED_STATUS: # Either newly created MissingAction, or one created by # previously added descendant of the action. action = action._start(written_message) else: action = action._end(written_message) return self._insert_action(action) else: # Special case where there is no action: if written_message.task_level.level == [1]: return self.transform([ "_nodes", self._root_level], written_message, [ "_completed"], lambda s: s.add(self._root_level)) else: return self._ensure_node_parents(written_message)
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], parser else: parser = self.transform(["_tasks", uuid], task) return [], parser
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 with a call to the generator function. This # happens with whatever Eliot action context happens to be active, # which is fine and correct and also irrelevant because no code in the # generator function can run until we call send or throw on it. gen = original(*a, **kw) # Initialize the per-generator context to a copy of the current context. context = copy_context() while True: try: # Whichever way we invoke the generator, we will do it # with the Eliot action context stack we've saved for it. # Then the context manager will re-save it and restore the # "outside" stack for us. # # Regarding the support of Twisted's inlineCallbacks-like # functionality (see eliot.twisted.inline_callbacks): # # The invocation may raise the inlineCallbacks internal # control flow exception _DefGen_Return. It is not wrong to # just let that propagate upwards here but inlineCallbacks # does think it is wrong. The behavior triggers a # DeprecationWarning to try to get us to fix our code. We # could explicitly handle and re-raise the _DefGen_Return but # only at the expense of depending on a private Twisted API. # For now, I'm opting to try to encourage Twisted to fix the # situation (or at least not worsen it): # https://twistedmatrix.com/trac/ticket/9590 # # Alternatively, _DefGen_Return is only required on Python 2. # When Python 2 support is dropped, this concern can be # eliminated by always using `return value` instead of # `returnValue(value)` (and adding the necessary logic to the # StopIteration handler below). def go(): if ok: value_out = gen.send(value_in) else: value_out = gen.throw(*value_in) # We have obtained a value from the generator. In # giving it to us, it has given up control. Note this # fact here. Importantly, this is within the # generator's action context so that we get a good # indication of where the yield occurred. # # This is noisy, enable only for debugging: if wrapper.debug: Message.log(message_type=u"yielded") return value_out value_out = context.run(go) except StopIteration: # When the generator raises this, it is signaling # completion. Leave the loop. break else: try: # Pass the generator's result along to whoever is # driving. Capture the result as the next value to # send inward. value_in = yield value_out except: # Or capture the exception if that's the flavor of the # next value. This could possibly include GeneratorExit # which turns out to be just fine because throwing it into # the inner generator effectively propagates the close # (and with the right context!) just as you would want. # True, the GeneratorExit does get re-throwing out of the # gen.throw call and hits _the_generator_context's # contextmanager. But @contextmanager extremely # conveniently eats it for us! Thanks, @contextmanager! ok = False value_in = exc_info() else: ok = True wrapper.debug = False return wrapper
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) if result != 0: raise IOError(-result, strerror(-result))
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): return self._action.run(errback, *args, **kwargs) self.result.addCallbacks( callbackWithContext, errbackWithContext, callbackArgs, callbackKeywords, errbackArgs, errbackKeywords) return self
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) return result self.result.addBoth(done) return self.result
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 previously. This indicates a programmer error.
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.decode("utf-8") return cls.default(self, o) return pyjson.dumps(obj, cls=WithBytes).encode("utf-8")
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 Python 2 with PyInstaller") path = original_module.__file__ if path.endswith(".pyc") or path.endswith(".pyo"): path = path[:-1] with open(path) as f: source = f.read() exec_(source, module.__dict__, module.__dict__) return module
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, **kwargs): return "" def lazycache(self, *args, **kwargs): return None module.linecache = FakeLineCache() return module
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 handler to get the traceback logged: d = DeferredContext(dostuff()) d.addCallback(process) # Final error handler. d.addErrback(writeFailure) @param failure: L{Failure} to write to the log. @type logger: L{eliot.ILogger}. Will be deprecated at some point, so just ignore it. @return: None
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 = [] self._destinations.extend(destinations) if buffered_messages: # Re-deliver buffered messages: for message in buffered_messages: self.send(message)
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, as C{unicode}. @return: Seconds since UTC Unix epoch as C{float}.
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", entry=x) as action: do(x) result = something(x * 2) action.addSuccessFields(result=result) Or alternatively: action = start_action(logger, "yourapp:subsystem:dosomething", entry=x) with action.context(): do(x) result = something(x * 2) action.addSuccessFields(result=result) action.finish() @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{eliot._validation._ActionSerializers} instance or C{None}. In the latter case no validation or serialization will be done for messages generated by the L{Action}. @param fields: Additional fields to add to the start message. @return: A new L{Action}.
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{eliot._validation._ActionSerializers} instance or C{None}. In the latter case no validation or serialization will be done for messages generated by the L{Action}. @param fields: Additional fields to add to the start message. @return: A new L{Action}.
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 TooManyCalls(f) with Action.continue_task(task_id=task_id): return f(*args, **kwargs) return restore_eliot_context
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} whose results should only be deserialized once. @param f: A callable. @return: One-time use callable that calls given function in context of a child of current Eliot action.
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__, wrapped_function.__qualname__) else: action_type = wrapped_function.__name__ if PY3 and include_args is not None: from inspect import signature sig = signature(wrapped_function) if set(include_args) - set(sig.parameters): raise ValueError( ("include_args ({}) lists arguments not in the " "wrapped function").format(include_args) ) @wraps(wrapped_function) def logging_wrapper(*args, **kwargs): callargs = getcallargs(wrapped_function, *args, **kwargs) # Remove self is it's included: if "self" in callargs: callargs.pop("self") # Filter arguments to log, if necessary: if include_args is not None: callargs = {k: callargs[k] for k in include_args} with start_action(action_type=action_type, **callargs) as ctx: result = wrapped_function(*args, **kwargs) if include_result: ctx.add_success_fields(result=result) return result return logging_wrapper
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 of strings, the arguments to log. @param include_result: True by default. If False, the return result isn't logged.
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.fromString(task_level), "eliot:remote_task") action._start({}) return action
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 bytes or unicode string. Required. @return: The new L{Action} instance.
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._serializers.success else: fields = _error_extraction.get_fields_for_exception( self._logger, exception) fields[EXCEPTION_FIELD] = "%s.%s" % ( exception.__class__.__module__, exception.__class__.__name__) fields[REASON_FIELD] = safeunicode(exception) fields[ACTION_STATUS_FIELD] = FAILED_STATUS if self._serializers is not None: serializer = self._serializers.failure fields.update(self._identification) Message(fields, serializer).write(self._logger, 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 L{Action.addSuccessFields} are used. Or an L{Exception}, in which case an C{"exception"} field is added with the given L{Exception} type and C{"reason"} with its contents.
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{"yourapp:subsystem:dosomething"}. @param serializers: Either a L{eliot._validation._ActionSerializers} instance or C{None}. In the latter case no validation or serialization will be done for messages generated by the L{Action}.
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: action = action._start(start_message) for child in children: if action._children.get(child.task_level, child) != child: raise DuplicateChild(action, child) action = action._add_child(child) if end_message: action = action._end(end_message) return action
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 iterable of C{WrittenMessage} and C{WrittenAction} @param WrittenMessage end_message: A message that has the same C{action_type} as this action. @raise WrongTask: If C{end_message} has a C{task_uuid} that differs from C{start_message.task_uuid}. @raise WrongTaskLevel: If any child message or C{end_message} has a C{task_level} that means it is not a direct child. @raise WrongActionType: If C{end_message} has an C{ACTION_TYPE_FIELD} that differs from the C{ACTION_TYPE_FIELD} of C{start_message}. @raise InvalidStatus: If C{end_message} doesn't have an C{action_status}, or has one that is not C{SUCCEEDED_STATUS} or C{FAILED_STATUS}. @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_level} indicating that it is not the first message of an action. @return: A new C{WrittenAction}.
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 it's not a direct child.
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 WrongTaskLevel: If C{message} has a C{task_level} that means it's not a direct child. @return: A new C{WrittenAction}.
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(start_message=start_message)
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_level} indicating that it is not the first message of an action.
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 not in (FAILED_STATUS, SUCCEEDED_STATUS): raise InvalidStatus(self, end_message) return self.set(end_message=end_message)
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{task_uuid}. @raise WrongTaskLevel: If C{end_message} has a C{task_level} that means it's not a direct child. @raise InvalidStatus: If C{end_message} doesn't have an C{action_status}, or has one that is not C{SUCCEEDED_STATUS} or C{FAILED_STATUS}. @return: A new, completed C{WrittenAction}.
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} @return: A L{Field}.
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 validate(value): if not isinstance(value, fixedClasses): raise ValidationError( value, "Field %r requires type to be one of %s" % (key, classes)) if extraValidator is not None: extraValidator(value) return klass(key, lambda v: v, description, extraValidator=validate)
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}, C{bool}, C{long}, C{list} and C{dict} and C{None} (the latter isn't strictly a class, but will be converted appropriately). @param description: A description of what this field contains. @type description: C{unicode} @param extraValidator: See description in L{Field.__init__}. @return: A L{Field}.
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 therefore reduce the number of function calls in a critical code path. @param message: A C{dict}.
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 allowed: fieldSet = set(self.fields) | set(RESERVED_FIELDS) for key in message: if key not in fieldSet: raise ValidationError(message, "Unexpected field %r" % (key, ))
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. @param fields: Extra fields to add to the message. @rtype: L{eliot.Action}
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 second line and later to match up with first line's # indentation: lines = value.split("\n") # indent lines are " <key length>| <value>" indent = "{}| ".format(" " * (2 + len(key))) value = "\n".join([lines[0]] + [indent + l for l in lines[1:]]) return " %s: %s\n" % (key, value) remaining = "" for field in [ACTION_TYPE_FIELD, MESSAGE_TYPE_FIELD, ACTION_STATUS_FIELD]: if field in message: remaining += add_field(remaining, field, message[field]) for (key, value) in sorted(message.items()): if key not in skip: remaining += add_field(remaining, key, value) level = "/" + "/".join(map(unicode, message[TASK_LEVEL_FIELD])) return "%s -> %s\n%sZ\n%s" % ( message[TASK_UUID_FIELD], level, # If we were returning or storing the datetime we'd want to use an # explicit timezone instead of a naive datetime, but since we're # just using it for formatting we needn't bother. datetime.utcfromtimestamp(message[TIMESTAMP_FIELD]).isoformat( sep=str(" ")), remaining, )
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()): stdout.write( "Not an Eliot message: {}\n\n".format(line.rstrip(b"\n"))) continue result = pretty_format(message) + "\n" if PY2: result = result.encode("utf-8") stdout.write(result)
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 write_traceback(logger) return {} return {}
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) finally: # Send headers if not already sent self.req.ensure_headers_sent() if hasattr(response, 'close'): response.close()
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 yields a NON-EMPTY string, or upon the application's first invocation of the write() callable.
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.', ) self.started_response = True # "if exc_info is provided, and the HTTP headers have already been # sent, start_response must raise an error, and should raise the # exc_info tuple." if self.req.sent_headers: try: six.reraise(*exc_info) finally: exc_info = None self.req.status = self._encode_status(status) for k, v in headers: if not isinstance(k, str): raise TypeError( 'WSGI response header key %r is not of type str.' % k, ) if not isinstance(v, str): raise TypeError( 'WSGI response header value %r is not of type str.' % v, ) if k.lower() == 'content-length': self.remaining_bytes_out = int(v) out_header = ntob(k), ntob(v) self.req.outheaders.append(out_header) return self.write
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 500 to the client. self.req.simple_response( '500 Internal Server Error', 'The requested resource returned more bytes than the ' 'declared Content-Length.', ) else: # Dang. We have probably already sent data. Truncate the chunk # to fit (so the client doesn't hang) and raise an error later. chunk = chunk[:rbo] self.req.ensure_headers_sent() self.req.write(chunk) if rbo is not None: rbo -= chunklen if rbo < 0: raise ValueError( 'Response body exceeds the declared Content-Length.', )
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_PROTOCOL': req.server.protocol, 'PATH_INFO': bton(req.path), 'QUERY_STRING': bton(req.qs), 'REMOTE_ADDR': req_conn.remote_addr or '', 'REMOTE_PORT': str(req_conn.remote_port or ''), 'REQUEST_METHOD': bton(req.method), 'REQUEST_URI': bton(req.uri), 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.server_name, # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol. 'SERVER_PROTOCOL': bton(req.request_protocol), 'SERVER_SOFTWARE': req.server.software, 'wsgi.errors': sys.stderr, 'wsgi.input': req.rfile, 'wsgi.input_terminated': bool(req.chunked_read), 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': bton(req.scheme), 'wsgi.version': self.version, } if isinstance(req.server.bind_addr, six.string_types): # AF_UNIX. This isn't really allowed by WSGI, which doesn't # address unix domain sockets. But it's better than nothing. env['SERVER_PORT'] = '' try: env['X_REMOTE_PID'] = str(req_conn.peer_pid) env['X_REMOTE_UID'] = str(req_conn.peer_uid) env['X_REMOTE_GID'] = str(req_conn.peer_gid) env['X_REMOTE_USER'] = str(req_conn.peer_user) env['X_REMOTE_GROUP'] = str(req_conn.peer_group) env['REMOTE_USER'] = env['X_REMOTE_USER'] except RuntimeError: else: env['SERVER_PORT'] = str(req.server.bind_addr[1]) # Request headers env.update( ('HTTP_' + bton(k).upper().replace('-', '_'), bton(v)) for k, v in req.inheaders.items() ) # CONTENT_TYPE/CONTENT_LENGTH ct = env.pop('HTTP_CONTENT_TYPE', None) if ct is not None: env['CONTENT_TYPE'] = ct cl = env.pop('HTTP_CONTENT_LENGTH', None) if cl is not None: env['CONTENT_LENGTH'] = cl if req.conn.ssl_env: env.update(req.conn.ssl_env) return env
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) env['QUERY_STRING'] = req.qs.decode(enc) except UnicodeDecodeError: # Fall back to latin 1 so apps can transcode if needed. env['wsgi.url_encoding'] = 'ISO-8859-1' env['PATH_INFO'] = env_10['PATH_INFO'] env['QUERY_STRING'] = env_10['QUERY_STRING'] env.update(map(self._decode_value, env.items())) return env
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.error as e: if e.args[0] not in errors.socket_errors_nonblocking: raise
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 e.args[0] not in errors.socket_error_eintr ) if what: raise
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 # else, assume a UNIX socket path # if the string begins with an @ symbol, use an abstract socket if bind_addr_string.startswith('@'): return AbstractSocket(bind_addr_string[1:]) return UnixSocket(path=bind_addr_string)
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, '') # create a server based on the arguments provided raw_args._wsgi_app.server(raw_args).safe_start()
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 return server.HTTPServer(**server_args)
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 cherrypy engine # 'pinging' the socket to assert it's connectable; # the 'ping' isn't SSL. return EMPTY_RESULT elif ex.errno == ssl.SSL_ERROR_SSL: if _assert_ssl_exc_contains(ex, 'http request'): # The client is speaking HTTP to an HTTPS server. raise errors.NoSSLError # Check if it's one of the known errors # Errors that are caught by PyOpenSSL, but thrown by # built-in ssl _block_errors = ( 'unknown protocol', 'unknown ca', 'unknown_ca', 'unknown error', 'https proxy request', 'inappropriate fallback', 'wrong version number', 'no shared cipher', 'certificate unknown', 'ccs received early', 'certificate verify failed', # client cert w/o trusted CA ) if _assert_ssl_exc_contains(ex, *_block_errors): # Accepted error, let's pass return EMPTY_RESULT elif _assert_ssl_exc_contains(ex, 'handshake operation timed out'): # This error is thrown by builtin SSL after a timeout # when client is speaking HTTP to an HTTPS server. # The connection can safely be dropped. return EMPTY_RESULT raise except generic_socket_error as exc: is_error0 = exc.args == (0, 'Error') if is_error0 and IS_ABOVE_OPENSSL10: return EMPTY_RESULT raise return s, self.get_environ(s)
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 string The OpenSSL program version } if self.context and self.context.verify_mode != ssl.CERT_NONE: client_cert = sock.getpeercert() if client_cert: for cert_key, env_var in self.CERT_KEY_TO_ENV.items(): ssl_environ.update( self.env_dn_dict(env_var, client_cert.get(cert_key)), ) return ssl_environ
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 return env
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 # between a "new handshake" error and "client dropped". # Note this isn't an endless loop: there's a timeout below. # Ref: https://stackoverflow.com/a/5133568/595220 time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return b'' errnum = e.args[0] if is_reader and errnum in errors.socket_errors_to_ignore: return b'' raise socket.error(errnum) except SSL.Error as e: if is_reader and e.args == (-1, 'Unexpected EOF'): return b'' thirdarg = None try: thirdarg = e.args[0][0][2] except IndexError: pass if thirdarg == 'http request': # The client is talking HTTP to an HTTPS server. raise errors.NoSSLError() raise errors.FatalSSLAlert(*e.args) if time.time() - start > self.ssl_timeout: raise socket.timeout('timed out')
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 # SSL_VERSION_LIBRARY string The OpenSSL program version } if self.certificate: # Server certificate attributes cert = open(self.certificate, 'rb').read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ssl_environ.update({ 'SSL_SERVER_M_VERSION': cert.get_version(), 'SSL_SERVER_M_SERIAL': cert.get_serial_number(), # 'SSL_SERVER_V_START': # Validity of server's certificate (start time), # 'SSL_SERVER_V_END': # Validity of server's certificate (end time), }) for prefix, dn in [ ('I', cert.get_issuer()), ('S', cert.get_subject()), ]: # X509Name objects don't seem to have a way to get the # complete DN string. Use str() and slice it instead, # because str(dn) == "<X509Name object '/C=US/ST=...'>" dnstr = str(dn)[18:-2] wsgikey = 'SSL_SERVER_%s_DN' % prefix ssl_environ[wsgikey] = dnstr # The DN should be of the form: /k1=v1/k2=v2, but we must allow # for any value to contain slashes itself (in a URL). while dnstr: pos = dnstr.rfind('=') dnstr, value = dnstr[:pos], dnstr[pos + 1:] pos = dnstr.rfind('/') dnstr, key = dnstr[:pos], dnstr[pos + 1:] if key and value: wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key) ssl_environ[wsgikey] = value return ssl_environ
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() return wrapped_socket # This is from past: # TODO: figure out what it's meant for else: return cheroot_server.CP_fileobject(sock, mode, bufsize)
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 KeyError() except KeyError: # The last [''] is important. mod = __import__(mod_path, globals(), locals(), ['']) # Let an AttributeError propagate outward. try: adapter = getattr(mod, attr_name) except AttributeError: raise AttributeError("'%s' object has no attribute '%s'" % (mod_path, attr_name)) return adapter
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