repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Bogdanp/dramatiq | dramatiq/watcher.py | setup_file_watcher | def setup_file_watcher(path, use_polling=False):
"""Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes.
"""
if use_polling:
observer_class = watchdog.observers.polling.PollingObserver
else:
observer_class = EVENTED_OBSERVER
file_event_handler = _SourceChangesHandler(patterns=["*.py"])
file_watcher = observer_class()
file_watcher.schedule(file_event_handler, path, recursive=True)
file_watcher.start()
return file_watcher | python | def setup_file_watcher(path, use_polling=False):
"""Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes.
"""
if use_polling:
observer_class = watchdog.observers.polling.PollingObserver
else:
observer_class = EVENTED_OBSERVER
file_event_handler = _SourceChangesHandler(patterns=["*.py"])
file_watcher = observer_class()
file_watcher.schedule(file_event_handler, path, recursive=True)
file_watcher.start()
return file_watcher | [
"def",
"setup_file_watcher",
"(",
"path",
",",
"use_polling",
"=",
"False",
")",
":",
"if",
"use_polling",
":",
"observer_class",
"=",
"watchdog",
".",
"observers",
".",
"polling",
".",
"PollingObserver",
"else",
":",
"observer_class",
"=",
"EVENTED_OBSERVER",
"... | Sets up a background thread that watches for source changes and
automatically sends SIGHUP to the current process whenever a file
changes. | [
"Sets",
"up",
"a",
"background",
"thread",
"that",
"watches",
"for",
"source",
"changes",
"and",
"automatically",
"sends",
"SIGHUP",
"to",
"the",
"current",
"process",
"whenever",
"a",
"file",
"changes",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/watcher.py#L16-L30 | train | 222,100 |
Bogdanp/dramatiq | dramatiq/brokers/stub.py | StubBroker.declare_queue | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self.queues[queue_name] = Queue()
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self.queues[delayed_name] = Queue()
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name) | python | def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue", queue_name)
self.queues[queue_name] = Queue()
self.emit_after("declare_queue", queue_name)
delayed_name = dq_name(queue_name)
self.queues[delayed_name] = Queue()
self.delay_queues.add(delayed_name)
self.emit_after("declare_delay_queue", delayed_name) | [
"def",
"declare_queue",
"(",
"self",
",",
"queue_name",
")",
":",
"if",
"queue_name",
"not",
"in",
"self",
".",
"queues",
":",
"self",
".",
"emit_before",
"(",
"\"declare_queue\"",
",",
"queue_name",
")",
"self",
".",
"queues",
"[",
"queue_name",
"]",
"=",... | Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue. | [
"Declare",
"a",
"queue",
".",
"Has",
"no",
"effect",
"if",
"a",
"queue",
"with",
"the",
"given",
"name",
"has",
"already",
"been",
"declared",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/stub.py#L66-L81 | train | 222,101 |
Bogdanp/dramatiq | dramatiq/brokers/stub.py | StubBroker.flush_all | def flush_all(self):
"""Drop all messages from all declared queues.
"""
for queue_name in chain(self.queues, self.delay_queues):
self.flush(queue_name) | python | def flush_all(self):
"""Drop all messages from all declared queues.
"""
for queue_name in chain(self.queues, self.delay_queues):
self.flush(queue_name) | [
"def",
"flush_all",
"(",
"self",
")",
":",
"for",
"queue_name",
"in",
"chain",
"(",
"self",
".",
"queues",
",",
"self",
".",
"delay_queues",
")",
":",
"self",
".",
"flush",
"(",
"queue_name",
")"
] | Drop all messages from all declared queues. | [
"Drop",
"all",
"messages",
"from",
"all",
"declared",
"queues",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/brokers/stub.py#L123-L127 | train | 222,102 |
Bogdanp/dramatiq | dramatiq/composition.py | pipeline.run | def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
return self | python | def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
return self | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"self",
".",
"broker",
".",
"enqueue",
"(",
"self",
".",
"messages",
"[",
"0",
"]",
",",
"delay",
"=",
"delay",
")",
"return",
"self"
] | Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself. | [
"Run",
"this",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L101-L112 | train | 222,103 |
Bogdanp/dramatiq | dramatiq/composition.py | pipeline.get_result | def get_result(self, *, block=False, timeout=None):
"""Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
return self.messages[-1].get_result(block=block, timeout=timeout) | python | def get_result(self, *, block=False, timeout=None):
"""Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result.
"""
return self.messages[-1].get_result(block=block, timeout=timeout) | [
"def",
"get_result",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"messages",
"[",
"-",
"1",
"]",
".",
"get_result",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"... | Get the result of this pipeline.
Pipeline results are represented by the result of the last
message in the chain.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
object: The result. | [
"Get",
"the",
"result",
"of",
"this",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L114-L132 | train | 222,104 |
Bogdanp/dramatiq | dramatiq/composition.py | pipeline.get_results | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for message in self.messages:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
yield message.get_result(block=block, timeout=timeout) | python | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for message in self.messages:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
yield message.get_result(block=block, timeout=timeout) | [
"def",
"get_results",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"deadline",
"=",
"None",
"if",
"timeout",
":",
"deadline",
"=",
"time",
".",
"monotonic",
"(",
")",
"+",
"timeout",
"/",
"1000",
"for",
... | Get the results of each job in the pipeline.
Parameters:
block(bool): Whether or not to block until a result is set.
timeout(int): The maximum amount of time, in ms, to wait for
a result when block is True. Defaults to 10 seconds.
Raises:
ResultMissing: When block is False and the result isn't set.
ResultTimeout: When waiting for a result times out.
Returns:
A result generator. | [
"Get",
"the",
"results",
"of",
"each",
"job",
"in",
"the",
"pipeline",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L134-L157 | train | 222,105 |
Bogdanp/dramatiq | dramatiq/composition.py | group.run | def run(self, *, delay=None):
"""Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by.
"""
for child in self.children:
if isinstance(child, (group, pipeline)):
child.run(delay=delay)
else:
self.broker.enqueue(child, delay=delay)
return self | python | def run(self, *, delay=None):
"""Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by.
"""
for child in self.children:
if isinstance(child, (group, pipeline)):
child.run(delay=delay)
else:
self.broker.enqueue(child, delay=delay)
return self | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"group",
",",
"pipeline",
")",
")",
":",
"child",
".",
"run",
"(",
"delay",
... | Run the actors in this group.
Parameters:
delay(int): The minimum amount of time, in milliseconds,
each message in the group should be delayed by. | [
"Run",
"the",
"actors",
"in",
"this",
"group",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L220-L233 | train | 222,106 |
Bogdanp/dramatiq | dramatiq/composition.py | group.get_results | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for child in self.children:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
if isinstance(child, group):
yield list(child.get_results(block=block, timeout=timeout))
else:
yield child.get_result(block=block, timeout=timeout) | python | def get_results(self, *, block=False, timeout=None):
"""Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator.
"""
deadline = None
if timeout:
deadline = time.monotonic() + timeout / 1000
for child in self.children:
if deadline:
timeout = max(0, int((deadline - time.monotonic()) * 1000))
if isinstance(child, group):
yield list(child.get_results(block=block, timeout=timeout))
else:
yield child.get_result(block=block, timeout=timeout) | [
"def",
"get_results",
"(",
"self",
",",
"*",
",",
"block",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"deadline",
"=",
"None",
"if",
"timeout",
":",
"deadline",
"=",
"time",
".",
"monotonic",
"(",
")",
"+",
"timeout",
"/",
"1000",
"for",
... | Get the results of each job in the group.
Parameters:
block(bool): Whether or not to block until the results are stored.
timeout(int): The maximum amount of time, in milliseconds,
to wait for results when block is True. Defaults to 10
seconds.
Raises:
ResultMissing: When block is False and the results aren't set.
ResultTimeout: When waiting for results times out.
Returns:
A result generator. | [
"Get",
"the",
"results",
"of",
"each",
"job",
"in",
"the",
"group",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L235-L262 | train | 222,107 |
Bogdanp/dramatiq | dramatiq/composition.py | group.wait | def wait(self, *, timeout=None):
"""Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds.
"""
for _ in self.get_results(block=True, timeout=timeout): # pragma: no cover
pass | python | def wait(self, *, timeout=None):
"""Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds.
"""
for _ in self.get_results(block=True, timeout=timeout): # pragma: no cover
pass | [
"def",
"wait",
"(",
"self",
",",
"*",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"_",
"in",
"self",
".",
"get_results",
"(",
"block",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
":",
"# pragma: no cover",
"pass"
] | Block until all the jobs in the group have finished or
until the timeout expires.
Parameters:
timeout(int): The maximum amount of time, in ms, to wait.
Defaults to 10 seconds. | [
"Block",
"until",
"all",
"the",
"jobs",
"in",
"the",
"group",
"have",
"finished",
"or",
"until",
"the",
"timeout",
"expires",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L264-L273 | train | 222,108 |
Bogdanp/dramatiq | dramatiq/actor.py | actor | def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options):
"""Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function.
"""
def decorator(fn):
nonlocal actor_name, broker
actor_name = actor_name or fn.__name__
if not _queue_name_re.fullmatch(queue_name):
raise ValueError(
"Queue names must start with a letter or an underscore followed "
"by any number of letters, digits, dashes or underscores."
)
broker = broker or get_broker()
invalid_options = set(options) - broker.actor_options
if invalid_options:
invalid_options_list = ", ".join(invalid_options)
raise ValueError((
"The following actor options are undefined: %s. "
"Did you forget to add a middleware to your Broker?"
) % invalid_options_list)
return actor_class(
fn, actor_name=actor_name, queue_name=queue_name,
priority=priority, broker=broker, options=options,
)
if fn is None:
return decorator
return decorator(fn) | python | def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options):
"""Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function.
"""
def decorator(fn):
nonlocal actor_name, broker
actor_name = actor_name or fn.__name__
if not _queue_name_re.fullmatch(queue_name):
raise ValueError(
"Queue names must start with a letter or an underscore followed "
"by any number of letters, digits, dashes or underscores."
)
broker = broker or get_broker()
invalid_options = set(options) - broker.actor_options
if invalid_options:
invalid_options_list = ", ".join(invalid_options)
raise ValueError((
"The following actor options are undefined: %s. "
"Did you forget to add a middleware to your Broker?"
) % invalid_options_list)
return actor_class(
fn, actor_name=actor_name, queue_name=queue_name,
priority=priority, broker=broker, options=options,
)
if fn is None:
return decorator
return decorator(fn) | [
"def",
"actor",
"(",
"fn",
"=",
"None",
",",
"*",
",",
"actor_class",
"=",
"Actor",
",",
"actor_name",
"=",
"None",
",",
"queue_name",
"=",
"\"default\"",
",",
"priority",
"=",
"0",
",",
"broker",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"d... | Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
queue_name='default',
actor_name='add',
args=(1, 2), kwargs={}, options={},
message_id='e0d27b45-7900-41da-bb97-553b8a081206',
message_timestamp=1497862448685)
Parameters:
fn(callable): The function to wrap.
actor_class(type): Type created by the decorator. Defaults to
:class:`Actor` but can be any callable as long as it returns an
actor and takes the same arguments as the :class:`Actor` class.
actor_name(str): The name of the actor.
queue_name(str): The name of the queue to use.
priority(int): The actor's global priority. If two tasks have
been pulled on a worker concurrently and one has a higher
priority than the other then it will be processed first.
Lower numbers represent higher priorities.
broker(Broker): The broker to use with this actor.
**options(dict): Arbitrary options that vary with the set of
middleware that you use. See ``get_broker().actor_options``.
Returns:
Actor: The decorated function. | [
"Declare",
"an",
"actor",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L157-L225 | train | 222,109 |
Bogdanp/dramatiq | dramatiq/actor.py | Actor.message | def message(self, *args, **kwargs):
"""Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker.
"""
return self.message_with_options(args=args, kwargs=kwargs) | python | def message(self, *args, **kwargs):
"""Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker.
"""
return self.message_with_options(args=args, kwargs=kwargs) | [
"def",
"message",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"message_with_options",
"(",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")"
] | Build a message. This method is useful if you want to
compose actors. See the actor composition documentation for
details.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Examples:
>>> (add.message(1, 2) | add.message(3))
pipeline([add(1, 2), add(3)])
Returns:
Message: A message that can be enqueued on a broker. | [
"Build",
"a",
"message",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"compose",
"actors",
".",
"See",
"the",
"actor",
"composition",
"documentation",
"for",
"details",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L54-L70 | train | 222,110 |
Bogdanp/dramatiq | dramatiq/actor.py | Actor.message_with_options | def message_with_options(self, *, args=None, kwargs=None, **options):
"""Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker.
"""
for name in ["on_failure", "on_success"]:
callback = options.get(name)
if isinstance(callback, Actor):
options[name] = callback.actor_name
elif not isinstance(callback, (type(None), str)):
raise TypeError(name + " value must be an Actor")
return Message(
queue_name=self.queue_name,
actor_name=self.actor_name,
args=args or (), kwargs=kwargs or {},
options=options,
) | python | def message_with_options(self, *, args=None, kwargs=None, **options):
"""Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker.
"""
for name in ["on_failure", "on_success"]:
callback = options.get(name)
if isinstance(callback, Actor):
options[name] = callback.actor_name
elif not isinstance(callback, (type(None), str)):
raise TypeError(name + " value must be an Actor")
return Message(
queue_name=self.queue_name,
actor_name=self.actor_name,
args=args or (), kwargs=kwargs or {},
options=options,
) | [
"def",
"message_with_options",
"(",
"self",
",",
"*",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"for",
"name",
"in",
"[",
"\"on_failure\"",
",",
"\"on_success\"",
"]",
":",
"callback",
"=",
"options",
"."... | Build a message with an arbitray set of processing options.
This method is useful if you want to compose actors. See the
actor composition documentation for details.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: A message that can be enqueued on a broker. | [
"Build",
"a",
"message",
"with",
"an",
"arbitray",
"set",
"of",
"processing",
"options",
".",
"This",
"method",
"is",
"useful",
"if",
"you",
"want",
"to",
"compose",
"actors",
".",
"See",
"the",
"actor",
"composition",
"documentation",
"for",
"details",
"."
... | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L72-L99 | train | 222,111 |
Bogdanp/dramatiq | dramatiq/actor.py | Actor.send | def send(self, *args, **kwargs):
"""Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message.
"""
return self.send_with_options(args=args, kwargs=kwargs) | python | def send(self, *args, **kwargs):
"""Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message.
"""
return self.send_with_options(args=args, kwargs=kwargs) | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"send_with_options",
"(",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")"
] | Asynchronously send a message to this actor.
Parameters:
*args(tuple): Positional arguments to send to the actor.
**kwargs(dict): Keyword arguments to send to the actor.
Returns:
Message: The enqueued message. | [
"Asynchronously",
"send",
"a",
"message",
"to",
"this",
"actor",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L101-L111 | train | 222,112 |
Bogdanp/dramatiq | dramatiq/actor.py | Actor.send_with_options | def send_with_options(self, *, args=None, kwargs=None, delay=None, **options):
"""Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message.
"""
message = self.message_with_options(args=args, kwargs=kwargs, **options)
return self.broker.enqueue(message, delay=delay) | python | def send_with_options(self, *, args=None, kwargs=None, delay=None, **options):
"""Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message.
"""
message = self.message_with_options(args=args, kwargs=kwargs, **options)
return self.broker.enqueue(message, delay=delay) | [
"def",
"send_with_options",
"(",
"self",
",",
"*",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"message",
"=",
"self",
".",
"message_with_options",
"(",
"args",
"=",
"args",
","... | Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
delay(int): The minimum amount of time, in milliseconds, the
message should be delayed by.
**options(dict): Arbitrary options that are passed to the
broker and any registered middleware.
Returns:
Message: The enqueued message. | [
"Asynchronously",
"send",
"a",
"message",
"to",
"this",
"actor",
"along",
"with",
"an",
"arbitrary",
"set",
"of",
"processing",
"options",
"for",
"the",
"broker",
"and",
"middleware",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L113-L130 | train | 222,113 |
Bogdanp/dramatiq | dramatiq/worker.py | Worker.start | def start(self):
"""Initialize the worker boot sequence and start up all the
worker threads.
"""
self.broker.emit_before("worker_boot", self)
worker_middleware = _WorkerMiddleware(self)
self.broker.add_middleware(worker_middleware)
for _ in range(self.worker_threads):
self._add_worker()
self.broker.emit_after("worker_boot", self) | python | def start(self):
"""Initialize the worker boot sequence and start up all the
worker threads.
"""
self.broker.emit_before("worker_boot", self)
worker_middleware = _WorkerMiddleware(self)
self.broker.add_middleware(worker_middleware)
for _ in range(self.worker_threads):
self._add_worker()
self.broker.emit_after("worker_boot", self) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"worker_boot\"",
",",
"self",
")",
"worker_middleware",
"=",
"_WorkerMiddleware",
"(",
"self",
")",
"self",
".",
"broker",
".",
"add_middleware",
"(",
"worker_middleware",... | Initialize the worker boot sequence and start up all the
worker threads. | [
"Initialize",
"the",
"worker",
"boot",
"sequence",
"and",
"start",
"up",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L80-L91 | train | 222,114 |
Bogdanp/dramatiq | dramatiq/worker.py | Worker.pause | def pause(self):
"""Pauses all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.pause()
for child in chain(self.consumers.values(), self.workers):
child.paused_event.wait() | python | def pause(self):
"""Pauses all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.pause()
for child in chain(self.consumers.values(), self.workers):
child.paused_event.wait() | [
"def",
"pause",
"(",
"self",
")",
":",
"for",
"child",
"in",
"chain",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"self",
".",
"workers",
")",
":",
"child",
".",
"pause",
"(",
")",
"for",
"child",
"in",
"chain",
"(",
"self",
".",... | Pauses all the worker threads. | [
"Pauses",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L93-L100 | train | 222,115 |
Bogdanp/dramatiq | dramatiq/worker.py | Worker.resume | def resume(self):
"""Resumes all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.resume() | python | def resume(self):
"""Resumes all the worker threads.
"""
for child in chain(self.consumers.values(), self.workers):
child.resume() | [
"def",
"resume",
"(",
"self",
")",
":",
"for",
"child",
"in",
"chain",
"(",
"self",
".",
"consumers",
".",
"values",
"(",
")",
",",
"self",
".",
"workers",
")",
":",
"child",
".",
"resume",
"(",
")"
] | Resumes all the worker threads. | [
"Resumes",
"all",
"the",
"worker",
"threads",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L102-L106 | train | 222,116 |
Bogdanp/dramatiq | dramatiq/worker.py | Worker.stop | def stop(self, timeout=600000):
"""Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
"""
self.broker.emit_before("worker_shutdown", self)
self.logger.info("Shutting down...")
# Stop workers before consumers. The consumers are kept alive
# during this process so that heartbeats keep being sent to
# the broker while workers finish their current tasks.
self.logger.debug("Stopping workers...")
for thread in self.workers:
thread.stop()
join_all(self.workers, timeout)
self.logger.debug("Workers stopped.")
self.logger.debug("Stopping consumers...")
for thread in self.consumers.values():
thread.stop()
join_all(self.consumers.values(), timeout)
self.logger.debug("Consumers stopped.")
self.logger.debug("Requeueing in-memory messages...")
messages_by_queue = defaultdict(list)
for _, message in iter_queue(self.work_queue):
messages_by_queue[message.queue_name].append(message)
for queue_name, messages in messages_by_queue.items():
try:
self.consumers[queue_name].requeue_messages(messages)
except ConnectionError:
self.logger.warning("Failed to requeue messages on queue %r.", queue_name, exc_info=True)
self.logger.debug("Done requeueing in-progress messages.")
self.logger.debug("Closing consumers...")
for consumer in self.consumers.values():
consumer.close()
self.logger.debug("Consumers closed.")
self.broker.emit_after("worker_shutdown", self)
self.logger.info("Worker has been shut down.") | python | def stop(self, timeout=600000):
"""Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down.
"""
self.broker.emit_before("worker_shutdown", self)
self.logger.info("Shutting down...")
# Stop workers before consumers. The consumers are kept alive
# during this process so that heartbeats keep being sent to
# the broker while workers finish their current tasks.
self.logger.debug("Stopping workers...")
for thread in self.workers:
thread.stop()
join_all(self.workers, timeout)
self.logger.debug("Workers stopped.")
self.logger.debug("Stopping consumers...")
for thread in self.consumers.values():
thread.stop()
join_all(self.consumers.values(), timeout)
self.logger.debug("Consumers stopped.")
self.logger.debug("Requeueing in-memory messages...")
messages_by_queue = defaultdict(list)
for _, message in iter_queue(self.work_queue):
messages_by_queue[message.queue_name].append(message)
for queue_name, messages in messages_by_queue.items():
try:
self.consumers[queue_name].requeue_messages(messages)
except ConnectionError:
self.logger.warning("Failed to requeue messages on queue %r.", queue_name, exc_info=True)
self.logger.debug("Done requeueing in-progress messages.")
self.logger.debug("Closing consumers...")
for consumer in self.consumers.values():
consumer.close()
self.logger.debug("Consumers closed.")
self.broker.emit_after("worker_shutdown", self)
self.logger.info("Worker has been shut down.") | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"600000",
")",
":",
"self",
".",
"broker",
".",
"emit_before",
"(",
"\"worker_shutdown\"",
",",
"self",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Shutting down...\"",
")",
"# Stop workers before consumers... | Gracefully stop the Worker and all of its consumers and
workers.
Parameters:
timeout(int): The number of milliseconds to wait for
everything to shut down. | [
"Gracefully",
"stop",
"the",
"Worker",
"and",
"all",
"of",
"its",
"consumers",
"and",
"workers",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L108-L153 | train | 222,117 |
Bogdanp/dramatiq | dramatiq/worker.py | Worker.join | def join(self):
"""Wait for this worker to complete its work in progress.
This method is useful when testing code.
"""
while True:
for consumer in self.consumers.values():
consumer.delay_queue.join()
self.work_queue.join()
# If nothing got put on the delay queues while we were
# joining on the work queue then it shoud be safe to exit.
# This could still miss stuff but the chances are slim.
for consumer in self.consumers.values():
if consumer.delay_queue.unfinished_tasks:
break
else:
if self.work_queue.unfinished_tasks:
continue
return | python | def join(self):
"""Wait for this worker to complete its work in progress.
This method is useful when testing code.
"""
while True:
for consumer in self.consumers.values():
consumer.delay_queue.join()
self.work_queue.join()
# If nothing got put on the delay queues while we were
# joining on the work queue then it shoud be safe to exit.
# This could still miss stuff but the chances are slim.
for consumer in self.consumers.values():
if consumer.delay_queue.unfinished_tasks:
break
else:
if self.work_queue.unfinished_tasks:
continue
return | [
"def",
"join",
"(",
"self",
")",
":",
"while",
"True",
":",
"for",
"consumer",
"in",
"self",
".",
"consumers",
".",
"values",
"(",
")",
":",
"consumer",
".",
"delay_queue",
".",
"join",
"(",
")",
"self",
".",
"work_queue",
".",
"join",
"(",
")",
"#... | Wait for this worker to complete its work in progress.
This method is useful when testing code. | [
"Wait",
"for",
"this",
"worker",
"to",
"complete",
"its",
"work",
"in",
"progress",
".",
"This",
"method",
"is",
"useful",
"when",
"testing",
"code",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L155-L174 | train | 222,118 |
Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.handle_delayed_messages | def handle_delayed_messages(self):
"""Enqueue any delayed messages whose eta has passed.
"""
for eta, message in iter_queue(self.delay_queue):
if eta > current_millis():
self.delay_queue.put((eta, message))
self.delay_queue.task_done()
break
queue_name = q_name(message.queue_name)
new_message = message.copy(queue_name=queue_name)
del new_message.options["eta"]
self.broker.enqueue(new_message)
self.post_process_message(message)
self.delay_queue.task_done() | python | def handle_delayed_messages(self):
"""Enqueue any delayed messages whose eta has passed.
"""
for eta, message in iter_queue(self.delay_queue):
if eta > current_millis():
self.delay_queue.put((eta, message))
self.delay_queue.task_done()
break
queue_name = q_name(message.queue_name)
new_message = message.copy(queue_name=queue_name)
del new_message.options["eta"]
self.broker.enqueue(new_message)
self.post_process_message(message)
self.delay_queue.task_done() | [
"def",
"handle_delayed_messages",
"(",
"self",
")",
":",
"for",
"eta",
",",
"message",
"in",
"iter_queue",
"(",
"self",
".",
"delay_queue",
")",
":",
"if",
"eta",
">",
"current_millis",
"(",
")",
":",
"self",
".",
"delay_queue",
".",
"put",
"(",
"(",
"... | Enqueue any delayed messages whose eta has passed. | [
"Enqueue",
"any",
"delayed",
"messages",
"whose",
"eta",
"has",
"passed",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L285-L300 | train | 222,119 |
Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.handle_message | def handle_message(self, message):
"""Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue.
"""
try:
if "eta" in message.options:
self.logger.debug("Pushing message %r onto delay queue.", message.message_id)
self.broker.emit_before("delay_message", message)
self.delay_queue.put((message.options.get("eta", 0), message))
else:
actor = self.broker.get_actor(message.actor_name)
self.logger.debug("Pushing message %r onto work queue.", message.message_id)
self.work_queue.put((actor.priority, message))
except ActorNotFound:
self.logger.error(
"Received message for undefined actor %r. Moving it to the DLQ.",
message.actor_name, exc_info=True,
)
message.fail()
self.post_process_message(message) | python | def handle_message(self, message):
"""Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue.
"""
try:
if "eta" in message.options:
self.logger.debug("Pushing message %r onto delay queue.", message.message_id)
self.broker.emit_before("delay_message", message)
self.delay_queue.put((message.options.get("eta", 0), message))
else:
actor = self.broker.get_actor(message.actor_name)
self.logger.debug("Pushing message %r onto work queue.", message.message_id)
self.work_queue.put((actor.priority, message))
except ActorNotFound:
self.logger.error(
"Received message for undefined actor %r. Moving it to the DLQ.",
message.actor_name, exc_info=True,
)
message.fail()
self.post_process_message(message) | [
"def",
"handle_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"if",
"\"eta\"",
"in",
"message",
".",
"options",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Pushing message %r onto delay queue.\"",
",",
"message",
".",
"message_id",
")",
"... | Handle a message received off of the underlying consumer.
If the message has an eta, delay it. Otherwise, put it on the
work queue. | [
"Handle",
"a",
"message",
"received",
"off",
"of",
"the",
"underlying",
"consumer",
".",
"If",
"the",
"message",
"has",
"an",
"eta",
"delay",
"it",
".",
"Otherwise",
"put",
"it",
"on",
"the",
"work",
"queue",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L302-L323 | train | 222,120 |
Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.post_process_message | def post_process_message(self, message):
"""Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected.
"""
while True:
try:
if message.failed:
self.logger.debug("Rejecting message %r.", message.message_id)
self.broker.emit_before("nack", message)
self.consumer.nack(message)
self.broker.emit_after("nack", message)
else:
self.logger.debug("Acknowledging message %r.", message.message_id)
self.broker.emit_before("ack", message)
self.consumer.ack(message)
self.broker.emit_after("ack", message)
return
# This applies to the Redis broker. The alternative to
# constantly retrying would be to give up here and let the
# message be re-processed after the worker is eventually
# stopped or restarted, but we'd be doing the same work
# twice in that case and the behaviour would surprise
# users who don't deploy frequently.
except ConnectionError as e:
self.logger.warning(
"Failed to post_process_message(%s) due to a connection error: %s\n"
"The operation will be retried in %s seconds until the connection recovers.\n"
"If you restart this worker before this operation succeeds, the message will be re-processed later.",
message, e, POST_PROCESS_MESSAGE_RETRY_DELAY_SECS
)
time.sleep(POST_PROCESS_MESSAGE_RETRY_DELAY_SECS)
continue
# Not much point retrying here so we bail. Most likely,
# the message will be re-run after the worker is stopped
# or restarted (because its ack lease will have expired).
except Exception: # pragma: no cover
self.logger.exception(
"Unhandled error during post_process_message(%s). You've found a bug in Dramatiq. Please report it!\n"
"Although your message has been processed, it will be processed again once this worker is restarted.",
message,
)
return | python | def post_process_message(self, message):
"""Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected.
"""
while True:
try:
if message.failed:
self.logger.debug("Rejecting message %r.", message.message_id)
self.broker.emit_before("nack", message)
self.consumer.nack(message)
self.broker.emit_after("nack", message)
else:
self.logger.debug("Acknowledging message %r.", message.message_id)
self.broker.emit_before("ack", message)
self.consumer.ack(message)
self.broker.emit_after("ack", message)
return
# This applies to the Redis broker. The alternative to
# constantly retrying would be to give up here and let the
# message be re-processed after the worker is eventually
# stopped or restarted, but we'd be doing the same work
# twice in that case and the behaviour would surprise
# users who don't deploy frequently.
except ConnectionError as e:
self.logger.warning(
"Failed to post_process_message(%s) due to a connection error: %s\n"
"The operation will be retried in %s seconds until the connection recovers.\n"
"If you restart this worker before this operation succeeds, the message will be re-processed later.",
message, e, POST_PROCESS_MESSAGE_RETRY_DELAY_SECS
)
time.sleep(POST_PROCESS_MESSAGE_RETRY_DELAY_SECS)
continue
# Not much point retrying here so we bail. Most likely,
# the message will be re-run after the worker is stopped
# or restarted (because its ack lease will have expired).
except Exception: # pragma: no cover
self.logger.exception(
"Unhandled error during post_process_message(%s). You've found a bug in Dramatiq. Please report it!\n"
"Although your message has been processed, it will be processed again once this worker is restarted.",
message,
)
return | [
"def",
"post_process_message",
"(",
"self",
",",
"message",
")",
":",
"while",
"True",
":",
"try",
":",
"if",
"message",
".",
"failed",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Rejecting message %r.\"",
",",
"message",
".",
"message_id",
")",
"sel... | Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected. | [
"Called",
"by",
"worker",
"threads",
"whenever",
"they",
"re",
"done",
"processing",
"individual",
"messages",
"signaling",
"that",
"each",
"message",
"is",
"ready",
"to",
"be",
"acked",
"or",
"rejected",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L325-L373 | train | 222,121 |
Bogdanp/dramatiq | dramatiq/worker.py | _ConsumerThread.close | def close(self):
"""Close this consumer thread and its underlying connection.
"""
try:
if self.consumer:
self.requeue_messages(m for _, m in iter_queue(self.delay_queue))
self.consumer.close()
except ConnectionError:
pass | python | def close(self):
"""Close this consumer thread and its underlying connection.
"""
try:
if self.consumer:
self.requeue_messages(m for _, m in iter_queue(self.delay_queue))
self.consumer.close()
except ConnectionError:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"consumer",
":",
"self",
".",
"requeue_messages",
"(",
"m",
"for",
"_",
",",
"m",
"in",
"iter_queue",
"(",
"self",
".",
"delay_queue",
")",
")",
"self",
".",
"consumer",
".",
"cl... | Close this consumer thread and its underlying connection. | [
"Close",
"this",
"consumer",
"thread",
"and",
"its",
"underlying",
"connection",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L403-L411 | train | 222,122 |
Bogdanp/dramatiq | dramatiq/worker.py | _WorkerThread.process_message | def process_message(self, message):
"""Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy)
"""
try:
self.logger.debug("Received message %s with id %r.", message, message.message_id)
self.broker.emit_before("process_message", message)
res = None
if not message.failed:
actor = self.broker.get_actor(message.actor_name)
res = actor(*message.args, **message.kwargs)
self.broker.emit_after("process_message", message, result=res)
except SkipMessage:
self.logger.warning("Message %s was skipped.", message)
self.broker.emit_after("skip_message", message)
except BaseException as e:
# Stuff the exception into the message [proxy] so that it
# may be used by the stub broker to provide a nicer
# testing experience.
message.stuff_exception(e)
if isinstance(e, RateLimitExceeded):
self.logger.warning("Rate limit exceeded in message %s: %s.", message, e)
else:
self.logger.warning("Failed to process message %s with unhandled exception.", message, exc_info=True)
self.broker.emit_after("process_message", message, exception=e)
finally:
# NOTE: There is no race here as any message that was
# processed must have come off of a consumer. Therefore,
# there has to be a consumer for that message's queue so
# this is safe. Probably.
self.consumers[message.queue_name].post_process_message(message)
self.work_queue.task_done() | python | def process_message(self, message):
"""Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy)
"""
try:
self.logger.debug("Received message %s with id %r.", message, message.message_id)
self.broker.emit_before("process_message", message)
res = None
if not message.failed:
actor = self.broker.get_actor(message.actor_name)
res = actor(*message.args, **message.kwargs)
self.broker.emit_after("process_message", message, result=res)
except SkipMessage:
self.logger.warning("Message %s was skipped.", message)
self.broker.emit_after("skip_message", message)
except BaseException as e:
# Stuff the exception into the message [proxy] so that it
# may be used by the stub broker to provide a nicer
# testing experience.
message.stuff_exception(e)
if isinstance(e, RateLimitExceeded):
self.logger.warning("Rate limit exceeded in message %s: %s.", message, e)
else:
self.logger.warning("Failed to process message %s with unhandled exception.", message, exc_info=True)
self.broker.emit_after("process_message", message, exception=e)
finally:
# NOTE: There is no race here as any message that was
# processed must have come off of a consumer. Therefore,
# there has to be a consumer for that message's queue so
# this is safe. Probably.
self.consumers[message.queue_name].post_process_message(message)
self.work_queue.task_done() | [
"def",
"process_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Received message %s with id %r.\"",
",",
"message",
",",
"message",
".",
"message_id",
")",
"self",
".",
"broker",
".",
"emit_before",
"... | Process a message pulled off of the work queue then push it
back to its associated consumer for post processing.
Parameters:
message(MessageProxy) | [
"Process",
"a",
"message",
"pulled",
"off",
"of",
"the",
"work",
"queue",
"then",
"push",
"it",
"back",
"to",
"its",
"associated",
"consumer",
"for",
"post",
"processing",
"."
] | a8cc2728478e794952a5a50c3fb19ec455fe91b6 | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/worker.py#L456-L497 | train | 222,123 |
github/octodns | octodns/manager.py | Manager.compare | def compare(self, a, b, zone):
'''
Compare zone data between 2 sources.
Note: only things supported by both sources will be considered
'''
self.log.info('compare: a=%s, b=%s, zone=%s', a, b, zone)
try:
a = [self.providers[source] for source in a]
b = [self.providers[source] for source in b]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
sub_zones = self.configured_sub_zones(zone)
za = Zone(zone, sub_zones)
for source in a:
source.populate(za)
zb = Zone(zone, sub_zones)
for source in b:
source.populate(zb)
return zb.changes(za, _AggregateTarget(a + b)) | python | def compare(self, a, b, zone):
'''
Compare zone data between 2 sources.
Note: only things supported by both sources will be considered
'''
self.log.info('compare: a=%s, b=%s, zone=%s', a, b, zone)
try:
a = [self.providers[source] for source in a]
b = [self.providers[source] for source in b]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
sub_zones = self.configured_sub_zones(zone)
za = Zone(zone, sub_zones)
for source in a:
source.populate(za)
zb = Zone(zone, sub_zones)
for source in b:
source.populate(zb)
return zb.changes(za, _AggregateTarget(a + b)) | [
"def",
"compare",
"(",
"self",
",",
"a",
",",
"b",
",",
"zone",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'compare: a=%s, b=%s, zone=%s'",
",",
"a",
",",
"b",
",",
"zone",
")",
"try",
":",
"a",
"=",
"[",
"self",
".",
"providers",
"[",
"sou... | Compare zone data between 2 sources.
Note: only things supported by both sources will be considered | [
"Compare",
"zone",
"data",
"between",
"2",
"sources",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/manager.py#L335-L358 | train | 222,124 |
github/octodns | octodns/manager.py | Manager.dump | def dump(self, zone, output_dir, lenient, split, source, *sources):
'''
Dump zone data from the specified source
'''
self.log.info('dump: zone=%s, sources=%s', zone, sources)
# We broke out source to force at least one to be passed, add it to any
# others we got.
sources = [source] + list(sources)
try:
sources = [self.providers[s] for s in sources]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
clz = YamlProvider
if split:
clz = SplitYamlProvider
target = clz('dump', output_dir)
zone = Zone(zone, self.configured_sub_zones(zone))
for source in sources:
source.populate(zone, lenient=lenient)
plan = target.plan(zone)
if plan is None:
plan = Plan(zone, zone, [], False)
target.apply(plan) | python | def dump(self, zone, output_dir, lenient, split, source, *sources):
'''
Dump zone data from the specified source
'''
self.log.info('dump: zone=%s, sources=%s', zone, sources)
# We broke out source to force at least one to be passed, add it to any
# others we got.
sources = [source] + list(sources)
try:
sources = [self.providers[s] for s in sources]
except KeyError as e:
raise Exception('Unknown source: {}'.format(e.args[0]))
clz = YamlProvider
if split:
clz = SplitYamlProvider
target = clz('dump', output_dir)
zone = Zone(zone, self.configured_sub_zones(zone))
for source in sources:
source.populate(zone, lenient=lenient)
plan = target.plan(zone)
if plan is None:
plan = Plan(zone, zone, [], False)
target.apply(plan) | [
"def",
"dump",
"(",
"self",
",",
"zone",
",",
"output_dir",
",",
"lenient",
",",
"split",
",",
"source",
",",
"*",
"sources",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'dump: zone=%s, sources=%s'",
",",
"zone",
",",
"sources",
")",
"# We broke out... | Dump zone data from the specified source | [
"Dump",
"zone",
"data",
"from",
"the",
"specified",
"source"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/manager.py#L360-L387 | train | 222,125 |
github/octodns | octodns/provider/dyn.py | _CachingDynZone.flush_zone | def flush_zone(cls, zone_name):
'''Flushes the zone cache, if there is one'''
cls.log.debug('flush_zone: zone_name=%s', zone_name)
try:
del cls._cache[zone_name]
except KeyError:
pass | python | def flush_zone(cls, zone_name):
'''Flushes the zone cache, if there is one'''
cls.log.debug('flush_zone: zone_name=%s', zone_name)
try:
del cls._cache[zone_name]
except KeyError:
pass | [
"def",
"flush_zone",
"(",
"cls",
",",
"zone_name",
")",
":",
"cls",
".",
"log",
".",
"debug",
"(",
"'flush_zone: zone_name=%s'",
",",
"zone_name",
")",
"try",
":",
"del",
"cls",
".",
"_cache",
"[",
"zone_name",
"]",
"except",
"KeyError",
":",
"pass"
] | Flushes the zone cache, if there is one | [
"Flushes",
"the",
"zone",
"cache",
"if",
"there",
"is",
"one"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/dyn.py#L156-L162 | train | 222,126 |
github/octodns | octodns/provider/azuredns.py | AzureProvider._check_zone | def _check_zone(self, name, create=False):
'''Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None
'''
self.log.debug('_check_zone: name=%s', name)
try:
if name in self._azure_zones:
return name
self._dns_client.zones.get(self._resource_group, name)
self._azure_zones.add(name)
return name
except CloudError as err:
msg = 'The Resource \'Microsoft.Network/dnszones/{}\''.format(name)
msg += ' under resource group \'{}\''.format(self._resource_group)
msg += ' was not found.'
if msg == err.message:
# Then the only error is that the zone doesn't currently exist
if create:
self.log.debug('_check_zone:no matching zone; creating %s',
name)
create_zone = self._dns_client.zones.create_or_update
create_zone(self._resource_group, name,
Zone(location='global'))
return name
else:
return
raise | python | def _check_zone(self, name, create=False):
'''Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None
'''
self.log.debug('_check_zone: name=%s', name)
try:
if name in self._azure_zones:
return name
self._dns_client.zones.get(self._resource_group, name)
self._azure_zones.add(name)
return name
except CloudError as err:
msg = 'The Resource \'Microsoft.Network/dnszones/{}\''.format(name)
msg += ' under resource group \'{}\''.format(self._resource_group)
msg += ' was not found.'
if msg == err.message:
# Then the only error is that the zone doesn't currently exist
if create:
self.log.debug('_check_zone:no matching zone; creating %s',
name)
create_zone = self._dns_client.zones.create_or_update
create_zone(self._resource_group, name,
Zone(location='global'))
return name
else:
return
raise | [
"def",
"_check_zone",
"(",
"self",
",",
"name",
",",
"create",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'_check_zone: name=%s'",
",",
"name",
")",
"try",
":",
"if",
"name",
"in",
"self",
".",
"_azure_zones",
":",
"return",
"name"... | Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zone of that name.
:type create: bool
:type return: str or None | [
"Checks",
"whether",
"a",
"zone",
"specified",
"in",
"a",
"source",
"exist",
"in",
"Azure",
"server",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/azuredns.py#L306-L341 | train | 222,127 |
github/octodns | octodns/provider/azuredns.py | AzureProvider._apply_Create | def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_sets.create_or_update
create(resource_group_name=ar.resource_group,
zone_name=ar.zone_name,
relative_record_set_name=ar.relative_record_set_name,
record_type=ar.record_type,
parameters=ar.params)
self.log.debug('* Success Create/Update: {}'.format(ar)) | python | def _apply_Create(self, change):
'''A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void
'''
ar = _AzureRecord(self._resource_group, change.new)
create = self._dns_client.record_sets.create_or_update
create(resource_group_name=ar.resource_group,
zone_name=ar.zone_name,
relative_record_set_name=ar.relative_record_set_name,
record_type=ar.record_type,
parameters=ar.params)
self.log.debug('* Success Create/Update: {}'.format(ar)) | [
"def",
"_apply_Create",
"(",
"self",
",",
"change",
")",
":",
"ar",
"=",
"_AzureRecord",
"(",
"self",
".",
"_resource_group",
",",
"change",
".",
"new",
")",
"create",
"=",
"self",
".",
"_dns_client",
".",
"record_sets",
".",
"create_or_update",
"create",
... | A record from change must be created.
:param change: a change object
:type change: octodns.record.Change
:type return: void | [
"A",
"record",
"from",
"change",
"must",
"be",
"created",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/azuredns.py#L450-L467 | train | 222,128 |
github/octodns | octodns/provider/base.py | BaseProvider.apply | def apply(self, plan):
'''
Submits actual planned changes to the provider. Returns the number of
changes made
'''
if self.apply_disabled:
self.log.info('apply: disabled')
return 0
self.log.info('apply: making changes')
self._apply(plan)
return len(plan.changes) | python | def apply(self, plan):
'''
Submits actual planned changes to the provider. Returns the number of
changes made
'''
if self.apply_disabled:
self.log.info('apply: disabled')
return 0
self.log.info('apply: making changes')
self._apply(plan)
return len(plan.changes) | [
"def",
"apply",
"(",
"self",
",",
"plan",
")",
":",
"if",
"self",
".",
"apply_disabled",
":",
"self",
".",
"log",
".",
"info",
"(",
"'apply: disabled'",
")",
"return",
"0",
"self",
".",
"log",
".",
"info",
"(",
"'apply: making changes'",
")",
"self",
"... | Submits actual planned changes to the provider. Returns the number of
changes made | [
"Submits",
"actual",
"planned",
"changes",
"to",
"the",
"provider",
".",
"Returns",
"the",
"number",
"of",
"changes",
"made"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/base.py#L83-L94 | train | 222,129 |
github/octodns | octodns/provider/ovh.py | OvhProvider._is_valid_dkim | def _is_valid_dkim(self, value):
"""Check if value is a valid DKIM"""
validator_dict = {'h': lambda val: val in ['sha1', 'sha256'],
's': lambda val: val in ['*', 'email'],
't': lambda val: val in ['y', 's'],
'v': lambda val: val == 'DKIM1',
'k': lambda val: val == 'rsa',
'n': lambda _: True,
'g': lambda _: True}
splitted = value.split('\\;')
found_key = False
for splitted_value in splitted:
sub_split = map(lambda x: x.strip(), splitted_value.split("=", 1))
if len(sub_split) < 2:
return False
key, value = sub_split[0], sub_split[1]
if key == "p":
is_valid_key = self._is_valid_dkim_key(value)
if not is_valid_key:
return False
found_key = True
else:
is_valid_key = validator_dict.get(key, lambda _: False)(value)
if not is_valid_key:
return False
return found_key | python | def _is_valid_dkim(self, value):
"""Check if value is a valid DKIM"""
validator_dict = {'h': lambda val: val in ['sha1', 'sha256'],
's': lambda val: val in ['*', 'email'],
't': lambda val: val in ['y', 's'],
'v': lambda val: val == 'DKIM1',
'k': lambda val: val == 'rsa',
'n': lambda _: True,
'g': lambda _: True}
splitted = value.split('\\;')
found_key = False
for splitted_value in splitted:
sub_split = map(lambda x: x.strip(), splitted_value.split("=", 1))
if len(sub_split) < 2:
return False
key, value = sub_split[0], sub_split[1]
if key == "p":
is_valid_key = self._is_valid_dkim_key(value)
if not is_valid_key:
return False
found_key = True
else:
is_valid_key = validator_dict.get(key, lambda _: False)(value)
if not is_valid_key:
return False
return found_key | [
"def",
"_is_valid_dkim",
"(",
"self",
",",
"value",
")",
":",
"validator_dict",
"=",
"{",
"'h'",
":",
"lambda",
"val",
":",
"val",
"in",
"[",
"'sha1'",
",",
"'sha256'",
"]",
",",
"'s'",
":",
"lambda",
"val",
":",
"val",
"in",
"[",
"'*'",
",",
"'ema... | Check if value is a valid DKIM | [
"Check",
"if",
"value",
"is",
"a",
"valid",
"DKIM"
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/ovh.py#L315-L341 | train | 222,130 |
github/octodns | octodns/provider/googlecloud.py | GoogleCloudProvider._get_gcloud_records | def _get_gcloud_records(self, gcloud_zone, page_token=None):
""" Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet
"""
gcloud_iterator = gcloud_zone.list_resource_record_sets(
page_token=page_token)
for gcloud_record in gcloud_iterator:
yield gcloud_record
# This is to get results which may be on a "paged" page.
# (if more than max_results) entries.
if gcloud_iterator.next_page_token:
for gcloud_record in self._get_gcloud_records(
gcloud_zone, gcloud_iterator.next_page_token):
# yield from is in python 3 only.
yield gcloud_record | python | def _get_gcloud_records(self, gcloud_zone, page_token=None):
""" Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet
"""
gcloud_iterator = gcloud_zone.list_resource_record_sets(
page_token=page_token)
for gcloud_record in gcloud_iterator:
yield gcloud_record
# This is to get results which may be on a "paged" page.
# (if more than max_results) entries.
if gcloud_iterator.next_page_token:
for gcloud_record in self._get_gcloud_records(
gcloud_zone, gcloud_iterator.next_page_token):
# yield from is in python 3 only.
yield gcloud_record | [
"def",
"_get_gcloud_records",
"(",
"self",
",",
"gcloud_zone",
",",
"page_token",
"=",
"None",
")",
":",
"gcloud_iterator",
"=",
"gcloud_zone",
".",
"list_resource_record_sets",
"(",
"page_token",
"=",
"page_token",
")",
"for",
"gcloud_record",
"in",
"gcloud_iterato... | Generator function which yields ResourceRecordSet for the managed
gcloud zone, until there are no more records to pull.
:param gcloud_zone: zone to pull records from
:type gcloud_zone: google.cloud.dns.ManagedZone
:param page_token: page token for the page to get
:return: a resource record set
:type return: google.cloud.dns.ResourceRecordSet | [
"Generator",
"function",
"which",
"yields",
"ResourceRecordSet",
"for",
"the",
"managed",
"gcloud",
"zone",
"until",
"there",
"are",
"no",
"more",
"records",
"to",
"pull",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/googlecloud.py#L150-L171 | train | 222,131 |
github/octodns | octodns/provider/googlecloud.py | GoogleCloudProvider._get_cloud_zones | def _get_cloud_zones(self, page_token=None):
"""Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void
"""
gcloud_zones = self.gcloud_client.list_zones(page_token=page_token)
for gcloud_zone in gcloud_zones:
self._gcloud_zones[gcloud_zone.dns_name] = gcloud_zone
if gcloud_zones.next_page_token:
self._get_cloud_zones(gcloud_zones.next_page_token) | python | def _get_cloud_zones(self, page_token=None):
"""Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void
"""
gcloud_zones = self.gcloud_client.list_zones(page_token=page_token)
for gcloud_zone in gcloud_zones:
self._gcloud_zones[gcloud_zone.dns_name] = gcloud_zone
if gcloud_zones.next_page_token:
self._get_cloud_zones(gcloud_zones.next_page_token) | [
"def",
"_get_cloud_zones",
"(",
"self",
",",
"page_token",
"=",
"None",
")",
":",
"gcloud_zones",
"=",
"self",
".",
"gcloud_client",
".",
"list_zones",
"(",
"page_token",
"=",
"page_token",
")",
"for",
"gcloud_zone",
"in",
"gcloud_zones",
":",
"self",
".",
"... | Load all ManagedZones into the self._gcloud_zones dict which is
mapped with the dns_name as key.
:return: void | [
"Load",
"all",
"ManagedZones",
"into",
"the",
"self",
".",
"_gcloud_zones",
"dict",
"which",
"is",
"mapped",
"with",
"the",
"dns_name",
"as",
"key",
"."
] | 65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6 | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/googlecloud.py#L173-L185 | train | 222,132 |
nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotTlsRecordPayloads.get_client_key_exchange_record | def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
"""A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
"""
pms_padding = cls._compute_pms_padding(modulus)
tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')
pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
final_pms = pms_with_padding_payload.format(
pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
)
cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
tls_version, exponent, modulus, int(final_pms, 16)
)
return cke_robot_record | python | def get_client_key_exchange_record(
cls,
robot_payload_enum: RobotPmsPaddingPayloadEnum,
tls_version: TlsVersionEnum,
modulus: int,
exponent: int
) -> TlsRsaClientKeyExchangeRecord:
"""A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
"""
pms_padding = cls._compute_pms_padding(modulus)
tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode('ascii')
pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
final_pms = pms_with_padding_payload.format(
pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
)
cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
tls_version, exponent, modulus, int(final_pms, 16)
)
return cke_robot_record | [
"def",
"get_client_key_exchange_record",
"(",
"cls",
",",
"robot_payload_enum",
":",
"RobotPmsPaddingPayloadEnum",
",",
"tls_version",
":",
"TlsVersionEnum",
",",
"modulus",
":",
"int",
",",
"exponent",
":",
"int",
")",
"->",
"TlsRsaClientKeyExchangeRecord",
":",
"pms... | A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding. | [
"A",
"client",
"key",
"exchange",
"record",
"with",
"a",
"hardcoded",
"pre_master_secret",
"and",
"a",
"valid",
"or",
"invalid",
"padding",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L71-L90 | train | 222,133 |
nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotTlsRecordPayloads.get_finished_record_bytes | def get_finished_record_bytes(cls, tls_version: TlsVersionEnum) -> bytes:
"""The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record.
"""
# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,
# etc.); as the Finished record contains a hashes of all previous records, it will be wrong and will cause
# servers to send a TLS Alert 20
# Here just like in the poc script, the Finished message does not match the Client Hello we sent
return b'\x16' + TlsRecordTlsVersionBytes[tls_version.name].value + cls._FINISHED_RECORD | python | def get_finished_record_bytes(cls, tls_version: TlsVersionEnum) -> bytes:
"""The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record.
"""
# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,
# etc.); as the Finished record contains a hashes of all previous records, it will be wrong and will cause
# servers to send a TLS Alert 20
# Here just like in the poc script, the Finished message does not match the Client Hello we sent
return b'\x16' + TlsRecordTlsVersionBytes[tls_version.name].value + cls._FINISHED_RECORD | [
"def",
"get_finished_record_bytes",
"(",
"cls",
",",
"tls_version",
":",
"TlsVersionEnum",
")",
"->",
"bytes",
":",
"# TODO(AD): The ROBOT poc script uses the same Finished record for all possible client hello (default, GCM,",
"# etc.); as the Finished record contains a hashes of all previ... | The Finished TLS record corresponding to the hardcoded PMS used in the Client Key Exchange record. | [
"The",
"Finished",
"TLS",
"record",
"corresponding",
"to",
"the",
"hardcoded",
"PMS",
"used",
"in",
"the",
"Client",
"Key",
"Exchange",
"record",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L109-L116 | train | 222,134 |
nabla-c0d3/sslyze | sslyze/plugins/robot_plugin.py | RobotServerResponsesAnalyzer.compute_result_enum | def compute_result_enum(self) -> RobotScanResultEnum:
"""Look at the server's response to each ROBOT payload and return the conclusion of the analysis.
"""
# Ensure the results were consistent
for payload_enum, server_responses in self._payload_responses.items():
# We ran the check twice per payload and the two responses should be the same
if server_responses[0] != server_responses[1]:
return RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS
# Check if the server acts as an oracle by checking if the server replied differently to the payloads
if len(set([server_responses[0] for server_responses in self._payload_responses.values()])) == 1:
# All server responses were identical - no oracle
return RobotScanResultEnum.NOT_VULNERABLE_NO_ORACLE
# All server responses were NOT identical, server is vulnerable
# Check to see if it is a weak oracle
response_1 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_FIRST_TWO_BYTES][0]
response_2 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_POSITION_00][0]
response_3 = self._payload_responses[RobotPmsPaddingPayloadEnum.NO_00_IN_THE_MIDDLE][0]
# From the original script:
# If the response to the invalid PKCS#1 request (oracle_bad1) is equal to both
# requests starting with 0002, we have a weak oracle. This is because the only
# case where we can distinguish valid from invalid requests is when we send
# correctly formatted PKCS#1 message with 0x00 on a correct position. This
# makes our oracle weak
if response_1 == response_2 == response_3:
return RobotScanResultEnum.VULNERABLE_WEAK_ORACLE
else:
return RobotScanResultEnum.VULNERABLE_STRONG_ORACLE | python | def compute_result_enum(self) -> RobotScanResultEnum:
"""Look at the server's response to each ROBOT payload and return the conclusion of the analysis.
"""
# Ensure the results were consistent
for payload_enum, server_responses in self._payload_responses.items():
# We ran the check twice per payload and the two responses should be the same
if server_responses[0] != server_responses[1]:
return RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS
# Check if the server acts as an oracle by checking if the server replied differently to the payloads
if len(set([server_responses[0] for server_responses in self._payload_responses.values()])) == 1:
# All server responses were identical - no oracle
return RobotScanResultEnum.NOT_VULNERABLE_NO_ORACLE
# All server responses were NOT identical, server is vulnerable
# Check to see if it is a weak oracle
response_1 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_FIRST_TWO_BYTES][0]
response_2 = self._payload_responses[RobotPmsPaddingPayloadEnum.WRONG_POSITION_00][0]
response_3 = self._payload_responses[RobotPmsPaddingPayloadEnum.NO_00_IN_THE_MIDDLE][0]
# From the original script:
# If the response to the invalid PKCS#1 request (oracle_bad1) is equal to both
# requests starting with 0002, we have a weak oracle. This is because the only
# case where we can distinguish valid from invalid requests is when we send
# correctly formatted PKCS#1 message with 0x00 on a correct position. This
# makes our oracle weak
if response_1 == response_2 == response_3:
return RobotScanResultEnum.VULNERABLE_WEAK_ORACLE
else:
return RobotScanResultEnum.VULNERABLE_STRONG_ORACLE | [
"def",
"compute_result_enum",
"(",
"self",
")",
"->",
"RobotScanResultEnum",
":",
"# Ensure the results were consistent",
"for",
"payload_enum",
",",
"server_responses",
"in",
"self",
".",
"_payload_responses",
".",
"items",
"(",
")",
":",
"# We ran the check twice per pa... | Look at the server's response to each ROBOT payload and return the conclusion of the analysis. | [
"Look",
"at",
"the",
"server",
"s",
"response",
"to",
"each",
"ROBOT",
"payload",
"and",
"return",
"the",
"conclusion",
"of",
"the",
"analysis",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/robot_plugin.py#L135-L164 | train | 222,135 |
nabla-c0d3/sslyze | sslyze/plugins/utils/trust_store/trust_store.py | TrustStore.is_extended_validation | def is_extended_validation(self, certificate: Certificate) -> bool:
"""Is the supplied server certificate EV?
"""
if not self.ev_oids:
raise ValueError('No EV OIDs supplied for {} store - cannot detect EV certificates'.format(self.name))
try:
cert_policies_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES)
except ExtensionNotFound:
return False
for policy in cert_policies_ext.value:
if policy.policy_identifier in self.ev_oids:
return True
return False | python | def is_extended_validation(self, certificate: Certificate) -> bool:
"""Is the supplied server certificate EV?
"""
if not self.ev_oids:
raise ValueError('No EV OIDs supplied for {} store - cannot detect EV certificates'.format(self.name))
try:
cert_policies_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES)
except ExtensionNotFound:
return False
for policy in cert_policies_ext.value:
if policy.policy_identifier in self.ev_oids:
return True
return False | [
"def",
"is_extended_validation",
"(",
"self",
",",
"certificate",
":",
"Certificate",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"ev_oids",
":",
"raise",
"ValueError",
"(",
"'No EV OIDs supplied for {} store - cannot detect EV certificates'",
".",
"format",
"("... | Is the supplied server certificate EV? | [
"Is",
"the",
"supplied",
"server",
"certificate",
"EV?"
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store.py#L58-L72 | train | 222,136 |
nabla-c0d3/sslyze | sslyze/synchronous_scanner.py | SynchronousScanner.run_scan_command | def run_scan_command(
self,
server_info: ServerConnectivityInfo,
scan_command: PluginScanCommand
) -> PluginScanResult:
"""Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass.
"""
plugin_class = self._plugins_repository.get_plugin_class_for_command(scan_command)
plugin = plugin_class()
return plugin.process_task(server_info, scan_command) | python | def run_scan_command(
self,
server_info: ServerConnectivityInfo,
scan_command: PluginScanCommand
) -> PluginScanResult:
"""Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass.
"""
plugin_class = self._plugins_repository.get_plugin_class_for_command(scan_command)
plugin = plugin_class()
return plugin.process_task(server_info, scan_command) | [
"def",
"run_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"PluginScanResult",
":",
"plugin_class",
"=",
"self",
".",
"_plugins_repository",
".",
"get_plugin_class_for_command",
"(... | Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
Returns:
The result of the scan command, which will be an instance of the scan command's
corresponding PluginScanResult subclass. | [
"Run",
"a",
"single",
"scan",
"command",
"against",
"a",
"server",
";",
"will",
"block",
"until",
"the",
"scan",
"command",
"has",
"been",
"completed",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/synchronous_scanner.py#L32-L50 | train | 222,137 |
nabla-c0d3/sslyze | sslyze/plugins/utils/trust_store/trust_store_repository.py | TrustStoresRepository.update_default | def update_default(cls) -> 'TrustStoresRepository':
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | python | def update_default(cls) -> 'TrustStoresRepository':
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = mkdtemp()
try:
# Download the latest trust stores
archive_path = join(temp_path, 'trust_stores_as_pem.tar.gz')
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = join(temp_path, 'extracted')
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY | [
"def",
"update_default",
"(",
"cls",
")",
"->",
"'TrustStoresRepository'",
":",
"temp_path",
"=",
"mkdtemp",
"(",
")",
"try",
":",
"# Download the latest trust stores",
"archive_path",
"=",
"join",
"(",
"temp_path",
",",
"'trust_stores_as_pem.tar.gz'",
")",
"urlretrie... | Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory. | [
"Update",
"the",
"default",
"trust",
"stores",
"used",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store_repository.py#L123-L146 | train | 222,138 |
nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | OpenSslCipherSuitesPlugin._get_preferred_cipher_suite | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
"""Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze.
"""
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | python | def _get_preferred_cipher_suite(
cls,
server_connectivity_info: ServerConnectivityInfo,
ssl_version: OpenSslVersionEnum,
accepted_cipher_list: List['AcceptedCipherSuite']
) -> Optional['AcceptedCipherSuite']:
"""Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze.
"""
if len(accepted_cipher_list) < 2:
return None
accepted_cipher_names = [cipher.openssl_name for cipher in accepted_cipher_list]
should_use_legacy_openssl = None
# For TLS 1.2, we need to figure whether the modern or legacy OpenSSL should be used to connect
if ssl_version == OpenSslVersionEnum.TLSV1_2:
should_use_legacy_openssl = True
# If there are more than two modern-supported cipher suites, use the modern OpenSSL
for cipher_name in accepted_cipher_names:
modern_supported_cipher_count = 0
if not WorkaroundForTls12ForCipherSuites.requires_legacy_openssl(cipher_name):
modern_supported_cipher_count += 1
if modern_supported_cipher_count > 1:
should_use_legacy_openssl = False
break
first_cipher_str = ', '.join(accepted_cipher_names)
# Swap the first two ciphers in the list to see if the server always picks the client's first cipher
second_cipher_str = ', '.join([accepted_cipher_names[1], accepted_cipher_names[0]] + accepted_cipher_names[2:])
try:
first_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, first_cipher_str, should_use_legacy_openssl
)
second_cipher = cls._get_selected_cipher_suite(
server_connectivity_info, ssl_version, second_cipher_str, should_use_legacy_openssl
)
except (SslHandshakeRejected, ConnectionError):
# Could not complete a handshake
return None
if first_cipher.name == second_cipher.name:
# The server has its own preference for picking a cipher suite
return first_cipher
else:
# The server has no preferred cipher suite as it follows the client's preference for picking a cipher suite
return None | [
"def",
"_get_preferred_cipher_suite",
"(",
"cls",
",",
"server_connectivity_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version",
":",
"OpenSslVersionEnum",
",",
"accepted_cipher_list",
":",
"List",
"[",
"'AcceptedCipherSuite'",
"]",
")",
"->",
"Optional",
"[",
"'Ac... | Try to detect the server's preferred cipher suite among all cipher suites supported by SSLyze. | [
"Try",
"to",
"detect",
"the",
"server",
"s",
"preferred",
"cipher",
"suite",
"among",
"all",
"cipher",
"suites",
"supported",
"by",
"SSLyze",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L283-L330 | train | 222,139 |
nabla-c0d3/sslyze | sslyze/plugins/openssl_cipher_suites_plugin.py | CipherSuite.name | def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | python | def name(self) -> str:
"""OpenSSL uses a different naming convention than the corresponding RFCs.
"""
return OPENSSL_TO_RFC_NAMES_MAPPING[self.ssl_version].get(self.openssl_name, self.openssl_name) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"OPENSSL_TO_RFC_NAMES_MAPPING",
"[",
"self",
".",
"ssl_version",
"]",
".",
"get",
"(",
"self",
".",
"openssl_name",
",",
"self",
".",
"openssl_name",
")"
] | OpenSSL uses a different naming convention than the corresponding RFCs. | [
"OpenSSL",
"uses",
"a",
"different",
"naming",
"convention",
"than",
"the",
"corresponding",
"RFCs",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/openssl_cipher_suites_plugin.py#L366-L369 | train | 222,140 |
nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.queue_scan_command | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
"""Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
"""
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | python | def queue_scan_command(self, server_info: ServerConnectivityInfo, scan_command: PluginScanCommand) -> None:
"""Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server.
"""
# Ensure we have the right processes and queues in place for this hostname
self._check_and_create_process(server_info.hostname)
# Add the task to the right queue
self._queued_tasks_nb += 1
if scan_command.is_aggressive:
# Aggressive commands should not be run in parallel against
# a given server so we use the priority queues to prevent this
self._hostname_queues_dict[server_info.hostname].put((server_info, scan_command))
else:
# Normal commands get put in the standard/shared queue
self._task_queue.put((server_info, scan_command)) | [
"def",
"queue_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"None",
":",
"# Ensure we have the right processes and queues in place for this hostname",
"self",
".",
"_check_and_create_proc... | Queue a scan command targeting a specific server.
Args:
server_info: The server's connectivity information. The test_connectivity_to_server() method must have been
called first to ensure that the server is online and accessible.
scan_command: The scan command to run against this server. | [
"Queue",
"a",
"scan",
"command",
"targeting",
"a",
"specific",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L83-L102 | train | 222,141 |
nabla-c0d3/sslyze | sslyze/concurrent_scanner.py | ConcurrentScanner.get_results | def get_results(self) -> Iterable[PluginScanResult]:
"""Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead.
"""
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | python | def get_results(self) -> Iterable[PluginScanResult]:
"""Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead.
"""
# Put a 'None' sentinel in the queue to let the each process know when every task has been completed
for _ in range(self._get_current_processes_nb()):
self._task_queue.put(None)
for hostname, hostname_queue in self._hostname_queues_dict.items():
for i in range(len(self._processes_dict[hostname])):
hostname_queue.put(None)
received_task_results = 0
# Go on until all the tasks have been completed and all processes are done
expected_task_results = self._queued_tasks_nb + self._get_current_processes_nb()
while received_task_results != expected_task_results:
result = self._result_queue.get()
self._result_queue.task_done()
received_task_results += 1
if result is None:
# Getting None means that one process was done
pass
else:
# Getting an actual result
yield result
# Ensure all the queues and processes are done
self._task_queue.join()
self._result_queue.join()
for hostname_queue in self._hostname_queues_dict.values():
hostname_queue.join()
for process_list in self._processes_dict.values():
for process in process_list:
process.join() | [
"def",
"get_results",
"(",
"self",
")",
"->",
"Iterable",
"[",
"PluginScanResult",
"]",
":",
"# Put a 'None' sentinel in the queue to let the each process know when every task has been completed",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_get_current_processes_nb",
"(",
... | Return the result of previously queued scan commands; new commands cannot be queued once this is called.
Returns:
The results of all the scan commands previously queued. Each result will be an instance of the scan
corresponding command's PluginScanResult subclass. If there was an unexpected error while running the scan
command, it will be a 'PluginRaisedExceptionScanResult' instance instead. | [
"Return",
"the",
"result",
"of",
"previously",
"queued",
"scan",
"commands",
";",
"new",
"commands",
"cannot",
"be",
"queued",
"once",
"this",
"is",
"called",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/concurrent_scanner.py#L135-L172 | train | 222,142 |
nabla-c0d3/sslyze | sslyze/utils/worker_process.py | WorkerProcess.run | def run(self) -> None:
"""The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates.
"""
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | python | def run(self) -> None:
"""The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates.
"""
from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult
# Start processing task in the priority queue first
current_queue_in = self.priority_queue_in
while True:
task = current_queue_in.get() # Grab a task from queue_in
if task is None: # All tasks have been completed
current_queue_in.task_done()
if current_queue_in == self.priority_queue_in:
# All high priority tasks have been completed; switch to low priority tasks
current_queue_in = self.queue_in
continue
else:
# All the tasks have been completed; pass on the sentinel to result_queue and exit
self.queue_out.put(None)
break
server_info, scan_command = task
try:
result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
except Exception as e:
# raise
result = PluginRaisedExceptionScanResult(server_info, scan_command, e)
# Send the result to queue_out
self.queue_out.put(result)
current_queue_in.task_done() | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"from",
"sslyze",
".",
"concurrent_scanner",
"import",
"PluginRaisedExceptionScanResult",
"# Start processing task in the priority queue first",
"current_queue_in",
"=",
"self",
".",
"priority_queue_in",
"while",
"True",
... | The process will first complete tasks it gets from self.queue_in.
Once it gets notified that all the tasks have been completed, it terminates. | [
"The",
"process",
"will",
"first",
"complete",
"tasks",
"it",
"gets",
"from",
"self",
".",
"queue_in",
".",
"Once",
"it",
"gets",
"notified",
"that",
"all",
"the",
"tasks",
"have",
"been",
"completed",
"it",
"terminates",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/worker_process.py#L26-L58 | train | 222,143 |
nabla-c0d3/sslyze | sslyze/utils/connection_helpers.py | ProxyTunnelingConnectionHelper.connect_socket | def connect_socket(self, sock: socket.socket) -> None:
"""Setup HTTP tunneling with the configured proxy.
"""
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | python | def connect_socket(self, sock: socket.socket) -> None:
"""Setup HTTP tunneling with the configured proxy.
"""
# Setup HTTP tunneling
try:
sock.connect((self._tunnel_host, self._tunnel_port))
except socket.timeout as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
except socket.error as e:
raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e)))
# Send a CONNECT request with the host we want to tunnel to
if self._tunnel_basic_auth_token is None:
sock.send(self.HTTP_CONNECT_REQ.format(self._server_host, self._server_port).encode('utf-8'))
else:
sock.send(self.HTTP_CONNECT_REQ_PROXY_AUTH_BASIC.format(
self._server_host, self._server_port, self._tunnel_basic_auth_token
).encode('utf-8'))
http_response = HttpResponseParser.parse_from_socket(sock)
# Check if the proxy was able to connect to the host
if http_response.status != 200:
raise ProxyError(self.ERR_CONNECT_REJECTED) | [
"def",
"connect_socket",
"(",
"self",
",",
"sock",
":",
"socket",
".",
"socket",
")",
"->",
"None",
":",
"# Setup HTTP tunneling",
"try",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"_tunnel_host",
",",
"self",
".",
"_tunnel_port",
")",
")",
"exc... | Setup HTTP tunneling with the configured proxy. | [
"Setup",
"HTTP",
"tunneling",
"with",
"the",
"configured",
"proxy",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/connection_helpers.py#L63-L85 | train | 222,144 |
nabla-c0d3/sslyze | sslyze/server_connectivity_info.py | ServerConnectivityInfo.get_preconfigured_ssl_connection | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
"""Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans.
"""
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | python | def get_preconfigured_ssl_connection(
self,
override_ssl_version: Optional[OpenSslVersionEnum] = None,
ssl_verify_locations: Optional[str] = None,
should_use_legacy_openssl: Optional[bool] = None,
) -> SslConnection:
"""Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans.
"""
if override_ssl_version is not None:
# Caller wants to override the ssl version to use for this connection
final_ssl_version = override_ssl_version
# Then we don't know which cipher suite is supported by the server for this ssl version
openssl_cipher_string = None
else:
# Use the ssl version and cipher suite that were successful during connectivity testing
final_ssl_version = self.highest_ssl_version_supported
openssl_cipher_string = self.openssl_cipher_string_supported
if should_use_legacy_openssl is not None:
# Caller wants to override which version of OpenSSL to use
# Then we don't know which cipher suite is supported by this version of OpenSSL
openssl_cipher_string = None
if self.client_auth_credentials is not None:
# If we have creds for client authentication, go ahead and use them
should_ignore_client_auth = False
else:
# Ignore client auth requests if the server allows optional TLS client authentication
should_ignore_client_auth = True
# But do not ignore them is client authentication is required so that the right exceptions get thrown
# within the plugins, providing a better output
if self.client_auth_requirement == ClientAuthenticationServerConfigurationEnum.REQUIRED:
should_ignore_client_auth = False
ssl_connection = SslConnectionConfigurator.get_connection(
ssl_version=final_ssl_version,
server_info=self,
openssl_cipher_string=openssl_cipher_string,
ssl_verify_locations=ssl_verify_locations,
should_use_legacy_openssl=should_use_legacy_openssl,
should_ignore_client_auth=should_ignore_client_auth,
)
return ssl_connection | [
"def",
"get_preconfigured_ssl_connection",
"(",
"self",
",",
"override_ssl_version",
":",
"Optional",
"[",
"OpenSslVersionEnum",
"]",
"=",
"None",
",",
"ssl_verify_locations",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"should_use_legacy_openssl",
":",
"Opt... | Get an SSLConnection instance with the right SSL configuration for successfully connecting to the server.
Used by all plugins to connect to the server and run scans. | [
"Get",
"an",
"SSLConnection",
"instance",
"with",
"the",
"right",
"SSL",
"configuration",
"for",
"successfully",
"connecting",
"to",
"the",
"server",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/server_connectivity_info.py#L70-L114 | train | 222,145 |
nabla-c0d3/sslyze | sslyze/cli/command_line_parser.py | CommandLineParser._add_plugin_options | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
"""Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser.
"""
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | python | def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None:
"""Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser.
"""
for plugin_class in available_plugins:
# Add the current plugin's commands to the parser
group = OptionGroup(self._parser, plugin_class.get_title(), plugin_class.get_description())
for option in plugin_class.get_cli_option_group():
group.add_option(option)
self._parser.add_option_group(group) | [
"def",
"_add_plugin_options",
"(",
"self",
",",
"available_plugins",
":",
"Set",
"[",
"Type",
"[",
"Plugin",
"]",
"]",
")",
"->",
"None",
":",
"for",
"plugin_class",
"in",
"available_plugins",
":",
"# Add the current plugin's commands to the parser",
"group",
"=",
... | Recovers the list of command line options implemented by the available plugins and adds them to the command
line parser. | [
"Recovers",
"the",
"list",
"of",
"command",
"line",
"options",
"implemented",
"by",
"the",
"available",
"plugins",
"and",
"adds",
"them",
"to",
"the",
"command",
"line",
"parser",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/command_line_parser.py#L428-L437 | train | 222,146 |
nabla-c0d3/sslyze | setup.py | get_long_description | def get_long_description():
"""Convert the README file into the long description.
"""
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | python | def get_long_description():
"""Convert the README file into the long description.
"""
with open(path.join(root_path, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
return long_description | [
"def",
"get_long_description",
"(",
")",
":",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"root_path",
",",
"'README.md'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"long_description",
"=",
"f",
".",
"read",
"(",
")",
"return",
"lon... | Convert the README file into the long description. | [
"Convert",
"the",
"README",
"file",
"into",
"the",
"long",
"description",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L23-L28 | train | 222,147 |
nabla-c0d3/sslyze | setup.py | get_include_files | def get_include_files():
""""Get the list of trust stores so they properly packaged when doing a cx_freeze build.
"""
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | python | def get_include_files():
""""Get the list of trust stores so they properly packaged when doing a cx_freeze build.
"""
plugin_data_files = []
trust_stores_pem_path = path.join(root_path, 'sslyze', 'plugins', 'utils', 'trust_store', 'pem_files')
for file in listdir(trust_stores_pem_path):
file = path.join(trust_stores_pem_path, file)
if path.isfile(file): # skip directories
filename = path.basename(file)
plugin_data_files.append((file, path.join('pem_files', filename)))
return plugin_data_files | [
"def",
"get_include_files",
"(",
")",
":",
"plugin_data_files",
"=",
"[",
"]",
"trust_stores_pem_path",
"=",
"path",
".",
"join",
"(",
"root_path",
",",
"'sslyze'",
",",
"'plugins'",
",",
"'utils'",
",",
"'trust_store'",
",",
"'pem_files'",
")",
"for",
"file",... | Get the list of trust stores so they properly packaged when doing a cx_freeze build. | [
"Get",
"the",
"list",
"of",
"trust",
"stores",
"so",
"they",
"properly",
"packaged",
"when",
"doing",
"a",
"cx_freeze",
"build",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/setup.py#L31-L41 | train | 222,148 |
nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_dns_subject_alternative_names | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | python | def get_dns_subject_alternative_names(certificate: cryptography.x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
subj_alt_names = san_ext.value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
return subj_alt_names | [
"def",
"get_dns_subject_alternative_names",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"List",
"[",
"str",
"]",
":",
"subj_alt_names",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"try",
":",
"san_ext",
"=",
"certi... | Retrieve all the DNS entries of the Subject Alternative Name extension. | [
"Retrieve",
"all",
"the",
"DNS",
"entries",
"of",
"the",
"Subject",
"Alternative",
"Name",
"extension",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L24-L33 | train | 222,149 |
nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.matches_hostname | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
"""Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | python | def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
"""Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
ssl.match_hostname(certificate_names, hostname) | [
"def",
"matches_hostname",
"(",
"cls",
",",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
",",
"hostname",
":",
"str",
")",
"->",
"None",
":",
"# Extract the names from the certificate to create the properly-formatted dictionary",
"certificate_names",... | Verify that the certificate was issued for the given hostname.
Raises:
CertificateError: If the certificate was not issued for the supplied hostname. | [
"Verify",
"that",
"the",
"certificate",
"was",
"issued",
"for",
"the",
"given",
"hostname",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L36-L48 | train | 222,150 |
nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.get_name_as_short_text | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
"""Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
"""
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | python | def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
"""Convert a name field returned by the cryptography module to a string suitable for displaying it to the user.
"""
# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
common_names = cls.get_common_names(name_field)
if common_names:
# We don't support certs with multiple CNs
return common_names[0]
else:
# Otherwise show the whole field
return cls.get_name_as_text(name_field) | [
"def",
"get_name_as_short_text",
"(",
"cls",
",",
"name_field",
":",
"cryptography",
".",
"x509",
".",
"Name",
")",
"->",
"str",
":",
"# Name_field is supposed to be a Subject or an Issuer; print the CN if there is one",
"common_names",
"=",
"cls",
".",
"get_common_names",
... | Convert a name field returned by the cryptography module to a string suitable for displaying it to the user. | [
"Convert",
"a",
"name",
"field",
"returned",
"by",
"the",
"cryptography",
"module",
"to",
"a",
"string",
"suitable",
"for",
"displaying",
"it",
"to",
"the",
"user",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L51-L61 | train | 222,151 |
nabla-c0d3/sslyze | sslyze/plugins/utils/certificate_utils.py | CertificateUtils.has_ocsp_must_staple_extension | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
"""Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
"""
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | python | def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool:
"""Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
"""
has_ocsp_must_staple = False
try:
tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
for feature_type in tls_feature_ext.value:
if feature_type == cryptography.x509.TLSFeatureType.status_request:
has_ocsp_must_staple = True
break
except ExtensionNotFound:
pass
return has_ocsp_must_staple | [
"def",
"has_ocsp_must_staple_extension",
"(",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"bool",
":",
"has_ocsp_must_staple",
"=",
"False",
"try",
":",
"tls_feature_ext",
"=",
"certificate",
".",
"extensions",
".",
"get_extension... | Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066. | [
"Return",
"True",
"if",
"the",
"certificate",
"has",
"the",
"OCSP",
"Must",
"-",
"Staple",
"extension",
"defined",
"in",
"RFC",
"6066",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/certificate_utils.py#L95-L108 | train | 222,152 |
nabla-c0d3/sslyze | sslyze/utils/tls_wrapped_protocol_helpers.py | HttpsHelper.send_request | def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | python | def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_response = HttpResponseParser.parse_from_ssl_connection(ssl_client)
if http_response.version == 9:
# HTTP 0.9 => Probably not an HTTP response
result = self.ERR_NOT_HTTP
else:
redirect = ''
if 300 <= http_response.status < 400:
redirect_location = http_response.getheader('Location')
if redirect_location:
# Add redirection URL to the result
redirect = f' - {redirect_location}'
result = self.GET_RESULT_FORMAT.format(http_response.status, http_response.reason, redirect)
except socket.timeout:
result = self.ERR_HTTP_TIMEOUT
except IOError:
result = self.ERR_GENERIC
return result | [
"def",
"send_request",
"(",
"self",
",",
"ssl_client",
":",
"SslClient",
")",
"->",
"str",
":",
"try",
":",
"ssl_client",
".",
"write",
"(",
"HttpRequestGenerator",
".",
"get_request",
"(",
"self",
".",
"_hostname",
")",
")",
"# Parse the response and print the ... | Send an HTTP GET to the server and return the HTTP status code. | [
"Send",
"an",
"HTTP",
"GET",
"to",
"the",
"server",
"and",
"return",
"the",
"HTTP",
"status",
"code",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/tls_wrapped_protocol_helpers.py#L65-L90 | train | 222,153 |
nabla-c0d3/sslyze | sslyze/plugins/plugins_repository.py | PluginsRepository.get_plugin_class_for_command | def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]:
"""Get the class of the plugin implementing the supplied scan command.
"""
return self._scan_command_classes_to_plugin_classes[scan_command.__class__] | python | def get_plugin_class_for_command(self, scan_command: PluginScanCommand) -> Type[Plugin]:
"""Get the class of the plugin implementing the supplied scan command.
"""
return self._scan_command_classes_to_plugin_classes[scan_command.__class__] | [
"def",
"get_plugin_class_for_command",
"(",
"self",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"Type",
"[",
"Plugin",
"]",
":",
"return",
"self",
".",
"_scan_command_classes_to_plugin_classes",
"[",
"scan_command",
".",
"__class__",
"]"
] | Get the class of the plugin implementing the supplied scan command. | [
"Get",
"the",
"class",
"of",
"the",
"plugin",
"implementing",
"the",
"supplied",
"scan",
"command",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugins_repository.py#L44-L47 | train | 222,154 |
nabla-c0d3/sslyze | sslyze/utils/http_response_parser.py | HttpResponseParser._parse | def _parse(read_method: Callable) -> HTTPResponse:
"""Trick to standardize the API between sockets and SSLConnection objects.
"""
response = read_method(4096)
while b'HTTP/' not in response or b'\r\n\r\n' not in response:
# Parse until the end of the headers
response += read_method(4096)
fake_sock = _FakeSocket(response)
response = HTTPResponse(fake_sock) # type: ignore
response.begin()
return response | python | def _parse(read_method: Callable) -> HTTPResponse:
"""Trick to standardize the API between sockets and SSLConnection objects.
"""
response = read_method(4096)
while b'HTTP/' not in response or b'\r\n\r\n' not in response:
# Parse until the end of the headers
response += read_method(4096)
fake_sock = _FakeSocket(response)
response = HTTPResponse(fake_sock) # type: ignore
response.begin()
return response | [
"def",
"_parse",
"(",
"read_method",
":",
"Callable",
")",
"->",
"HTTPResponse",
":",
"response",
"=",
"read_method",
"(",
"4096",
")",
"while",
"b'HTTP/'",
"not",
"in",
"response",
"or",
"b'\\r\\n\\r\\n'",
"not",
"in",
"response",
":",
"# Parse until the end of... | Trick to standardize the API between sockets and SSLConnection objects. | [
"Trick",
"to",
"standardize",
"the",
"API",
"between",
"sockets",
"and",
"SSLConnection",
"objects",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/http_response_parser.py#L26-L37 | train | 222,155 |
nabla-c0d3/sslyze | sslyze/utils/thread_pool.py | _work_function | def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None:
"""Work function expected to run within threads.
"""
while True:
job = job_q.get()
if isinstance(job, _ThreadPoolSentinel):
# All the work is done, get out
result_q.put(_ThreadPoolSentinel())
error_q.put(_ThreadPoolSentinel())
job_q.task_done()
break
work_function = job[0]
args = job[1]
try:
result = work_function(*args)
except Exception as e:
error_q.put((job, e))
else:
result_q.put((job, result))
finally:
job_q.task_done() | python | def _work_function(job_q: Queue, result_q: Queue, error_q: Queue) -> None:
"""Work function expected to run within threads.
"""
while True:
job = job_q.get()
if isinstance(job, _ThreadPoolSentinel):
# All the work is done, get out
result_q.put(_ThreadPoolSentinel())
error_q.put(_ThreadPoolSentinel())
job_q.task_done()
break
work_function = job[0]
args = job[1]
try:
result = work_function(*args)
except Exception as e:
error_q.put((job, e))
else:
result_q.put((job, result))
finally:
job_q.task_done() | [
"def",
"_work_function",
"(",
"job_q",
":",
"Queue",
",",
"result_q",
":",
"Queue",
",",
"error_q",
":",
"Queue",
")",
"->",
"None",
":",
"while",
"True",
":",
"job",
"=",
"job_q",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"job",
",",
"_ThreadPo... | Work function expected to run within threads. | [
"Work",
"function",
"expected",
"to",
"run",
"within",
"threads",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/utils/thread_pool.py#L93-L115 | train | 222,156 |
nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_with_session_id | def _resume_with_session_id(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum
) -> bool:
"""Perform one session resumption using Session IDs.
"""
session1 = self._resume_ssl_session(server_info, ssl_version_to_use)
try:
# Recover the session ID
session1_id = self._extract_session_id(session1)
except IndexError:
# Session ID not assigned
return False
if session1_id == '':
# Session ID empty
return False
# Try to resume that SSL session
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1)
try:
# Recover the session ID
session2_id = self._extract_session_id(session2)
except IndexError:
# Session ID not assigned
return False
# Finally, compare the two Session IDs
if session1_id != session2_id:
# Session ID assigned but not accepted
return False
return True | python | def _resume_with_session_id(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum
) -> bool:
"""Perform one session resumption using Session IDs.
"""
session1 = self._resume_ssl_session(server_info, ssl_version_to_use)
try:
# Recover the session ID
session1_id = self._extract_session_id(session1)
except IndexError:
# Session ID not assigned
return False
if session1_id == '':
# Session ID empty
return False
# Try to resume that SSL session
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1)
try:
# Recover the session ID
session2_id = self._extract_session_id(session2)
except IndexError:
# Session ID not assigned
return False
# Finally, compare the two Session IDs
if session1_id != session2_id:
# Session ID assigned but not accepted
return False
return True | [
"def",
"_resume_with_session_id",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
")",
"->",
"bool",
":",
"session1",
"=",
"self",
".",
"_resume_ssl_session",
"(",
"server_info",
",",
"ssl_version_t... | Perform one session resumption using Session IDs. | [
"Perform",
"one",
"session",
"resumption",
"using",
"Session",
"IDs",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L151-L184 | train | 222,157 |
nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_with_session_ticket | def _resume_with_session_ticket(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
) -> TslSessionTicketSupportEnum:
"""Perform one session resumption using TLS Session Tickets.
"""
# Connect to the server and keep the SSL session
try:
session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True)
except SslHandshakeRejected:
if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3:
return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED
else:
raise
try:
# Recover the TLS ticket
session1_tls_ticket = self._extract_tls_session_ticket(session1)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Try to resume that session using the TLS ticket
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True)
try:
# Recover the TLS ticket
session2_tls_ticket = self._extract_tls_session_ticket(session2)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Finally, compare the two TLS Tickets
if session1_tls_ticket != session2_tls_ticket:
return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED
return TslSessionTicketSupportEnum.SUCCEEDED | python | def _resume_with_session_ticket(
self,
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
) -> TslSessionTicketSupportEnum:
"""Perform one session resumption using TLS Session Tickets.
"""
# Connect to the server and keep the SSL session
try:
session1 = self._resume_ssl_session(server_info, ssl_version_to_use, should_enable_tls_ticket=True)
except SslHandshakeRejected:
if server_info.highest_ssl_version_supported >= OpenSslVersionEnum.TLSV1_3:
return TslSessionTicketSupportEnum.FAILED_ONLY_TLS_1_3_SUPPORTED
else:
raise
try:
# Recover the TLS ticket
session1_tls_ticket = self._extract_tls_session_ticket(session1)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Try to resume that session using the TLS ticket
session2 = self._resume_ssl_session(server_info, ssl_version_to_use, session1, should_enable_tls_ticket=True)
try:
# Recover the TLS ticket
session2_tls_ticket = self._extract_tls_session_ticket(session2)
except IndexError:
return TslSessionTicketSupportEnum.FAILED_TICKET_NOT_ASSIGNED
# Finally, compare the two TLS Tickets
if session1_tls_ticket != session2_tls_ticket:
return TslSessionTicketSupportEnum.FAILED_TICKED_IGNORED
return TslSessionTicketSupportEnum.SUCCEEDED | [
"def",
"_resume_with_session_ticket",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
",",
")",
"->",
"TslSessionTicketSupportEnum",
":",
"# Connect to the server and keep the SSL session",
"try",
":",
"ses... | Perform one session resumption using TLS Session Tickets. | [
"Perform",
"one",
"session",
"resumption",
"using",
"TLS",
"Session",
"Tickets",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L186-L220 | train | 222,158 |
nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._extract_session_id | def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set.
"""
session_string = ((ssl_session.as_text()).split('Session-ID:'))[1]
session_id = (session_string.split('Session-ID-ctx:'))[0].strip()
return session_id | python | def _extract_session_id(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set.
"""
session_string = ((ssl_session.as_text()).split('Session-ID:'))[1]
session_id = (session_string.split('Session-ID-ctx:'))[0].strip()
return session_id | [
"def",
"_extract_session_id",
"(",
"ssl_session",
":",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
")",
"->",
"str",
":",
"session_string",
"=",
"(",
"(",
"ssl_session",
".",
"as_text",
"(",
")",
")",
".",
"split",
"(",
"'Session-ID:'",
")",
")",
"[",
"1... | Extract the SSL session ID from a SSL session object or raises IndexError if the session ID was not set. | [
"Extract",
"the",
"SSL",
"session",
"ID",
"from",
"a",
"SSL",
"session",
"object",
"or",
"raises",
"IndexError",
"if",
"the",
"session",
"ID",
"was",
"not",
"set",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L223-L228 | train | 222,159 |
nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._extract_tls_session_ticket | def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set.
"""
session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
session_tls_ticket = (session_string.split('Compression:'))[0]
return session_tls_ticket | python | def _extract_tls_session_ticket(ssl_session: nassl._nassl.SSL_SESSION) -> str:
"""Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set.
"""
session_string = ((ssl_session.as_text()).split('TLS session ticket:'))[1]
session_tls_ticket = (session_string.split('Compression:'))[0]
return session_tls_ticket | [
"def",
"_extract_tls_session_ticket",
"(",
"ssl_session",
":",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
")",
"->",
"str",
":",
"session_string",
"=",
"(",
"(",
"ssl_session",
".",
"as_text",
"(",
")",
")",
".",
"split",
"(",
"'TLS session ticket:'",
")",
... | Extract the TLS session ticket from a SSL session object or raises IndexError if the ticket was not set. | [
"Extract",
"the",
"TLS",
"session",
"ticket",
"from",
"a",
"SSL",
"session",
"object",
"or",
"raises",
"IndexError",
"if",
"the",
"ticket",
"was",
"not",
"set",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L231-L236 | train | 222,160 |
nabla-c0d3/sslyze | sslyze/plugins/session_resumption_plugin.py | SessionResumptionPlugin._resume_ssl_session | def _resume_ssl_session(
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
ssl_session: Optional[nassl._nassl.SSL_SESSION] = None,
should_enable_tls_ticket: bool = False
) -> nassl._nassl.SSL_SESSION:
"""Connect to the server and returns the session object that was assigned for that connection.
If ssl_session is given, tries to resume that session.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use)
if not should_enable_tls_ticket:
# Need to disable TLS tickets to test session IDs, according to rfc5077:
# If a ticket is presented by the client, the server MUST NOT attempt
# to use the Session ID in the ClientHello for stateful session resumption
ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets.
if ssl_session:
ssl_connection.ssl_client.set_session(ssl_session)
try:
# Perform the SSL handshake
ssl_connection.connect()
new_session = ssl_connection.ssl_client.get_session() # Get session data
finally:
ssl_connection.close()
return new_session | python | def _resume_ssl_session(
server_info: ServerConnectivityInfo,
ssl_version_to_use: OpenSslVersionEnum,
ssl_session: Optional[nassl._nassl.SSL_SESSION] = None,
should_enable_tls_ticket: bool = False
) -> nassl._nassl.SSL_SESSION:
"""Connect to the server and returns the session object that was assigned for that connection.
If ssl_session is given, tries to resume that session.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(override_ssl_version=ssl_version_to_use)
if not should_enable_tls_ticket:
# Need to disable TLS tickets to test session IDs, according to rfc5077:
# If a ticket is presented by the client, the server MUST NOT attempt
# to use the Session ID in the ClientHello for stateful session resumption
ssl_connection.ssl_client.disable_stateless_session_resumption() # Turning off TLS tickets.
if ssl_session:
ssl_connection.ssl_client.set_session(ssl_session)
try:
# Perform the SSL handshake
ssl_connection.connect()
new_session = ssl_connection.ssl_client.get_session() # Get session data
finally:
ssl_connection.close()
return new_session | [
"def",
"_resume_ssl_session",
"(",
"server_info",
":",
"ServerConnectivityInfo",
",",
"ssl_version_to_use",
":",
"OpenSslVersionEnum",
",",
"ssl_session",
":",
"Optional",
"[",
"nassl",
".",
"_nassl",
".",
"SSL_SESSION",
"]",
"=",
"None",
",",
"should_enable_tls_ticke... | Connect to the server and returns the session object that was assigned for that connection.
If ssl_session is given, tries to resume that session. | [
"Connect",
"to",
"the",
"server",
"and",
"returns",
"the",
"session",
"object",
"that",
"was",
"assigned",
"for",
"that",
"connection",
".",
"If",
"ssl_session",
"is",
"given",
"tries",
"to",
"resume",
"that",
"session",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/session_resumption_plugin.py#L239-L265 | train | 222,161 |
nabla-c0d3/sslyze | sslyze/cli/json_output.py | _object_to_json_dict | def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
"""Convert an object to a dictionary suitable for the JSON output.
"""
if isinstance(obj, Enum):
# Properly serialize Enums (such as OpenSslVersionEnum)
result = obj.name
elif isinstance(obj, ObjectIdentifier):
# Use dotted string representation for OIDs
result = obj.dotted_string
elif isinstance(obj, x509._Certificate):
# Properly serialize certificates
certificate = obj
result = { # type: ignore
# Add general info
'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),
# Add some of the fields of the cert
'subject': CertificateUtils.get_name_as_text(certificate.subject),
'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
'serialNumber': str(certificate.serial_number),
'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
'signatureAlgorithm': certificate.signature_hash_algorithm.name,
'publicKey': {
'algorithm': CertificateUtils.get_public_key_type(certificate)
},
}
dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
if dns_alt_names:
result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore
# Add some info about the public key
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore
result['publicKey']['curve'] = public_key.curve.name # type: ignore
else:
result['publicKey']['size'] = str(public_key.key_size)
result['publicKey']['exponent'] = str(public_key.public_numbers().e)
elif isinstance(obj, object):
# Some objects (like str) don't have a __dict__
if hasattr(obj, '__dict__'):
result = {}
for key, value in obj.__dict__.items():
# Remove private attributes
if key.startswith('_'):
continue
result[key] = _object_to_json_dict(value)
else:
# Simple object like a bool
result = obj
else:
raise TypeError('Unknown type: {}'.format(repr(obj)))
return result | python | def _object_to_json_dict(obj: Any) -> Union[bool, int, float, str, Dict[str, Any]]:
"""Convert an object to a dictionary suitable for the JSON output.
"""
if isinstance(obj, Enum):
# Properly serialize Enums (such as OpenSslVersionEnum)
result = obj.name
elif isinstance(obj, ObjectIdentifier):
# Use dotted string representation for OIDs
result = obj.dotted_string
elif isinstance(obj, x509._Certificate):
# Properly serialize certificates
certificate = obj
result = { # type: ignore
# Add general info
'as_pem': obj.public_bytes(Encoding.PEM).decode('ascii'),
'hpkp_pin': CertificateUtils.get_hpkp_pin(obj),
# Add some of the fields of the cert
'subject': CertificateUtils.get_name_as_text(certificate.subject),
'issuer': CertificateUtils.get_name_as_text(certificate.issuer),
'serialNumber': str(certificate.serial_number),
'notBefore': certificate.not_valid_before.strftime("%Y-%m-%d %H:%M:%S"),
'notAfter': certificate.not_valid_after.strftime("%Y-%m-%d %H:%M:%S"),
'signatureAlgorithm': certificate.signature_hash_algorithm.name,
'publicKey': {
'algorithm': CertificateUtils.get_public_key_type(certificate)
},
}
dns_alt_names = CertificateUtils.get_dns_subject_alternative_names(certificate)
if dns_alt_names:
result['subjectAlternativeName'] = {'DNS': dns_alt_names} # type: ignore
# Add some info about the public key
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
result['publicKey']['size'] = str(public_key.curve.key_size) # type: ignore
result['publicKey']['curve'] = public_key.curve.name # type: ignore
else:
result['publicKey']['size'] = str(public_key.key_size)
result['publicKey']['exponent'] = str(public_key.public_numbers().e)
elif isinstance(obj, object):
# Some objects (like str) don't have a __dict__
if hasattr(obj, '__dict__'):
result = {}
for key, value in obj.__dict__.items():
# Remove private attributes
if key.startswith('_'):
continue
result[key] = _object_to_json_dict(value)
else:
# Simple object like a bool
result = obj
else:
raise TypeError('Unknown type: {}'.format(repr(obj)))
return result | [
"def",
"_object_to_json_dict",
"(",
"obj",
":",
"Any",
")",
"->",
"Union",
"[",
"bool",
",",
"int",
",",
"float",
",",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Enum",
")",
":",
"# Properly ser... | Convert an object to a dictionary suitable for the JSON output. | [
"Convert",
"an",
"object",
"to",
"a",
"dictionary",
"suitable",
"for",
"the",
"JSON",
"output",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/cli/json_output.py#L84-L145 | train | 222,162 |
nabla-c0d3/sslyze | sslyze/plugins/certificate_info_plugin.py | CertificateInfoPlugin._get_and_verify_certificate_chain | def _get_and_verify_certificate_chain(
server_info: ServerConnectivityInfo,
trust_store: TrustStore
) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
"""Connects to the target server and uses the supplied trust store to validate the server's certificate.
Returns the server's certificate and OCSP response.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)
# Enable OCSP stapling
ssl_connection.ssl_client.set_tlsext_status_ocsp()
try: # Perform the SSL handshake
ssl_connection.connect()
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
except ClientCertificateRequested: # The server asked for a client cert
# We can get the server cert anyway
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
finally:
ssl_connection.close()
# Parse the certificates using the cryptography module
parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
for x509_cert in x509_cert_chain]
return parsed_x509_chain, verify_str, ocsp_response | python | def _get_and_verify_certificate_chain(
server_info: ServerConnectivityInfo,
trust_store: TrustStore
) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
"""Connects to the target server and uses the supplied trust store to validate the server's certificate.
Returns the server's certificate and OCSP response.
"""
ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)
# Enable OCSP stapling
ssl_connection.ssl_client.set_tlsext_status_ocsp()
try: # Perform the SSL handshake
ssl_connection.connect()
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
except ClientCertificateRequested: # The server asked for a client cert
# We can get the server cert anyway
ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
(_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()
finally:
ssl_connection.close()
# Parse the certificates using the cryptography module
parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
for x509_cert in x509_cert_chain]
return parsed_x509_chain, verify_str, ocsp_response | [
"def",
"_get_and_verify_certificate_chain",
"(",
"server_info",
":",
"ServerConnectivityInfo",
",",
"trust_store",
":",
"TrustStore",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Certificate",
"]",
",",
"str",
",",
"Optional",
"[",
"OcspResponse",
"]",
"]",
":",
"ssl_... | Connects to the target server and uses the supplied trust store to validate the server's certificate.
Returns the server's certificate and OCSP response. | [
"Connects",
"to",
"the",
"target",
"server",
"and",
"uses",
"the",
"supplied",
"trust",
"store",
"to",
"validate",
"the",
"server",
"s",
"certificate",
".",
"Returns",
"the",
"server",
"s",
"certificate",
"and",
"OCSP",
"response",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/certificate_info_plugin.py#L171-L202 | train | 222,163 |
nabla-c0d3/sslyze | sslyze/plugins/plugin_base.py | PluginScanCommand.get_description | def get_description(cls) -> str:
"""The description is expected to be the command class' docstring.
"""
if cls.__doc__ is None:
raise ValueError('No docstring found for {}'.format(cls.__name__))
return cls.__doc__.strip() | python | def get_description(cls) -> str:
"""The description is expected to be the command class' docstring.
"""
if cls.__doc__ is None:
raise ValueError('No docstring found for {}'.format(cls.__name__))
return cls.__doc__.strip() | [
"def",
"get_description",
"(",
"cls",
")",
"->",
"str",
":",
"if",
"cls",
".",
"__doc__",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No docstring found for {}'",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")",
"return",
"cls",
".",
"__doc__",
... | The description is expected to be the command class' docstring. | [
"The",
"description",
"is",
"expected",
"to",
"be",
"the",
"command",
"class",
"docstring",
"."
] | 0fb3ae668453d7ecf616d0755f237ca7be9f62fa | https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/plugin_base.py#L30-L35 | train | 222,164 |
kennethreitz/inbox.py | inbox.py | Inbox.serve | def serve(self, port=None, address=None):
"""Serves the SMTP server on the given port and address."""
port = port or self.port
address = address or self.address
log.info('Starting SMTP server at {0}:{1}'.format(address, port))
server = InboxServer(self.collator, (address, port), None)
try:
asyncore.loop()
except KeyboardInterrupt:
log.info('Cleaning up') | python | def serve(self, port=None, address=None):
"""Serves the SMTP server on the given port and address."""
port = port or self.port
address = address or self.address
log.info('Starting SMTP server at {0}:{1}'.format(address, port))
server = InboxServer(self.collator, (address, port), None)
try:
asyncore.loop()
except KeyboardInterrupt:
log.info('Cleaning up') | [
"def",
"serve",
"(",
"self",
",",
"port",
"=",
"None",
",",
"address",
"=",
"None",
")",
":",
"port",
"=",
"port",
"or",
"self",
".",
"port",
"address",
"=",
"address",
"or",
"self",
".",
"address",
"log",
".",
"info",
"(",
"'Starting SMTP server at {0... | Serves the SMTP server on the given port and address. | [
"Serves",
"the",
"SMTP",
"server",
"on",
"the",
"given",
"port",
"and",
"address",
"."
] | 493f8d9834a41ac9012f13da5693697efdcb1826 | https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L41-L53 | train | 222,165 |
kennethreitz/inbox.py | inbox.py | Inbox.dispatch | def dispatch(self):
"""Command-line dispatch."""
parser = argparse.ArgumentParser(description='Run an Inbox server.')
parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to')
parser.add_argument('port', metavar='port', type=int, help='port to bind to')
args = parser.parse_args()
self.serve(port=args.port, address=args.addr) | python | def dispatch(self):
"""Command-line dispatch."""
parser = argparse.ArgumentParser(description='Run an Inbox server.')
parser.add_argument('addr', metavar='addr', type=str, help='addr to bind to')
parser.add_argument('port', metavar='port', type=int, help='port to bind to')
args = parser.parse_args()
self.serve(port=args.port, address=args.addr) | [
"def",
"dispatch",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Run an Inbox server.'",
")",
"parser",
".",
"add_argument",
"(",
"'addr'",
",",
"metavar",
"=",
"'addr'",
",",
"type",
"=",
"str",
",",
"... | Command-line dispatch. | [
"Command",
"-",
"line",
"dispatch",
"."
] | 493f8d9834a41ac9012f13da5693697efdcb1826 | https://github.com/kennethreitz/inbox.py/blob/493f8d9834a41ac9012f13da5693697efdcb1826/inbox.py#L55-L64 | train | 222,166 |
securestate/termineter | lib/c1219/data.py | format_ltime | def format_ltime(endianess, tm_format, data):
"""
Return data formatted into a human readable time stamp.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bytes data: The packed and machine-formatted data to parse
:rtype: str
"""
if tm_format == 0:
return ''
elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type
y = data[0]
year = '????'
if 90 <= y <= 99:
year = '19' + str(y)
elif 0 <= y <= 9:
year = '200' + str(y)
elif 10 <= y <= 89:
year = '20' + str(y)
month = data[1]
day = data[2]
hour = data[3]
minute = data[4]
second = data[5]
elif tm_format == 3 or tm_format == 4:
if tm_format == 3:
u_time = float(struct.unpack(endianess + 'I', data[0:4])[0])
second = float(data[4])
final_time = time.gmtime((u_time * 60) + second)
elif tm_format == 4:
final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0]))
year = str(final_time.tm_year)
month = str(final_time.tm_mon)
day = str(final_time.tm_mday)
hour = str(final_time.tm_hour)
minute = str(final_time.tm_min)
second = str(final_time.tm_sec)
return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second) | python | def format_ltime(endianess, tm_format, data):
"""
Return data formatted into a human readable time stamp.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bytes data: The packed and machine-formatted data to parse
:rtype: str
"""
if tm_format == 0:
return ''
elif tm_format == 1 or tm_format == 2: # I can't find solid documentation on the BCD data-type
y = data[0]
year = '????'
if 90 <= y <= 99:
year = '19' + str(y)
elif 0 <= y <= 9:
year = '200' + str(y)
elif 10 <= y <= 89:
year = '20' + str(y)
month = data[1]
day = data[2]
hour = data[3]
minute = data[4]
second = data[5]
elif tm_format == 3 or tm_format == 4:
if tm_format == 3:
u_time = float(struct.unpack(endianess + 'I', data[0:4])[0])
second = float(data[4])
final_time = time.gmtime((u_time * 60) + second)
elif tm_format == 4:
final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0]))
year = str(final_time.tm_year)
month = str(final_time.tm_mon)
day = str(final_time.tm_mday)
hour = str(final_time.tm_hour)
minute = str(final_time.tm_min)
second = str(final_time.tm_sec)
return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second) | [
"def",
"format_ltime",
"(",
"endianess",
",",
"tm_format",
",",
"data",
")",
":",
"if",
"tm_format",
"==",
"0",
":",
"return",
"''",
"elif",
"tm_format",
"==",
"1",
"or",
"tm_format",
"==",
"2",
":",
"# I can't find solid documentation on the BCD data-type",
"y"... | Return data formatted into a human readable time stamp.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bytes data: The packed and machine-formatted data to parse
:rtype: str | [
"Return",
"data",
"formatted",
"into",
"a",
"human",
"readable",
"time",
"stamp",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L40-L80 | train | 222,167 |
securestate/termineter | lib/c1219/data.py | get_history_entry_record | def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
"""
Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bool event_number_flag: Whether or not an event number is included.
:param bool hist_seq_nbr_flag: Whether or not an history sequence number
is included.
:param str data: The packed and machine-formatted data to parse
:rtype: dict
"""
rcd = {}
if hist_date_time_flag:
tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)])
if tmstmp:
rcd['Time'] = tmstmp
data = data[LTIME_LENGTH.get(tm_format):]
if event_number_flag:
rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
if hist_seq_nbr_flag:
rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0]
rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2]
rcd['Arguments'] = data[4:]
return rcd | python | def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
"""
Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bool event_number_flag: Whether or not an event number is included.
:param bool hist_seq_nbr_flag: Whether or not an history sequence number
is included.
:param str data: The packed and machine-formatted data to parse
:rtype: dict
"""
rcd = {}
if hist_date_time_flag:
tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)])
if tmstmp:
rcd['Time'] = tmstmp
data = data[LTIME_LENGTH.get(tm_format):]
if event_number_flag:
rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
if hist_seq_nbr_flag:
rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0]
data = data[2:]
rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0]
rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2]
rcd['Arguments'] = data[4:]
return rcd | [
"def",
"get_history_entry_record",
"(",
"endianess",
",",
"hist_date_time_flag",
",",
"tm_format",
",",
"event_number_flag",
",",
"hist_seq_nbr_flag",
",",
"data",
")",
":",
"rcd",
"=",
"{",
"}",
"if",
"hist_date_time_flag",
":",
"tmstmp",
"=",
"format_ltime",
"("... | Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
:param bool event_number_flag: Whether or not an event number is included.
:param bool hist_seq_nbr_flag: Whether or not an history sequence number
is included.
:param str data: The packed and machine-formatted data to parse
:rtype: dict | [
"Return",
"data",
"formatted",
"into",
"a",
"log",
"entry",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L82-L111 | train | 222,168 |
securestate/termineter | lib/c1219/data.py | get_table_idbb_field | def get_table_idbb_field(endianess, data):
"""
Return data from a packed TABLE_IDB_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 0x7ff
std_vs_mfg = bool(bfld & 0x800)
selector = (bfld & 0xf000) >> 12
return (proc_nbr, std_vs_mfg, selector) | python | def get_table_idbb_field(endianess, data):
"""
Return data from a packed TABLE_IDB_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 0x7ff
std_vs_mfg = bool(bfld & 0x800)
selector = (bfld & 0xf000) >> 12
return (proc_nbr, std_vs_mfg, selector) | [
"def",
"get_table_idbb_field",
"(",
"endianess",
",",
"data",
")",
":",
"bfld",
"=",
"struct",
".",
"unpack",
"(",
"endianess",
"+",
"'H'",
",",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"proc_nbr",
"=",
"bfld",
"&",
"0x7ff",
"std_vs_mfg",
"=",... | Return data from a packed TABLE_IDB_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg) | [
"Return",
"data",
"from",
"a",
"packed",
"TABLE_IDB_BFLD",
"bit",
"-",
"field",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L113-L126 | train | 222,169 |
securestate/termineter | lib/c1219/data.py | get_table_idcb_field | def get_table_idcb_field(endianess, data):
"""
Return data from a packed TABLE_IDC_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 2047
std_vs_mfg = bool(bfld & 2048)
proc_flag = bool(bfld & 4096)
flag1 = bool(bfld & 8192)
flag2 = bool(bfld & 16384)
flag3 = bool(bfld & 32768)
return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | python | def get_table_idcb_field(endianess, data):
"""
Return data from a packed TABLE_IDC_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
"""
bfld = struct.unpack(endianess + 'H', data[:2])[0]
proc_nbr = bfld & 2047
std_vs_mfg = bool(bfld & 2048)
proc_flag = bool(bfld & 4096)
flag1 = bool(bfld & 8192)
flag2 = bool(bfld & 16384)
flag3 = bool(bfld & 32768)
return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | [
"def",
"get_table_idcb_field",
"(",
"endianess",
",",
"data",
")",
":",
"bfld",
"=",
"struct",
".",
"unpack",
"(",
"endianess",
"+",
"'H'",
",",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"proc_nbr",
"=",
"bfld",
"&",
"2047",
"std_vs_mfg",
"=",
... | Return data from a packed TABLE_IDC_BFLD bit-field.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param str data: The packed and machine-formatted data to parse
:rtype: tuple
:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3) | [
"Return",
"data",
"from",
"a",
"packed",
"TABLE_IDC_BFLD",
"bit",
"-",
"field",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1219/data.py#L128-L144 | train | 222,170 |
securestate/termineter | lib/termineter/utilities.py | unique | def unique(seq, idfunc=None):
"""
Unique a list or tuple and preserve the order
@type idfunc: Function or None
@param idfunc: If idfunc is provided it will be called during the
comparison process.
"""
if idfunc is None:
idfunc = lambda x: x
preserved_type = type(seq)
seen = {}
result = []
for item in seq:
marker = idfunc(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return preserved_type(result) | python | def unique(seq, idfunc=None):
"""
Unique a list or tuple and preserve the order
@type idfunc: Function or None
@param idfunc: If idfunc is provided it will be called during the
comparison process.
"""
if idfunc is None:
idfunc = lambda x: x
preserved_type = type(seq)
seen = {}
result = []
for item in seq:
marker = idfunc(item)
if marker in seen:
continue
seen[marker] = 1
result.append(item)
return preserved_type(result) | [
"def",
"unique",
"(",
"seq",
",",
"idfunc",
"=",
"None",
")",
":",
"if",
"idfunc",
"is",
"None",
":",
"idfunc",
"=",
"lambda",
"x",
":",
"x",
"preserved_type",
"=",
"type",
"(",
"seq",
")",
"seen",
"=",
"{",
"}",
"result",
"=",
"[",
"]",
"for",
... | Unique a list or tuple and preserve the order
@type idfunc: Function or None
@param idfunc: If idfunc is provided it will be called during the
comparison process. | [
"Unique",
"a",
"list",
"or",
"tuple",
"and",
"preserve",
"the",
"order"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/utilities.py#L63-L82 | train | 222,171 |
securestate/termineter | lib/termineter/interface.py | InteractiveInterpreter.do_ipy | def do_ipy(self, args):
"""Start an interactive Python interpreter"""
import c1218.data
import c1219.data
from c1219.access.general import C1219GeneralAccess
from c1219.access.security import C1219SecurityAccess
from c1219.access.log import C1219LogAccess
from c1219.access.telephone import C1219TelephoneAccess
vars = {
'termineter.__version__': termineter.__version__,
'C1218Packet': c1218.data.C1218Packet,
'C1218ReadRequest': c1218.data.C1218ReadRequest,
'C1218WriteRequest': c1218.data.C1218WriteRequest,
'C1219ProcedureInit': c1219.data.C1219ProcedureInit,
'C1219GeneralAccess': C1219GeneralAccess,
'C1219SecurityAccess': C1219SecurityAccess,
'C1219LogAccess': C1219LogAccess,
'C1219TelephoneAccess': C1219TelephoneAccess,
'frmwk': self.frmwk,
'os': os,
'sys': sys
}
banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep
banner += os.linesep
banner += 'The framework instance is in the \'frmwk\' variable.'
if self.frmwk.is_serial_connected():
vars['conn'] = self.frmwk.serial_connection
banner += os.linesep
banner += 'The connection instance is in the \'conn\' variable.'
try:
import IPython.terminal.embed
except ImportError:
pyconsole = code.InteractiveConsole(vars)
savestdin = os.dup(sys.stdin.fileno())
savestdout = os.dup(sys.stdout.fileno())
savestderr = os.dup(sys.stderr.fileno())
try:
pyconsole.interact(banner)
except SystemExit:
sys.stdin = os.fdopen(savestdin, 'r', 0)
sys.stdout = os.fdopen(savestdout, 'w', 0)
sys.stderr = os.fdopen(savestderr, 'w', 0)
else:
self.print_line(banner)
pyconsole = IPython.terminal.embed.InteractiveShellEmbed(
ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython')
)
pyconsole.mainloop(vars) | python | def do_ipy(self, args):
"""Start an interactive Python interpreter"""
import c1218.data
import c1219.data
from c1219.access.general import C1219GeneralAccess
from c1219.access.security import C1219SecurityAccess
from c1219.access.log import C1219LogAccess
from c1219.access.telephone import C1219TelephoneAccess
vars = {
'termineter.__version__': termineter.__version__,
'C1218Packet': c1218.data.C1218Packet,
'C1218ReadRequest': c1218.data.C1218ReadRequest,
'C1218WriteRequest': c1218.data.C1218WriteRequest,
'C1219ProcedureInit': c1219.data.C1219ProcedureInit,
'C1219GeneralAccess': C1219GeneralAccess,
'C1219SecurityAccess': C1219SecurityAccess,
'C1219LogAccess': C1219LogAccess,
'C1219TelephoneAccess': C1219TelephoneAccess,
'frmwk': self.frmwk,
'os': os,
'sys': sys
}
banner = 'Python ' + sys.version + ' on ' + sys.platform + os.linesep
banner += os.linesep
banner += 'The framework instance is in the \'frmwk\' variable.'
if self.frmwk.is_serial_connected():
vars['conn'] = self.frmwk.serial_connection
banner += os.linesep
banner += 'The connection instance is in the \'conn\' variable.'
try:
import IPython.terminal.embed
except ImportError:
pyconsole = code.InteractiveConsole(vars)
savestdin = os.dup(sys.stdin.fileno())
savestdout = os.dup(sys.stdout.fileno())
savestderr = os.dup(sys.stderr.fileno())
try:
pyconsole.interact(banner)
except SystemExit:
sys.stdin = os.fdopen(savestdin, 'r', 0)
sys.stdout = os.fdopen(savestdout, 'w', 0)
sys.stderr = os.fdopen(savestderr, 'w', 0)
else:
self.print_line(banner)
pyconsole = IPython.terminal.embed.InteractiveShellEmbed(
ipython_dir=os.path.join(self.frmwk.directories.user_data, 'ipython')
)
pyconsole.mainloop(vars) | [
"def",
"do_ipy",
"(",
"self",
",",
"args",
")",
":",
"import",
"c1218",
".",
"data",
"import",
"c1219",
".",
"data",
"from",
"c1219",
".",
"access",
".",
"general",
"import",
"C1219GeneralAccess",
"from",
"c1219",
".",
"access",
".",
"security",
"import",
... | Start an interactive Python interpreter | [
"Start",
"an",
"interactive",
"Python",
"interpreter"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L308-L355 | train | 222,172 |
securestate/termineter | lib/termineter/interface.py | InteractiveInterpreter.do_reload | def do_reload(self, args):
"""Reload a module in to the framework"""
if args.module is not None:
if args.module not in self.frmwk.modules:
self.print_error('Invalid Module Selected.')
return
module = self.frmwk.modules[args.module]
elif self.frmwk.current_module:
module = self.frmwk.current_module
else:
self.print_error('Must \'use\' module first')
return
self.reload_module(module) | python | def do_reload(self, args):
"""Reload a module in to the framework"""
if args.module is not None:
if args.module not in self.frmwk.modules:
self.print_error('Invalid Module Selected.')
return
module = self.frmwk.modules[args.module]
elif self.frmwk.current_module:
module = self.frmwk.current_module
else:
self.print_error('Must \'use\' module first')
return
self.reload_module(module) | [
"def",
"do_reload",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"module",
"is",
"not",
"None",
":",
"if",
"args",
".",
"module",
"not",
"in",
"self",
".",
"frmwk",
".",
"modules",
":",
"self",
".",
"print_error",
"(",
"'Invalid Module Select... | Reload a module in to the framework | [
"Reload",
"a",
"module",
"in",
"to",
"the",
"framework"
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/interface.py#L428-L440 | train | 222,173 |
securestate/termineter | lib/c1218/connection.py | ConnectionBase.send | def send(self, data):
"""
This sends a raw C12.18 frame and waits checks for an ACK response.
In the event that a NACK is received, this function will attempt
to resend the frame up to 3 times.
:param data: the data to be transmitted
:type data: str, :py:class:`~c1218.data.C1218Packet`
"""
if not isinstance(data, C1218Packet):
data = C1218Packet(data)
if self.toggle_control: # bit wise, fuck yeah
if self._toggle_bit:
data.set_control(ord(data.control) | 0x20)
self._toggle_bit = False
elif not self._toggle_bit:
if ord(data.control) & 0x20:
data.set_control(ord(data.control) ^ 0x20)
self._toggle_bit = True
elif self.toggle_control and not isinstance(data, C1218Packet):
self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance')
data = data.build()
self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
for pktcount in range(0, 3):
self.write(data)
response = self.serial_h.read(1)
if response == NACK:
self.loggerio.warning('received a NACK after writing data')
time.sleep(0.10)
elif len(response) == 0:
self.loggerio.error('received empty response after writing data')
time.sleep(0.10)
elif response != ACK:
self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data')
else:
return
self.loggerio.critical('failed 3 times to correctly send a frame')
raise C1218IOError('failed 3 times to correctly send a frame') | python | def send(self, data):
"""
This sends a raw C12.18 frame and waits checks for an ACK response.
In the event that a NACK is received, this function will attempt
to resend the frame up to 3 times.
:param data: the data to be transmitted
:type data: str, :py:class:`~c1218.data.C1218Packet`
"""
if not isinstance(data, C1218Packet):
data = C1218Packet(data)
if self.toggle_control: # bit wise, fuck yeah
if self._toggle_bit:
data.set_control(ord(data.control) | 0x20)
self._toggle_bit = False
elif not self._toggle_bit:
if ord(data.control) & 0x20:
data.set_control(ord(data.control) ^ 0x20)
self._toggle_bit = True
elif self.toggle_control and not isinstance(data, C1218Packet):
self.loggerio.warning('toggle bit is on but the data is not a C1218Packet instance')
data = data.build()
self.loggerio.debug("sending frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
for pktcount in range(0, 3):
self.write(data)
response = self.serial_h.read(1)
if response == NACK:
self.loggerio.warning('received a NACK after writing data')
time.sleep(0.10)
elif len(response) == 0:
self.loggerio.error('received empty response after writing data')
time.sleep(0.10)
elif response != ACK:
self.loggerio.error('received unknown response: ' + hex(ord(response)) + ' after writing data')
else:
return
self.loggerio.critical('failed 3 times to correctly send a frame')
raise C1218IOError('failed 3 times to correctly send a frame') | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"C1218Packet",
")",
":",
"data",
"=",
"C1218Packet",
"(",
"data",
")",
"if",
"self",
".",
"toggle_control",
":",
"# bit wise, fuck yeah",
"if",
"self",
".",
... | This sends a raw C12.18 frame and waits checks for an ACK response.
In the event that a NACK is received, this function will attempt
to resend the frame up to 3 times.
:param data: the data to be transmitted
:type data: str, :py:class:`~c1218.data.C1218Packet` | [
"This",
"sends",
"a",
"raw",
"C12",
".",
"18",
"frame",
"and",
"waits",
"checks",
"for",
"an",
"ACK",
"response",
".",
"In",
"the",
"event",
"that",
"a",
"NACK",
"is",
"received",
"this",
"function",
"will",
"attempt",
"to",
"resend",
"the",
"frame",
"... | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L120-L157 | train | 222,174 |
securestate/termineter | lib/c1218/connection.py | ConnectionBase.recv | def recv(self, full_frame=False):
"""
Receive a C1218Packet, the payload data is returned.
:param bool full_frame: If set to True, the entire C1218 frame is
returned instead of just the payload.
"""
payloadbuffer = b''
tries = 3
while tries:
tmpbuffer = self.serial_h.read(1)
if tmpbuffer != b'\xee':
self.loggerio.error('did not receive \\xee as the first byte of the frame')
self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
tries -= 1
continue
tmpbuffer += self.serial_h.read(5)
sequence, length = struct.unpack('>xxxBH', tmpbuffer)
payload = self.serial_h.read(length)
tmpbuffer += payload
chksum = self.serial_h.read(2)
if chksum == packet_checksum(tmpbuffer):
self.serial_h.write(ACK)
data = tmpbuffer + chksum
self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
payloadbuffer += payload
if sequence == 0:
if full_frame:
payloadbuffer = data
if sys.version_info[0] == 2:
payloadbuffer = bytearray(payloadbuffer)
return payloadbuffer
else:
tries = 3
else:
self.serial_h.write(NACK)
self.loggerio.warning('crc does not match on received frame')
tries -= 1
self.loggerio.critical('failed 3 times to correctly receive a frame')
raise C1218IOError('failed 3 times to correctly receive a frame') | python | def recv(self, full_frame=False):
"""
Receive a C1218Packet, the payload data is returned.
:param bool full_frame: If set to True, the entire C1218 frame is
returned instead of just the payload.
"""
payloadbuffer = b''
tries = 3
while tries:
tmpbuffer = self.serial_h.read(1)
if tmpbuffer != b'\xee':
self.loggerio.error('did not receive \\xee as the first byte of the frame')
self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
tries -= 1
continue
tmpbuffer += self.serial_h.read(5)
sequence, length = struct.unpack('>xxxBH', tmpbuffer)
payload = self.serial_h.read(length)
tmpbuffer += payload
chksum = self.serial_h.read(2)
if chksum == packet_checksum(tmpbuffer):
self.serial_h.write(ACK)
data = tmpbuffer + chksum
self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
payloadbuffer += payload
if sequence == 0:
if full_frame:
payloadbuffer = data
if sys.version_info[0] == 2:
payloadbuffer = bytearray(payloadbuffer)
return payloadbuffer
else:
tries = 3
else:
self.serial_h.write(NACK)
self.loggerio.warning('crc does not match on received frame')
tries -= 1
self.loggerio.critical('failed 3 times to correctly receive a frame')
raise C1218IOError('failed 3 times to correctly receive a frame') | [
"def",
"recv",
"(",
"self",
",",
"full_frame",
"=",
"False",
")",
":",
"payloadbuffer",
"=",
"b''",
"tries",
"=",
"3",
"while",
"tries",
":",
"tmpbuffer",
"=",
"self",
".",
"serial_h",
".",
"read",
"(",
"1",
")",
"if",
"tmpbuffer",
"!=",
"b'\\xee'",
... | Receive a C1218Packet, the payload data is returned.
:param bool full_frame: If set to True, the entire C1218 frame is
returned instead of just the payload. | [
"Receive",
"a",
"C1218Packet",
"the",
"payload",
"data",
"is",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L159-L198 | train | 222,175 |
securestate/termineter | lib/c1218/connection.py | ConnectionBase.read | def read(self, size):
"""
Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection.
"""
data = self.serial_h.read(size)
self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8'))
self.serial_h.write(ACK)
if sys.version_info[0] == 2:
data = bytearray(data)
return data | python | def read(self, size):
"""
Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection.
"""
data = self.serial_h.read(size)
self.logger.debug('read data, length: ' + str(len(data)) + ' data: ' + binascii.b2a_hex(data).decode('utf-8'))
self.serial_h.write(ACK)
if sys.version_info[0] == 2:
data = bytearray(data)
return data | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"data",
"=",
"self",
".",
"serial_h",
".",
"read",
"(",
"size",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'read data, length: '",
"+",
"str",
"(",
"len",
"(",
"data",
")",
")",
"+",
"' data: ... | Read raw data from the serial connection. This function is not
meant to be called directly.
:param int size: The number of bytes to read from the serial connection. | [
"Read",
"raw",
"data",
"from",
"the",
"serial",
"connection",
".",
"This",
"function",
"is",
"not",
"meant",
"to",
"be",
"called",
"directly",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L210-L222 | train | 222,176 |
securestate/termineter | lib/c1218/connection.py | ConnectionBase.close | def close(self):
"""
Send a terminate request and then disconnect from the serial device.
"""
if self._initialized:
self.stop()
self.logged_in = False
return self.serial_h.close() | python | def close(self):
"""
Send a terminate request and then disconnect from the serial device.
"""
if self._initialized:
self.stop()
self.logged_in = False
return self.serial_h.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"logged_in",
"=",
"False",
"return",
"self",
".",
"serial_h",
".",
"close",
"(",
")"
] | Send a terminate request and then disconnect from the serial device. | [
"Send",
"a",
"terminate",
"request",
"and",
"then",
"disconnect",
"from",
"the",
"serial",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L224-L231 | train | 222,177 |
securestate/termineter | lib/c1218/connection.py | Connection.start | def start(self):
"""
Send an identity request and then a negotiation request.
"""
self.serial_h.flushOutput()
self.serial_h.flushInput()
self.send(C1218IdentRequest())
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to identification service request')
return False
self._initialized = True
self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600))
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to negotiate service request')
self.stop()
raise C1218NegotiateError('received incorrect response to negotiate service request', data[0])
return True | python | def start(self):
"""
Send an identity request and then a negotiation request.
"""
self.serial_h.flushOutput()
self.serial_h.flushInput()
self.send(C1218IdentRequest())
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to identification service request')
return False
self._initialized = True
self.send(C1218NegotiateRequest(self.c1218_pktsize, self.c1218_nbrpkts, baudrate=9600))
data = self.recv()
if data[0] != 0x00:
self.logger.error('received incorrect response to negotiate service request')
self.stop()
raise C1218NegotiateError('received incorrect response to negotiate service request', data[0])
return True | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"serial_h",
".",
"flushOutput",
"(",
")",
"self",
".",
"serial_h",
".",
"flushInput",
"(",
")",
"self",
".",
"send",
"(",
"C1218IdentRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
... | Send an identity request and then a negotiation request. | [
"Send",
"an",
"identity",
"request",
"and",
"then",
"a",
"negotiation",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L278-L297 | train | 222,178 |
securestate/termineter | lib/c1218/connection.py | Connection.stop | def stop(self, force=False):
"""
Send a terminate request.
:param bool force: ignore the remote devices response
"""
if self._initialized:
self.send(C1218TerminateRequest())
data = self.recv()
if data == b'\x00' or force:
self._initialized = False
self._toggle_bit = False
return True
return False | python | def stop(self, force=False):
"""
Send a terminate request.
:param bool force: ignore the remote devices response
"""
if self._initialized:
self.send(C1218TerminateRequest())
data = self.recv()
if data == b'\x00' or force:
self._initialized = False
self._toggle_bit = False
return True
return False | [
"def",
"stop",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"send",
"(",
"C1218TerminateRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
"if",
"data",
"==",
"b'\\x00'",
... | Send a terminate request.
:param bool force: ignore the remote devices response | [
"Send",
"a",
"terminate",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L299-L312 | train | 222,179 |
securestate/termineter | lib/c1218/connection.py | Connection.login | def login(self, username='0000', userid=0, password=None):
"""
Log into the connected device.
:param str username: the username to log in with (len(username) <= 10)
:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)
:param str password: password to log in with (len(password) <= 20)
:rtype: bool
"""
if password and len(password) > 20:
self.logger.error('password longer than 20 characters received')
raise Exception('password longer than 20 characters, login failed')
self.send(C1218LogonRequest(username, userid))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, username and user id rejected')
return False
if password is not None:
self.send(C1218SecurityRequest(password))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, password rejected')
return False
self.logged_in = True
return True | python | def login(self, username='0000', userid=0, password=None):
"""
Log into the connected device.
:param str username: the username to log in with (len(username) <= 10)
:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)
:param str password: password to log in with (len(password) <= 20)
:rtype: bool
"""
if password and len(password) > 20:
self.logger.error('password longer than 20 characters received')
raise Exception('password longer than 20 characters, login failed')
self.send(C1218LogonRequest(username, userid))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, username and user id rejected')
return False
if password is not None:
self.send(C1218SecurityRequest(password))
data = self.recv()
if data != b'\x00':
self.logger.warning('login failed, password rejected')
return False
self.logged_in = True
return True | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"'0000'",
",",
"userid",
"=",
"0",
",",
"password",
"=",
"None",
")",
":",
"if",
"password",
"and",
"len",
"(",
"password",
")",
">",
"20",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'password... | Log into the connected device.
:param str username: the username to log in with (len(username) <= 10)
:param int userid: the userid to log in with (0x0000 <= userid <= 0xffff)
:param str password: password to log in with (len(password) <= 20)
:rtype: bool | [
"Log",
"into",
"the",
"connected",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L314-L341 | train | 222,180 |
securestate/termineter | lib/c1218/connection.py | Connection.logoff | def logoff(self):
"""
Send a logoff request.
:rtype: bool
"""
self.send(C1218LogoffRequest())
data = self.recv()
if data == b'\x00':
self._initialized = False
return True
return False | python | def logoff(self):
"""
Send a logoff request.
:rtype: bool
"""
self.send(C1218LogoffRequest())
data = self.recv()
if data == b'\x00':
self._initialized = False
return True
return False | [
"def",
"logoff",
"(",
"self",
")",
":",
"self",
".",
"send",
"(",
"C1218LogoffRequest",
"(",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
"if",
"data",
"==",
"b'\\x00'",
":",
"self",
".",
"_initialized",
"=",
"False",
"return",
"True",
"retu... | Send a logoff request.
:rtype: bool | [
"Send",
"a",
"logoff",
"request",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L343-L354 | train | 222,181 |
securestate/termineter | lib/c1218/connection.py | Connection.get_table_data | def get_table_data(self, tableid, octetcount=None, offset=None):
"""
Read data from a table. If successful, all of the data from the
requested table will be returned.
:param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff)
:param int octetcount: Limit the amount of data read, only works if
the meter supports this type of reading.
:param int offset: The offset at which to start to read the data from.
"""
if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys():
self.logger.info('returning cached table #' + str(tableid))
return self._table_cache[tableid]
self.send(C1218ReadRequest(tableid, offset, octetcount))
data = self.recv()
status = data[0]
if status != 0x00:
status = status
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details)
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status)
if len(data) < 4:
if len(data) == 0:
self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned')
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
length = struct.unpack('>H', data[1:3])[0]
chksum = data[-1]
data = data[3:-1]
if len(data) != length:
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
if not check_data_checksum(data, chksum):
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum')
if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys():
self.logger.info('caching table #' + str(tableid))
self._table_cache[tableid] = data
return data | python | def get_table_data(self, tableid, octetcount=None, offset=None):
"""
Read data from a table. If successful, all of the data from the
requested table will be returned.
:param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff)
:param int octetcount: Limit the amount of data read, only works if
the meter supports this type of reading.
:param int offset: The offset at which to start to read the data from.
"""
if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys():
self.logger.info('returning cached table #' + str(tableid))
return self._table_cache[tableid]
self.send(C1218ReadRequest(tableid, offset, octetcount))
data = self.recv()
status = data[0]
if status != 0x00:
status = status
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not read table id: ' + str(tableid) + ', error: ' + details)
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: ' + details, status)
if len(data) < 4:
if len(data) == 0:
self.logger.error('could not read table id: ' + str(tableid) + ', error: no data was returned')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: no data was returned')
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length (less than 4)')
length = struct.unpack('>H', data[1:3])[0]
chksum = data[-1]
data = data[3:-1]
if len(data) != length:
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid length')
if not check_data_checksum(data, chksum):
self.logger.error('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid check sum')
raise C1218ReadTableError('could not read table id: ' + str(tableid) + ', error: data read was corrupt, invalid checksum')
if self.caching_enabled and tableid in self._cacheable_tables and not tableid in self._table_cache.keys():
self.logger.info('caching table #' + str(tableid))
self._table_cache[tableid] = data
return data | [
"def",
"get_table_data",
"(",
"self",
",",
"tableid",
",",
"octetcount",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"if",
"self",
".",
"caching_enabled",
"and",
"tableid",
"in",
"self",
".",
"_cacheable_tables",
"and",
"tableid",
"in",
"self",
".",... | Read data from a table. If successful, all of the data from the
requested table will be returned.
:param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff)
:param int octetcount: Limit the amount of data read, only works if
the meter supports this type of reading.
:param int offset: The offset at which to start to read the data from. | [
"Read",
"data",
"from",
"a",
"table",
".",
"If",
"successful",
"all",
"of",
"the",
"data",
"from",
"the",
"requested",
"table",
"will",
"be",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L356-L396 | train | 222,182 |
securestate/termineter | lib/c1218/connection.py | Connection.set_table_data | def set_table_data(self, tableid, data, offset=None):
"""
Write data to a table.
:param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff)
:param str data: The data to write into the table.
:param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff).
"""
self.send(C1218WriteRequest(tableid, data, offset))
data = self.recv()
if data[0] != 0x00:
status = data[0]
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not write data to the table, error: ' + details)
raise C1218WriteTableError('could not write data to the table, error: ' + details, status)
return | python | def set_table_data(self, tableid, data, offset=None):
"""
Write data to a table.
:param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff)
:param str data: The data to write into the table.
:param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff).
"""
self.send(C1218WriteRequest(tableid, data, offset))
data = self.recv()
if data[0] != 0x00:
status = data[0]
details = (C1218_RESPONSE_CODES.get(status) or 'unknown response code')
self.logger.error('could not write data to the table, error: ' + details)
raise C1218WriteTableError('could not write data to the table, error: ' + details, status)
return | [
"def",
"set_table_data",
"(",
"self",
",",
"tableid",
",",
"data",
",",
"offset",
"=",
"None",
")",
":",
"self",
".",
"send",
"(",
"C1218WriteRequest",
"(",
"tableid",
",",
"data",
",",
"offset",
")",
")",
"data",
"=",
"self",
".",
"recv",
"(",
")",
... | Write data to a table.
:param int tableid: The table number to write to (0x0000 <= tableid <= 0xffff)
:param str data: The data to write into the table.
:param int offset: The offset at which to start to write the data (0x000000 <= octetcount <= 0xffffff). | [
"Write",
"data",
"to",
"a",
"table",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L398-L413 | train | 222,183 |
securestate/termineter | lib/c1218/connection.py | Connection.run_procedure | def run_procedure(self, process_number, std_vs_mfg, params=''):
"""
Initiate a C1219 procedure, the request is written to table 7 and
the response is read from table 8.
:param int process_number: The numeric procedure identifier (0 <= process_number <= 2047).
:param bool std_vs_mfg: Whether the procedure is manufacturer specified
or not. True is manufacturer specified.
:param bytes params: The parameters to pass to the procedure initiation request.
:return: A tuple of the result code and the response data.
:rtype: tuple
"""
seqnum = random.randint(2, 254)
self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')')
procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build()
self.set_table_data(7, procedure_request)
response = self.get_table_data(8)
if response[:3] == procedure_request[:3]:
return response[3], response[4:]
else:
self.logger.error('invalid response from procedure response table (table #8)')
raise C1219ProcedureError('invalid response from procedure response table (table #8)') | python | def run_procedure(self, process_number, std_vs_mfg, params=''):
"""
Initiate a C1219 procedure, the request is written to table 7 and
the response is read from table 8.
:param int process_number: The numeric procedure identifier (0 <= process_number <= 2047).
:param bool std_vs_mfg: Whether the procedure is manufacturer specified
or not. True is manufacturer specified.
:param bytes params: The parameters to pass to the procedure initiation request.
:return: A tuple of the result code and the response data.
:rtype: tuple
"""
seqnum = random.randint(2, 254)
self.logger.info('starting procedure: ' + str(process_number) + ' (' + hex(process_number) + ') sequence number: ' + str(seqnum) + ' (' + hex(seqnum) + ')')
procedure_request = C1219ProcedureInit(self.c1219_endian, process_number, std_vs_mfg, 0, seqnum, params).build()
self.set_table_data(7, procedure_request)
response = self.get_table_data(8)
if response[:3] == procedure_request[:3]:
return response[3], response[4:]
else:
self.logger.error('invalid response from procedure response table (table #8)')
raise C1219ProcedureError('invalid response from procedure response table (table #8)') | [
"def",
"run_procedure",
"(",
"self",
",",
"process_number",
",",
"std_vs_mfg",
",",
"params",
"=",
"''",
")",
":",
"seqnum",
"=",
"random",
".",
"randint",
"(",
"2",
",",
"254",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'starting procedure: '",
"+",... | Initiate a C1219 procedure, the request is written to table 7 and
the response is read from table 8.
:param int process_number: The numeric procedure identifier (0 <= process_number <= 2047).
:param bool std_vs_mfg: Whether the procedure is manufacturer specified
or not. True is manufacturer specified.
:param bytes params: The parameters to pass to the procedure initiation request.
:return: A tuple of the result code and the response data.
:rtype: tuple | [
"Initiate",
"a",
"C1219",
"procedure",
"the",
"request",
"is",
"written",
"to",
"table",
"7",
"and",
"the",
"response",
"is",
"read",
"from",
"table",
"8",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/c1218/connection.py#L415-L437 | train | 222,184 |
securestate/termineter | lib/termineter/options.py | Options.add_string | def add_string(self, name, help, required=True, default=None):
"""
Add a new option with a type of String.
:param str name: The name of the option, how it will be referenced.
:param str help: The string returned as help to describe how the option is used.
:param bool required: Whether to require that this option be set or not.
:param str default: The default value for this option. If required is True and the user must specify it, set to anything but None.
"""
self._options[name] = Option(name, 'str', help, required, default=default) | python | def add_string(self, name, help, required=True, default=None):
"""
Add a new option with a type of String.
:param str name: The name of the option, how it will be referenced.
:param str help: The string returned as help to describe how the option is used.
:param bool required: Whether to require that this option be set or not.
:param str default: The default value for this option. If required is True and the user must specify it, set to anything but None.
"""
self._options[name] = Option(name, 'str', help, required, default=default) | [
"def",
"add_string",
"(",
"self",
",",
"name",
",",
"help",
",",
"required",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_options",
"[",
"name",
"]",
"=",
"Option",
"(",
"name",
",",
"'str'",
",",
"help",
",",
"required",
",",... | Add a new option with a type of String.
:param str name: The name of the option, how it will be referenced.
:param str help: The string returned as help to describe how the option is used.
:param bool required: Whether to require that this option be set or not.
:param str default: The default value for this option. If required is True and the user must specify it, set to anything but None. | [
"Add",
"a",
"new",
"option",
"with",
"a",
"type",
"of",
"String",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L80-L89 | train | 222,185 |
securestate/termineter | lib/termineter/options.py | Options.set_option_value | def set_option_value(self, name, value):
"""
Set an option's value.
:param str name: The name of the option to set the value for.
:param str value: The value to set the option to, it will be converted from a string.
:return: The previous value for the specified option.
"""
option = self.get_option(name)
old_value = option.value
if option.type in ('str', 'rfile'):
option.value = value
elif option.type == 'int':
value = value.lower()
if not value.isdigit():
if value.startswith('0x') and string_is_hex(value[2:]):
value = int(value[2:], 16)
else:
raise TypeError('invalid value type')
option.value = int(value)
elif option.type == 'flt':
if value.count('.') > 1:
raise TypeError('invalid value type')
if not value.replace('.', '').isdigit():
raise TypeError('invalid value type')
option.value = float(value)
elif option.type == 'bool':
if value.lower() in ['true', '1', 'on']:
option.value = True
elif value.lower() in ['false', '0', 'off']:
option.value = False
else:
raise TypeError('invalid value type')
else:
raise Exception('unknown value type')
if option.callback and not option.callback(value, old_value):
option.value = old_value
return False
return True | python | def set_option_value(self, name, value):
"""
Set an option's value.
:param str name: The name of the option to set the value for.
:param str value: The value to set the option to, it will be converted from a string.
:return: The previous value for the specified option.
"""
option = self.get_option(name)
old_value = option.value
if option.type in ('str', 'rfile'):
option.value = value
elif option.type == 'int':
value = value.lower()
if not value.isdigit():
if value.startswith('0x') and string_is_hex(value[2:]):
value = int(value[2:], 16)
else:
raise TypeError('invalid value type')
option.value = int(value)
elif option.type == 'flt':
if value.count('.') > 1:
raise TypeError('invalid value type')
if not value.replace('.', '').isdigit():
raise TypeError('invalid value type')
option.value = float(value)
elif option.type == 'bool':
if value.lower() in ['true', '1', 'on']:
option.value = True
elif value.lower() in ['false', '0', 'off']:
option.value = False
else:
raise TypeError('invalid value type')
else:
raise Exception('unknown value type')
if option.callback and not option.callback(value, old_value):
option.value = old_value
return False
return True | [
"def",
"set_option_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"option",
"=",
"self",
".",
"get_option",
"(",
"name",
")",
"old_value",
"=",
"option",
".",
"value",
"if",
"option",
".",
"type",
"in",
"(",
"'str'",
",",
"'rfile'",
")",
"... | Set an option's value.
:param str name: The name of the option to set the value for.
:param str value: The value to set the option to, it will be converted from a string.
:return: The previous value for the specified option. | [
"Set",
"an",
"option",
"s",
"value",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L153-L191 | train | 222,186 |
securestate/termineter | lib/termineter/options.py | Options.get_missing_options | def get_missing_options(self):
"""
Get a list of options that are required, but with default values
of None.
"""
return [option.name for option in self._options.values() if option.required and option.value is None] | python | def get_missing_options(self):
"""
Get a list of options that are required, but with default values
of None.
"""
return [option.name for option in self._options.values() if option.required and option.value is None] | [
"def",
"get_missing_options",
"(",
"self",
")",
":",
"return",
"[",
"option",
".",
"name",
"for",
"option",
"in",
"self",
".",
"_options",
".",
"values",
"(",
")",
"if",
"option",
".",
"required",
"and",
"option",
".",
"value",
"is",
"None",
"]"
] | Get a list of options that are required, but with default values
of None. | [
"Get",
"a",
"list",
"of",
"options",
"that",
"are",
"required",
"but",
"with",
"default",
"values",
"of",
"None",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L193-L198 | train | 222,187 |
securestate/termineter | lib/termineter/__init__.py | get_revision | def get_revision():
"""
Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:return: The git revision tag if it's available.
:rtype: str
"""
git_bin = smoke_zephyr.utilities.which('git')
if not git_bin:
return None
proc_h = subprocess.Popen(
(git_bin, 'rev-parse', 'HEAD'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
rev = proc_h.stdout.read().strip()
proc_h.wait()
if not len(rev):
return None
return rev.decode('utf-8') | python | def get_revision():
"""
Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:return: The git revision tag if it's available.
:rtype: str
"""
git_bin = smoke_zephyr.utilities.which('git')
if not git_bin:
return None
proc_h = subprocess.Popen(
(git_bin, 'rev-parse', 'HEAD'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
rev = proc_h.stdout.read().strip()
proc_h.wait()
if not len(rev):
return None
return rev.decode('utf-8') | [
"def",
"get_revision",
"(",
")",
":",
"git_bin",
"=",
"smoke_zephyr",
".",
"utilities",
".",
"which",
"(",
"'git'",
")",
"if",
"not",
"git_bin",
":",
"return",
"None",
"proc_h",
"=",
"subprocess",
".",
"Popen",
"(",
"(",
"git_bin",
",",
"'rev-parse'",
",... | Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:return: The git revision tag if it's available.
:rtype: str | [
"Retrieve",
"the",
"current",
"git",
"revision",
"identifier",
".",
"If",
"the",
"git",
"binary",
"can",
"not",
"be",
"found",
"or",
"the",
"repository",
"information",
"is",
"unavailable",
"None",
"will",
"be",
"returned",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/__init__.py#L42-L64 | train | 222,188 |
securestate/termineter | lib/termineter/core.py | Framework.reload_module | def reload_module(self, module_path=None):
"""
Reloads a module into the framework. If module_path is not
specified, then the current_module variable is used. Returns True
on success, False on error.
@type module_path: String
@param module_path: The name of the module to reload
"""
if module_path is None:
if self.current_module is not None:
module_path = self.current_module.name
else:
self.logger.warning('must specify module if not module is currently being used')
return False
if module_path not in self.module:
self.logger.error('invalid module requested for reload')
raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload')
self.logger.info('reloading module: ' + module_path)
module_instance = self.import_module(module_path, reload_module=True)
if not isinstance(module_instance, termineter.module.TermineterModule):
self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class')
if not hasattr(module_instance, 'run'):
self.logger.error('module: ' + module_path + ' has no run() method')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method')
if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options):
self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances')
raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances')
module_instance.name = module_path.split('/')[-1]
module_instance.path = module_path
self.modules[module_path] = module_instance
if self.current_module is not None:
if self.current_module.path == module_instance.path:
self.current_module = module_instance
return True | python | def reload_module(self, module_path=None):
"""
Reloads a module into the framework. If module_path is not
specified, then the current_module variable is used. Returns True
on success, False on error.
@type module_path: String
@param module_path: The name of the module to reload
"""
if module_path is None:
if self.current_module is not None:
module_path = self.current_module.name
else:
self.logger.warning('must specify module if not module is currently being used')
return False
if module_path not in self.module:
self.logger.error('invalid module requested for reload')
raise termineter.errors.FrameworkRuntimeError('invalid module requested for reload')
self.logger.info('reloading module: ' + module_path)
module_instance = self.import_module(module_path, reload_module=True)
if not isinstance(module_instance, termineter.module.TermineterModule):
self.logger.error('module: ' + module_path + ' is not derived from the TermineterModule class')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' is not derived from the TermineterModule class')
if not hasattr(module_instance, 'run'):
self.logger.error('module: ' + module_path + ' has no run() method')
raise termineter.errors.FrameworkRuntimeError('module: ' + module_path + ' has no run() method')
if not isinstance(module_instance.options, termineter.options.Options) or not isinstance(module_instance.advanced_options, termineter.options.Options):
self.logger.error('module: ' + module_path + ' options and advanced_options must be termineter.options.Options instances')
raise termineter.errors.FrameworkRuntimeError('options and advanced_options must be termineter.options.Options instances')
module_instance.name = module_path.split('/')[-1]
module_instance.path = module_path
self.modules[module_path] = module_instance
if self.current_module is not None:
if self.current_module.path == module_instance.path:
self.current_module = module_instance
return True | [
"def",
"reload_module",
"(",
"self",
",",
"module_path",
"=",
"None",
")",
":",
"if",
"module_path",
"is",
"None",
":",
"if",
"self",
".",
"current_module",
"is",
"not",
"None",
":",
"module_path",
"=",
"self",
".",
"current_module",
".",
"name",
"else",
... | Reloads a module into the framework. If module_path is not
specified, then the current_module variable is used. Returns True
on success, False on error.
@type module_path: String
@param module_path: The name of the module to reload | [
"Reloads",
"a",
"module",
"into",
"the",
"framework",
".",
"If",
"module_path",
"is",
"not",
"specified",
"then",
"the",
"current_module",
"variable",
"is",
"used",
".",
"Returns",
"True",
"on",
"success",
"False",
"on",
"error",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L168-L204 | train | 222,189 |
securestate/termineter | lib/termineter/core.py | Framework.serial_disconnect | def serial_disconnect(self):
"""
Closes the serial connection to the meter and disconnects from the
device.
"""
if self._serial_connected:
try:
self.serial_connection.close()
except c1218.errors.C1218IOError as error:
self.logger.error('caught C1218IOError: ' + str(error))
except serial.serialutil.SerialException as error:
self.logger.error('caught SerialException: ' + str(error))
self._serial_connected = False
self.logger.warning('the serial interface has been disconnected')
return True | python | def serial_disconnect(self):
"""
Closes the serial connection to the meter and disconnects from the
device.
"""
if self._serial_connected:
try:
self.serial_connection.close()
except c1218.errors.C1218IOError as error:
self.logger.error('caught C1218IOError: ' + str(error))
except serial.serialutil.SerialException as error:
self.logger.error('caught SerialException: ' + str(error))
self._serial_connected = False
self.logger.warning('the serial interface has been disconnected')
return True | [
"def",
"serial_disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_serial_connected",
":",
"try",
":",
"self",
".",
"serial_connection",
".",
"close",
"(",
")",
"except",
"c1218",
".",
"errors",
".",
"C1218IOError",
"as",
"error",
":",
"self",
".",
... | Closes the serial connection to the meter and disconnects from the
device. | [
"Closes",
"the",
"serial",
"connection",
"to",
"the",
"meter",
"and",
"disconnects",
"from",
"the",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L324-L338 | train | 222,190 |
securestate/termineter | lib/termineter/core.py | Framework.serial_get | def serial_get(self):
"""
Create the serial connection from the framework settings and return
it, setting the framework instance in the process.
"""
frmwk_c1218_settings = {
'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'],
'pktsize': self.advanced_options['C1218_PACKET_SIZE']
}
frmwk_serial_settings = termineter.utilities.get_default_serial_settings()
frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE']
frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE']
frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS']
self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION'])
try:
self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES'])
except Exception as error:
self.logger.error('could not open the serial device')
raise error
return self.serial_connection | python | def serial_get(self):
"""
Create the serial connection from the framework settings and return
it, setting the framework instance in the process.
"""
frmwk_c1218_settings = {
'nbrpkts': self.advanced_options['C1218_MAX_PACKETS'],
'pktsize': self.advanced_options['C1218_PACKET_SIZE']
}
frmwk_serial_settings = termineter.utilities.get_default_serial_settings()
frmwk_serial_settings['baudrate'] = self.advanced_options['SERIAL_BAUD_RATE']
frmwk_serial_settings['bytesize'] = self.advanced_options['SERIAL_BYTE_SIZE']
frmwk_serial_settings['stopbits'] = self.advanced_options['SERIAL_STOP_BITS']
self.logger.info('opening serial device: ' + self.options['SERIAL_CONNECTION'])
try:
self.serial_connection = c1218.connection.Connection(self.options['SERIAL_CONNECTION'], c1218_settings=frmwk_c1218_settings, serial_settings=frmwk_serial_settings, enable_cache=self.advanced_options['CACHE_TABLES'])
except Exception as error:
self.logger.error('could not open the serial device')
raise error
return self.serial_connection | [
"def",
"serial_get",
"(",
"self",
")",
":",
"frmwk_c1218_settings",
"=",
"{",
"'nbrpkts'",
":",
"self",
".",
"advanced_options",
"[",
"'C1218_MAX_PACKETS'",
"]",
",",
"'pktsize'",
":",
"self",
".",
"advanced_options",
"[",
"'C1218_PACKET_SIZE'",
"]",
"}",
"frmwk... | Create the serial connection from the framework settings and return
it, setting the framework instance in the process. | [
"Create",
"the",
"serial",
"connection",
"from",
"the",
"framework",
"settings",
"and",
"return",
"it",
"setting",
"the",
"framework",
"instance",
"in",
"the",
"process",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L340-L361 | train | 222,191 |
securestate/termineter | lib/termineter/core.py | Framework.serial_connect | def serial_connect(self):
"""
Connect to the serial device.
"""
self.serial_get()
try:
self.serial_connection.start()
except c1218.errors.C1218IOError as error:
self.logger.error('serial connection has been opened but the meter is unresponsive')
raise error
self._serial_connected = True
return True | python | def serial_connect(self):
"""
Connect to the serial device.
"""
self.serial_get()
try:
self.serial_connection.start()
except c1218.errors.C1218IOError as error:
self.logger.error('serial connection has been opened but the meter is unresponsive')
raise error
self._serial_connected = True
return True | [
"def",
"serial_connect",
"(",
"self",
")",
":",
"self",
".",
"serial_get",
"(",
")",
"try",
":",
"self",
".",
"serial_connection",
".",
"start",
"(",
")",
"except",
"c1218",
".",
"errors",
".",
"C1218IOError",
"as",
"error",
":",
"self",
".",
"logger",
... | Connect to the serial device. | [
"Connect",
"to",
"the",
"serial",
"device",
"."
] | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L363-L374 | train | 222,192 |
securestate/termineter | lib/termineter/core.py | Framework.serial_login | def serial_login(self):
"""
Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be
called by modules in order to login with a username and password configured within the framework instance.
"""
if not self._serial_connected:
raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected')
username = self.options['USERNAME']
user_id = self.options['USER_ID']
password = self.options['PASSWORD']
if self.options['PASSWORD_HEX']:
hex_regex = re.compile('^([0-9a-fA-F]{2})+$')
if hex_regex.match(password) is None:
self.print_error('Invalid characters in password')
raise termineter.errors.FrameworkConfigurationError('invalid characters in password')
password = binascii.a2b_hex(password)
if len(username) > 10:
self.print_error('Username cannot be longer than 10 characters')
raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters')
if not (0 <= user_id <= 0xffff):
self.print_error('User id must be between 0 and 0xffff')
raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff')
if len(password) > 20:
self.print_error('Password cannot be longer than 20 characters')
raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters')
if not self.serial_connection.login(username, user_id, password):
return False
return True | python | def serial_login(self):
"""
Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be
called by modules in order to login with a username and password configured within the framework instance.
"""
if not self._serial_connected:
raise termineter.errors.FrameworkRuntimeError('the serial interface is disconnected')
username = self.options['USERNAME']
user_id = self.options['USER_ID']
password = self.options['PASSWORD']
if self.options['PASSWORD_HEX']:
hex_regex = re.compile('^([0-9a-fA-F]{2})+$')
if hex_regex.match(password) is None:
self.print_error('Invalid characters in password')
raise termineter.errors.FrameworkConfigurationError('invalid characters in password')
password = binascii.a2b_hex(password)
if len(username) > 10:
self.print_error('Username cannot be longer than 10 characters')
raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters')
if not (0 <= user_id <= 0xffff):
self.print_error('User id must be between 0 and 0xffff')
raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff')
if len(password) > 20:
self.print_error('Password cannot be longer than 20 characters')
raise termineter.errors.FrameworkConfigurationError('password cannot be longer than 20 characters')
if not self.serial_connection.login(username, user_id, password):
return False
return True | [
"def",
"serial_login",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_serial_connected",
":",
"raise",
"termineter",
".",
"errors",
".",
"FrameworkRuntimeError",
"(",
"'the serial interface is disconnected'",
")",
"username",
"=",
"self",
".",
"options",
"[",
... | Attempt to log into the meter over the C12.18 protocol. Returns True on success, False on a failure. This can be
called by modules in order to login with a username and password configured within the framework instance. | [
"Attempt",
"to",
"log",
"into",
"the",
"meter",
"over",
"the",
"C12",
".",
"18",
"protocol",
".",
"Returns",
"True",
"on",
"success",
"False",
"on",
"a",
"failure",
".",
"This",
"can",
"be",
"called",
"by",
"modules",
"in",
"order",
"to",
"login",
"wit... | d657d25d97c7739e650b951c396404e857e56625 | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/core.py#L376-L405 | train | 222,193 |
MasoniteFramework/masonite | databases/seeds/user_table_seeder.py | UserTableSeeder.run | def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | python | def run(self):
"""
Run the database seeds.
"""
self.factory.register(User, self.users_factory)
self.factory(User, 50).create() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"register",
"(",
"User",
",",
"self",
".",
"users_factory",
")",
"self",
".",
"factory",
"(",
"User",
",",
"50",
")",
".",
"create",
"(",
")"
] | Run the database seeds. | [
"Run",
"the",
"database",
"seeds",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/seeds/user_table_seeder.py#L18-L24 | train | 222,194 |
MasoniteFramework/masonite | bootstrap/start.py | app | def app(environ, start_response):
"""The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response
"""
from wsgi import container
"""Add Environ To Service Container
Add the environ to the service container. The environ is generated by the
the WSGI server above and used by a service provider to manipulate the
incoming requests
"""
container.bind('Environ', environ)
"""Execute All Service Providers That Require The WSGI Server
Run all service provider boot methods if the wsgi attribute is true.
"""
try:
for provider in container.make('WSGIProviders'):
container.resolve(provider.boot)
except Exception as e:
container.make('ExceptionHandler').load_exception(e)
"""We Are Ready For Launch
If we have a solid response and not redirecting then we need to return
a 200 status code along with the data. If we don't, then we'll have
to return a 302 redirection to where ever the user would like go
to next.
"""
start_response(container.make('Request').get_status_code(),
container.make('Request').get_and_reset_headers())
"""Final Step
This will take the data variable from the Service Container and return
it to the WSGI server.
"""
return iter([bytes(container.make('Response'), 'utf-8')]) | python | def app(environ, start_response):
"""The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response
"""
from wsgi import container
"""Add Environ To Service Container
Add the environ to the service container. The environ is generated by the
the WSGI server above and used by a service provider to manipulate the
incoming requests
"""
container.bind('Environ', environ)
"""Execute All Service Providers That Require The WSGI Server
Run all service provider boot methods if the wsgi attribute is true.
"""
try:
for provider in container.make('WSGIProviders'):
container.resolve(provider.boot)
except Exception as e:
container.make('ExceptionHandler').load_exception(e)
"""We Are Ready For Launch
If we have a solid response and not redirecting then we need to return
a 200 status code along with the data. If we don't, then we'll have
to return a 302 redirection to where ever the user would like go
to next.
"""
start_response(container.make('Request').get_status_code(),
container.make('Request').get_and_reset_headers())
"""Final Step
This will take the data variable from the Service Container and return
it to the WSGI server.
"""
return iter([bytes(container.make('Response'), 'utf-8')]) | [
"def",
"app",
"(",
"environ",
",",
"start_response",
")",
":",
"from",
"wsgi",
"import",
"container",
"\"\"\"Add Environ To Service Container\n Add the environ to the service container. The environ is generated by the\n the WSGI server above and used by a service provider to manipulate... | The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response | [
"The",
"WSGI",
"Application",
"Server",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/bootstrap/start.py#L12-L57 | train | 222,195 |
MasoniteFramework/masonite | databases/migrations/2018_01_09_043202_create_users_table.py | CreateUsersTable.up | def up(self):
"""Run the migrations."""
with self.schema.create('users') as table:
table.increments('id')
table.string('name')
table.string('email').unique()
table.string('password')
table.string('remember_token').nullable()
table.timestamp('verified_at').nullable()
table.timestamps() | python | def up(self):
"""Run the migrations."""
with self.schema.create('users') as table:
table.increments('id')
table.string('name')
table.string('email').unique()
table.string('password')
table.string('remember_token').nullable()
table.timestamp('verified_at').nullable()
table.timestamps() | [
"def",
"up",
"(",
"self",
")",
":",
"with",
"self",
".",
"schema",
".",
"create",
"(",
"'users'",
")",
"as",
"table",
":",
"table",
".",
"increments",
"(",
"'id'",
")",
"table",
".",
"string",
"(",
"'name'",
")",
"table",
".",
"string",
"(",
"'emai... | Run the migrations. | [
"Run",
"the",
"migrations",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/databases/migrations/2018_01_09_043202_create_users_table.py#L6-L15 | train | 222,196 |
MasoniteFramework/masonite | app/http/middleware/VerifyEmailMiddleware.py | VerifyEmailMiddleware.before | def before(self):
"""Run This Middleware Before The Route Executes."""
user = self.request.user()
if user and user.verified_at is None:
self.request.redirect('/email/verify') | python | def before(self):
"""Run This Middleware Before The Route Executes."""
user = self.request.user()
if user and user.verified_at is None:
self.request.redirect('/email/verify') | [
"def",
"before",
"(",
"self",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"(",
")",
"if",
"user",
"and",
"user",
".",
"verified_at",
"is",
"None",
":",
"self",
".",
"request",
".",
"redirect",
"(",
"'/email/verify'",
")"
] | Run This Middleware Before The Route Executes. | [
"Run",
"This",
"Middleware",
"Before",
"The",
"Route",
"Executes",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/middleware/VerifyEmailMiddleware.py#L17-L22 | train | 222,197 |
MasoniteFramework/masonite | app/http/controllers/WelcomeController.py | WelcomeController.show | def show(self, view: View, request: Request):
"""Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class.
"""
return view.render('welcome', {
'app': request.app().make('Application')
}) | python | def show(self, view: View, request: Request):
"""Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class.
"""
return view.render('welcome', {
'app': request.app().make('Application')
}) | [
"def",
"show",
"(",
"self",
",",
"view",
":",
"View",
",",
"request",
":",
"Request",
")",
":",
"return",
"view",
".",
"render",
"(",
"'welcome'",
",",
"{",
"'app'",
":",
"request",
".",
"app",
"(",
")",
".",
"make",
"(",
"'Application'",
")",
"}",... | Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class. | [
"Show",
"the",
"welcome",
"page",
"."
] | c9bcca8f59169934c2accd8cecb2b996bb5e1a0d | https://github.com/MasoniteFramework/masonite/blob/c9bcca8f59169934c2accd8cecb2b996bb5e1a0d/app/http/controllers/WelcomeController.py#L10-L22 | train | 222,198 |
pybluez/pybluez | bluetooth/btcommon.py | is_valid_address | def is_valid_address (s):
"""
returns True if address is a valid Bluetooth address
valid address are always strings of the form XX:XX:XX:XX:XX:XX
where X is a hexadecimal character. For example,
01:23:45:67:89:AB is a valid address, but
IN:VA:LI:DA:DD:RE is not
"""
try:
pairs = s.split (":")
if len (pairs) != 6: return False
if not all(0 <= int(b, 16) <= 255 for b in pairs): return False
except:
return False
return True | python | def is_valid_address (s):
"""
returns True if address is a valid Bluetooth address
valid address are always strings of the form XX:XX:XX:XX:XX:XX
where X is a hexadecimal character. For example,
01:23:45:67:89:AB is a valid address, but
IN:VA:LI:DA:DD:RE is not
"""
try:
pairs = s.split (":")
if len (pairs) != 6: return False
if not all(0 <= int(b, 16) <= 255 for b in pairs): return False
except:
return False
return True | [
"def",
"is_valid_address",
"(",
"s",
")",
":",
"try",
":",
"pairs",
"=",
"s",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"pairs",
")",
"!=",
"6",
":",
"return",
"False",
"if",
"not",
"all",
"(",
"0",
"<=",
"int",
"(",
"b",
",",
"16",
... | returns True if address is a valid Bluetooth address
valid address are always strings of the form XX:XX:XX:XX:XX:XX
where X is a hexadecimal character. For example,
01:23:45:67:89:AB is a valid address, but
IN:VA:LI:DA:DD:RE is not | [
"returns",
"True",
"if",
"address",
"is",
"a",
"valid",
"Bluetooth",
"address"
] | e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9 | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/bluetooth/btcommon.py#L182-L197 | train | 222,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.