id int32 0 252k | 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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,100 | RedHatInsights/insights-core | insights/combiners/uptime.py | uptime | def uptime(ut, facter):
"""Check uptime and facts to get the uptime information.
Prefer uptime to facts.
Returns:
insights.combiners.uptime.Uptime: A named tuple with `currtime`,
`updays`, `uphhmm`, `users`, `loadavg` and `uptime` components.
Raises:
Exception: If no data is available from both of the parsers.
"""
ut = ut
if ut and ut.loadavg:
return Uptime(ut.currtime, ut.updays, ut.uphhmm,
ut.users, ut.loadavg, ut.uptime)
ft = facter
if ft and hasattr(ft, 'uptime_seconds'):
import datetime
secs = int(ft.uptime_seconds)
up_dd = secs // (3600 * 24)
up_hh = (secs % (3600 * 24)) // 3600
up_mm = (secs % 3600) // 60
updays = str(up_dd) if up_dd > 0 else ''
uphhmm = '%02d:%02d' % (up_hh, up_mm)
up_time = datetime.timedelta(seconds=secs)
return Uptime(None, updays, uphhmm, None, None, up_time)
raise Exception("Unable to get uptime information.") | python | def uptime(ut, facter):
"""Check uptime and facts to get the uptime information.
Prefer uptime to facts.
Returns:
insights.combiners.uptime.Uptime: A named tuple with `currtime`,
`updays`, `uphhmm`, `users`, `loadavg` and `uptime` components.
Raises:
Exception: If no data is available from both of the parsers.
"""
ut = ut
if ut and ut.loadavg:
return Uptime(ut.currtime, ut.updays, ut.uphhmm,
ut.users, ut.loadavg, ut.uptime)
ft = facter
if ft and hasattr(ft, 'uptime_seconds'):
import datetime
secs = int(ft.uptime_seconds)
up_dd = secs // (3600 * 24)
up_hh = (secs % (3600 * 24)) // 3600
up_mm = (secs % 3600) // 60
updays = str(up_dd) if up_dd > 0 else ''
uphhmm = '%02d:%02d' % (up_hh, up_mm)
up_time = datetime.timedelta(seconds=secs)
return Uptime(None, updays, uphhmm, None, None, up_time)
raise Exception("Unable to get uptime information.") | [
"def",
"uptime",
"(",
"ut",
",",
"facter",
")",
":",
"ut",
"=",
"ut",
"if",
"ut",
"and",
"ut",
".",
"loadavg",
":",
"return",
"Uptime",
"(",
"ut",
".",
"currtime",
",",
"ut",
".",
"updays",
",",
"ut",
".",
"uphhmm",
",",
"ut",
".",
"users",
","... | Check uptime and facts to get the uptime information.
Prefer uptime to facts.
Returns:
insights.combiners.uptime.Uptime: A named tuple with `currtime`,
`updays`, `uphhmm`, `users`, `loadavg` and `uptime` components.
Raises:
Exception: If no data is available from both of the parsers. | [
"Check",
"uptime",
"and",
"facts",
"to",
"get",
"the",
"uptime",
"information",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/uptime.py#L31-L60 |
226,101 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/utils/__init__.py | get_node | def get_node(service_name, host_name):
"""Generates Node message from params and system information.
"""
return common_pb2.Node(
identifier=common_pb2.ProcessIdentifier(
host_name=socket.gethostname() if host_name is None
else host_name,
pid=os.getpid(),
start_timestamp=proto_ts_from_datetime(
datetime.datetime.utcnow())),
library_info=common_pb2.LibraryInfo(
language=common_pb2.LibraryInfo.Language.Value('PYTHON'),
exporter_version=EXPORTER_VERSION,
core_library_version=opencensus_version),
service_info=common_pb2.ServiceInfo(name=service_name)) | python | def get_node(service_name, host_name):
"""Generates Node message from params and system information.
"""
return common_pb2.Node(
identifier=common_pb2.ProcessIdentifier(
host_name=socket.gethostname() if host_name is None
else host_name,
pid=os.getpid(),
start_timestamp=proto_ts_from_datetime(
datetime.datetime.utcnow())),
library_info=common_pb2.LibraryInfo(
language=common_pb2.LibraryInfo.Language.Value('PYTHON'),
exporter_version=EXPORTER_VERSION,
core_library_version=opencensus_version),
service_info=common_pb2.ServiceInfo(name=service_name)) | [
"def",
"get_node",
"(",
"service_name",
",",
"host_name",
")",
":",
"return",
"common_pb2",
".",
"Node",
"(",
"identifier",
"=",
"common_pb2",
".",
"ProcessIdentifier",
"(",
"host_name",
"=",
"socket",
".",
"gethostname",
"(",
")",
"if",
"host_name",
"is",
"... | Generates Node message from params and system information. | [
"Generates",
"Node",
"message",
"from",
"params",
"and",
"system",
"information",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/utils/__init__.py#L17-L31 |
226,102 | census-instrumentation/opencensus-python | opencensus/trace/tracers/context_tracer.py | ContextTracer.end_span | def end_span(self, *args, **kwargs):
"""End a span. Update the span_id in SpanContext to the current span's
parent span id; Update the current span.
"""
cur_span = self.current_span()
if cur_span is None and self._spans_list:
cur_span = self._spans_list[-1]
if cur_span is None:
logging.warning('No active span, cannot do end_span.')
return
cur_span.finish()
self.span_context.span_id = cur_span.parent_span.span_id if \
cur_span.parent_span else None
if isinstance(cur_span.parent_span, trace_span.Span):
execution_context.set_current_span(cur_span.parent_span)
else:
execution_context.set_current_span(None)
with self._spans_list_condition:
if cur_span in self._spans_list:
span_datas = self.get_span_datas(cur_span)
self.exporter.export(span_datas)
self._spans_list.remove(cur_span)
return cur_span | python | def end_span(self, *args, **kwargs):
"""End a span. Update the span_id in SpanContext to the current span's
parent span id; Update the current span.
"""
cur_span = self.current_span()
if cur_span is None and self._spans_list:
cur_span = self._spans_list[-1]
if cur_span is None:
logging.warning('No active span, cannot do end_span.')
return
cur_span.finish()
self.span_context.span_id = cur_span.parent_span.span_id if \
cur_span.parent_span else None
if isinstance(cur_span.parent_span, trace_span.Span):
execution_context.set_current_span(cur_span.parent_span)
else:
execution_context.set_current_span(None)
with self._spans_list_condition:
if cur_span in self._spans_list:
span_datas = self.get_span_datas(cur_span)
self.exporter.export(span_datas)
self._spans_list.remove(cur_span)
return cur_span | [
"def",
"end_span",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cur_span",
"=",
"self",
".",
"current_span",
"(",
")",
"if",
"cur_span",
"is",
"None",
"and",
"self",
".",
"_spans_list",
":",
"cur_span",
"=",
"self",
".",
"_spans... | End a span. Update the span_id in SpanContext to the current span's
parent span id; Update the current span. | [
"End",
"a",
"span",
".",
"Update",
"the",
"span_id",
"in",
"SpanContext",
"to",
"the",
"current",
"span",
"s",
"parent",
"span",
"id",
";",
"Update",
"the",
"current",
"span",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L99-L126 |
226,103 | census-instrumentation/opencensus-python | opencensus/trace/tracers/context_tracer.py | ContextTracer.add_attribute_to_current_span | def add_attribute_to_current_span(self, attribute_key, attribute_value):
"""Add attribute to current span.
:type attribute_key: str
:param attribute_key: Attribute key.
:type attribute_value:str
:param attribute_value: Attribute value.
"""
current_span = self.current_span()
current_span.add_attribute(attribute_key, attribute_value) | python | def add_attribute_to_current_span(self, attribute_key, attribute_value):
"""Add attribute to current span.
:type attribute_key: str
:param attribute_key: Attribute key.
:type attribute_value:str
:param attribute_value: Attribute value.
"""
current_span = self.current_span()
current_span.add_attribute(attribute_key, attribute_value) | [
"def",
"add_attribute_to_current_span",
"(",
"self",
",",
"attribute_key",
",",
"attribute_value",
")",
":",
"current_span",
"=",
"self",
".",
"current_span",
"(",
")",
"current_span",
".",
"add_attribute",
"(",
"attribute_key",
",",
"attribute_value",
")"
] | Add attribute to current span.
:type attribute_key: str
:param attribute_key: Attribute key.
:type attribute_value:str
:param attribute_value: Attribute value. | [
"Add",
"attribute",
"to",
"current",
"span",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L137-L147 |
226,104 | census-instrumentation/opencensus-python | opencensus/trace/tracers/context_tracer.py | ContextTracer.get_span_datas | def get_span_datas(self, span):
"""Extracts a list of SpanData tuples from a span
:rtype: list of opencensus.trace.span_data.SpanData
:return list of SpanData tuples
"""
span_datas = [
span_data_module.SpanData(
name=ss.name,
context=self.span_context,
span_id=ss.span_id,
parent_span_id=ss.parent_span.span_id if
ss.parent_span else None,
attributes=ss.attributes,
start_time=ss.start_time,
end_time=ss.end_time,
child_span_count=len(ss.children),
stack_trace=ss.stack_trace,
time_events=ss.time_events,
links=ss.links,
status=ss.status,
same_process_as_parent_span=ss.same_process_as_parent_span,
span_kind=ss.span_kind
)
for ss in span
]
return span_datas | python | def get_span_datas(self, span):
"""Extracts a list of SpanData tuples from a span
:rtype: list of opencensus.trace.span_data.SpanData
:return list of SpanData tuples
"""
span_datas = [
span_data_module.SpanData(
name=ss.name,
context=self.span_context,
span_id=ss.span_id,
parent_span_id=ss.parent_span.span_id if
ss.parent_span else None,
attributes=ss.attributes,
start_time=ss.start_time,
end_time=ss.end_time,
child_span_count=len(ss.children),
stack_trace=ss.stack_trace,
time_events=ss.time_events,
links=ss.links,
status=ss.status,
same_process_as_parent_span=ss.same_process_as_parent_span,
span_kind=ss.span_kind
)
for ss in span
]
return span_datas | [
"def",
"get_span_datas",
"(",
"self",
",",
"span",
")",
":",
"span_datas",
"=",
"[",
"span_data_module",
".",
"SpanData",
"(",
"name",
"=",
"ss",
".",
"name",
",",
"context",
"=",
"self",
".",
"span_context",
",",
"span_id",
"=",
"ss",
".",
"span_id",
... | Extracts a list of SpanData tuples from a span
:rtype: list of opencensus.trace.span_data.SpanData
:return list of SpanData tuples | [
"Extracts",
"a",
"list",
"of",
"SpanData",
"tuples",
"from",
"a",
"span"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L149-L176 |
226,105 | census-instrumentation/opencensus-python | opencensus/metrics/export/metric_producer.py | MetricProducerManager.add | def add(self, metric_producer):
"""Add a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to add.
"""
if metric_producer is None:
raise ValueError
with self.mp_lock:
self.metric_producers.add(metric_producer) | python | def add(self, metric_producer):
"""Add a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to add.
"""
if metric_producer is None:
raise ValueError
with self.mp_lock:
self.metric_producers.add(metric_producer) | [
"def",
"add",
"(",
"self",
",",
"metric_producer",
")",
":",
"if",
"metric_producer",
"is",
"None",
":",
"raise",
"ValueError",
"with",
"self",
".",
"mp_lock",
":",
"self",
".",
"metric_producers",
".",
"add",
"(",
"metric_producer",
")"
] | Add a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to add. | [
"Add",
"a",
"metric",
"producer",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric_producer.py#L44-L53 |
226,106 | census-instrumentation/opencensus-python | opencensus/metrics/export/metric_producer.py | MetricProducerManager.remove | def remove(self, metric_producer):
"""Remove a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to remove.
"""
if metric_producer is None:
raise ValueError
try:
with self.mp_lock:
self.metric_producers.remove(metric_producer)
except KeyError:
pass | python | def remove(self, metric_producer):
"""Remove a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to remove.
"""
if metric_producer is None:
raise ValueError
try:
with self.mp_lock:
self.metric_producers.remove(metric_producer)
except KeyError:
pass | [
"def",
"remove",
"(",
"self",
",",
"metric_producer",
")",
":",
"if",
"metric_producer",
"is",
"None",
":",
"raise",
"ValueError",
"try",
":",
"with",
"self",
".",
"mp_lock",
":",
"self",
".",
"metric_producers",
".",
"remove",
"(",
"metric_producer",
")",
... | Remove a metric producer.
:type metric_producer: :class: 'MetricProducer'
:param metric_producer: The metric producer to remove. | [
"Remove",
"a",
"metric",
"producer",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric_producer.py#L55-L67 |
226,107 | census-instrumentation/opencensus-python | contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py | add_message_event | def add_message_event(proto_message, span, message_event_type, message_id=1):
"""Adds a MessageEvent to the span based off of the given protobuf
message
"""
span.add_time_event(
time_event=time_event.TimeEvent(
datetime.utcnow(),
message_event=time_event.MessageEvent(
message_id,
type=message_event_type,
uncompressed_size_bytes=proto_message.ByteSize()
)
)
) | python | def add_message_event(proto_message, span, message_event_type, message_id=1):
"""Adds a MessageEvent to the span based off of the given protobuf
message
"""
span.add_time_event(
time_event=time_event.TimeEvent(
datetime.utcnow(),
message_event=time_event.MessageEvent(
message_id,
type=message_event_type,
uncompressed_size_bytes=proto_message.ByteSize()
)
)
) | [
"def",
"add_message_event",
"(",
"proto_message",
",",
"span",
",",
"message_event_type",
",",
"message_id",
"=",
"1",
")",
":",
"span",
".",
"add_time_event",
"(",
"time_event",
"=",
"time_event",
".",
"TimeEvent",
"(",
"datetime",
".",
"utcnow",
"(",
")",
... | Adds a MessageEvent to the span based off of the given protobuf
message | [
"Adds",
"a",
"MessageEvent",
"to",
"the",
"span",
"based",
"off",
"of",
"the",
"given",
"protobuf",
"message"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py#L9-L22 |
226,108 | census-instrumentation/opencensus-python | contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py | wrap_iter_with_message_events | def wrap_iter_with_message_events(
request_or_response_iter,
span,
message_event_type
):
"""Wraps a request or response iterator to add message events to the span
for each proto message sent or received
"""
for message_id, message in enumerate(request_or_response_iter, start=1):
add_message_event(
proto_message=message,
span=span,
message_event_type=message_event_type,
message_id=message_id
)
yield message | python | def wrap_iter_with_message_events(
request_or_response_iter,
span,
message_event_type
):
"""Wraps a request or response iterator to add message events to the span
for each proto message sent or received
"""
for message_id, message in enumerate(request_or_response_iter, start=1):
add_message_event(
proto_message=message,
span=span,
message_event_type=message_event_type,
message_id=message_id
)
yield message | [
"def",
"wrap_iter_with_message_events",
"(",
"request_or_response_iter",
",",
"span",
",",
"message_event_type",
")",
":",
"for",
"message_id",
",",
"message",
"in",
"enumerate",
"(",
"request_or_response_iter",
",",
"start",
"=",
"1",
")",
":",
"add_message_event",
... | Wraps a request or response iterator to add message events to the span
for each proto message sent or received | [
"Wraps",
"a",
"request",
"or",
"response",
"iterator",
"to",
"add",
"message",
"events",
"to",
"the",
"span",
"for",
"each",
"proto",
"message",
"sent",
"or",
"received"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py#L25-L40 |
226,109 | census-instrumentation/opencensus-python | opencensus/trace/stack_trace.py | StackFrame.format_stack_frame_json | def format_stack_frame_json(self):
"""Convert StackFrame object to json format."""
stack_frame_json = {}
stack_frame_json['function_name'] = get_truncatable_str(
self.func_name)
stack_frame_json['original_function_name'] = get_truncatable_str(
self.original_func_name)
stack_frame_json['file_name'] = get_truncatable_str(self.file_name)
stack_frame_json['line_number'] = self.line_num
stack_frame_json['column_number'] = self.col_num
stack_frame_json['load_module'] = {
'module': get_truncatable_str(self.load_module),
'build_id': get_truncatable_str(self.build_id),
}
stack_frame_json['source_version'] = get_truncatable_str(
self.source_version)
return stack_frame_json | python | def format_stack_frame_json(self):
"""Convert StackFrame object to json format."""
stack_frame_json = {}
stack_frame_json['function_name'] = get_truncatable_str(
self.func_name)
stack_frame_json['original_function_name'] = get_truncatable_str(
self.original_func_name)
stack_frame_json['file_name'] = get_truncatable_str(self.file_name)
stack_frame_json['line_number'] = self.line_num
stack_frame_json['column_number'] = self.col_num
stack_frame_json['load_module'] = {
'module': get_truncatable_str(self.load_module),
'build_id': get_truncatable_str(self.build_id),
}
stack_frame_json['source_version'] = get_truncatable_str(
self.source_version)
return stack_frame_json | [
"def",
"format_stack_frame_json",
"(",
"self",
")",
":",
"stack_frame_json",
"=",
"{",
"}",
"stack_frame_json",
"[",
"'function_name'",
"]",
"=",
"get_truncatable_str",
"(",
"self",
".",
"func_name",
")",
"stack_frame_json",
"[",
"'original_function_name'",
"]",
"="... | Convert StackFrame object to json format. | [
"Convert",
"StackFrame",
"object",
"to",
"json",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L86-L103 |
226,110 | census-instrumentation/opencensus-python | opencensus/trace/stack_trace.py | StackTrace.from_traceback | def from_traceback(cls, tb):
"""Initializes a StackTrace from a python traceback instance"""
stack_trace = cls(
stack_trace_hash_id=generate_hash_id_from_traceback(tb)
)
# use the add_stack_frame so that json formatting is applied
for tb_frame_info in traceback.extract_tb(tb):
filename, line_num, fn_name, _ = tb_frame_info
stack_trace.add_stack_frame(
StackFrame(
func_name=fn_name,
original_func_name=fn_name,
file_name=filename,
line_num=line_num,
col_num=0, # I don't think this is available in python
load_module=filename,
build_id=BUILD_ID,
source_version=SOURCE_VERSION
)
)
return stack_trace | python | def from_traceback(cls, tb):
"""Initializes a StackTrace from a python traceback instance"""
stack_trace = cls(
stack_trace_hash_id=generate_hash_id_from_traceback(tb)
)
# use the add_stack_frame so that json formatting is applied
for tb_frame_info in traceback.extract_tb(tb):
filename, line_num, fn_name, _ = tb_frame_info
stack_trace.add_stack_frame(
StackFrame(
func_name=fn_name,
original_func_name=fn_name,
file_name=filename,
line_num=line_num,
col_num=0, # I don't think this is available in python
load_module=filename,
build_id=BUILD_ID,
source_version=SOURCE_VERSION
)
)
return stack_trace | [
"def",
"from_traceback",
"(",
"cls",
",",
"tb",
")",
":",
"stack_trace",
"=",
"cls",
"(",
"stack_trace_hash_id",
"=",
"generate_hash_id_from_traceback",
"(",
"tb",
")",
")",
"# use the add_stack_frame so that json formatting is applied",
"for",
"tb_frame_info",
"in",
"t... | Initializes a StackTrace from a python traceback instance | [
"Initializes",
"a",
"StackTrace",
"from",
"a",
"python",
"traceback",
"instance"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L134-L154 |
226,111 | census-instrumentation/opencensus-python | opencensus/trace/stack_trace.py | StackTrace.add_stack_frame | def add_stack_frame(self, stack_frame):
"""Add StackFrame to frames list."""
if len(self.stack_frames) >= MAX_FRAMES:
self.dropped_frames_count += 1
else:
self.stack_frames.append(stack_frame.format_stack_frame_json()) | python | def add_stack_frame(self, stack_frame):
"""Add StackFrame to frames list."""
if len(self.stack_frames) >= MAX_FRAMES:
self.dropped_frames_count += 1
else:
self.stack_frames.append(stack_frame.format_stack_frame_json()) | [
"def",
"add_stack_frame",
"(",
"self",
",",
"stack_frame",
")",
":",
"if",
"len",
"(",
"self",
".",
"stack_frames",
")",
">=",
"MAX_FRAMES",
":",
"self",
".",
"dropped_frames_count",
"+=",
"1",
"else",
":",
"self",
".",
"stack_frames",
".",
"append",
"(",
... | Add StackFrame to frames list. | [
"Add",
"StackFrame",
"to",
"frames",
"list",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L156-L161 |
226,112 | census-instrumentation/opencensus-python | opencensus/trace/stack_trace.py | StackTrace.format_stack_trace_json | def format_stack_trace_json(self):
"""Convert a StackTrace object to json format."""
stack_trace_json = {}
if self.stack_frames:
stack_trace_json['stack_frames'] = {
'frame': self.stack_frames,
'dropped_frames_count': self.dropped_frames_count
}
stack_trace_json['stack_trace_hash_id'] = self.stack_trace_hash_id
return stack_trace_json | python | def format_stack_trace_json(self):
"""Convert a StackTrace object to json format."""
stack_trace_json = {}
if self.stack_frames:
stack_trace_json['stack_frames'] = {
'frame': self.stack_frames,
'dropped_frames_count': self.dropped_frames_count
}
stack_trace_json['stack_trace_hash_id'] = self.stack_trace_hash_id
return stack_trace_json | [
"def",
"format_stack_trace_json",
"(",
"self",
")",
":",
"stack_trace_json",
"=",
"{",
"}",
"if",
"self",
".",
"stack_frames",
":",
"stack_trace_json",
"[",
"'stack_frames'",
"]",
"=",
"{",
"'frame'",
":",
"self",
".",
"stack_frames",
",",
"'dropped_frames_count... | Convert a StackTrace object to json format. | [
"Convert",
"a",
"StackTrace",
"object",
"to",
"json",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L163-L175 |
226,113 | census-instrumentation/opencensus-python | opencensus/stats/view_manager.py | ViewManager.register_view | def register_view(self, view):
"""registers the given view"""
self.measure_to_view_map.register_view(view=view, timestamp=self.time) | python | def register_view(self, view):
"""registers the given view"""
self.measure_to_view_map.register_view(view=view, timestamp=self.time) | [
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"self",
".",
"measure_to_view_map",
".",
"register_view",
"(",
"view",
"=",
"view",
",",
"timestamp",
"=",
"self",
".",
"time",
")"
] | registers the given view | [
"registers",
"the",
"given",
"view"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_manager.py#L35-L37 |
226,114 | census-instrumentation/opencensus-python | opencensus/stats/view_manager.py | ViewManager.get_view | def get_view(self, view_name):
"""gets the view given the view name """
return self.measure_to_view_map.get_view(view_name=view_name,
timestamp=self.time) | python | def get_view(self, view_name):
"""gets the view given the view name """
return self.measure_to_view_map.get_view(view_name=view_name,
timestamp=self.time) | [
"def",
"get_view",
"(",
"self",
",",
"view_name",
")",
":",
"return",
"self",
".",
"measure_to_view_map",
".",
"get_view",
"(",
"view_name",
"=",
"view_name",
",",
"timestamp",
"=",
"self",
".",
"time",
")"
] | gets the view given the view name | [
"gets",
"the",
"view",
"given",
"the",
"view",
"name"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_manager.py#L39-L42 |
226,115 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | new_stats_exporter | def new_stats_exporter(options=None, interval=None):
"""Get a stats exporter and running transport thread.
Create a new `StackdriverStatsExporter` with the given options and start
periodically exporting stats to stackdriver in the background.
Fall back to default auth if `options` is null. This will raise
`google.auth.exceptions.DefaultCredentialsError` if default credentials
aren't configured.
See `opencensus.metrics.transport.get_exporter_thread` for details on the
transport thread.
:type options: :class:`Options`
:param exporter: Options to pass to the exporter
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`StackdriverStatsExporter`
:return: The newly-created exporter.
"""
if options is None:
_, project_id = google.auth.default()
options = Options(project_id=project_id)
if str(options.project_id).strip() == "":
raise ValueError(ERROR_BLANK_PROJECT_ID)
ci = client_info.ClientInfo(client_library_version=get_user_agent_slug())
client = monitoring_v3.MetricServiceClient(client_info=ci)
exporter = StackdriverStatsExporter(client=client, options=options)
transport.get_exporter_thread(stats.stats, exporter, interval=interval)
return exporter | python | def new_stats_exporter(options=None, interval=None):
"""Get a stats exporter and running transport thread.
Create a new `StackdriverStatsExporter` with the given options and start
periodically exporting stats to stackdriver in the background.
Fall back to default auth if `options` is null. This will raise
`google.auth.exceptions.DefaultCredentialsError` if default credentials
aren't configured.
See `opencensus.metrics.transport.get_exporter_thread` for details on the
transport thread.
:type options: :class:`Options`
:param exporter: Options to pass to the exporter
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`StackdriverStatsExporter`
:return: The newly-created exporter.
"""
if options is None:
_, project_id = google.auth.default()
options = Options(project_id=project_id)
if str(options.project_id).strip() == "":
raise ValueError(ERROR_BLANK_PROJECT_ID)
ci = client_info.ClientInfo(client_library_version=get_user_agent_slug())
client = monitoring_v3.MetricServiceClient(client_info=ci)
exporter = StackdriverStatsExporter(client=client, options=options)
transport.get_exporter_thread(stats.stats, exporter, interval=interval)
return exporter | [
"def",
"new_stats_exporter",
"(",
"options",
"=",
"None",
",",
"interval",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"_",
",",
"project_id",
"=",
"google",
".",
"auth",
".",
"default",
"(",
")",
"options",
"=",
"Options",
"(",
"project... | Get a stats exporter and running transport thread.
Create a new `StackdriverStatsExporter` with the given options and start
periodically exporting stats to stackdriver in the background.
Fall back to default auth if `options` is null. This will raise
`google.auth.exceptions.DefaultCredentialsError` if default credentials
aren't configured.
See `opencensus.metrics.transport.get_exporter_thread` for details on the
transport thread.
:type options: :class:`Options`
:param exporter: Options to pass to the exporter
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`StackdriverStatsExporter`
:return: The newly-created exporter. | [
"Get",
"a",
"stats",
"exporter",
"and",
"running",
"transport",
"thread",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L366-L399 |
226,116 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | namespaced_view_name | def namespaced_view_name(view_name, metric_prefix):
""" create string to be used as metric type
"""
metric_prefix = metric_prefix or "custom.googleapis.com/opencensus"
return os.path.join(metric_prefix, view_name).replace('\\', '/') | python | def namespaced_view_name(view_name, metric_prefix):
""" create string to be used as metric type
"""
metric_prefix = metric_prefix or "custom.googleapis.com/opencensus"
return os.path.join(metric_prefix, view_name).replace('\\', '/') | [
"def",
"namespaced_view_name",
"(",
"view_name",
",",
"metric_prefix",
")",
":",
"metric_prefix",
"=",
"metric_prefix",
"or",
"\"custom.googleapis.com/opencensus\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"metric_prefix",
",",
"view_name",
")",
".",
"replace... | create string to be used as metric type | [
"create",
"string",
"to",
"be",
"used",
"as",
"metric",
"type"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L412-L416 |
226,117 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | new_label_descriptors | def new_label_descriptors(defaults, keys):
""" create labels for the metric_descriptor
that will be sent to Stackdriver Monitoring
"""
label_descriptors = []
for lk in itertools.chain.from_iterable((defaults.keys(), keys)):
label = {}
label["key"] = sanitize_label(lk.key)
label["description"] = lk.description
label_descriptors.append(label)
return label_descriptors | python | def new_label_descriptors(defaults, keys):
""" create labels for the metric_descriptor
that will be sent to Stackdriver Monitoring
"""
label_descriptors = []
for lk in itertools.chain.from_iterable((defaults.keys(), keys)):
label = {}
label["key"] = sanitize_label(lk.key)
label["description"] = lk.description
label_descriptors.append(label)
return label_descriptors | [
"def",
"new_label_descriptors",
"(",
"defaults",
",",
"keys",
")",
":",
"label_descriptors",
"=",
"[",
"]",
"for",
"lk",
"in",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"(",
"defaults",
".",
"keys",
"(",
")",
",",
"keys",
")",
")",
":",
"la... | create labels for the metric_descriptor
that will be sent to Stackdriver Monitoring | [
"create",
"labels",
"for",
"the",
"metric_descriptor",
"that",
"will",
"be",
"sent",
"to",
"Stackdriver",
"Monitoring"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L419-L430 |
226,118 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | sanitize_label | def sanitize_label(text):
"""Remove characters not accepted in labels key
This replaces any non-word characters (alphanumeric or underscore), with
an underscore. It also ensures that the first character is a letter by
prepending with 'key' if necessary, and trims the text to 100 characters.
"""
if not text:
return text
text = re.sub('\\W+', '_', text)
if text[0] in string.digits:
text = "key_" + text
elif text[0] == '_':
text = "key" + text
return text[:100] | python | def sanitize_label(text):
"""Remove characters not accepted in labels key
This replaces any non-word characters (alphanumeric or underscore), with
an underscore. It also ensures that the first character is a letter by
prepending with 'key' if necessary, and trims the text to 100 characters.
"""
if not text:
return text
text = re.sub('\\W+', '_', text)
if text[0] in string.digits:
text = "key_" + text
elif text[0] == '_':
text = "key" + text
return text[:100] | [
"def",
"sanitize_label",
"(",
"text",
")",
":",
"if",
"not",
"text",
":",
"return",
"text",
"text",
"=",
"re",
".",
"sub",
"(",
"'\\\\W+'",
",",
"'_'",
",",
"text",
")",
"if",
"text",
"[",
"0",
"]",
"in",
"string",
".",
"digits",
":",
"text",
"="... | Remove characters not accepted in labels key
This replaces any non-word characters (alphanumeric or underscore), with
an underscore. It also ensures that the first character is a letter by
prepending with 'key' if necessary, and trims the text to 100 characters. | [
"Remove",
"characters",
"not",
"accepted",
"in",
"labels",
"key"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L433-L447 |
226,119 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | StackdriverStatsExporter._convert_series | def _convert_series(self, metric, ts):
"""Convert an OC timeseries to a SD series."""
series = monitoring_v3.types.TimeSeries()
series.metric.type = self.get_metric_type(metric.descriptor)
for lk, lv in self.options.default_monitoring_labels.items():
series.metric.labels[lk.key] = lv.value
for key, val in zip(metric.descriptor.label_keys, ts.label_values):
if val.value is not None:
safe_key = sanitize_label(key.key)
series.metric.labels[safe_key] = val.value
set_monitored_resource(series, self.options.resource)
for point in ts.points:
sd_point = series.points.add()
# this just modifies points, no return
self._convert_point(metric, ts, point, sd_point)
return series | python | def _convert_series(self, metric, ts):
"""Convert an OC timeseries to a SD series."""
series = monitoring_v3.types.TimeSeries()
series.metric.type = self.get_metric_type(metric.descriptor)
for lk, lv in self.options.default_monitoring_labels.items():
series.metric.labels[lk.key] = lv.value
for key, val in zip(metric.descriptor.label_keys, ts.label_values):
if val.value is not None:
safe_key = sanitize_label(key.key)
series.metric.labels[safe_key] = val.value
set_monitored_resource(series, self.options.resource)
for point in ts.points:
sd_point = series.points.add()
# this just modifies points, no return
self._convert_point(metric, ts, point, sd_point)
return series | [
"def",
"_convert_series",
"(",
"self",
",",
"metric",
",",
"ts",
")",
":",
"series",
"=",
"monitoring_v3",
".",
"types",
".",
"TimeSeries",
"(",
")",
"series",
".",
"metric",
".",
"type",
"=",
"self",
".",
"get_metric_type",
"(",
"metric",
".",
"descript... | Convert an OC timeseries to a SD series. | [
"Convert",
"an",
"OC",
"timeseries",
"to",
"a",
"SD",
"series",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L172-L191 |
226,120 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | StackdriverStatsExporter._convert_point | def _convert_point(self, metric, ts, point, sd_point):
"""Convert an OC metric point to a SD point."""
if (metric.descriptor.type == metric_descriptor.MetricDescriptorType
.CUMULATIVE_DISTRIBUTION):
sd_dist_val = sd_point.value.distribution_value
sd_dist_val.count = point.value.count
sd_dist_val.sum_of_squared_deviation =\
point.value.sum_of_squared_deviation
assert sd_dist_val.bucket_options.explicit_buckets.bounds == []
sd_dist_val.bucket_options.explicit_buckets.bounds.extend(
[0.0] +
list(map(float, point.value.bucket_options.type_.bounds))
)
assert sd_dist_val.bucket_counts == []
sd_dist_val.bucket_counts.extend(
[0] +
[bb.count for bb in point.value.buckets]
)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64):
sd_point.value.int64_value = int(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE):
sd_point.value.double_value = float(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.GAUGE_INT64):
sd_point.value.int64_value = int(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE):
sd_point.value.double_value = float(point.value.value)
# TODO: handle SUMMARY metrics, #567
else: # pragma: NO COVER
raise TypeError("Unsupported metric type: {}"
.format(metric.descriptor.type))
end = point.timestamp
if ts.start_timestamp is None:
start = end
else:
start = datetime.strptime(ts.start_timestamp, EPOCH_PATTERN)
timestamp_start = (start - EPOCH_DATETIME).total_seconds()
timestamp_end = (end - EPOCH_DATETIME).total_seconds()
sd_point.interval.end_time.seconds = int(timestamp_end)
secs = sd_point.interval.end_time.seconds
sd_point.interval.end_time.nanos = int((timestamp_end - secs) * 1e9)
start_time = sd_point.interval.start_time
start_time.seconds = int(timestamp_start)
start_time.nanos = int((timestamp_start - start_time.seconds) * 1e9) | python | def _convert_point(self, metric, ts, point, sd_point):
"""Convert an OC metric point to a SD point."""
if (metric.descriptor.type == metric_descriptor.MetricDescriptorType
.CUMULATIVE_DISTRIBUTION):
sd_dist_val = sd_point.value.distribution_value
sd_dist_val.count = point.value.count
sd_dist_val.sum_of_squared_deviation =\
point.value.sum_of_squared_deviation
assert sd_dist_val.bucket_options.explicit_buckets.bounds == []
sd_dist_val.bucket_options.explicit_buckets.bounds.extend(
[0.0] +
list(map(float, point.value.bucket_options.type_.bounds))
)
assert sd_dist_val.bucket_counts == []
sd_dist_val.bucket_counts.extend(
[0] +
[bb.count for bb in point.value.buckets]
)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64):
sd_point.value.int64_value = int(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE):
sd_point.value.double_value = float(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.GAUGE_INT64):
sd_point.value.int64_value = int(point.value.value)
elif (metric.descriptor.type ==
metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE):
sd_point.value.double_value = float(point.value.value)
# TODO: handle SUMMARY metrics, #567
else: # pragma: NO COVER
raise TypeError("Unsupported metric type: {}"
.format(metric.descriptor.type))
end = point.timestamp
if ts.start_timestamp is None:
start = end
else:
start = datetime.strptime(ts.start_timestamp, EPOCH_PATTERN)
timestamp_start = (start - EPOCH_DATETIME).total_seconds()
timestamp_end = (end - EPOCH_DATETIME).total_seconds()
sd_point.interval.end_time.seconds = int(timestamp_end)
secs = sd_point.interval.end_time.seconds
sd_point.interval.end_time.nanos = int((timestamp_end - secs) * 1e9)
start_time = sd_point.interval.start_time
start_time.seconds = int(timestamp_start)
start_time.nanos = int((timestamp_start - start_time.seconds) * 1e9) | [
"def",
"_convert_point",
"(",
"self",
",",
"metric",
",",
"ts",
",",
"point",
",",
"sd_point",
")",
":",
"if",
"(",
"metric",
".",
"descriptor",
".",
"type",
"==",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_DISTRIBUTION",
")",
":",
"s... | Convert an OC metric point to a SD point. | [
"Convert",
"an",
"OC",
"metric",
"point",
"to",
"a",
"SD",
"point",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L193-L252 |
226,121 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | StackdriverStatsExporter.get_metric_descriptor | def get_metric_descriptor(self, oc_md):
"""Convert an OC metric descriptor to a SD metric descriptor."""
try:
metric_kind, value_type = OC_MD_TO_SD_TYPE[oc_md.type]
except KeyError:
raise TypeError("Unsupported metric type: {}".format(oc_md.type))
if self.options.metric_prefix:
display_name_prefix = self.options.metric_prefix
else:
display_name_prefix = DEFAULT_DISPLAY_NAME_PREFIX
desc_labels = new_label_descriptors(
self.options.default_monitoring_labels, oc_md.label_keys)
descriptor = monitoring_v3.types.MetricDescriptor(labels=desc_labels)
metric_type = self.get_metric_type(oc_md)
descriptor.type = metric_type
descriptor.metric_kind = metric_kind
descriptor.value_type = value_type
descriptor.description = oc_md.description
descriptor.unit = oc_md.unit
descriptor.name = ("projects/{}/metricDescriptors/{}"
.format(self.options.project_id, metric_type))
descriptor.display_name = ("{}/{}"
.format(display_name_prefix, oc_md.name))
return descriptor | python | def get_metric_descriptor(self, oc_md):
"""Convert an OC metric descriptor to a SD metric descriptor."""
try:
metric_kind, value_type = OC_MD_TO_SD_TYPE[oc_md.type]
except KeyError:
raise TypeError("Unsupported metric type: {}".format(oc_md.type))
if self.options.metric_prefix:
display_name_prefix = self.options.metric_prefix
else:
display_name_prefix = DEFAULT_DISPLAY_NAME_PREFIX
desc_labels = new_label_descriptors(
self.options.default_monitoring_labels, oc_md.label_keys)
descriptor = monitoring_v3.types.MetricDescriptor(labels=desc_labels)
metric_type = self.get_metric_type(oc_md)
descriptor.type = metric_type
descriptor.metric_kind = metric_kind
descriptor.value_type = value_type
descriptor.description = oc_md.description
descriptor.unit = oc_md.unit
descriptor.name = ("projects/{}/metricDescriptors/{}"
.format(self.options.project_id, metric_type))
descriptor.display_name = ("{}/{}"
.format(display_name_prefix, oc_md.name))
return descriptor | [
"def",
"get_metric_descriptor",
"(",
"self",
",",
"oc_md",
")",
":",
"try",
":",
"metric_kind",
",",
"value_type",
"=",
"OC_MD_TO_SD_TYPE",
"[",
"oc_md",
".",
"type",
"]",
"except",
"KeyError",
":",
"raise",
"TypeError",
"(",
"\"Unsupported metric type: {}\"",
"... | Convert an OC metric descriptor to a SD metric descriptor. | [
"Convert",
"an",
"OC",
"metric",
"descriptor",
"to",
"a",
"SD",
"metric",
"descriptor",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L258-L285 |
226,122 | census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py | StackdriverStatsExporter.register_metric_descriptor | def register_metric_descriptor(self, oc_md):
"""Register a metric descriptor with stackdriver."""
metric_type = self.get_metric_type(oc_md)
with self._md_lock:
if metric_type in self._md_cache:
return self._md_cache[metric_type]
descriptor = self.get_metric_descriptor(oc_md)
project_name = self.client.project_path(self.options.project_id)
sd_md = self.client.create_metric_descriptor(project_name, descriptor)
with self._md_lock:
self._md_cache[metric_type] = sd_md
return sd_md | python | def register_metric_descriptor(self, oc_md):
"""Register a metric descriptor with stackdriver."""
metric_type = self.get_metric_type(oc_md)
with self._md_lock:
if metric_type in self._md_cache:
return self._md_cache[metric_type]
descriptor = self.get_metric_descriptor(oc_md)
project_name = self.client.project_path(self.options.project_id)
sd_md = self.client.create_metric_descriptor(project_name, descriptor)
with self._md_lock:
self._md_cache[metric_type] = sd_md
return sd_md | [
"def",
"register_metric_descriptor",
"(",
"self",
",",
"oc_md",
")",
":",
"metric_type",
"=",
"self",
".",
"get_metric_type",
"(",
"oc_md",
")",
"with",
"self",
".",
"_md_lock",
":",
"if",
"metric_type",
"in",
"self",
".",
"_md_cache",
":",
"return",
"self",... | Register a metric descriptor with stackdriver. | [
"Register",
"a",
"metric",
"descriptor",
"with",
"stackdriver",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L287-L299 |
226,123 | census-instrumentation/opencensus-python | opencensus/trace/propagation/google_cloud_format.py | GoogleCloudFormatPropagator.from_headers | def from_headers(self, headers):
"""Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.
"""
if headers is None:
return SpanContext()
header = headers.get(_TRACE_CONTEXT_HEADER_NAME)
if header is None:
return SpanContext()
header = str(header.encode('utf-8'))
return self.from_header(header) | python | def from_headers(self, headers):
"""Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.
"""
if headers is None:
return SpanContext()
header = headers.get(_TRACE_CONTEXT_HEADER_NAME)
if header is None:
return SpanContext()
header = str(header.encode('utf-8'))
return self.from_header(header) | [
"def",
"from_headers",
"(",
"self",
",",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"SpanContext",
"(",
")",
"header",
"=",
"headers",
".",
"get",
"(",
"_TRACE_CONTEXT_HEADER_NAME",
")",
"if",
"header",
"is",
"None",
":",
"return",
... | Generate a SpanContext object using the trace context header.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header. | [
"Generate",
"a",
"SpanContext",
"object",
"using",
"the",
"trace",
"context",
"header",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/google_cloud_format.py#L77-L92 |
226,124 | census-instrumentation/opencensus-python | opencensus/trace/propagation/google_cloud_format.py | GoogleCloudFormatPropagator.to_header | def to_header(self, span_context):
"""Convert a SpanContext object to header string.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: str
:returns: A trace context header string in google cloud format.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = span_context.trace_options.trace_options_byte
header = '{}/{};o={}'.format(
trace_id,
span_id,
int(trace_options))
return header | python | def to_header(self, span_context):
"""Convert a SpanContext object to header string.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: str
:returns: A trace context header string in google cloud format.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = span_context.trace_options.trace_options_byte
header = '{}/{};o={}'.format(
trace_id,
span_id,
int(trace_options))
return header | [
"def",
"to_header",
"(",
"self",
",",
"span_context",
")",
":",
"trace_id",
"=",
"span_context",
".",
"trace_id",
"span_id",
"=",
"span_context",
".",
"span_id",
"trace_options",
"=",
"span_context",
".",
"trace_options",
".",
"trace_options_byte",
"header",
"=",
... | Convert a SpanContext object to header string.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: str
:returns: A trace context header string in google cloud format. | [
"Convert",
"a",
"SpanContext",
"object",
"to",
"header",
"string",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/google_cloud_format.py#L94-L112 |
226,125 | census-instrumentation/opencensus-python | contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py | _extract_annotations_from_span | def _extract_annotations_from_span(span):
"""Extract and convert time event annotations to zipkin annotations"""
if span.time_events is None:
return []
annotations = []
for time_event in span.time_events:
annotation = time_event.annotation
if not annotation:
continue
event_timestamp_mus = timestamp_to_microseconds(time_event.timestamp)
annotations.append({'timestamp': int(round(event_timestamp_mus)),
'value': annotation.description})
return annotations | python | def _extract_annotations_from_span(span):
"""Extract and convert time event annotations to zipkin annotations"""
if span.time_events is None:
return []
annotations = []
for time_event in span.time_events:
annotation = time_event.annotation
if not annotation:
continue
event_timestamp_mus = timestamp_to_microseconds(time_event.timestamp)
annotations.append({'timestamp': int(round(event_timestamp_mus)),
'value': annotation.description})
return annotations | [
"def",
"_extract_annotations_from_span",
"(",
"span",
")",
":",
"if",
"span",
".",
"time_events",
"is",
"None",
":",
"return",
"[",
"]",
"annotations",
"=",
"[",
"]",
"for",
"time_event",
"in",
"span",
".",
"time_events",
":",
"annotation",
"=",
"time_event"... | Extract and convert time event annotations to zipkin annotations | [
"Extract",
"and",
"convert",
"time",
"event",
"annotations",
"to",
"zipkin",
"annotations"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L202-L217 |
226,126 | census-instrumentation/opencensus-python | contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py | ZipkinExporter.emit | def emit(self, span_datas):
"""Send SpanData tuples to Zipkin server, default using the v2 API.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
try:
zipkin_spans = self.translate_to_zipkin(span_datas)
result = requests.post(
url=self.url,
data=json.dumps(zipkin_spans),
headers=ZIPKIN_HEADERS)
if result.status_code not in SUCCESS_STATUS_CODE:
logging.error(
"Failed to send spans to Zipkin server! Spans are {}"
.format(zipkin_spans))
except Exception as e: # pragma: NO COVER
logging.error(getattr(e, 'message', e)) | python | def emit(self, span_datas):
"""Send SpanData tuples to Zipkin server, default using the v2 API.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
try:
zipkin_spans = self.translate_to_zipkin(span_datas)
result = requests.post(
url=self.url,
data=json.dumps(zipkin_spans),
headers=ZIPKIN_HEADERS)
if result.status_code not in SUCCESS_STATUS_CODE:
logging.error(
"Failed to send spans to Zipkin server! Spans are {}"
.format(zipkin_spans))
except Exception as e: # pragma: NO COVER
logging.error(getattr(e, 'message', e)) | [
"def",
"emit",
"(",
"self",
",",
"span_datas",
")",
":",
"try",
":",
"zipkin_spans",
"=",
"self",
".",
"translate_to_zipkin",
"(",
"span_datas",
")",
"result",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"self",
".",
"url",
",",
"data",
"=",
"json",... | Send SpanData tuples to Zipkin server, default using the v2 API.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit | [
"Send",
"SpanData",
"tuples",
"to",
"Zipkin",
"server",
"default",
"using",
"the",
"v2",
"API",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L99-L120 |
226,127 | census-instrumentation/opencensus-python | contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py | ZipkinExporter.translate_to_zipkin | def translate_to_zipkin(self, span_datas):
"""Translate the opencensus spans to zipkin spans.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit
:rtype: list
:returns: List of zipkin format spans.
"""
local_endpoint = {
'serviceName': self.service_name,
'port': self.port,
}
if self.ipv4 is not None:
local_endpoint['ipv4'] = self.ipv4
if self.ipv6 is not None:
local_endpoint['ipv6'] = self.ipv6
zipkin_spans = []
for span in span_datas:
# Timestamp in zipkin spans is int of microseconds.
start_timestamp_mus = timestamp_to_microseconds(span.start_time)
end_timestamp_mus = timestamp_to_microseconds(span.end_time)
duration_mus = end_timestamp_mus - start_timestamp_mus
zipkin_span = {
'traceId': span.context.trace_id,
'id': str(span.span_id),
'name': span.name,
'timestamp': int(round(start_timestamp_mus)),
'duration': int(round(duration_mus)),
'localEndpoint': local_endpoint,
'tags': _extract_tags_from_span(span.attributes),
'annotations': _extract_annotations_from_span(span),
}
span_kind = span.span_kind
parent_span_id = span.parent_span_id
if span_kind is not None:
kind = SPAN_KIND_MAP.get(span_kind)
# Zipkin API for span kind only accept
# enum(CLIENT|SERVER|PRODUCER|CONSUMER|Absent)
if kind is not None:
zipkin_span['kind'] = kind
if parent_span_id is not None:
zipkin_span['parentId'] = str(parent_span_id)
zipkin_spans.append(zipkin_span)
return zipkin_spans | python | def translate_to_zipkin(self, span_datas):
"""Translate the opencensus spans to zipkin spans.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit
:rtype: list
:returns: List of zipkin format spans.
"""
local_endpoint = {
'serviceName': self.service_name,
'port': self.port,
}
if self.ipv4 is not None:
local_endpoint['ipv4'] = self.ipv4
if self.ipv6 is not None:
local_endpoint['ipv6'] = self.ipv6
zipkin_spans = []
for span in span_datas:
# Timestamp in zipkin spans is int of microseconds.
start_timestamp_mus = timestamp_to_microseconds(span.start_time)
end_timestamp_mus = timestamp_to_microseconds(span.end_time)
duration_mus = end_timestamp_mus - start_timestamp_mus
zipkin_span = {
'traceId': span.context.trace_id,
'id': str(span.span_id),
'name': span.name,
'timestamp': int(round(start_timestamp_mus)),
'duration': int(round(duration_mus)),
'localEndpoint': local_endpoint,
'tags': _extract_tags_from_span(span.attributes),
'annotations': _extract_annotations_from_span(span),
}
span_kind = span.span_kind
parent_span_id = span.parent_span_id
if span_kind is not None:
kind = SPAN_KIND_MAP.get(span_kind)
# Zipkin API for span kind only accept
# enum(CLIENT|SERVER|PRODUCER|CONSUMER|Absent)
if kind is not None:
zipkin_span['kind'] = kind
if parent_span_id is not None:
zipkin_span['parentId'] = str(parent_span_id)
zipkin_spans.append(zipkin_span)
return zipkin_spans | [
"def",
"translate_to_zipkin",
"(",
"self",
",",
"span_datas",
")",
":",
"local_endpoint",
"=",
"{",
"'serviceName'",
":",
"self",
".",
"service_name",
",",
"'port'",
":",
"self",
".",
"port",
",",
"}",
"if",
"self",
".",
"ipv4",
"is",
"not",
"None",
":",... | Translate the opencensus spans to zipkin spans.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit
:rtype: list
:returns: List of zipkin format spans. | [
"Translate",
"the",
"opencensus",
"spans",
"to",
"zipkin",
"spans",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L125-L182 |
226,128 | census-instrumentation/opencensus-python | contrib/opencensus-ext-sqlalchemy/opencensus/ext/sqlalchemy/trace.py | trace_engine | def trace_engine(engine):
"""Register the event before cursor execute and after cursor execute
to the event listner of the engine.
"""
event.listen(engine, 'before_cursor_execute', _before_cursor_execute)
event.listen(engine, 'after_cursor_execute', _after_cursor_execute) | python | def trace_engine(engine):
"""Register the event before cursor execute and after cursor execute
to the event listner of the engine.
"""
event.listen(engine, 'before_cursor_execute', _before_cursor_execute)
event.listen(engine, 'after_cursor_execute', _after_cursor_execute) | [
"def",
"trace_engine",
"(",
"engine",
")",
":",
"event",
".",
"listen",
"(",
"engine",
",",
"'before_cursor_execute'",
",",
"_before_cursor_execute",
")",
"event",
".",
"listen",
"(",
"engine",
",",
"'after_cursor_execute'",
",",
"_after_cursor_execute",
")"
] | Register the event before cursor execute and after cursor execute
to the event listner of the engine. | [
"Register",
"the",
"event",
"before",
"cursor",
"execute",
"and",
"after",
"cursor",
"execute",
"to",
"the",
"event",
"listner",
"of",
"the",
"engine",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-sqlalchemy/opencensus/ext/sqlalchemy/trace.py#L38-L43 |
226,129 | census-instrumentation/opencensus-python | opencensus/metrics/export/time_series.py | TimeSeries.check_points_type | def check_points_type(self, type_class):
"""Check that each point's value is an instance of `type_class`.
`type_class` should typically be a Value type, i.e. one that extends
:class: `opencensus.metrics.export.value.Value`.
:type type_class: type
:param type_class: Type to check against.
:rtype: bool
:return: Whether all points are instances of `type_class`.
"""
for point in self.points:
if (point.value is not None
and not isinstance(point.value, type_class)):
return False
return True | python | def check_points_type(self, type_class):
"""Check that each point's value is an instance of `type_class`.
`type_class` should typically be a Value type, i.e. one that extends
:class: `opencensus.metrics.export.value.Value`.
:type type_class: type
:param type_class: Type to check against.
:rtype: bool
:return: Whether all points are instances of `type_class`.
"""
for point in self.points:
if (point.value is not None
and not isinstance(point.value, type_class)):
return False
return True | [
"def",
"check_points_type",
"(",
"self",
",",
"type_class",
")",
":",
"for",
"point",
"in",
"self",
".",
"points",
":",
"if",
"(",
"point",
".",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"point",
".",
"value",
",",
"type_class",
")... | Check that each point's value is an instance of `type_class`.
`type_class` should typically be a Value type, i.e. one that extends
:class: `opencensus.metrics.export.value.Value`.
:type type_class: type
:param type_class: Type to check against.
:rtype: bool
:return: Whether all points are instances of `type_class`. | [
"Check",
"that",
"each",
"point",
"s",
"value",
"is",
"an",
"instance",
"of",
"type_class",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/time_series.py#L74-L90 |
226,130 | census-instrumentation/opencensus-python | opencensus/log/__init__.py | get_log_attrs | def get_log_attrs():
"""Get logging attributes from the opencensus context.
:rtype: :class:`LogAttrs`
:return: The current span's trace ID, span ID, and sampling decision.
"""
try:
tracer = execution_context.get_opencensus_tracer()
if tracer is None:
raise RuntimeError
except Exception: # noqa
_meta_logger.error("Failed to get opencensus tracer")
return ATTR_DEFAULTS
try:
trace_id = tracer.span_context.trace_id
if trace_id is None:
trace_id = ATTR_DEFAULTS.trace_id
except Exception: # noqa
_meta_logger.error("Failed to get opencensus trace ID")
trace_id = ATTR_DEFAULTS.trace_id
try:
span_id = tracer.span_context.span_id
if span_id is None:
span_id = ATTR_DEFAULTS.span_id
except Exception: # noqa
_meta_logger.error("Failed to get opencensus span ID")
span_id = ATTR_DEFAULTS.span_id
try:
sampling_decision = tracer.span_context.trace_options.get_enabled
if sampling_decision is None:
sampling_decision = ATTR_DEFAULTS.sampling_decision
except AttributeError:
sampling_decision = ATTR_DEFAULTS.sampling_decision
except Exception: # noqa
_meta_logger.error("Failed to get opencensus sampling decision")
sampling_decision = ATTR_DEFAULTS.sampling_decision
return LogAttrs(trace_id, span_id, sampling_decision) | python | def get_log_attrs():
"""Get logging attributes from the opencensus context.
:rtype: :class:`LogAttrs`
:return: The current span's trace ID, span ID, and sampling decision.
"""
try:
tracer = execution_context.get_opencensus_tracer()
if tracer is None:
raise RuntimeError
except Exception: # noqa
_meta_logger.error("Failed to get opencensus tracer")
return ATTR_DEFAULTS
try:
trace_id = tracer.span_context.trace_id
if trace_id is None:
trace_id = ATTR_DEFAULTS.trace_id
except Exception: # noqa
_meta_logger.error("Failed to get opencensus trace ID")
trace_id = ATTR_DEFAULTS.trace_id
try:
span_id = tracer.span_context.span_id
if span_id is None:
span_id = ATTR_DEFAULTS.span_id
except Exception: # noqa
_meta_logger.error("Failed to get opencensus span ID")
span_id = ATTR_DEFAULTS.span_id
try:
sampling_decision = tracer.span_context.trace_options.get_enabled
if sampling_decision is None:
sampling_decision = ATTR_DEFAULTS.sampling_decision
except AttributeError:
sampling_decision = ATTR_DEFAULTS.sampling_decision
except Exception: # noqa
_meta_logger.error("Failed to get opencensus sampling decision")
sampling_decision = ATTR_DEFAULTS.sampling_decision
return LogAttrs(trace_id, span_id, sampling_decision) | [
"def",
"get_log_attrs",
"(",
")",
":",
"try",
":",
"tracer",
"=",
"execution_context",
".",
"get_opencensus_tracer",
"(",
")",
"if",
"tracer",
"is",
"None",
":",
"raise",
"RuntimeError",
"except",
"Exception",
":",
"# noqa",
"_meta_logger",
".",
"error",
"(",
... | Get logging attributes from the opencensus context.
:rtype: :class:`LogAttrs`
:return: The current span's trace ID, span ID, and sampling decision. | [
"Get",
"logging",
"attributes",
"from",
"the",
"opencensus",
"context",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/log/__init__.py#L33-L73 |
226,131 | census-instrumentation/opencensus-python | contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py | trace_integration | def trace_integration(tracer=None):
"""Trace the Google Cloud Client libraries by integrating with
the transport level including HTTP and gRPC.
"""
log.info('Integrated module: {}'.format(MODULE_NAME))
# Integrate with gRPC
trace_grpc(tracer)
# Integrate with HTTP
trace_http(tracer) | python | def trace_integration(tracer=None):
"""Trace the Google Cloud Client libraries by integrating with
the transport level including HTTP and gRPC.
"""
log.info('Integrated module: {}'.format(MODULE_NAME))
# Integrate with gRPC
trace_grpc(tracer)
# Integrate with HTTP
trace_http(tracer) | [
"def",
"trace_integration",
"(",
"tracer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Integrated module: {}'",
".",
"format",
"(",
"MODULE_NAME",
")",
")",
"# Integrate with gRPC",
"trace_grpc",
"(",
"tracer",
")",
"# Integrate with HTTP",
"trace_http",
"("... | Trace the Google Cloud Client libraries by integrating with
the transport level including HTTP and gRPC. | [
"Trace",
"the",
"Google",
"Cloud",
"Client",
"libraries",
"by",
"integrating",
"with",
"the",
"transport",
"level",
"including",
"HTTP",
"and",
"gRPC",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L37-L47 |
226,132 | census-instrumentation/opencensus-python | contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py | trace_grpc | def trace_grpc(tracer=None):
"""Integrate with gRPC."""
# Wrap google.cloud._helpers.make_secure_channel
make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
make_secure_channel_wrapped = wrap_make_secure_channel(
make_secure_channel_func, tracer)
setattr(
_helpers,
MAKE_SECURE_CHANNEL,
make_secure_channel_wrapped)
# Wrap the grpc.insecure_channel.
insecure_channel_func = getattr(grpc, INSECURE_CHANNEL)
insecure_channel_wrapped = wrap_insecure_channel(
insecure_channel_func, tracer)
setattr(
grpc,
INSECURE_CHANNEL,
insecure_channel_wrapped)
# Wrap google.api_core.grpc_helpers.create_channel
create_channel_func = getattr(grpc_helpers, CREATE_CHANNEL)
create_channel_wrapped = wrap_create_channel(create_channel_func, tracer)
setattr(
grpc_helpers,
CREATE_CHANNEL,
create_channel_wrapped) | python | def trace_grpc(tracer=None):
"""Integrate with gRPC."""
# Wrap google.cloud._helpers.make_secure_channel
make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
make_secure_channel_wrapped = wrap_make_secure_channel(
make_secure_channel_func, tracer)
setattr(
_helpers,
MAKE_SECURE_CHANNEL,
make_secure_channel_wrapped)
# Wrap the grpc.insecure_channel.
insecure_channel_func = getattr(grpc, INSECURE_CHANNEL)
insecure_channel_wrapped = wrap_insecure_channel(
insecure_channel_func, tracer)
setattr(
grpc,
INSECURE_CHANNEL,
insecure_channel_wrapped)
# Wrap google.api_core.grpc_helpers.create_channel
create_channel_func = getattr(grpc_helpers, CREATE_CHANNEL)
create_channel_wrapped = wrap_create_channel(create_channel_func, tracer)
setattr(
grpc_helpers,
CREATE_CHANNEL,
create_channel_wrapped) | [
"def",
"trace_grpc",
"(",
"tracer",
"=",
"None",
")",
":",
"# Wrap google.cloud._helpers.make_secure_channel",
"make_secure_channel_func",
"=",
"getattr",
"(",
"_helpers",
",",
"MAKE_SECURE_CHANNEL",
")",
"make_secure_channel_wrapped",
"=",
"wrap_make_secure_channel",
"(",
... | Integrate with gRPC. | [
"Integrate",
"with",
"gRPC",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L50-L76 |
226,133 | census-instrumentation/opencensus-python | contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py | wrap_make_secure_channel | def wrap_make_secure_channel(make_secure_channel_func, tracer=None):
"""Wrap the google.cloud._helpers.make_secure_channel."""
def call(*args, **kwargs):
channel = make_secure_channel_func(*args, **kwargs)
try:
host = kwargs.get('host')
tracer_interceptor = OpenCensusClientInterceptor(tracer, host)
intercepted_channel = grpc.intercept_channel(
channel, tracer_interceptor)
return intercepted_channel # pragma: NO COVER
except Exception:
log.warning(
'Failed to wrap secure channel, '
'clientlibs grpc calls not traced.')
return channel
return call | python | def wrap_make_secure_channel(make_secure_channel_func, tracer=None):
"""Wrap the google.cloud._helpers.make_secure_channel."""
def call(*args, **kwargs):
channel = make_secure_channel_func(*args, **kwargs)
try:
host = kwargs.get('host')
tracer_interceptor = OpenCensusClientInterceptor(tracer, host)
intercepted_channel = grpc.intercept_channel(
channel, tracer_interceptor)
return intercepted_channel # pragma: NO COVER
except Exception:
log.warning(
'Failed to wrap secure channel, '
'clientlibs grpc calls not traced.')
return channel
return call | [
"def",
"wrap_make_secure_channel",
"(",
"make_secure_channel_func",
",",
"tracer",
"=",
"None",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"channel",
"=",
"make_secure_channel_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwar... | Wrap the google.cloud._helpers.make_secure_channel. | [
"Wrap",
"the",
"google",
".",
"cloud",
".",
"_helpers",
".",
"make_secure_channel",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L84-L100 |
226,134 | census-instrumentation/opencensus-python | contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py | wrap_insecure_channel | def wrap_insecure_channel(insecure_channel_func, tracer=None):
"""Wrap the grpc.insecure_channel."""
def call(*args, **kwargs):
channel = insecure_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
intercepted_channel = grpc.intercept_channel(
channel, tracer_interceptor)
return intercepted_channel # pragma: NO COVER
except Exception:
log.warning(
'Failed to wrap insecure channel, '
'clientlibs grpc calls not traced.')
return channel
return call | python | def wrap_insecure_channel(insecure_channel_func, tracer=None):
"""Wrap the grpc.insecure_channel."""
def call(*args, **kwargs):
channel = insecure_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
intercepted_channel = grpc.intercept_channel(
channel, tracer_interceptor)
return intercepted_channel # pragma: NO COVER
except Exception:
log.warning(
'Failed to wrap insecure channel, '
'clientlibs grpc calls not traced.')
return channel
return call | [
"def",
"wrap_insecure_channel",
"(",
"insecure_channel_func",
",",
"tracer",
"=",
"None",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"channel",
"=",
"insecure_channel_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Wrap the grpc.insecure_channel. | [
"Wrap",
"the",
"grpc",
".",
"insecure_channel",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L103-L119 |
226,135 | census-instrumentation/opencensus-python | contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py | _convert_reftype_to_jaeger_reftype | def _convert_reftype_to_jaeger_reftype(ref):
"""Convert opencensus reference types to jaeger reference types."""
if ref == link_module.Type.CHILD_LINKED_SPAN:
return jaeger.SpanRefType.CHILD_OF
if ref == link_module.Type.PARENT_LINKED_SPAN:
return jaeger.SpanRefType.FOLLOWS_FROM
return None | python | def _convert_reftype_to_jaeger_reftype(ref):
"""Convert opencensus reference types to jaeger reference types."""
if ref == link_module.Type.CHILD_LINKED_SPAN:
return jaeger.SpanRefType.CHILD_OF
if ref == link_module.Type.PARENT_LINKED_SPAN:
return jaeger.SpanRefType.FOLLOWS_FROM
return None | [
"def",
"_convert_reftype_to_jaeger_reftype",
"(",
"ref",
")",
":",
"if",
"ref",
"==",
"link_module",
".",
"Type",
".",
"CHILD_LINKED_SPAN",
":",
"return",
"jaeger",
".",
"SpanRefType",
".",
"CHILD_OF",
"if",
"ref",
"==",
"link_module",
".",
"Type",
".",
"PAREN... | Convert opencensus reference types to jaeger reference types. | [
"Convert",
"opencensus",
"reference",
"types",
"to",
"jaeger",
"reference",
"types",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L238-L244 |
226,136 | census-instrumentation/opencensus-python | contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py | _convert_hex_str_to_int | def _convert_hex_str_to_int(val):
"""Convert hexadecimal formatted ids to signed int64"""
if val is None:
return None
hex_num = int(val, 16)
# ensure it fits into 64-bit
if hex_num > 0x7FFFFFFFFFFFFFFF:
hex_num -= 0x10000000000000000
assert -9223372036854775808 <= hex_num <= 9223372036854775807
return hex_num | python | def _convert_hex_str_to_int(val):
"""Convert hexadecimal formatted ids to signed int64"""
if val is None:
return None
hex_num = int(val, 16)
# ensure it fits into 64-bit
if hex_num > 0x7FFFFFFFFFFFFFFF:
hex_num -= 0x10000000000000000
assert -9223372036854775808 <= hex_num <= 9223372036854775807
return hex_num | [
"def",
"_convert_hex_str_to_int",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"None",
"hex_num",
"=",
"int",
"(",
"val",
",",
"16",
")",
"# ensure it fits into 64-bit",
"if",
"hex_num",
">",
"0x7FFFFFFFFFFFFFFF",
":",
"hex_num",
"-=",
"0... | Convert hexadecimal formatted ids to signed int64 | [
"Convert",
"hexadecimal",
"formatted",
"ids",
"to",
"signed",
"int64"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L247-L258 |
226,137 | census-instrumentation/opencensus-python | contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py | _convert_attribute_to_tag | def _convert_attribute_to_tag(key, attr):
"""Convert the attributes to jaeger tags."""
if isinstance(attr, bool):
return jaeger.Tag(
key=key,
vBool=attr,
vType=jaeger.TagType.BOOL)
if isinstance(attr, str):
return jaeger.Tag(
key=key,
vStr=attr,
vType=jaeger.TagType.STRING)
if isinstance(attr, int):
return jaeger.Tag(
key=key,
vLong=attr,
vType=jaeger.TagType.LONG)
if isinstance(attr, float):
return jaeger.Tag(
key=key,
vDouble=attr,
vType=jaeger.TagType.DOUBLE)
logging.warn('Could not serialize attribute \
{}:{} to tag'.format(key, attr))
return None | python | def _convert_attribute_to_tag(key, attr):
"""Convert the attributes to jaeger tags."""
if isinstance(attr, bool):
return jaeger.Tag(
key=key,
vBool=attr,
vType=jaeger.TagType.BOOL)
if isinstance(attr, str):
return jaeger.Tag(
key=key,
vStr=attr,
vType=jaeger.TagType.STRING)
if isinstance(attr, int):
return jaeger.Tag(
key=key,
vLong=attr,
vType=jaeger.TagType.LONG)
if isinstance(attr, float):
return jaeger.Tag(
key=key,
vDouble=attr,
vType=jaeger.TagType.DOUBLE)
logging.warn('Could not serialize attribute \
{}:{} to tag'.format(key, attr))
return None | [
"def",
"_convert_attribute_to_tag",
"(",
"key",
",",
"attr",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"bool",
")",
":",
"return",
"jaeger",
".",
"Tag",
"(",
"key",
"=",
"key",
",",
"vBool",
"=",
"attr",
",",
"vType",
"=",
"jaeger",
".",
"TagTy... | Convert the attributes to jaeger tags. | [
"Convert",
"the",
"attributes",
"to",
"jaeger",
"tags",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L298-L322 |
226,138 | census-instrumentation/opencensus-python | contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py | JaegerExporter.translate_to_jaeger | def translate_to_jaeger(self, span_datas):
"""Translate the spans to Jaeger format.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit
"""
top_span = span_datas[0]
trace_id = top_span.context.trace_id if top_span.context is not None \
else None
jaeger_spans = []
for span in span_datas:
start_timestamp_ms = timestamp_to_microseconds(span.start_time)
end_timestamp_ms = timestamp_to_microseconds(span.end_time)
duration_ms = end_timestamp_ms - start_timestamp_ms
tags = _extract_tags(span.attributes)
status = span.status
if status is not None:
tags.append(jaeger.Tag(
key='status.code',
vType=jaeger.TagType.LONG,
vLong=status.code))
tags.append(jaeger.Tag(
key='status.message',
vType=jaeger.TagType.STRING,
vStr=status.message))
refs = _extract_refs_from_span(span)
logs = _extract_logs_from_span(span)
context = span.context
flags = None
if context is not None:
flags = int(context.trace_options.trace_options_byte)
span_id = span.span_id
parent_span_id = span.parent_span_id
jaeger_span = jaeger.Span(
traceIdHigh=_convert_hex_str_to_int(trace_id[0:16]),
traceIdLow=_convert_hex_str_to_int(trace_id[16:32]),
spanId=_convert_hex_str_to_int(span_id),
operationName=span.name,
startTime=int(round(start_timestamp_ms)),
duration=int(round(duration_ms)),
tags=tags,
logs=logs,
references=refs,
flags=flags,
parentSpanId=_convert_hex_str_to_int(parent_span_id or '0'))
jaeger_spans.append(jaeger_span)
return jaeger_spans | python | def translate_to_jaeger(self, span_datas):
"""Translate the spans to Jaeger format.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit
"""
top_span = span_datas[0]
trace_id = top_span.context.trace_id if top_span.context is not None \
else None
jaeger_spans = []
for span in span_datas:
start_timestamp_ms = timestamp_to_microseconds(span.start_time)
end_timestamp_ms = timestamp_to_microseconds(span.end_time)
duration_ms = end_timestamp_ms - start_timestamp_ms
tags = _extract_tags(span.attributes)
status = span.status
if status is not None:
tags.append(jaeger.Tag(
key='status.code',
vType=jaeger.TagType.LONG,
vLong=status.code))
tags.append(jaeger.Tag(
key='status.message',
vType=jaeger.TagType.STRING,
vStr=status.message))
refs = _extract_refs_from_span(span)
logs = _extract_logs_from_span(span)
context = span.context
flags = None
if context is not None:
flags = int(context.trace_options.trace_options_byte)
span_id = span.span_id
parent_span_id = span.parent_span_id
jaeger_span = jaeger.Span(
traceIdHigh=_convert_hex_str_to_int(trace_id[0:16]),
traceIdLow=_convert_hex_str_to_int(trace_id[16:32]),
spanId=_convert_hex_str_to_int(span_id),
operationName=span.name,
startTime=int(round(start_timestamp_ms)),
duration=int(round(duration_ms)),
tags=tags,
logs=logs,
references=refs,
flags=flags,
parentSpanId=_convert_hex_str_to_int(parent_span_id or '0'))
jaeger_spans.append(jaeger_span)
return jaeger_spans | [
"def",
"translate_to_jaeger",
"(",
"self",
",",
"span_datas",
")",
":",
"top_span",
"=",
"span_datas",
"[",
"0",
"]",
"trace_id",
"=",
"top_span",
".",
"context",
".",
"trace_id",
"if",
"top_span",
".",
"context",
"is",
"not",
"None",
"else",
"None",
"jaeg... | Translate the spans to Jaeger format.
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param span_datas:
SpanData tuples to emit | [
"Translate",
"the",
"spans",
"to",
"Jaeger",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L159-L220 |
226,139 | census-instrumentation/opencensus-python | contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py | Collector.emit | def emit(self, batch):
"""Submits batches to Thrift HTTP Server through Binary Protocol.
:type batch:
:class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch`
:param batch: Object to emit Jaeger spans.
"""
try:
self.client.submitBatches([batch])
# it will call http_transport.flush() and
# status code and message will be updated
code = self.http_transport.code
msg = self.http_transport.message
if code >= 300 or code < 200:
logging.error("Traces cannot be uploaded;\
HTTP status code: {}, message {}".format(code, msg))
except Exception as e: # pragma: NO COVER
logging.error(getattr(e, 'message', e))
finally:
if self.http_transport.isOpen():
self.http_transport.close() | python | def emit(self, batch):
"""Submits batches to Thrift HTTP Server through Binary Protocol.
:type batch:
:class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch`
:param batch: Object to emit Jaeger spans.
"""
try:
self.client.submitBatches([batch])
# it will call http_transport.flush() and
# status code and message will be updated
code = self.http_transport.code
msg = self.http_transport.message
if code >= 300 or code < 200:
logging.error("Traces cannot be uploaded;\
HTTP status code: {}, message {}".format(code, msg))
except Exception as e: # pragma: NO COVER
logging.error(getattr(e, 'message', e))
finally:
if self.http_transport.isOpen():
self.http_transport.close() | [
"def",
"emit",
"(",
"self",
",",
"batch",
")",
":",
"try",
":",
"self",
".",
"client",
".",
"submitBatches",
"(",
"[",
"batch",
"]",
")",
"# it will call http_transport.flush() and",
"# status code and message will be updated",
"code",
"=",
"self",
".",
"http_tran... | Submits batches to Thrift HTTP Server through Binary Protocol.
:type batch:
:class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch`
:param batch: Object to emit Jaeger spans. | [
"Submits",
"batches",
"to",
"Thrift",
"HTTP",
"Server",
"through",
"Binary",
"Protocol",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L369-L390 |
226,140 | census-instrumentation/opencensus-python | opencensus/stats/view_data.py | ViewData.get_tag_values | def get_tag_values(self, tags, columns):
"""function to get the tag values from tags and columns"""
tag_values = []
i = 0
while i < len(columns):
tag_key = columns[i]
if tag_key in tags:
tag_values.append(tags.get(tag_key))
else:
tag_values.append(None)
i += 1
return tag_values | python | def get_tag_values(self, tags, columns):
"""function to get the tag values from tags and columns"""
tag_values = []
i = 0
while i < len(columns):
tag_key = columns[i]
if tag_key in tags:
tag_values.append(tags.get(tag_key))
else:
tag_values.append(None)
i += 1
return tag_values | [
"def",
"get_tag_values",
"(",
"self",
",",
"tags",
",",
"columns",
")",
":",
"tag_values",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"columns",
")",
":",
"tag_key",
"=",
"columns",
"[",
"i",
"]",
"if",
"tag_key",
"in",
"tags",
... | function to get the tag values from tags and columns | [
"function",
"to",
"get",
"the",
"tag",
"values",
"from",
"tags",
"and",
"columns"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_data.py#L72-L83 |
226,141 | census-instrumentation/opencensus-python | opencensus/stats/view_data.py | ViewData.record | def record(self, context, value, timestamp, attachments=None):
"""records the view data against context"""
if context is None:
tags = dict()
else:
tags = context.map
tag_values = self.get_tag_values(tags=tags,
columns=self.view.columns)
tuple_vals = tuple(tag_values)
if tuple_vals not in self.tag_value_aggregation_data_map:
self.tag_value_aggregation_data_map[tuple_vals] = copy.deepcopy(
self.view.aggregation.aggregation_data)
self.tag_value_aggregation_data_map.get(tuple_vals).\
add_sample(value, timestamp, attachments) | python | def record(self, context, value, timestamp, attachments=None):
"""records the view data against context"""
if context is None:
tags = dict()
else:
tags = context.map
tag_values = self.get_tag_values(tags=tags,
columns=self.view.columns)
tuple_vals = tuple(tag_values)
if tuple_vals not in self.tag_value_aggregation_data_map:
self.tag_value_aggregation_data_map[tuple_vals] = copy.deepcopy(
self.view.aggregation.aggregation_data)
self.tag_value_aggregation_data_map.get(tuple_vals).\
add_sample(value, timestamp, attachments) | [
"def",
"record",
"(",
"self",
",",
"context",
",",
"value",
",",
"timestamp",
",",
"attachments",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"tags",
"=",
"dict",
"(",
")",
"else",
":",
"tags",
"=",
"context",
".",
"map",
"tag_values",... | records the view data against context | [
"records",
"the",
"view",
"data",
"against",
"context"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_data.py#L85-L98 |
226,142 | census-instrumentation/opencensus-python | contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py | trace_integration | def trace_integration(tracer=None):
"""Wrap the httplib to trace."""
log.info('Integrated module: {}'.format(MODULE_NAME))
# Wrap the httplib request function
request_func = getattr(
httplib.HTTPConnection, HTTPLIB_REQUEST_FUNC)
wrapped_request = wrap_httplib_request(request_func)
setattr(httplib.HTTPConnection, request_func.__name__, wrapped_request)
# Wrap the httplib response function
response_func = getattr(
httplib.HTTPConnection, HTTPLIB_RESPONSE_FUNC)
wrapped_response = wrap_httplib_response(response_func)
setattr(httplib.HTTPConnection, response_func.__name__, wrapped_response) | python | def trace_integration(tracer=None):
"""Wrap the httplib to trace."""
log.info('Integrated module: {}'.format(MODULE_NAME))
# Wrap the httplib request function
request_func = getattr(
httplib.HTTPConnection, HTTPLIB_REQUEST_FUNC)
wrapped_request = wrap_httplib_request(request_func)
setattr(httplib.HTTPConnection, request_func.__name__, wrapped_request)
# Wrap the httplib response function
response_func = getattr(
httplib.HTTPConnection, HTTPLIB_RESPONSE_FUNC)
wrapped_response = wrap_httplib_response(response_func)
setattr(httplib.HTTPConnection, response_func.__name__, wrapped_response) | [
"def",
"trace_integration",
"(",
"tracer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Integrated module: {}'",
".",
"format",
"(",
"MODULE_NAME",
")",
")",
"# Wrap the httplib request function",
"request_func",
"=",
"getattr",
"(",
"httplib",
".",
"HTTPConn... | Wrap the httplib to trace. | [
"Wrap",
"the",
"httplib",
"to",
"trace",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L41-L55 |
226,143 | census-instrumentation/opencensus-python | contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py | wrap_httplib_request | def wrap_httplib_request(request_func):
"""Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later.
"""
def call(self, method, url, body, headers, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
dest_url = '{}:{}'.format(self._dns_host, self.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return request_func(self, method, url, body,
headers, *args, **kwargs)
_span = _tracer.start_span()
_span.span_kind = span_module.SpanKind.CLIENT
_span.name = '[httplib]{}'.format(request_func.__name__)
# Add the request url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
# Add the request method to attributes
_tracer.add_attribute_to_current_span(HTTP_METHOD, method)
# Store the current span id to thread local.
execution_context.set_opencensus_attr(
'httplib/current_span_id', _span.span_id)
try:
headers = headers.copy()
headers.update(_tracer.propagator.to_headers(
_span.context_tracer.span_context))
except Exception: # pragma: NO COVER
pass
return request_func(self, method, url, body, headers, *args, **kwargs)
return call | python | def wrap_httplib_request(request_func):
"""Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later.
"""
def call(self, method, url, body, headers, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
dest_url = '{}:{}'.format(self._dns_host, self.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return request_func(self, method, url, body,
headers, *args, **kwargs)
_span = _tracer.start_span()
_span.span_kind = span_module.SpanKind.CLIENT
_span.name = '[httplib]{}'.format(request_func.__name__)
# Add the request url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
# Add the request method to attributes
_tracer.add_attribute_to_current_span(HTTP_METHOD, method)
# Store the current span id to thread local.
execution_context.set_opencensus_attr(
'httplib/current_span_id', _span.span_id)
try:
headers = headers.copy()
headers.update(_tracer.propagator.to_headers(
_span.context_tracer.span_context))
except Exception: # pragma: NO COVER
pass
return request_func(self, method, url, body, headers, *args, **kwargs)
return call | [
"def",
"wrap_httplib_request",
"(",
"request_func",
")",
":",
"def",
"call",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
",",
"headers",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_tracer",
"=",
"execution_context",
".",
"get_opencens... | Wrap the httplib request function to trace. Create a new span and update
and close the span in the response later. | [
"Wrap",
"the",
"httplib",
"request",
"function",
"to",
"trace",
".",
"Create",
"a",
"new",
"span",
"and",
"update",
"and",
"close",
"the",
"span",
"in",
"the",
"response",
"later",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L58-L92 |
226,144 | census-instrumentation/opencensus-python | contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py | wrap_httplib_response | def wrap_httplib_response(response_func):
"""Wrap the httplib response function to trace.
If there is a corresponding httplib request span, update and close it.
If not, return the response.
"""
def call(self, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
current_span_id = execution_context.get_opencensus_attr(
'httplib/current_span_id')
span = _tracer.current_span()
# No corresponding request span is found, request not traced.
if not span or span.span_id != current_span_id:
return response_func(self, *args, **kwargs)
result = response_func(self, *args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status))
_tracer.end_span()
return result
return call | python | def wrap_httplib_response(response_func):
"""Wrap the httplib response function to trace.
If there is a corresponding httplib request span, update and close it.
If not, return the response.
"""
def call(self, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
current_span_id = execution_context.get_opencensus_attr(
'httplib/current_span_id')
span = _tracer.current_span()
# No corresponding request span is found, request not traced.
if not span or span.span_id != current_span_id:
return response_func(self, *args, **kwargs)
result = response_func(self, *args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status))
_tracer.end_span()
return result
return call | [
"def",
"wrap_httplib_response",
"(",
"response_func",
")",
":",
"def",
"call",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_tracer",
"=",
"execution_context",
".",
"get_opencensus_tracer",
"(",
")",
"current_span_id",
"=",
"execution_con... | Wrap the httplib response function to trace.
If there is a corresponding httplib request span, update and close it.
If not, return the response. | [
"Wrap",
"the",
"httplib",
"response",
"function",
"to",
"trace",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L95-L122 |
226,145 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | get_timeseries_list | def get_timeseries_list(points, timestamp):
"""Convert a list of `GaugePoint`s into a list of `TimeSeries`.
Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each
measurement in `points`. Each series contains a single
:class:`opencensus.metrics.export.point.Point` that represents the last
recorded value of the measurement.
:type points: list(:class:`GaugePoint`)
:param points: The list of measurements to convert.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: list(:class:`opencensus.metrics.export.time_series.TimeSeries`)
:return: A list of one `TimeSeries` for each point in `points`.
"""
ts_list = []
for lv, gp in points.items():
point = point_module.Point(gp.to_point_value(), timestamp)
ts_list.append(time_series.TimeSeries(lv, [point], timestamp))
return ts_list | python | def get_timeseries_list(points, timestamp):
"""Convert a list of `GaugePoint`s into a list of `TimeSeries`.
Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each
measurement in `points`. Each series contains a single
:class:`opencensus.metrics.export.point.Point` that represents the last
recorded value of the measurement.
:type points: list(:class:`GaugePoint`)
:param points: The list of measurements to convert.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: list(:class:`opencensus.metrics.export.time_series.TimeSeries`)
:return: A list of one `TimeSeries` for each point in `points`.
"""
ts_list = []
for lv, gp in points.items():
point = point_module.Point(gp.to_point_value(), timestamp)
ts_list.append(time_series.TimeSeries(lv, [point], timestamp))
return ts_list | [
"def",
"get_timeseries_list",
"(",
"points",
",",
"timestamp",
")",
":",
"ts_list",
"=",
"[",
"]",
"for",
"lv",
",",
"gp",
"in",
"points",
".",
"items",
"(",
")",
":",
"point",
"=",
"point_module",
".",
"Point",
"(",
"gp",
".",
"to_point_value",
"(",
... | Convert a list of `GaugePoint`s into a list of `TimeSeries`.
Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each
measurement in `points`. Each series contains a single
:class:`opencensus.metrics.export.point.Point` that represents the last
recorded value of the measurement.
:type points: list(:class:`GaugePoint`)
:param points: The list of measurements to convert.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: list(:class:`opencensus.metrics.export.time_series.TimeSeries`)
:return: A list of one `TimeSeries` for each point in `points`. | [
"Convert",
"a",
"list",
"of",
"GaugePoint",
"s",
"into",
"a",
"list",
"of",
"TimeSeries",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L29-L50 |
226,146 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | GaugePointLong.add | def add(self, val):
"""Add `val` to the current value.
:type val: int
:param val: Value to add.
"""
if not isinstance(val, six.integer_types):
raise ValueError("GaugePointLong only supports integer types")
with self._value_lock:
self.value += val | python | def add(self, val):
"""Add `val` to the current value.
:type val: int
:param val: Value to add.
"""
if not isinstance(val, six.integer_types):
raise ValueError("GaugePointLong only supports integer types")
with self._value_lock:
self.value += val | [
"def",
"add",
"(",
"self",
",",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"ValueError",
"(",
"\"GaugePointLong only supports integer types\"",
")",
"with",
"self",
".",
"_value_lock",
":",
"s... | Add `val` to the current value.
:type val: int
:param val: Value to add. | [
"Add",
"val",
"to",
"the",
"current",
"value",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L80-L89 |
226,147 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | DerivedGaugePoint.get_value | def get_value(self):
"""Get the current value of the underlying measurement.
Calls the tracked function and stores the value in the wrapped
measurement as a side-effect.
:rtype: int, float, or None
:return: The current value of the wrapped function, or `None` if it no
longer exists.
"""
try:
val = self.func()()
except TypeError: # The underlying function has been GC'd
return None
self.gauge_point._set(val)
return self.gauge_point.get_value() | python | def get_value(self):
"""Get the current value of the underlying measurement.
Calls the tracked function and stores the value in the wrapped
measurement as a side-effect.
:rtype: int, float, or None
:return: The current value of the wrapped function, or `None` if it no
longer exists.
"""
try:
val = self.func()()
except TypeError: # The underlying function has been GC'd
return None
self.gauge_point._set(val)
return self.gauge_point.get_value() | [
"def",
"get_value",
"(",
"self",
")",
":",
"try",
":",
"val",
"=",
"self",
".",
"func",
"(",
")",
"(",
")",
"except",
"TypeError",
":",
"# The underlying function has been GC'd",
"return",
"None",
"self",
".",
"gauge_point",
".",
"_set",
"(",
"val",
")",
... | Get the current value of the underlying measurement.
Calls the tracked function and stores the value in the wrapped
measurement as a side-effect.
:rtype: int, float, or None
:return: The current value of the wrapped function, or `None` if it no
longer exists. | [
"Get",
"the",
"current",
"value",
"of",
"the",
"underlying",
"measurement",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L205-L221 |
226,148 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | BaseGauge.remove_time_series | def remove_time_series(self, label_values):
"""Remove the time series for specific label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: Label values of the time series to remove.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
self._remove_time_series(label_values) | python | def remove_time_series(self, label_values):
"""Remove the time series for specific label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: Label values of the time series to remove.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
self._remove_time_series(label_values) | [
"def",
"remove_time_series",
"(",
"self",
",",
"label_values",
")",
":",
"if",
"label_values",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"any",
"(",
"lv",
"is",
"None",
"for",
"lv",
"in",
"label_values",
")",
":",
"raise",
"ValueError",
"if",
"len",
... | Remove the time series for specific label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: Label values of the time series to remove. | [
"Remove",
"the",
"time",
"series",
"for",
"specific",
"label",
"values",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L265-L277 |
226,149 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | BaseGauge.get_metric | def get_metric(self, timestamp):
"""Get a metric including all current time series.
Get a :class:`opencensus.metrics.export.metric.Metric` with one
:class:`opencensus.metrics.export.time_series.TimeSeries` for each
set of label values with a recorded measurement. Each `TimeSeries`
has a single point that represents the last recorded value.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: :class:`opencensus.metrics.export.metric.Metric` or None
:return: A converted metric for all current measurements.
"""
if not self.points:
return None
with self._points_lock:
ts_list = get_timeseries_list(self.points, timestamp)
return metric.Metric(self.descriptor, ts_list) | python | def get_metric(self, timestamp):
"""Get a metric including all current time series.
Get a :class:`opencensus.metrics.export.metric.Metric` with one
:class:`opencensus.metrics.export.time_series.TimeSeries` for each
set of label values with a recorded measurement. Each `TimeSeries`
has a single point that represents the last recorded value.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: :class:`opencensus.metrics.export.metric.Metric` or None
:return: A converted metric for all current measurements.
"""
if not self.points:
return None
with self._points_lock:
ts_list = get_timeseries_list(self.points, timestamp)
return metric.Metric(self.descriptor, ts_list) | [
"def",
"get_metric",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"not",
"self",
".",
"points",
":",
"return",
"None",
"with",
"self",
".",
"_points_lock",
":",
"ts_list",
"=",
"get_timeseries_list",
"(",
"self",
".",
"points",
",",
"timestamp",
")",
"... | Get a metric including all current time series.
Get a :class:`opencensus.metrics.export.metric.Metric` with one
:class:`opencensus.metrics.export.time_series.TimeSeries` for each
set of label values with a recorded measurement. Each `TimeSeries`
has a single point that represents the last recorded value.
:type timestamp: :class:`datetime.datetime`
:param timestamp: Recording time to report, usually the current time.
:rtype: :class:`opencensus.metrics.export.metric.Metric` or None
:return: A converted metric for all current measurements. | [
"Get",
"a",
"metric",
"including",
"all",
"current",
"time",
"series",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L288-L307 |
226,150 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | Gauge.get_or_create_time_series | def get_or_create_time_series(self, label_values):
"""Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:class:`opencensus.metrics.export.cumulative.CumulativePointLong`,
or
:class:`opencensus.metrics.export.cumulative.CumulativePointDouble`
:return: A mutable point that represents the last value of the
measurement.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
return self._get_or_create_time_series(label_values) | python | def get_or_create_time_series(self, label_values):
"""Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:class:`opencensus.metrics.export.cumulative.CumulativePointLong`,
or
:class:`opencensus.metrics.export.cumulative.CumulativePointDouble`
:return: A mutable point that represents the last value of the
measurement.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
return self._get_or_create_time_series(label_values) | [
"def",
"get_or_create_time_series",
"(",
"self",
",",
"label_values",
")",
":",
"if",
"label_values",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"any",
"(",
"lv",
"is",
"None",
"for",
"lv",
"in",
"label_values",
")",
":",
"raise",
"ValueError",
"if",
... | Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:class:`opencensus.metrics.export.cumulative.CumulativePointLong`,
or
:class:`opencensus.metrics.export.cumulative.CumulativePointDouble`
:return: A mutable point that represents the last value of the
measurement. | [
"Get",
"a",
"mutable",
"measurement",
"for",
"the",
"given",
"set",
"of",
"label",
"values",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L336-L355 |
226,151 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | DerivedGauge.create_time_series | def create_time_series(self, label_values, func):
"""Create a derived measurement to trac `func`.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
if func is None:
raise ValueError
return self._create_time_series(label_values, func) | python | def create_time_series(self, label_values, func):
"""Create a derived measurement to trac `func`.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`.
"""
if label_values is None:
raise ValueError
if any(lv is None for lv in label_values):
raise ValueError
if len(label_values) != self._len_label_keys:
raise ValueError
if func is None:
raise ValueError
return self._create_time_series(label_values, func) | [
"def",
"create_time_series",
"(",
"self",
",",
"label_values",
",",
"func",
")",
":",
"if",
"label_values",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"any",
"(",
"lv",
"is",
"None",
"for",
"lv",
"in",
"label_values",
")",
":",
"raise",
"ValueError",
... | Create a derived measurement to trac `func`.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`. | [
"Create",
"a",
"derived",
"measurement",
"to",
"trac",
"func",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L412-L432 |
226,152 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | DerivedGauge.create_default_time_series | def create_default_time_series(self, func):
"""Create the default derived measurement for this gauge.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`.
"""
if func is None:
raise ValueError
return self._create_time_series(self.default_label_values, func) | python | def create_default_time_series(self, func):
"""Create the default derived measurement for this gauge.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`.
"""
if func is None:
raise ValueError
return self._create_time_series(self.default_label_values, func) | [
"def",
"create_default_time_series",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"is",
"None",
":",
"raise",
"ValueError",
"return",
"self",
".",
"_create_time_series",
"(",
"self",
".",
"default_label_values",
",",
"func",
")"
] | Create the default derived measurement for this gauge.
:type func: function
:param func: The function to track.
:rtype: :class:`DerivedGaugePoint`
:return: A read-only measurement that tracks `func`. | [
"Create",
"the",
"default",
"derived",
"measurement",
"for",
"this",
"gauge",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L434-L445 |
226,153 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | Registry.add_gauge | def add_gauge(self, gauge):
"""Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
:class:`opencensus.metrics.export.cumulative.DoubleCumulative`,
:class:`DerivedLongGauge`, :class:`DerivedDoubleGauge`
:class:`opencensus.metrics.export.cumulative.DerivedLongCumulative`,
or
:class:`opencensus.metrics.export.cumulative.DerivedDoubleCumulative`
:param gauge: The gauge to add to the registry.
"""
if gauge is None:
raise ValueError
name = gauge.descriptor.name
with self._gauges_lock:
if name in self.gauges:
raise ValueError(
'Another gauge named "{}" is already registered'
.format(name))
self.gauges[name] = gauge | python | def add_gauge(self, gauge):
"""Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
:class:`opencensus.metrics.export.cumulative.DoubleCumulative`,
:class:`DerivedLongGauge`, :class:`DerivedDoubleGauge`
:class:`opencensus.metrics.export.cumulative.DerivedLongCumulative`,
or
:class:`opencensus.metrics.export.cumulative.DerivedDoubleCumulative`
:param gauge: The gauge to add to the registry.
"""
if gauge is None:
raise ValueError
name = gauge.descriptor.name
with self._gauges_lock:
if name in self.gauges:
raise ValueError(
'Another gauge named "{}" is already registered'
.format(name))
self.gauges[name] = gauge | [
"def",
"add_gauge",
"(",
"self",
",",
"gauge",
")",
":",
"if",
"gauge",
"is",
"None",
":",
"raise",
"ValueError",
"name",
"=",
"gauge",
".",
"descriptor",
".",
"name",
"with",
"self",
".",
"_gauges_lock",
":",
"if",
"name",
"in",
"self",
".",
"gauges",... | Add `gauge` to the registry.
Raises a `ValueError` if another gauge with the same name already
exists in the registry.
:type gauge: class:`LongGauge`, class:`DoubleGauge`,
:class:`opencensus.metrics.export.cumulative.LongCumulative`,
:class:`opencensus.metrics.export.cumulative.DoubleCumulative`,
:class:`DerivedLongGauge`, :class:`DerivedDoubleGauge`
:class:`opencensus.metrics.export.cumulative.DerivedLongCumulative`,
or
:class:`opencensus.metrics.export.cumulative.DerivedDoubleCumulative`
:param gauge: The gauge to add to the registry. | [
"Add",
"gauge",
"to",
"the",
"registry",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L473-L496 |
226,154 | census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | Registry.get_metrics | def get_metrics(self):
"""Get a metric for each gauge in the registry at the current time.
:rtype: set(:class:`opencensus.metrics.export.metric.Metric`)
:return: A set of `Metric`s, one for each registered gauge.
"""
now = datetime.utcnow()
metrics = set()
for gauge in self.gauges.values():
metrics.add(gauge.get_metric(now))
return metrics | python | def get_metrics(self):
"""Get a metric for each gauge in the registry at the current time.
:rtype: set(:class:`opencensus.metrics.export.metric.Metric`)
:return: A set of `Metric`s, one for each registered gauge.
"""
now = datetime.utcnow()
metrics = set()
for gauge in self.gauges.values():
metrics.add(gauge.get_metric(now))
return metrics | [
"def",
"get_metrics",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"metrics",
"=",
"set",
"(",
")",
"for",
"gauge",
"in",
"self",
".",
"gauges",
".",
"values",
"(",
")",
":",
"metrics",
".",
"add",
"(",
"gauge",
".",
"g... | Get a metric for each gauge in the registry at the current time.
:rtype: set(:class:`opencensus.metrics.export.metric.Metric`)
:return: A set of `Metric`s, one for each registered gauge. | [
"Get",
"a",
"metric",
"for",
"each",
"gauge",
"in",
"the",
"registry",
"at",
"the",
"current",
"time",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L498-L508 |
226,155 | census-instrumentation/opencensus-python | opencensus/common/monitored_resource/gcp_metadata_config.py | GcpMetadataConfig._initialize_metadata_service | def _initialize_metadata_service(cls):
"""Initialize metadata service once and load gcp metadata into map
This method should only be called once.
"""
if cls.inited:
return
instance_id = cls.get_attribute('instance/id')
if instance_id is not None:
cls.is_running = True
_GCP_METADATA_MAP['instance_id'] = instance_id
# fetch attributes from metadata request
for attribute_key, attribute_uri in _GCE_ATTRIBUTES.items():
if attribute_key not in _GCP_METADATA_MAP:
attribute_value = cls.get_attribute(attribute_uri)
if attribute_value is not None: # pragma: NO COVER
_GCP_METADATA_MAP[attribute_key] = attribute_value
cls.inited = True | python | def _initialize_metadata_service(cls):
"""Initialize metadata service once and load gcp metadata into map
This method should only be called once.
"""
if cls.inited:
return
instance_id = cls.get_attribute('instance/id')
if instance_id is not None:
cls.is_running = True
_GCP_METADATA_MAP['instance_id'] = instance_id
# fetch attributes from metadata request
for attribute_key, attribute_uri in _GCE_ATTRIBUTES.items():
if attribute_key not in _GCP_METADATA_MAP:
attribute_value = cls.get_attribute(attribute_uri)
if attribute_value is not None: # pragma: NO COVER
_GCP_METADATA_MAP[attribute_key] = attribute_value
cls.inited = True | [
"def",
"_initialize_metadata_service",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"inited",
":",
"return",
"instance_id",
"=",
"cls",
".",
"get_attribute",
"(",
"'instance/id'",
")",
"if",
"instance_id",
"is",
"not",
"None",
":",
"cls",
".",
"is_running",
"=",
... | Initialize metadata service once and load gcp metadata into map
This method should only be called once. | [
"Initialize",
"metadata",
"service",
"once",
"and",
"load",
"gcp",
"metadata",
"into",
"map",
"This",
"method",
"should",
"only",
"be",
"called",
"once",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/monitored_resource/gcp_metadata_config.py#L59-L80 |
226,156 | census-instrumentation/opencensus-python | opencensus/trace/propagation/binary_format.py | BinaryFormatPropagator.to_header | def to_header(self, span_context):
"""Convert a SpanContext object to header in binary format.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: bytes
:returns: A trace context header in binary format.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = int(span_context.trace_options.trace_options_byte)
# If there is no span_id in this context, set it to 0, which is
# considered invalid and won't be set as the downstream parent span_id.
if span_id is None:
span_id = span_context_module.INVALID_SPAN_ID
# Convert trace_id to bytes with length 16, treat span_id as 64 bit
# integer which is unsigned long long type and convert it to bytes with
# length 8, trace_option is integer with length 1.
return struct.pack(
BINARY_FORMAT,
VERSION_ID,
TRACE_ID_FIELD_ID,
binascii.unhexlify(trace_id),
SPAN_ID_FIELD_ID,
binascii.unhexlify(span_id),
TRACE_OPTION_FIELD_ID,
trace_options) | python | def to_header(self, span_context):
"""Convert a SpanContext object to header in binary format.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: bytes
:returns: A trace context header in binary format.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = int(span_context.trace_options.trace_options_byte)
# If there is no span_id in this context, set it to 0, which is
# considered invalid and won't be set as the downstream parent span_id.
if span_id is None:
span_id = span_context_module.INVALID_SPAN_ID
# Convert trace_id to bytes with length 16, treat span_id as 64 bit
# integer which is unsigned long long type and convert it to bytes with
# length 8, trace_option is integer with length 1.
return struct.pack(
BINARY_FORMAT,
VERSION_ID,
TRACE_ID_FIELD_ID,
binascii.unhexlify(trace_id),
SPAN_ID_FIELD_ID,
binascii.unhexlify(span_id),
TRACE_OPTION_FIELD_ID,
trace_options) | [
"def",
"to_header",
"(",
"self",
",",
"span_context",
")",
":",
"trace_id",
"=",
"span_context",
".",
"trace_id",
"span_id",
"=",
"span_context",
".",
"span_id",
"trace_options",
"=",
"int",
"(",
"span_context",
".",
"trace_options",
".",
"trace_options_byte",
"... | Convert a SpanContext object to header in binary format.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: bytes
:returns: A trace context header in binary format. | [
"Convert",
"a",
"SpanContext",
"object",
"to",
"header",
"in",
"binary",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/binary_format.py#L138-L168 |
226,157 | census-instrumentation/opencensus-python | opencensus/trace/propagation/text_format.py | TextFormatPropagator.from_carrier | def from_carrier(self, carrier):
"""Generate a SpanContext object using the information in the carrier.
:type carrier: dict
:param carrier: The carrier which has the trace_id, span_id, options
information for creating a SpanContext.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the carrier.
"""
trace_id = None
span_id = None
trace_options = None
for key in carrier:
key = key.lower()
if key == _TRACE_ID_KEY:
trace_id = carrier[key]
if key == _SPAN_ID_KEY:
span_id = carrier[key]
if key == _TRACE_OPTIONS_KEY:
trace_options = bool(carrier[key])
if trace_options is None:
trace_options = DEFAULT_TRACE_OPTIONS
return SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=TraceOptions(trace_options),
from_header=True) | python | def from_carrier(self, carrier):
"""Generate a SpanContext object using the information in the carrier.
:type carrier: dict
:param carrier: The carrier which has the trace_id, span_id, options
information for creating a SpanContext.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the carrier.
"""
trace_id = None
span_id = None
trace_options = None
for key in carrier:
key = key.lower()
if key == _TRACE_ID_KEY:
trace_id = carrier[key]
if key == _SPAN_ID_KEY:
span_id = carrier[key]
if key == _TRACE_OPTIONS_KEY:
trace_options = bool(carrier[key])
if trace_options is None:
trace_options = DEFAULT_TRACE_OPTIONS
return SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=TraceOptions(trace_options),
from_header=True) | [
"def",
"from_carrier",
"(",
"self",
",",
"carrier",
")",
":",
"trace_id",
"=",
"None",
"span_id",
"=",
"None",
"trace_options",
"=",
"None",
"for",
"key",
"in",
"carrier",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"key",
"==",
"_TRACE_ID_KE... | Generate a SpanContext object using the information in the carrier.
:type carrier: dict
:param carrier: The carrier which has the trace_id, span_id, options
information for creating a SpanContext.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the carrier. | [
"Generate",
"a",
"SpanContext",
"object",
"using",
"the",
"information",
"in",
"the",
"carrier",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/text_format.py#L31-L61 |
226,158 | census-instrumentation/opencensus-python | opencensus/trace/propagation/text_format.py | TextFormatPropagator.to_carrier | def to_carrier(self, span_context, carrier):
"""Inject the SpanContext fields to carrier dict.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:type carrier: dict
:param carrier: The carrier which holds the trace_id, span_id, options
information from a SpanContext.
:rtype: dict
:returns: The carrier which holds the span context information.
"""
carrier[_TRACE_ID_KEY] = str(span_context.trace_id)
if span_context.span_id is not None:
carrier[_SPAN_ID_KEY] = str(span_context.span_id)
carrier[_TRACE_OPTIONS_KEY] = str(
span_context.trace_options.trace_options_byte)
return carrier | python | def to_carrier(self, span_context, carrier):
"""Inject the SpanContext fields to carrier dict.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:type carrier: dict
:param carrier: The carrier which holds the trace_id, span_id, options
information from a SpanContext.
:rtype: dict
:returns: The carrier which holds the span context information.
"""
carrier[_TRACE_ID_KEY] = str(span_context.trace_id)
if span_context.span_id is not None:
carrier[_SPAN_ID_KEY] = str(span_context.span_id)
carrier[_TRACE_OPTIONS_KEY] = str(
span_context.trace_options.trace_options_byte)
return carrier | [
"def",
"to_carrier",
"(",
"self",
",",
"span_context",
",",
"carrier",
")",
":",
"carrier",
"[",
"_TRACE_ID_KEY",
"]",
"=",
"str",
"(",
"span_context",
".",
"trace_id",
")",
"if",
"span_context",
".",
"span_id",
"is",
"not",
"None",
":",
"carrier",
"[",
... | Inject the SpanContext fields to carrier dict.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:type carrier: dict
:param carrier: The carrier which holds the trace_id, span_id, options
information from a SpanContext.
:rtype: dict
:returns: The carrier which holds the span context information. | [
"Inject",
"the",
"SpanContext",
"fields",
"to",
"carrier",
"dict",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/text_format.py#L63-L85 |
226,159 | census-instrumentation/opencensus-python | opencensus/trace/propagation/b3_format.py | B3FormatPropagator.from_headers | def from_headers(self, headers):
"""Generate a SpanContext object from B3 propagation headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from B3 propagation headers.
"""
if headers is None:
return SpanContext(from_header=False)
trace_id, span_id, sampled = None, None, None
state = headers.get(_STATE_HEADER_KEY)
if state:
fields = state.split('-', 4)
if len(fields) == 1:
sampled = fields[0]
elif len(fields) == 2:
trace_id, span_id = fields
elif len(fields) == 3:
trace_id, span_id, sampled = fields
elif len(fields) == 4:
trace_id, span_id, sampled, _parent_span_id = fields
else:
return SpanContext(from_header=False)
else:
trace_id = headers.get(_TRACE_ID_KEY)
span_id = headers.get(_SPAN_ID_KEY)
sampled = headers.get(_SAMPLED_KEY)
if sampled is not None:
# The specification encodes an enabled tracing decision as "1".
# In the wild pre-standard implementations might still send "true".
# "d" is set in the single header case when debugging is enabled.
sampled = sampled.lower() in ('1', 'd', 'true')
else:
# If there's no incoming sampling decision, it was deferred to us.
# Even though we set it to False here, we might still sample
# depending on the tracer configuration.
sampled = False
trace_options = TraceOptions()
trace_options.set_enabled(sampled)
# TraceId and SpanId headers both have to exist
if not trace_id or not span_id:
return SpanContext(trace_options=trace_options)
# Convert 64-bit trace ids to 128-bit
if len(trace_id) == 16:
trace_id = '0'*16 + trace_id
span_context = SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=trace_options,
from_header=True
)
return span_context | python | def from_headers(self, headers):
"""Generate a SpanContext object from B3 propagation headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from B3 propagation headers.
"""
if headers is None:
return SpanContext(from_header=False)
trace_id, span_id, sampled = None, None, None
state = headers.get(_STATE_HEADER_KEY)
if state:
fields = state.split('-', 4)
if len(fields) == 1:
sampled = fields[0]
elif len(fields) == 2:
trace_id, span_id = fields
elif len(fields) == 3:
trace_id, span_id, sampled = fields
elif len(fields) == 4:
trace_id, span_id, sampled, _parent_span_id = fields
else:
return SpanContext(from_header=False)
else:
trace_id = headers.get(_TRACE_ID_KEY)
span_id = headers.get(_SPAN_ID_KEY)
sampled = headers.get(_SAMPLED_KEY)
if sampled is not None:
# The specification encodes an enabled tracing decision as "1".
# In the wild pre-standard implementations might still send "true".
# "d" is set in the single header case when debugging is enabled.
sampled = sampled.lower() in ('1', 'd', 'true')
else:
# If there's no incoming sampling decision, it was deferred to us.
# Even though we set it to False here, we might still sample
# depending on the tracer configuration.
sampled = False
trace_options = TraceOptions()
trace_options.set_enabled(sampled)
# TraceId and SpanId headers both have to exist
if not trace_id or not span_id:
return SpanContext(trace_options=trace_options)
# Convert 64-bit trace ids to 128-bit
if len(trace_id) == 16:
trace_id = '0'*16 + trace_id
span_context = SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=trace_options,
from_header=True
)
return span_context | [
"def",
"from_headers",
"(",
"self",
",",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"SpanContext",
"(",
"from_header",
"=",
"False",
")",
"trace_id",
",",
"span_id",
",",
"sampled",
"=",
"None",
",",
"None",
",",
"None",
"state",
... | Generate a SpanContext object from B3 propagation headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from B3 propagation headers. | [
"Generate",
"a",
"SpanContext",
"object",
"from",
"B3",
"propagation",
"headers",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/b3_format.py#L31-L93 |
226,160 | census-instrumentation/opencensus-python | opencensus/trace/propagation/b3_format.py | B3FormatPropagator.to_headers | def to_headers(self, span_context):
"""Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers.
"""
if not span_context.span_id:
span_id = INVALID_SPAN_ID
else:
span_id = span_context.span_id
sampled = span_context.trace_options.enabled
return {
_TRACE_ID_KEY: span_context.trace_id,
_SPAN_ID_KEY: span_id,
_SAMPLED_KEY: '1' if sampled else '0'
} | python | def to_headers(self, span_context):
"""Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers.
"""
if not span_context.span_id:
span_id = INVALID_SPAN_ID
else:
span_id = span_context.span_id
sampled = span_context.trace_options.enabled
return {
_TRACE_ID_KEY: span_context.trace_id,
_SPAN_ID_KEY: span_id,
_SAMPLED_KEY: '1' if sampled else '0'
} | [
"def",
"to_headers",
"(",
"self",
",",
"span_context",
")",
":",
"if",
"not",
"span_context",
".",
"span_id",
":",
"span_id",
"=",
"INVALID_SPAN_ID",
"else",
":",
"span_id",
"=",
"span_context",
".",
"span_id",
"sampled",
"=",
"span_context",
".",
"trace_optio... | Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers. | [
"Convert",
"a",
"SpanContext",
"object",
"to",
"B3",
"propagation",
"headers",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/b3_format.py#L95-L117 |
226,161 | census-instrumentation/opencensus-python | opencensus/trace/span_context.py | SpanContext._check_span_id | def _check_span_id(self, span_id):
"""Check the format of the span_id to ensure it is 16-character hex
value representing a 64-bit number. If span_id is invalid, logs a
warning message and returns None
:type span_id: str
:param span_id: Identifier for the span, unique within a span.
:rtype: str
:returns: Span_id for the current span.
"""
if span_id is None:
return None
assert isinstance(span_id, six.string_types)
if span_id is INVALID_SPAN_ID:
logging.warning(
'Span_id {} is invalid (cannot be all zero)'.format(span_id))
self.from_header = False
return None
match = SPAN_ID_PATTERN.match(span_id)
if match:
return span_id
else:
logging.warning(
'Span_id {} does not the match the '
'required format'.format(span_id))
self.from_header = False
return None | python | def _check_span_id(self, span_id):
"""Check the format of the span_id to ensure it is 16-character hex
value representing a 64-bit number. If span_id is invalid, logs a
warning message and returns None
:type span_id: str
:param span_id: Identifier for the span, unique within a span.
:rtype: str
:returns: Span_id for the current span.
"""
if span_id is None:
return None
assert isinstance(span_id, six.string_types)
if span_id is INVALID_SPAN_ID:
logging.warning(
'Span_id {} is invalid (cannot be all zero)'.format(span_id))
self.from_header = False
return None
match = SPAN_ID_PATTERN.match(span_id)
if match:
return span_id
else:
logging.warning(
'Span_id {} does not the match the '
'required format'.format(span_id))
self.from_header = False
return None | [
"def",
"_check_span_id",
"(",
"self",
",",
"span_id",
")",
":",
"if",
"span_id",
"is",
"None",
":",
"return",
"None",
"assert",
"isinstance",
"(",
"span_id",
",",
"six",
".",
"string_types",
")",
"if",
"span_id",
"is",
"INVALID_SPAN_ID",
":",
"logging",
".... | Check the format of the span_id to ensure it is 16-character hex
value representing a 64-bit number. If span_id is invalid, logs a
warning message and returns None
:type span_id: str
:param span_id: Identifier for the span, unique within a span.
:rtype: str
:returns: Span_id for the current span. | [
"Check",
"the",
"format",
"of",
"the",
"span_id",
"to",
"ensure",
"it",
"is",
"16",
"-",
"character",
"hex",
"value",
"representing",
"a",
"64",
"-",
"bit",
"number",
".",
"If",
"span_id",
"is",
"invalid",
"logs",
"a",
"warning",
"message",
"and",
"retur... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span_context.py#L88-L118 |
226,162 | census-instrumentation/opencensus-python | opencensus/trace/span_context.py | SpanContext._check_trace_id | def _check_trace_id(self, trace_id):
"""Check the format of the trace_id to ensure it is 32-character hex
value representing a 128-bit number. If trace_id is invalid, returns a
randomly generated trace id
:type trace_id: str
:param trace_id:
:rtype: str
:returns: Trace_id for the current context.
"""
assert isinstance(trace_id, six.string_types)
if trace_id is _INVALID_TRACE_ID:
logging.warning(
'Trace_id {} is invalid (cannot be all zero), '
'generating a new one.'.format(trace_id))
self.from_header = False
return generate_trace_id()
match = TRACE_ID_PATTERN.match(trace_id)
if match:
return trace_id
else:
logging.warning(
'Trace_id {} does not the match the required format,'
'generating a new one instead.'.format(trace_id))
self.from_header = False
return generate_trace_id() | python | def _check_trace_id(self, trace_id):
"""Check the format of the trace_id to ensure it is 32-character hex
value representing a 128-bit number. If trace_id is invalid, returns a
randomly generated trace id
:type trace_id: str
:param trace_id:
:rtype: str
:returns: Trace_id for the current context.
"""
assert isinstance(trace_id, six.string_types)
if trace_id is _INVALID_TRACE_ID:
logging.warning(
'Trace_id {} is invalid (cannot be all zero), '
'generating a new one.'.format(trace_id))
self.from_header = False
return generate_trace_id()
match = TRACE_ID_PATTERN.match(trace_id)
if match:
return trace_id
else:
logging.warning(
'Trace_id {} does not the match the required format,'
'generating a new one instead.'.format(trace_id))
self.from_header = False
return generate_trace_id() | [
"def",
"_check_trace_id",
"(",
"self",
",",
"trace_id",
")",
":",
"assert",
"isinstance",
"(",
"trace_id",
",",
"six",
".",
"string_types",
")",
"if",
"trace_id",
"is",
"_INVALID_TRACE_ID",
":",
"logging",
".",
"warning",
"(",
"'Trace_id {} is invalid (cannot be a... | Check the format of the trace_id to ensure it is 32-character hex
value representing a 128-bit number. If trace_id is invalid, returns a
randomly generated trace id
:type trace_id: str
:param trace_id:
:rtype: str
:returns: Trace_id for the current context. | [
"Check",
"the",
"format",
"of",
"the",
"trace_id",
"to",
"ensure",
"it",
"is",
"32",
"-",
"character",
"hex",
"value",
"representing",
"a",
"128",
"-",
"bit",
"number",
".",
"If",
"trace_id",
"is",
"invalid",
"returns",
"a",
"randomly",
"generated",
"trace... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span_context.py#L120-L149 |
226,163 | census-instrumentation/opencensus-python | opencensus/trace/status.py | Status.format_status_json | def format_status_json(self):
"""Convert a Status object to json format."""
status_json = {}
status_json['code'] = self.code
status_json['message'] = self.message
if self.details is not None:
status_json['details'] = self.details
return status_json | python | def format_status_json(self):
"""Convert a Status object to json format."""
status_json = {}
status_json['code'] = self.code
status_json['message'] = self.message
if self.details is not None:
status_json['details'] = self.details
return status_json | [
"def",
"format_status_json",
"(",
"self",
")",
":",
"status_json",
"=",
"{",
"}",
"status_json",
"[",
"'code'",
"]",
"=",
"self",
".",
"code",
"status_json",
"[",
"'message'",
"]",
"=",
"self",
".",
"message",
"if",
"self",
".",
"details",
"is",
"not",
... | Convert a Status object to json format. | [
"Convert",
"a",
"Status",
"object",
"to",
"json",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/status.py#L47-L57 |
226,164 | census-instrumentation/opencensus-python | opencensus/trace/propagation/trace_context_http_header_format.py | TraceContextPropagator.from_headers | def from_headers(self, headers):
"""Generate a SpanContext object using the W3C Distributed Tracing headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.
"""
if headers is None:
return SpanContext()
header = headers.get(_TRACEPARENT_HEADER_NAME)
if header is None:
return SpanContext()
match = re.search(_TRACEPARENT_HEADER_FORMAT_RE, header)
if not match:
return SpanContext()
version = match.group(1)
trace_id = match.group(2)
span_id = match.group(3)
trace_options = match.group(4)
if trace_id == '0' * 32 or span_id == '0' * 16:
return SpanContext()
if version == '00':
if match.group(5):
return SpanContext()
if version == 'ff':
return SpanContext()
span_context = SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=TraceOptions(trace_options),
from_header=True)
header = headers.get(_TRACESTATE_HEADER_NAME)
if header is None:
return span_context
try:
tracestate = TracestateStringFormatter().from_string(header)
if tracestate.is_valid():
span_context.tracestate = \
TracestateStringFormatter().from_string(header)
except ValueError:
pass
return span_context | python | def from_headers(self, headers):
"""Generate a SpanContext object using the W3C Distributed Tracing headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header.
"""
if headers is None:
return SpanContext()
header = headers.get(_TRACEPARENT_HEADER_NAME)
if header is None:
return SpanContext()
match = re.search(_TRACEPARENT_HEADER_FORMAT_RE, header)
if not match:
return SpanContext()
version = match.group(1)
trace_id = match.group(2)
span_id = match.group(3)
trace_options = match.group(4)
if trace_id == '0' * 32 or span_id == '0' * 16:
return SpanContext()
if version == '00':
if match.group(5):
return SpanContext()
if version == 'ff':
return SpanContext()
span_context = SpanContext(
trace_id=trace_id,
span_id=span_id,
trace_options=TraceOptions(trace_options),
from_header=True)
header = headers.get(_TRACESTATE_HEADER_NAME)
if header is None:
return span_context
try:
tracestate = TracestateStringFormatter().from_string(header)
if tracestate.is_valid():
span_context.tracestate = \
TracestateStringFormatter().from_string(header)
except ValueError:
pass
return span_context | [
"def",
"from_headers",
"(",
"self",
",",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"SpanContext",
"(",
")",
"header",
"=",
"headers",
".",
"get",
"(",
"_TRACEPARENT_HEADER_NAME",
")",
"if",
"header",
"is",
"None",
":",
"return",
... | Generate a SpanContext object using the W3C Distributed Tracing headers.
:type headers: dict
:param headers: HTTP request headers.
:rtype: :class:`~opencensus.trace.span_context.SpanContext`
:returns: SpanContext generated from the trace context header. | [
"Generate",
"a",
"SpanContext",
"object",
"using",
"the",
"W3C",
"Distributed",
"Tracing",
"headers",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/trace_context_http_header_format.py#L33-L83 |
226,165 | census-instrumentation/opencensus-python | opencensus/trace/propagation/trace_context_http_header_format.py | TraceContextPropagator.to_headers | def to_headers(self, span_context):
"""Convert a SpanContext object to W3C Distributed Tracing headers,
using version 0.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: W3C Distributed Tracing headers.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = span_context.trace_options.enabled
# Convert the trace options
trace_options = '01' if trace_options else '00'
headers = {
_TRACEPARENT_HEADER_NAME: '00-{}-{}-{}'.format(
trace_id,
span_id,
trace_options
),
}
tracestate = span_context.tracestate
if tracestate:
headers[_TRACESTATE_HEADER_NAME] = \
TracestateStringFormatter().to_string(tracestate)
return headers | python | def to_headers(self, span_context):
"""Convert a SpanContext object to W3C Distributed Tracing headers,
using version 0.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: W3C Distributed Tracing headers.
"""
trace_id = span_context.trace_id
span_id = span_context.span_id
trace_options = span_context.trace_options.enabled
# Convert the trace options
trace_options = '01' if trace_options else '00'
headers = {
_TRACEPARENT_HEADER_NAME: '00-{}-{}-{}'.format(
trace_id,
span_id,
trace_options
),
}
tracestate = span_context.tracestate
if tracestate:
headers[_TRACESTATE_HEADER_NAME] = \
TracestateStringFormatter().to_string(tracestate)
return headers | [
"def",
"to_headers",
"(",
"self",
",",
"span_context",
")",
":",
"trace_id",
"=",
"span_context",
".",
"trace_id",
"span_id",
"=",
"span_context",
".",
"span_id",
"trace_options",
"=",
"span_context",
".",
"trace_options",
".",
"enabled",
"# Convert the trace option... | Convert a SpanContext object to W3C Distributed Tracing headers,
using version 0.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: W3C Distributed Tracing headers. | [
"Convert",
"a",
"SpanContext",
"object",
"to",
"W3C",
"Distributed",
"Tracing",
"headers",
"using",
"version",
"0",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/trace_context_http_header_format.py#L85-L114 |
226,166 | census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | get_truncatable_str | def get_truncatable_str(str_to_convert):
"""Truncate a string if exceed limit and record the truncated bytes
count.
"""
truncated, truncated_byte_count = check_str_length(
str_to_convert, MAX_LENGTH)
result = {
'value': truncated,
'truncated_byte_count': truncated_byte_count,
}
return result | python | def get_truncatable_str(str_to_convert):
"""Truncate a string if exceed limit and record the truncated bytes
count.
"""
truncated, truncated_byte_count = check_str_length(
str_to_convert, MAX_LENGTH)
result = {
'value': truncated,
'truncated_byte_count': truncated_byte_count,
}
return result | [
"def",
"get_truncatable_str",
"(",
"str_to_convert",
")",
":",
"truncated",
",",
"truncated_byte_count",
"=",
"check_str_length",
"(",
"str_to_convert",
",",
"MAX_LENGTH",
")",
"result",
"=",
"{",
"'value'",
":",
"truncated",
",",
"'truncated_byte_count'",
":",
"tru... | Truncate a string if exceed limit and record the truncated bytes
count. | [
"Truncate",
"a",
"string",
"if",
"exceed",
"limit",
"and",
"record",
"the",
"truncated",
"bytes",
"count",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/utils/__init__.py#L32-L43 |
226,167 | census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | check_str_length | def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self if not exceeded length, or truncated string
if exceeded and the truncated byte count.
"""
str_bytes = str_to_check.encode(UTF8)
str_len = len(str_bytes)
truncated_byte_count = 0
if str_len > limit:
truncated_byte_count = str_len - limit
str_bytes = str_bytes[:limit]
result = str(str_bytes.decode(UTF8, errors='ignore'))
return (result, truncated_byte_count) | python | def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self if not exceeded length, or truncated string
if exceeded and the truncated byte count.
"""
str_bytes = str_to_check.encode(UTF8)
str_len = len(str_bytes)
truncated_byte_count = 0
if str_len > limit:
truncated_byte_count = str_len - limit
str_bytes = str_bytes[:limit]
result = str(str_bytes.decode(UTF8, errors='ignore'))
return (result, truncated_byte_count) | [
"def",
"check_str_length",
"(",
"str_to_check",
",",
"limit",
"=",
"MAX_LENGTH",
")",
":",
"str_bytes",
"=",
"str_to_check",
".",
"encode",
"(",
"UTF8",
")",
"str_len",
"=",
"len",
"(",
"str_bytes",
")",
"truncated_byte_count",
"=",
"0",
"if",
"str_len",
">"... | Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self if not exceeded length, or truncated string
if exceeded and the truncated byte count. | [
"Check",
"the",
"length",
"of",
"a",
"string",
".",
"If",
"exceeds",
"limit",
"then",
"truncate",
"it",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/utils/__init__.py#L46-L69 |
226,168 | census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | iuniq | def iuniq(ible):
"""Get an iterator over unique items of `ible`."""
items = set()
for item in ible:
if item not in items:
items.add(item)
yield item | python | def iuniq(ible):
"""Get an iterator over unique items of `ible`."""
items = set()
for item in ible:
if item not in items:
items.add(item)
yield item | [
"def",
"iuniq",
"(",
"ible",
")",
":",
"items",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"ible",
":",
"if",
"item",
"not",
"in",
"items",
":",
"items",
".",
"add",
"(",
"item",
")",
"yield",
"item"
] | Get an iterator over unique items of `ible`. | [
"Get",
"an",
"iterator",
"over",
"unique",
"items",
"of",
"ible",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/utils/__init__.py#L90-L96 |
226,169 | census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | window | def window(ible, length):
"""Split `ible` into multiple lists of length `length`.
>>> list(window(range(5), 2))
[[0, 1], [2, 3], [4]]
"""
if length <= 0: # pragma: NO COVER
raise ValueError
ible = iter(ible)
while True:
elts = [xx for ii, xx in zip(range(length), ible)]
if elts:
yield elts
else:
break | python | def window(ible, length):
"""Split `ible` into multiple lists of length `length`.
>>> list(window(range(5), 2))
[[0, 1], [2, 3], [4]]
"""
if length <= 0: # pragma: NO COVER
raise ValueError
ible = iter(ible)
while True:
elts = [xx for ii, xx in zip(range(length), ible)]
if elts:
yield elts
else:
break | [
"def",
"window",
"(",
"ible",
",",
"length",
")",
":",
"if",
"length",
"<=",
"0",
":",
"# pragma: NO COVER",
"raise",
"ValueError",
"ible",
"=",
"iter",
"(",
"ible",
")",
"while",
"True",
":",
"elts",
"=",
"[",
"xx",
"for",
"ii",
",",
"xx",
"in",
"... | Split `ible` into multiple lists of length `length`.
>>> list(window(range(5), 2))
[[0, 1], [2, 3], [4]] | [
"Split",
"ible",
"into",
"multiple",
"lists",
"of",
"length",
"length",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/utils/__init__.py#L104-L118 |
226,170 | census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | get_weakref | def get_weakref(func):
"""Get a weak reference to bound or unbound `func`.
If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
otherwise get a wrapper that simulates weakref.ref.
"""
if func is None:
raise ValueError
if not hasattr(func, '__self__'):
return weakref.ref(func)
return WeakMethod(func) | python | def get_weakref(func):
"""Get a weak reference to bound or unbound `func`.
If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
otherwise get a wrapper that simulates weakref.ref.
"""
if func is None:
raise ValueError
if not hasattr(func, '__self__'):
return weakref.ref(func)
return WeakMethod(func) | [
"def",
"get_weakref",
"(",
"func",
")",
":",
"if",
"func",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__self__'",
")",
":",
"return",
"weakref",
".",
"ref",
"(",
"func",
")",
"return",
"WeakMethod",
"(",
"func... | Get a weak reference to bound or unbound `func`.
If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
otherwise get a wrapper that simulates weakref.ref. | [
"Get",
"a",
"weak",
"reference",
"to",
"bound",
"or",
"unbound",
"func",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/utils/__init__.py#L121-L131 |
226,171 | census-instrumentation/opencensus-python | contrib/opencensus-ext-dbapi/opencensus/ext/dbapi/trace.py | wrap_conn | def wrap_conn(conn_func):
"""Wrap the mysql conn object with TraceConnection."""
def call(*args, **kwargs):
try:
conn = conn_func(*args, **kwargs)
cursor_func = getattr(conn, CURSOR_WRAP_METHOD)
wrapped = wrap_cursor(cursor_func)
setattr(conn, cursor_func.__name__, wrapped)
return conn
except Exception: # pragma: NO COVER
logging.warning('Fail to wrap conn, mysql not traced.')
return conn_func(*args, **kwargs)
return call | python | def wrap_conn(conn_func):
"""Wrap the mysql conn object with TraceConnection."""
def call(*args, **kwargs):
try:
conn = conn_func(*args, **kwargs)
cursor_func = getattr(conn, CURSOR_WRAP_METHOD)
wrapped = wrap_cursor(cursor_func)
setattr(conn, cursor_func.__name__, wrapped)
return conn
except Exception: # pragma: NO COVER
logging.warning('Fail to wrap conn, mysql not traced.')
return conn_func(*args, **kwargs)
return call | [
"def",
"wrap_conn",
"(",
"conn_func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cursor_func",
"=",
"getattr",
"(",
"conn",
... | Wrap the mysql conn object with TraceConnection. | [
"Wrap",
"the",
"mysql",
"conn",
"object",
"with",
"TraceConnection",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-dbapi/opencensus/ext/dbapi/trace.py#L24-L36 |
226,172 | census-instrumentation/opencensus-python | opencensus/stats/measurement_map.py | MeasurementMap.measure_int_put | def measure_int_put(self, measure, value):
"""associates the measure of type Int with the given value"""
if value < 0:
# Should be an error in a later release.
logger.warning("Cannot record negative values")
self._measurement_map[measure] = value | python | def measure_int_put(self, measure, value):
"""associates the measure of type Int with the given value"""
if value < 0:
# Should be an error in a later release.
logger.warning("Cannot record negative values")
self._measurement_map[measure] = value | [
"def",
"measure_int_put",
"(",
"self",
",",
"measure",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"# Should be an error in a later release.",
"logger",
".",
"warning",
"(",
"\"Cannot record negative values\"",
")",
"self",
".",
"_measurement_map",
"[",
... | associates the measure of type Int with the given value | [
"associates",
"the",
"measure",
"of",
"type",
"Int",
"with",
"the",
"given",
"value"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measurement_map.py#L61-L66 |
226,173 | census-instrumentation/opencensus-python | opencensus/stats/measurement_map.py | MeasurementMap.measure_float_put | def measure_float_put(self, measure, value):
"""associates the measure of type Float with the given value"""
if value < 0:
# Should be an error in a later release.
logger.warning("Cannot record negative values")
self._measurement_map[measure] = value | python | def measure_float_put(self, measure, value):
"""associates the measure of type Float with the given value"""
if value < 0:
# Should be an error in a later release.
logger.warning("Cannot record negative values")
self._measurement_map[measure] = value | [
"def",
"measure_float_put",
"(",
"self",
",",
"measure",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"# Should be an error in a later release.",
"logger",
".",
"warning",
"(",
"\"Cannot record negative values\"",
")",
"self",
".",
"_measurement_map",
"[",
... | associates the measure of type Float with the given value | [
"associates",
"the",
"measure",
"of",
"type",
"Float",
"with",
"the",
"given",
"value"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measurement_map.py#L68-L73 |
226,174 | census-instrumentation/opencensus-python | opencensus/stats/measurement_map.py | MeasurementMap.measure_put_attachment | def measure_put_attachment(self, key, value):
"""Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last value will be kept.
"""
if self._attachments is None:
self._attachments = dict()
if key is None or not isinstance(key, str):
raise TypeError('attachment key should not be '
'empty and should be a string')
if value is None or not isinstance(value, str):
raise TypeError('attachment value should not be '
'empty and should be a string')
self._attachments[key] = value | python | def measure_put_attachment(self, key, value):
"""Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last value will be kept.
"""
if self._attachments is None:
self._attachments = dict()
if key is None or not isinstance(key, str):
raise TypeError('attachment key should not be '
'empty and should be a string')
if value is None or not isinstance(value, str):
raise TypeError('attachment value should not be '
'empty and should be a string')
self._attachments[key] = value | [
"def",
"measure_put_attachment",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"_attachments",
"is",
"None",
":",
"self",
".",
"_attachments",
"=",
"dict",
"(",
")",
"if",
"key",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"key"... | Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last value will be kept. | [
"Associate",
"the",
"contextual",
"information",
"of",
"an",
"Exemplar",
"to",
"this",
"MeasureMap",
"Contextual",
"information",
"is",
"represented",
"as",
"key",
"-",
"value",
"string",
"pairs",
".",
"If",
"this",
"method",
"is",
"called",
"multiple",
"times",... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measurement_map.py#L75-L91 |
226,175 | census-instrumentation/opencensus-python | opencensus/stats/measurement_map.py | MeasurementMap.record | def record(self, tags=None):
"""records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context.
"""
if tags is None:
tags = TagContext.get()
if self._invalid:
logger.warning("Measurement map has included negative value "
"measurements, refusing to record")
return
for measure, value in self.measurement_map.items():
if value < 0:
self._invalid = True
logger.warning("Dropping values, value to record must be "
"non-negative")
logger.info("Measure '{}' has negative value ({}), refusing "
"to record measurements from {}"
.format(measure.name, value, self))
return
self.measure_to_view_map.record(
tags=tags,
measurement_map=self.measurement_map,
timestamp=utils.to_iso_str(),
attachments=self.attachments
) | python | def record(self, tags=None):
"""records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context.
"""
if tags is None:
tags = TagContext.get()
if self._invalid:
logger.warning("Measurement map has included negative value "
"measurements, refusing to record")
return
for measure, value in self.measurement_map.items():
if value < 0:
self._invalid = True
logger.warning("Dropping values, value to record must be "
"non-negative")
logger.info("Measure '{}' has negative value ({}), refusing "
"to record measurements from {}"
.format(measure.name, value, self))
return
self.measure_to_view_map.record(
tags=tags,
measurement_map=self.measurement_map,
timestamp=utils.to_iso_str(),
attachments=self.attachments
) | [
"def",
"record",
"(",
"self",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"TagContext",
".",
"get",
"(",
")",
"if",
"self",
".",
"_invalid",
":",
"logger",
".",
"warning",
"(",
"\"Measurement map has included negativ... | records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context. | [
"records",
"all",
"the",
"measures",
"at",
"the",
"same",
"time",
"with",
"a",
"tag_map",
".",
"tag_map",
"could",
"either",
"be",
"explicitly",
"passed",
"to",
"the",
"method",
"or",
"implicitly",
"read",
"from",
"current",
"runtime",
"context",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measurement_map.py#L93-L119 |
226,176 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py | translate_to_trace_proto | def translate_to_trace_proto(span_data):
"""Translates the opencensus spans to ocagent proto spans.
:type span_data: :class:`~opencensus.trace.span_data.SpanData`
:param span_data: SpanData tuples to convert to protobuf spans
:rtype: :class:`~opencensus.proto.trace.Span`
:returns: Protobuf format span.
"""
if not span_data:
return None
pb_span = trace_pb2.Span(
name=trace_pb2.TruncatableString(value=span_data.name),
kind=span_data.span_kind,
trace_id=hex_str_to_bytes_str(span_data.context.trace_id),
span_id=hex_str_to_bytes_str(span_data.span_id),
parent_span_id=hex_str_to_bytes_str(span_data.parent_span_id)
if span_data.parent_span_id is not None else None,
start_time=ocagent_utils.proto_ts_from_datetime_str(
span_data.start_time),
end_time=ocagent_utils.proto_ts_from_datetime_str(span_data.end_time),
status=trace_pb2.Status(
code=span_data.status.code,
message=span_data.status.message)
if span_data.status is not None else None,
same_process_as_parent_span=BoolValue(
value=span_data.same_process_as_parent_span)
if span_data.same_process_as_parent_span is not None
else None,
child_span_count=UInt32Value(value=span_data.child_span_count)
if span_data.child_span_count is not None else None)
# attributes
if span_data.attributes is not None:
for attribute_key, attribute_value \
in span_data.attributes.items():
add_proto_attribute_value(
pb_span.attributes,
attribute_key,
attribute_value)
# time events
if span_data.time_events is not None:
for span_data_event in span_data.time_events:
if span_data_event.message_event is not None:
pb_event = pb_span.time_events.time_event.add()
pb_event.time.FromJsonString(span_data_event.timestamp)
set_proto_message_event(
pb_event.message_event,
span_data_event.message_event)
elif span_data_event.annotation is not None:
pb_event = pb_span.time_events.time_event.add()
pb_event.time.FromJsonString(span_data_event.timestamp)
set_proto_annotation(
pb_event.annotation,
span_data_event.annotation)
# links
if span_data.links is not None:
for link in span_data.links:
pb_link = pb_span.links.link.add(
trace_id=hex_str_to_bytes_str(link.trace_id),
span_id=hex_str_to_bytes_str(link.span_id),
type=link.type)
if link.attributes is not None and \
link.attributes.attributes is not None:
for attribute_key, attribute_value \
in link.attributes.attributes.items():
add_proto_attribute_value(
pb_link.attributes,
attribute_key,
attribute_value)
# tracestate
if span_data.context.tracestate is not None:
for (key, value) in span_data.context.tracestate.items():
pb_span.tracestate.entries.add(key=key, value=value)
return pb_span | python | def translate_to_trace_proto(span_data):
"""Translates the opencensus spans to ocagent proto spans.
:type span_data: :class:`~opencensus.trace.span_data.SpanData`
:param span_data: SpanData tuples to convert to protobuf spans
:rtype: :class:`~opencensus.proto.trace.Span`
:returns: Protobuf format span.
"""
if not span_data:
return None
pb_span = trace_pb2.Span(
name=trace_pb2.TruncatableString(value=span_data.name),
kind=span_data.span_kind,
trace_id=hex_str_to_bytes_str(span_data.context.trace_id),
span_id=hex_str_to_bytes_str(span_data.span_id),
parent_span_id=hex_str_to_bytes_str(span_data.parent_span_id)
if span_data.parent_span_id is not None else None,
start_time=ocagent_utils.proto_ts_from_datetime_str(
span_data.start_time),
end_time=ocagent_utils.proto_ts_from_datetime_str(span_data.end_time),
status=trace_pb2.Status(
code=span_data.status.code,
message=span_data.status.message)
if span_data.status is not None else None,
same_process_as_parent_span=BoolValue(
value=span_data.same_process_as_parent_span)
if span_data.same_process_as_parent_span is not None
else None,
child_span_count=UInt32Value(value=span_data.child_span_count)
if span_data.child_span_count is not None else None)
# attributes
if span_data.attributes is not None:
for attribute_key, attribute_value \
in span_data.attributes.items():
add_proto_attribute_value(
pb_span.attributes,
attribute_key,
attribute_value)
# time events
if span_data.time_events is not None:
for span_data_event in span_data.time_events:
if span_data_event.message_event is not None:
pb_event = pb_span.time_events.time_event.add()
pb_event.time.FromJsonString(span_data_event.timestamp)
set_proto_message_event(
pb_event.message_event,
span_data_event.message_event)
elif span_data_event.annotation is not None:
pb_event = pb_span.time_events.time_event.add()
pb_event.time.FromJsonString(span_data_event.timestamp)
set_proto_annotation(
pb_event.annotation,
span_data_event.annotation)
# links
if span_data.links is not None:
for link in span_data.links:
pb_link = pb_span.links.link.add(
trace_id=hex_str_to_bytes_str(link.trace_id),
span_id=hex_str_to_bytes_str(link.span_id),
type=link.type)
if link.attributes is not None and \
link.attributes.attributes is not None:
for attribute_key, attribute_value \
in link.attributes.attributes.items():
add_proto_attribute_value(
pb_link.attributes,
attribute_key,
attribute_value)
# tracestate
if span_data.context.tracestate is not None:
for (key, value) in span_data.context.tracestate.items():
pb_span.tracestate.entries.add(key=key, value=value)
return pb_span | [
"def",
"translate_to_trace_proto",
"(",
"span_data",
")",
":",
"if",
"not",
"span_data",
":",
"return",
"None",
"pb_span",
"=",
"trace_pb2",
".",
"Span",
"(",
"name",
"=",
"trace_pb2",
".",
"TruncatableString",
"(",
"value",
"=",
"span_data",
".",
"name",
")... | Translates the opencensus spans to ocagent proto spans.
:type span_data: :class:`~opencensus.trace.span_data.SpanData`
:param span_data: SpanData tuples to convert to protobuf spans
:rtype: :class:`~opencensus.proto.trace.Span`
:returns: Protobuf format span. | [
"Translates",
"the",
"opencensus",
"spans",
"to",
"ocagent",
"proto",
"spans",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py#L22-L103 |
226,177 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py | set_proto_message_event | def set_proto_message_event(
pb_message_event,
span_data_message_event):
"""Sets properties on the protobuf message event.
:type pb_message_event:
:class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent`
:param pb_message_event: protobuf message event
:type span_data_message_event:
:class: `~opencensus.trace.time_event.MessageEvent`
:param span_data_message_event: opencensus message event
"""
pb_message_event.type = span_data_message_event.type
pb_message_event.id = span_data_message_event.id
pb_message_event.uncompressed_size = \
span_data_message_event.uncompressed_size_bytes
pb_message_event.compressed_size = \
span_data_message_event.compressed_size_bytes | python | def set_proto_message_event(
pb_message_event,
span_data_message_event):
"""Sets properties on the protobuf message event.
:type pb_message_event:
:class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent`
:param pb_message_event: protobuf message event
:type span_data_message_event:
:class: `~opencensus.trace.time_event.MessageEvent`
:param span_data_message_event: opencensus message event
"""
pb_message_event.type = span_data_message_event.type
pb_message_event.id = span_data_message_event.id
pb_message_event.uncompressed_size = \
span_data_message_event.uncompressed_size_bytes
pb_message_event.compressed_size = \
span_data_message_event.compressed_size_bytes | [
"def",
"set_proto_message_event",
"(",
"pb_message_event",
",",
"span_data_message_event",
")",
":",
"pb_message_event",
".",
"type",
"=",
"span_data_message_event",
".",
"type",
"pb_message_event",
".",
"id",
"=",
"span_data_message_event",
".",
"id",
"pb_message_event",... | Sets properties on the protobuf message event.
:type pb_message_event:
:class: `~opencensus.proto.trace.Span.TimeEvent.MessageEvent`
:param pb_message_event: protobuf message event
:type span_data_message_event:
:class: `~opencensus.trace.time_event.MessageEvent`
:param span_data_message_event: opencensus message event | [
"Sets",
"properties",
"on",
"the",
"protobuf",
"message",
"event",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py#L106-L125 |
226,178 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py | set_proto_annotation | def set_proto_annotation(pb_annotation, span_data_annotation):
"""Sets properties on the protobuf Span annotation.
:type pb_annotation:
:class: `~opencensus.proto.trace.Span.TimeEvent.Annotation`
:param pb_annotation: protobuf annotation
:type span_data_annotation:
:class: `~opencensus.trace.time_event.Annotation`
:param span_data_annotation: opencensus annotation
"""
pb_annotation.description.value = span_data_annotation.description
if span_data_annotation.attributes is not None \
and span_data_annotation.attributes.attributes is not None:
for attribute_key, attribute_value in \
span_data_annotation.attributes.attributes.items():
add_proto_attribute_value(
pb_annotation.attributes,
attribute_key,
attribute_value) | python | def set_proto_annotation(pb_annotation, span_data_annotation):
"""Sets properties on the protobuf Span annotation.
:type pb_annotation:
:class: `~opencensus.proto.trace.Span.TimeEvent.Annotation`
:param pb_annotation: protobuf annotation
:type span_data_annotation:
:class: `~opencensus.trace.time_event.Annotation`
:param span_data_annotation: opencensus annotation
"""
pb_annotation.description.value = span_data_annotation.description
if span_data_annotation.attributes is not None \
and span_data_annotation.attributes.attributes is not None:
for attribute_key, attribute_value in \
span_data_annotation.attributes.attributes.items():
add_proto_attribute_value(
pb_annotation.attributes,
attribute_key,
attribute_value) | [
"def",
"set_proto_annotation",
"(",
"pb_annotation",
",",
"span_data_annotation",
")",
":",
"pb_annotation",
".",
"description",
".",
"value",
"=",
"span_data_annotation",
".",
"description",
"if",
"span_data_annotation",
".",
"attributes",
"is",
"not",
"None",
"and",... | Sets properties on the protobuf Span annotation.
:type pb_annotation:
:class: `~opencensus.proto.trace.Span.TimeEvent.Annotation`
:param pb_annotation: protobuf annotation
:type span_data_annotation:
:class: `~opencensus.trace.time_event.Annotation`
:param span_data_annotation: opencensus annotation | [
"Sets",
"properties",
"on",
"the",
"protobuf",
"Span",
"annotation",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py#L128-L149 |
226,179 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py | add_proto_attribute_value | def add_proto_attribute_value(
pb_attributes,
attribute_key,
attribute_value):
"""Sets string, int, boolean or float value on protobuf
span, link or annotation attributes.
:type pb_attributes:
:class: `~opencensus.proto.trace.Span.Attributes`
:param pb_attributes: protobuf Span's attributes property
:type attribute_key: str
:param attribute_key: attribute key to set
:type attribute_value: str or int or bool or float
:param attribute_value: attribute value
"""
if isinstance(attribute_value, bool):
pb_attributes.attribute_map[attribute_key].\
bool_value = attribute_value
elif isinstance(attribute_value, int):
pb_attributes.attribute_map[attribute_key].\
int_value = attribute_value
elif isinstance(attribute_value, str):
pb_attributes.attribute_map[attribute_key].\
string_value.value = attribute_value
elif isinstance(attribute_value, float):
pb_attributes.attribute_map[attribute_key].\
double_value = attribute_value
else:
pb_attributes.attribute_map[attribute_key].\
string_value.value = str(attribute_value) | python | def add_proto_attribute_value(
pb_attributes,
attribute_key,
attribute_value):
"""Sets string, int, boolean or float value on protobuf
span, link or annotation attributes.
:type pb_attributes:
:class: `~opencensus.proto.trace.Span.Attributes`
:param pb_attributes: protobuf Span's attributes property
:type attribute_key: str
:param attribute_key: attribute key to set
:type attribute_value: str or int or bool or float
:param attribute_value: attribute value
"""
if isinstance(attribute_value, bool):
pb_attributes.attribute_map[attribute_key].\
bool_value = attribute_value
elif isinstance(attribute_value, int):
pb_attributes.attribute_map[attribute_key].\
int_value = attribute_value
elif isinstance(attribute_value, str):
pb_attributes.attribute_map[attribute_key].\
string_value.value = attribute_value
elif isinstance(attribute_value, float):
pb_attributes.attribute_map[attribute_key].\
double_value = attribute_value
else:
pb_attributes.attribute_map[attribute_key].\
string_value.value = str(attribute_value) | [
"def",
"add_proto_attribute_value",
"(",
"pb_attributes",
",",
"attribute_key",
",",
"attribute_value",
")",
":",
"if",
"isinstance",
"(",
"attribute_value",
",",
"bool",
")",
":",
"pb_attributes",
".",
"attribute_map",
"[",
"attribute_key",
"]",
".",
"bool_value",
... | Sets string, int, boolean or float value on protobuf
span, link or annotation attributes.
:type pb_attributes:
:class: `~opencensus.proto.trace.Span.Attributes`
:param pb_attributes: protobuf Span's attributes property
:type attribute_key: str
:param attribute_key: attribute key to set
:type attribute_value: str or int or bool or float
:param attribute_value: attribute value | [
"Sets",
"string",
"int",
"boolean",
"or",
"float",
"value",
"on",
"protobuf",
"span",
"link",
"or",
"annotation",
"attributes",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/utils.py#L165-L197 |
226,180 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py | TraceExporter.generate_span_requests | def generate_span_requests(self, span_datas):
"""Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
:rtype: list of
`~gen.opencensus.agent.trace.v1.trace_service_pb2.ExportTraceServiceRequest`
:returns: List of span export requests.
"""
pb_spans = [
utils.translate_to_trace_proto(span_data)
for span_data in span_datas
]
# TODO: send node once per channel
yield trace_service_pb2.ExportTraceServiceRequest(
node=self.node,
spans=pb_spans) | python | def generate_span_requests(self, span_datas):
"""Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
:rtype: list of
`~gen.opencensus.agent.trace.v1.trace_service_pb2.ExportTraceServiceRequest`
:returns: List of span export requests.
"""
pb_spans = [
utils.translate_to_trace_proto(span_data)
for span_data in span_datas
]
# TODO: send node once per channel
yield trace_service_pb2.ExportTraceServiceRequest(
node=self.node,
spans=pb_spans) | [
"def",
"generate_span_requests",
"(",
"self",
",",
"span_datas",
")",
":",
"pb_spans",
"=",
"[",
"utils",
".",
"translate_to_trace_proto",
"(",
"span_data",
")",
"for",
"span_data",
"in",
"span_datas",
"]",
"# TODO: send node once per channel",
"yield",
"trace_service... | Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
:rtype: list of
`~gen.opencensus.agent.trace.v1.trace_service_pb2.ExportTraceServiceRequest`
:returns: List of span export requests. | [
"Span",
"request",
"generator",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py#L113-L134 |
226,181 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py | TraceExporter.update_config | def update_config(self, config):
"""Sends TraceConfig to the agent and gets agent's config in reply.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: `~opencensus.proto.trace.v1.TraceConfig`
:returns: Trace config from agent.
"""
# do not allow updating config simultaneously
lock = Lock()
with lock:
# TODO: keep the stream alive.
# The stream is terminated after iteration completes.
# To keep it alive, we can enqueue proto configs here
# and asyncronously read them and send to the agent.
config_responses = self.client.Config(
self.generate_config_request(config))
agent_config = next(config_responses)
return agent_config | python | def update_config(self, config):
"""Sends TraceConfig to the agent and gets agent's config in reply.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: `~opencensus.proto.trace.v1.TraceConfig`
:returns: Trace config from agent.
"""
# do not allow updating config simultaneously
lock = Lock()
with lock:
# TODO: keep the stream alive.
# The stream is terminated after iteration completes.
# To keep it alive, we can enqueue proto configs here
# and asyncronously read them and send to the agent.
config_responses = self.client.Config(
self.generate_config_request(config))
agent_config = next(config_responses)
return agent_config | [
"def",
"update_config",
"(",
"self",
",",
"config",
")",
":",
"# do not allow updating config simultaneously",
"lock",
"=",
"Lock",
"(",
")",
"with",
"lock",
":",
"# TODO: keep the stream alive.",
"# The stream is terminated after iteration completes.",
"# To keep it alive, we ... | Sends TraceConfig to the agent and gets agent's config in reply.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: `~opencensus.proto.trace.v1.TraceConfig`
:returns: Trace config from agent. | [
"Sends",
"TraceConfig",
"to",
"the",
"agent",
"and",
"gets",
"agent",
"s",
"config",
"in",
"reply",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py#L137-L158 |
226,182 | census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py | TraceExporter.generate_config_request | def generate_config_request(self, config):
"""ConfigTraceServiceRequest generator.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: iterator of
`~opencensus.proto.agent.trace.v1.CurrentLibraryConfig`
:returns: Iterator of config requests.
"""
# TODO: send node once per channel
request = trace_service_pb2.CurrentLibraryConfig(
node=self.node,
config=config)
yield request | python | def generate_config_request(self, config):
"""ConfigTraceServiceRequest generator.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: iterator of
`~opencensus.proto.agent.trace.v1.CurrentLibraryConfig`
:returns: Iterator of config requests.
"""
# TODO: send node once per channel
request = trace_service_pb2.CurrentLibraryConfig(
node=self.node,
config=config)
yield request | [
"def",
"generate_config_request",
"(",
"self",
",",
"config",
")",
":",
"# TODO: send node once per channel",
"request",
"=",
"trace_service_pb2",
".",
"CurrentLibraryConfig",
"(",
"node",
"=",
"self",
".",
"node",
",",
"config",
"=",
"config",
")",
"yield",
"requ... | ConfigTraceServiceRequest generator.
:type config: `~opencensus.proto.trace.v1.TraceConfig`
:param config: Trace config with sampling and other settings
:rtype: iterator of
`~opencensus.proto.agent.trace.v1.CurrentLibraryConfig`
:returns: Iterator of config requests. | [
"ConfigTraceServiceRequest",
"generator",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py#L160-L176 |
226,183 | census-instrumentation/opencensus-python | contrib/opencensus-ext-pyramid/opencensus/ext/pyramid/config.py | _set_default_configs | def _set_default_configs(user_settings, default):
"""Set the default value to user settings if user not specified
the value.
"""
for key in default:
if key not in user_settings:
user_settings[key] = default[key]
return user_settings | python | def _set_default_configs(user_settings, default):
"""Set the default value to user settings if user not specified
the value.
"""
for key in default:
if key not in user_settings:
user_settings[key] = default[key]
return user_settings | [
"def",
"_set_default_configs",
"(",
"user_settings",
",",
"default",
")",
":",
"for",
"key",
"in",
"default",
":",
"if",
"key",
"not",
"in",
"user_settings",
":",
"user_settings",
"[",
"key",
"]",
"=",
"default",
"[",
"key",
"]",
"return",
"user_settings"
] | Set the default value to user settings if user not specified
the value. | [
"Set",
"the",
"default",
"value",
"to",
"user",
"settings",
"if",
"user",
"not",
"specified",
"the",
"value",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-pyramid/opencensus/ext/pyramid/config.py#L45-L53 |
226,184 | census-instrumentation/opencensus-python | opencensus/trace/link.py | Link.format_link_json | def format_link_json(self):
"""Convert a Link object to json format."""
link_json = {}
link_json['trace_id'] = self.trace_id
link_json['span_id'] = self.span_id
link_json['type'] = self.type
if self.attributes is not None:
link_json['attributes'] = self.attributes
return link_json | python | def format_link_json(self):
"""Convert a Link object to json format."""
link_json = {}
link_json['trace_id'] = self.trace_id
link_json['span_id'] = self.span_id
link_json['type'] = self.type
if self.attributes is not None:
link_json['attributes'] = self.attributes
return link_json | [
"def",
"format_link_json",
"(",
"self",
")",
":",
"link_json",
"=",
"{",
"}",
"link_json",
"[",
"'trace_id'",
"]",
"=",
"self",
".",
"trace_id",
"link_json",
"[",
"'span_id'",
"]",
"=",
"self",
".",
"span_id",
"link_json",
"[",
"'type'",
"]",
"=",
"self"... | Convert a Link object to json format. | [
"Convert",
"a",
"Link",
"object",
"to",
"json",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/link.py#L61-L71 |
226,185 | census-instrumentation/opencensus-python | contrib/opencensus-ext-grpc/opencensus/ext/grpc/server_interceptor.py | _wrap_rpc_behavior | def _wrap_rpc_behavior(handler, fn):
"""Returns a new rpc handler that wraps the given function"""
if handler is None:
return None
if handler.request_streaming and handler.response_streaming:
behavior_fn = handler.stream_stream
handler_factory = grpc.stream_stream_rpc_method_handler
elif handler.request_streaming and not handler.response_streaming:
behavior_fn = handler.stream_unary
handler_factory = grpc.stream_unary_rpc_method_handler
elif not handler.request_streaming and handler.response_streaming:
behavior_fn = handler.unary_stream
handler_factory = grpc.unary_stream_rpc_method_handler
else:
behavior_fn = handler.unary_unary
handler_factory = grpc.unary_unary_rpc_method_handler
return handler_factory(
fn(behavior_fn, handler.request_streaming,
handler.response_streaming),
request_deserializer=handler.request_deserializer,
response_serializer=handler.response_serializer
) | python | def _wrap_rpc_behavior(handler, fn):
"""Returns a new rpc handler that wraps the given function"""
if handler is None:
return None
if handler.request_streaming and handler.response_streaming:
behavior_fn = handler.stream_stream
handler_factory = grpc.stream_stream_rpc_method_handler
elif handler.request_streaming and not handler.response_streaming:
behavior_fn = handler.stream_unary
handler_factory = grpc.stream_unary_rpc_method_handler
elif not handler.request_streaming and handler.response_streaming:
behavior_fn = handler.unary_stream
handler_factory = grpc.unary_stream_rpc_method_handler
else:
behavior_fn = handler.unary_unary
handler_factory = grpc.unary_unary_rpc_method_handler
return handler_factory(
fn(behavior_fn, handler.request_streaming,
handler.response_streaming),
request_deserializer=handler.request_deserializer,
response_serializer=handler.response_serializer
) | [
"def",
"_wrap_rpc_behavior",
"(",
"handler",
",",
"fn",
")",
":",
"if",
"handler",
"is",
"None",
":",
"return",
"None",
"if",
"handler",
".",
"request_streaming",
"and",
"handler",
".",
"response_streaming",
":",
"behavior_fn",
"=",
"handler",
".",
"stream_str... | Returns a new rpc handler that wraps the given function | [
"Returns",
"a",
"new",
"rpc",
"handler",
"that",
"wraps",
"the",
"given",
"function"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/server_interceptor.py#L136-L159 |
226,186 | census-instrumentation/opencensus-python | contrib/opencensus-ext-grpc/opencensus/ext/grpc/server_interceptor.py | _get_span_name | def _get_span_name(servicer_context):
"""Generates a span name based off of the gRPC server rpc_request_info"""
method_name = servicer_context._rpc_event.call_details.method[1:]
if isinstance(method_name, bytes):
method_name = method_name.decode('utf-8')
method_name = method_name.replace('/', '.')
return '{}.{}'.format(RECV_PREFIX, method_name) | python | def _get_span_name(servicer_context):
"""Generates a span name based off of the gRPC server rpc_request_info"""
method_name = servicer_context._rpc_event.call_details.method[1:]
if isinstance(method_name, bytes):
method_name = method_name.decode('utf-8')
method_name = method_name.replace('/', '.')
return '{}.{}'.format(RECV_PREFIX, method_name) | [
"def",
"_get_span_name",
"(",
"servicer_context",
")",
":",
"method_name",
"=",
"servicer_context",
".",
"_rpc_event",
".",
"call_details",
".",
"method",
"[",
"1",
":",
"]",
"if",
"isinstance",
"(",
"method_name",
",",
"bytes",
")",
":",
"method_name",
"=",
... | Generates a span name based off of the gRPC server rpc_request_info | [
"Generates",
"a",
"span",
"name",
"based",
"off",
"of",
"the",
"gRPC",
"server",
"rpc_request_info"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/server_interceptor.py#L162-L168 |
226,187 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | new_stats_exporter | def new_stats_exporter(option):
""" new_stats_exporter returns an exporter
that exports stats to Prometheus.
"""
if option.namespace == "":
raise ValueError("Namespace can not be empty string.")
collector = new_collector(option)
exporter = PrometheusStatsExporter(options=option,
gatherer=option.registry,
collector=collector)
return exporter | python | def new_stats_exporter(option):
""" new_stats_exporter returns an exporter
that exports stats to Prometheus.
"""
if option.namespace == "":
raise ValueError("Namespace can not be empty string.")
collector = new_collector(option)
exporter = PrometheusStatsExporter(options=option,
gatherer=option.registry,
collector=collector)
return exporter | [
"def",
"new_stats_exporter",
"(",
"option",
")",
":",
"if",
"option",
".",
"namespace",
"==",
"\"\"",
":",
"raise",
"ValueError",
"(",
"\"Namespace can not be empty string.\"",
")",
"collector",
"=",
"new_collector",
"(",
"option",
")",
"exporter",
"=",
"Prometheu... | new_stats_exporter returns an exporter
that exports stats to Prometheus. | [
"new_stats_exporter",
"returns",
"an",
"exporter",
"that",
"exports",
"stats",
"to",
"Prometheus",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L335-L347 |
226,188 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | get_view_name | def get_view_name(namespace, view):
""" create the name for the view
"""
name = ""
if namespace != "":
name = namespace + "_"
return sanitize(name + view.name) | python | def get_view_name(namespace, view):
""" create the name for the view
"""
name = ""
if namespace != "":
name = namespace + "_"
return sanitize(name + view.name) | [
"def",
"get_view_name",
"(",
"namespace",
",",
"view",
")",
":",
"name",
"=",
"\"\"",
"if",
"namespace",
"!=",
"\"\"",
":",
"name",
"=",
"namespace",
"+",
"\"_\"",
"return",
"sanitize",
"(",
"name",
"+",
"view",
".",
"name",
")"
] | create the name for the view | [
"create",
"the",
"name",
"for",
"the",
"view"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L358-L364 |
226,189 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | Collector.register_view | def register_view(self, view):
""" register_view will create the needed structure
in order to be able to sent all data to Prometheus
"""
v_name = get_view_name(self.options.namespace, view)
if v_name not in self.registered_views:
desc = {'name': v_name,
'documentation': view.description,
'labels': list(map(sanitize, view.columns))}
self.registered_views[v_name] = desc
self.registry.register(self) | python | def register_view(self, view):
""" register_view will create the needed structure
in order to be able to sent all data to Prometheus
"""
v_name = get_view_name(self.options.namespace, view)
if v_name not in self.registered_views:
desc = {'name': v_name,
'documentation': view.description,
'labels': list(map(sanitize, view.columns))}
self.registered_views[v_name] = desc
self.registry.register(self) | [
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"v_name",
"=",
"get_view_name",
"(",
"self",
".",
"options",
".",
"namespace",
",",
"view",
")",
"if",
"v_name",
"not",
"in",
"self",
".",
"registered_views",
":",
"desc",
"=",
"{",
"'name'",
... | register_view will create the needed structure
in order to be able to sent all data to Prometheus | [
"register_view",
"will",
"create",
"the",
"needed",
"structure",
"in",
"order",
"to",
"be",
"able",
"to",
"sent",
"all",
"data",
"to",
"Prometheus"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L121-L132 |
226,190 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | Collector.add_view_data | def add_view_data(self, view_data):
""" Add view data object to be sent to server
"""
self.register_view(view_data.view)
v_name = get_view_name(self.options.namespace, view_data.view)
self.view_name_to_data_map[v_name] = view_data | python | def add_view_data(self, view_data):
""" Add view data object to be sent to server
"""
self.register_view(view_data.view)
v_name = get_view_name(self.options.namespace, view_data.view)
self.view_name_to_data_map[v_name] = view_data | [
"def",
"add_view_data",
"(",
"self",
",",
"view_data",
")",
":",
"self",
".",
"register_view",
"(",
"view_data",
".",
"view",
")",
"v_name",
"=",
"get_view_name",
"(",
"self",
".",
"options",
".",
"namespace",
",",
"view_data",
".",
"view",
")",
"self",
... | Add view data object to be sent to server | [
"Add",
"view",
"data",
"object",
"to",
"be",
"sent",
"to",
"server"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L134-L139 |
226,191 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | Collector.to_metric | def to_metric(self, desc, tag_values, agg_data):
""" to_metric translate the data that OpenCensus create
to Prometheus format, using Prometheus Metric object
:type desc: dict
:param desc: The map that describes view definition
:type tag_values: tuple of :class:
`~opencensus.tags.tag_value.TagValue`
:param object of opencensus.tags.tag_value.TagValue:
TagValue object used as label values
:type agg_data: object of :class:
`~opencensus.stats.aggregation_data.AggregationData`
:param object of opencensus.stats.aggregation_data.AggregationData:
Aggregated data that needs to be converted as Prometheus samples
:rtype: :class:`~prometheus_client.core.CounterMetricFamily` or
:class:`~prometheus_client.core.HistogramMetricFamily` or
:class:`~prometheus_client.core.UnknownMetricFamily` or
:class:`~prometheus_client.core.GaugeMetricFamily`
:returns: A Prometheus metric object
"""
metric_name = desc['name']
metric_description = desc['documentation']
label_keys = desc['labels']
assert(len(tag_values) == len(label_keys))
# Prometheus requires that all tag values be strings hence
# the need to cast none to the empty string before exporting. See
# https://github.com/census-instrumentation/opencensus-python/issues/480
tag_values = [tv if tv else "" for tv in tag_values]
if isinstance(agg_data, aggregation_data_module.CountAggregationData):
metric = CounterMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.count_data)
return metric
elif isinstance(agg_data,
aggregation_data_module.DistributionAggregationData):
assert(agg_data.bounds == sorted(agg_data.bounds))
# buckets are a list of buckets. Each bucket is another list with
# a pair of bucket name and value, or a triple of bucket name,
# value, and exemplar. buckets need to be in order.
buckets = []
cum_count = 0 # Prometheus buckets expect cumulative count.
for ii, bound in enumerate(agg_data.bounds):
cum_count += agg_data.counts_per_bucket[ii]
bucket = [str(bound), cum_count]
buckets.append(bucket)
# Prometheus requires buckets to be sorted, and +Inf present.
# In OpenCensus we don't have +Inf in the bucket bonds so need to
# append it here.
buckets.append(["+Inf", agg_data.count_data])
metric = HistogramMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
buckets=buckets,
sum_value=agg_data.sum,)
return metric
elif isinstance(agg_data,
aggregation_data_module.SumAggregationDataFloat):
metric = UnknownMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.sum_data)
return metric
elif isinstance(agg_data,
aggregation_data_module.LastValueAggregationData):
metric = GaugeMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.value)
return metric
else:
raise ValueError("unsupported aggregation type %s"
% type(agg_data)) | python | def to_metric(self, desc, tag_values, agg_data):
""" to_metric translate the data that OpenCensus create
to Prometheus format, using Prometheus Metric object
:type desc: dict
:param desc: The map that describes view definition
:type tag_values: tuple of :class:
`~opencensus.tags.tag_value.TagValue`
:param object of opencensus.tags.tag_value.TagValue:
TagValue object used as label values
:type agg_data: object of :class:
`~opencensus.stats.aggregation_data.AggregationData`
:param object of opencensus.stats.aggregation_data.AggregationData:
Aggregated data that needs to be converted as Prometheus samples
:rtype: :class:`~prometheus_client.core.CounterMetricFamily` or
:class:`~prometheus_client.core.HistogramMetricFamily` or
:class:`~prometheus_client.core.UnknownMetricFamily` or
:class:`~prometheus_client.core.GaugeMetricFamily`
:returns: A Prometheus metric object
"""
metric_name = desc['name']
metric_description = desc['documentation']
label_keys = desc['labels']
assert(len(tag_values) == len(label_keys))
# Prometheus requires that all tag values be strings hence
# the need to cast none to the empty string before exporting. See
# https://github.com/census-instrumentation/opencensus-python/issues/480
tag_values = [tv if tv else "" for tv in tag_values]
if isinstance(agg_data, aggregation_data_module.CountAggregationData):
metric = CounterMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.count_data)
return metric
elif isinstance(agg_data,
aggregation_data_module.DistributionAggregationData):
assert(agg_data.bounds == sorted(agg_data.bounds))
# buckets are a list of buckets. Each bucket is another list with
# a pair of bucket name and value, or a triple of bucket name,
# value, and exemplar. buckets need to be in order.
buckets = []
cum_count = 0 # Prometheus buckets expect cumulative count.
for ii, bound in enumerate(agg_data.bounds):
cum_count += agg_data.counts_per_bucket[ii]
bucket = [str(bound), cum_count]
buckets.append(bucket)
# Prometheus requires buckets to be sorted, and +Inf present.
# In OpenCensus we don't have +Inf in the bucket bonds so need to
# append it here.
buckets.append(["+Inf", agg_data.count_data])
metric = HistogramMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
buckets=buckets,
sum_value=agg_data.sum,)
return metric
elif isinstance(agg_data,
aggregation_data_module.SumAggregationDataFloat):
metric = UnknownMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.sum_data)
return metric
elif isinstance(agg_data,
aggregation_data_module.LastValueAggregationData):
metric = GaugeMetricFamily(name=metric_name,
documentation=metric_description,
labels=label_keys)
metric.add_metric(labels=tag_values,
value=agg_data.value)
return metric
else:
raise ValueError("unsupported aggregation type %s"
% type(agg_data)) | [
"def",
"to_metric",
"(",
"self",
",",
"desc",
",",
"tag_values",
",",
"agg_data",
")",
":",
"metric_name",
"=",
"desc",
"[",
"'name'",
"]",
"metric_description",
"=",
"desc",
"[",
"'documentation'",
"]",
"label_keys",
"=",
"desc",
"[",
"'labels'",
"]",
"as... | to_metric translate the data that OpenCensus create
to Prometheus format, using Prometheus Metric object
:type desc: dict
:param desc: The map that describes view definition
:type tag_values: tuple of :class:
`~opencensus.tags.tag_value.TagValue`
:param object of opencensus.tags.tag_value.TagValue:
TagValue object used as label values
:type agg_data: object of :class:
`~opencensus.stats.aggregation_data.AggregationData`
:param object of opencensus.stats.aggregation_data.AggregationData:
Aggregated data that needs to be converted as Prometheus samples
:rtype: :class:`~prometheus_client.core.CounterMetricFamily` or
:class:`~prometheus_client.core.HistogramMetricFamily` or
:class:`~prometheus_client.core.UnknownMetricFamily` or
:class:`~prometheus_client.core.GaugeMetricFamily`
:returns: A Prometheus metric object | [
"to_metric",
"translate",
"the",
"data",
"that",
"OpenCensus",
"create",
"to",
"Prometheus",
"format",
"using",
"Prometheus",
"Metric",
"object"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L142-L228 |
226,192 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | Collector.collect | def collect(self): # pragma: NO COVER
"""Collect fetches the statistics from OpenCensus
and delivers them as Prometheus Metrics.
Collect is invoked every time a prometheus.Gatherer is run
for example when the HTTP endpoint is invoked by Prometheus.
"""
for v_name, view_data in self.view_name_to_data_map.items():
if v_name not in self.registered_views:
continue
desc = self.registered_views[v_name]
for tag_values in view_data.tag_value_aggregation_data_map:
agg_data = view_data.tag_value_aggregation_data_map[tag_values]
metric = self.to_metric(desc, tag_values, agg_data)
yield metric | python | def collect(self): # pragma: NO COVER
"""Collect fetches the statistics from OpenCensus
and delivers them as Prometheus Metrics.
Collect is invoked every time a prometheus.Gatherer is run
for example when the HTTP endpoint is invoked by Prometheus.
"""
for v_name, view_data in self.view_name_to_data_map.items():
if v_name not in self.registered_views:
continue
desc = self.registered_views[v_name]
for tag_values in view_data.tag_value_aggregation_data_map:
agg_data = view_data.tag_value_aggregation_data_map[tag_values]
metric = self.to_metric(desc, tag_values, agg_data)
yield metric | [
"def",
"collect",
"(",
"self",
")",
":",
"# pragma: NO COVER",
"for",
"v_name",
",",
"view_data",
"in",
"self",
".",
"view_name_to_data_map",
".",
"items",
"(",
")",
":",
"if",
"v_name",
"not",
"in",
"self",
".",
"registered_views",
":",
"continue",
"desc",
... | Collect fetches the statistics from OpenCensus
and delivers them as Prometheus Metrics.
Collect is invoked every time a prometheus.Gatherer is run
for example when the HTTP endpoint is invoked by Prometheus. | [
"Collect",
"fetches",
"the",
"statistics",
"from",
"OpenCensus",
"and",
"delivers",
"them",
"as",
"Prometheus",
"Metrics",
".",
"Collect",
"is",
"invoked",
"every",
"time",
"a",
"prometheus",
".",
"Gatherer",
"is",
"run",
"for",
"example",
"when",
"the",
"HTTP... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L230-L243 |
226,193 | census-instrumentation/opencensus-python | contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py | PrometheusStatsExporter.serve_http | def serve_http(self):
""" serve_http serves the Prometheus endpoint.
"""
start_http_server(port=self.options.port,
addr=str(self.options.address)) | python | def serve_http(self):
""" serve_http serves the Prometheus endpoint.
"""
start_http_server(port=self.options.port,
addr=str(self.options.address)) | [
"def",
"serve_http",
"(",
"self",
")",
":",
"start_http_server",
"(",
"port",
"=",
"self",
".",
"options",
".",
"port",
",",
"addr",
"=",
"str",
"(",
"self",
".",
"options",
".",
"address",
")",
")"
] | serve_http serves the Prometheus endpoint. | [
"serve_http",
"serves",
"the",
"Prometheus",
"endpoint",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-prometheus/opencensus/ext/prometheus/stats_exporter/__init__.py#L328-L332 |
226,194 | census-instrumentation/opencensus-python | opencensus/trace/time_event.py | TimeEvent.format_time_event_json | def format_time_event_json(self):
"""Convert a TimeEvent object to json format."""
time_event = {}
time_event['time'] = self.timestamp
if self.annotation is not None:
time_event['annotation'] = self.annotation.format_annotation_json()
if self.message_event is not None:
time_event['message_event'] = \
self.message_event.format_message_event_json()
return time_event | python | def format_time_event_json(self):
"""Convert a TimeEvent object to json format."""
time_event = {}
time_event['time'] = self.timestamp
if self.annotation is not None:
time_event['annotation'] = self.annotation.format_annotation_json()
if self.message_event is not None:
time_event['message_event'] = \
self.message_event.format_message_event_json()
return time_event | [
"def",
"format_time_event_json",
"(",
"self",
")",
":",
"time_event",
"=",
"{",
"}",
"time_event",
"[",
"'time'",
"]",
"=",
"self",
".",
"timestamp",
"if",
"self",
".",
"annotation",
"is",
"not",
"None",
":",
"time_event",
"[",
"'annotation'",
"]",
"=",
... | Convert a TimeEvent object to json format. | [
"Convert",
"a",
"TimeEvent",
"object",
"to",
"json",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/time_event.py#L139-L151 |
226,195 | census-instrumentation/opencensus-python | opencensus/trace/samplers/probability.py | ProbabilitySampler.should_sample | def should_sample(self, trace_id):
"""Make the sampling decision based on the lower 8 bytes of the trace
ID. If the value is less than the bound, return True, else False.
:type trace_id: str
:param trace_id: Trace ID of the current trace.
:rtype: bool
:returns: The sampling decision.
"""
lower_long = get_lower_long_from_trace_id(trace_id)
bound = self.rate * MAX_VALUE
if lower_long <= bound:
return True
else:
return False | python | def should_sample(self, trace_id):
"""Make the sampling decision based on the lower 8 bytes of the trace
ID. If the value is less than the bound, return True, else False.
:type trace_id: str
:param trace_id: Trace ID of the current trace.
:rtype: bool
:returns: The sampling decision.
"""
lower_long = get_lower_long_from_trace_id(trace_id)
bound = self.rate * MAX_VALUE
if lower_long <= bound:
return True
else:
return False | [
"def",
"should_sample",
"(",
"self",
",",
"trace_id",
")",
":",
"lower_long",
"=",
"get_lower_long_from_trace_id",
"(",
"trace_id",
")",
"bound",
"=",
"self",
".",
"rate",
"*",
"MAX_VALUE",
"if",
"lower_long",
"<=",
"bound",
":",
"return",
"True",
"else",
":... | Make the sampling decision based on the lower 8 bytes of the trace
ID. If the value is less than the bound, return True, else False.
:type trace_id: str
:param trace_id: Trace ID of the current trace.
:rtype: bool
:returns: The sampling decision. | [
"Make",
"the",
"sampling",
"decision",
"based",
"on",
"the",
"lower",
"8",
"bytes",
"of",
"the",
"trace",
"ID",
".",
"If",
"the",
"value",
"is",
"less",
"than",
"the",
"bound",
"return",
"True",
"else",
"False",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/samplers/probability.py#L37-L53 |
226,196 | census-instrumentation/opencensus-python | opencensus/metrics/export/cumulative.py | CumulativePointLong.add | def add(self, val):
"""Add `val` to the current value if it's positive.
Return without adding if `val` is not positive.
:type val: int
:param val: Value to add.
"""
if not isinstance(val, six.integer_types):
raise ValueError("CumulativePointLong only supports integer types")
if val > 0:
super(CumulativePointLong, self).add(val) | python | def add(self, val):
"""Add `val` to the current value if it's positive.
Return without adding if `val` is not positive.
:type val: int
:param val: Value to add.
"""
if not isinstance(val, six.integer_types):
raise ValueError("CumulativePointLong only supports integer types")
if val > 0:
super(CumulativePointLong, self).add(val) | [
"def",
"add",
"(",
"self",
",",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"ValueError",
"(",
"\"CumulativePointLong only supports integer types\"",
")",
"if",
"val",
">",
"0",
":",
"super",
... | Add `val` to the current value if it's positive.
Return without adding if `val` is not positive.
:type val: int
:param val: Value to add. | [
"Add",
"val",
"to",
"the",
"current",
"value",
"if",
"it",
"s",
"positive",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/cumulative.py#L30-L41 |
226,197 | census-instrumentation/opencensus-python | opencensus/trace/tracer.py | Tracer.should_sample | def should_sample(self):
"""Determine whether to sample this request or not.
If the context enables tracing, return True.
Else follow the decision of the sampler.
:rtype: bool
:returns: Whether to trace the request or not.
"""
return self.span_context.trace_options.enabled \
or self.sampler.should_sample(self.span_context.trace_id) | python | def should_sample(self):
"""Determine whether to sample this request or not.
If the context enables tracing, return True.
Else follow the decision of the sampler.
:rtype: bool
:returns: Whether to trace the request or not.
"""
return self.span_context.trace_options.enabled \
or self.sampler.should_sample(self.span_context.trace_id) | [
"def",
"should_sample",
"(",
"self",
")",
":",
"return",
"self",
".",
"span_context",
".",
"trace_options",
".",
"enabled",
"or",
"self",
".",
"sampler",
".",
"should_sample",
"(",
"self",
".",
"span_context",
".",
"trace_id",
")"
] | Determine whether to sample this request or not.
If the context enables tracing, return True.
Else follow the decision of the sampler.
:rtype: bool
:returns: Whether to trace the request or not. | [
"Determine",
"whether",
"to",
"sample",
"this",
"request",
"or",
"not",
".",
"If",
"the",
"context",
"enables",
"tracing",
"return",
"True",
".",
"Else",
"follow",
"the",
"decision",
"of",
"the",
"sampler",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracer.py#L69-L78 |
226,198 | census-instrumentation/opencensus-python | opencensus/trace/tracer.py | Tracer.get_tracer | def get_tracer(self):
"""Return a tracer according to the sampling decision."""
sampled = self.should_sample()
if sampled:
self.span_context.trace_options.set_enabled(True)
return context_tracer.ContextTracer(
exporter=self.exporter,
span_context=self.span_context)
else:
return noop_tracer.NoopTracer() | python | def get_tracer(self):
"""Return a tracer according to the sampling decision."""
sampled = self.should_sample()
if sampled:
self.span_context.trace_options.set_enabled(True)
return context_tracer.ContextTracer(
exporter=self.exporter,
span_context=self.span_context)
else:
return noop_tracer.NoopTracer() | [
"def",
"get_tracer",
"(",
"self",
")",
":",
"sampled",
"=",
"self",
".",
"should_sample",
"(",
")",
"if",
"sampled",
":",
"self",
".",
"span_context",
".",
"trace_options",
".",
"set_enabled",
"(",
"True",
")",
"return",
"context_tracer",
".",
"ContextTracer... | Return a tracer according to the sampling decision. | [
"Return",
"a",
"tracer",
"according",
"to",
"the",
"sampling",
"decision",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracer.py#L80-L90 |
226,199 | census-instrumentation/opencensus-python | opencensus/trace/tracer.py | Tracer.trace_decorator | def trace_decorator(self):
"""Decorator to trace a function."""
def decorator(func):
def wrapper(*args, **kwargs):
self.tracer.start_span(name=func.__name__)
return_value = func(*args, **kwargs)
self.tracer.end_span()
return return_value
return wrapper
return decorator | python | def trace_decorator(self):
"""Decorator to trace a function."""
def decorator(func):
def wrapper(*args, **kwargs):
self.tracer.start_span(name=func.__name__)
return_value = func(*args, **kwargs)
self.tracer.end_span()
return return_value
return wrapper
return decorator | [
"def",
"trace_decorator",
"(",
"self",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"tracer",
".",
"start_span",
"(",
"name",
"=",
"func",
".",
"__name__",
... | Decorator to trace a function. | [
"Decorator",
"to",
"trace",
"a",
"function",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracer.py#L136-L149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.