repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 | train | 221,000 |
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 | train | 221,001 |
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 | train | 221,002 |
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 | train | 221,003 |
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 | train | 221,004 |
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 | train | 221,005 |
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 | train | 221,006 |
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 | train | 221,007 |
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 | train | 221,008 |
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 | train | 221,009 |
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 | train | 221,010 |
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 | train | 221,011 |
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 | train | 221,012 |
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 | train | 221,013 |
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 | train | 221,014 |
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 | train | 221,015 |
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 | train | 221,016 |
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 | train | 221,017 |
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 | train | 221,018 |
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 | train | 221,019 |
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 | train | 221,020 |
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 | train | 221,021 |
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 | train | 221,022 |
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 | train | 221,023 |
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 | train | 221,024 |
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 | train | 221,025 |
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 | train | 221,026 |
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 | train | 221,027 |
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 | train | 221,028 |
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 | train | 221,029 |
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 | train | 221,030 |
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 | train | 221,031 |
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 | train | 221,032 |
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 | train | 221,033 |
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 | train | 221,034 |
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 | train | 221,035 |
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 | train | 221,036 |
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 | train | 221,037 |
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 | train | 221,038 |
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 | train | 221,039 |
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 | train | 221,040 |
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 | train | 221,041 |
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 | train | 221,042 |
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 | train | 221,043 |
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 | train | 221,044 |
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 | train | 221,045 |
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 | train | 221,046 |
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 | train | 221,047 |
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 | train | 221,048 |
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 | train | 221,049 |
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 | train | 221,050 |
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 | train | 221,051 |
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 | train | 221,052 |
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 | train | 221,053 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py | set_attributes | def set_attributes(trace):
"""Automatically set attributes for Google Cloud environment."""
spans = trace.get('spans')
for span in spans:
if span.get('attributes') is None:
span['attributes'] = {}
if is_gae_environment():
set_gae_attributes(span)
set_common_attributes(span)
set_monitored_resource_attributes(span) | python | def set_attributes(trace):
"""Automatically set attributes for Google Cloud environment."""
spans = trace.get('spans')
for span in spans:
if span.get('attributes') is None:
span['attributes'] = {}
if is_gae_environment():
set_gae_attributes(span)
set_common_attributes(span)
set_monitored_resource_attributes(span) | [
"def",
"set_attributes",
"(",
"trace",
")",
":",
"spans",
"=",
"trace",
".",
"get",
"(",
"'spans'",
")",
"for",
"span",
"in",
"spans",
":",
"if",
"span",
".",
"get",
"(",
"'attributes'",
")",
"is",
"None",
":",
"span",
"[",
"'attributes'",
"]",
"=",
... | Automatically set attributes for Google Cloud environment. | [
"Automatically",
"set",
"attributes",
"for",
"Google",
"Cloud",
"environment",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py#L62-L74 | train | 221,054 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py | set_common_attributes | def set_common_attributes(span):
"""Set the common attributes."""
common = {
attributes_helper.COMMON_ATTRIBUTES.get('AGENT'): AGENT,
}
common_attrs = Attributes(common)\
.format_attributes_json()\
.get('attributeMap')
_update_attr_map(span, common_attrs) | python | def set_common_attributes(span):
"""Set the common attributes."""
common = {
attributes_helper.COMMON_ATTRIBUTES.get('AGENT'): AGENT,
}
common_attrs = Attributes(common)\
.format_attributes_json()\
.get('attributeMap')
_update_attr_map(span, common_attrs) | [
"def",
"set_common_attributes",
"(",
"span",
")",
":",
"common",
"=",
"{",
"attributes_helper",
".",
"COMMON_ATTRIBUTES",
".",
"get",
"(",
"'AGENT'",
")",
":",
"AGENT",
",",
"}",
"common_attrs",
"=",
"Attributes",
"(",
"common",
")",
".",
"format_attributes_js... | Set the common attributes. | [
"Set",
"the",
"common",
"attributes",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py#L142-L151 | train | 221,055 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py | set_gae_attributes | def set_gae_attributes(span):
"""Set the GAE environment common attributes."""
for env_var, attribute_key in GAE_ATTRIBUTES.items():
attribute_value = os.environ.get(env_var)
if attribute_value is not None:
pair = {attribute_key: attribute_value}
pair_attrs = Attributes(pair)\
.format_attributes_json()\
.get('attributeMap')
_update_attr_map(span, pair_attrs) | python | def set_gae_attributes(span):
"""Set the GAE environment common attributes."""
for env_var, attribute_key in GAE_ATTRIBUTES.items():
attribute_value = os.environ.get(env_var)
if attribute_value is not None:
pair = {attribute_key: attribute_value}
pair_attrs = Attributes(pair)\
.format_attributes_json()\
.get('attributeMap')
_update_attr_map(span, pair_attrs) | [
"def",
"set_gae_attributes",
"(",
"span",
")",
":",
"for",
"env_var",
",",
"attribute_key",
"in",
"GAE_ATTRIBUTES",
".",
"items",
"(",
")",
":",
"attribute_value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_var",
")",
"if",
"attribute_value",
"is",
"... | Set the GAE environment common attributes. | [
"Set",
"the",
"GAE",
"environment",
"common",
"attributes",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py#L154-L165 | train | 221,056 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py | StackdriverExporter.translate_to_stackdriver | def translate_to_stackdriver(self, trace):
"""Translate the spans json to Stackdriver format.
See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/
projects.traces/batchWrite
:type trace: dict
:param trace: Trace dictionary
:rtype: dict
:returns: Spans in Google Cloud StackDriver Trace format.
"""
set_attributes(trace)
spans_json = trace.get('spans')
trace_id = trace.get('traceId')
for span in spans_json:
span_name = 'projects/{}/traces/{}/spans/{}'.format(
self.project_id, trace_id, span.get('spanId'))
span_json = {
'name': span_name,
'displayName': span.get('displayName'),
'startTime': span.get('startTime'),
'endTime': span.get('endTime'),
'spanId': str(span.get('spanId')),
'attributes': self.map_attributes(span.get('attributes')),
'links': span.get('links'),
'status': span.get('status'),
'stackTrace': span.get('stackTrace'),
'timeEvents': span.get('timeEvents'),
'sameProcessAsParentSpan': span.get('sameProcessAsParentSpan'),
'childSpanCount': span.get('childSpanCount')
}
if span.get('parentSpanId') is not None:
parent_span_id = str(span.get('parentSpanId'))
span_json['parentSpanId'] = parent_span_id
yield span_json | python | def translate_to_stackdriver(self, trace):
"""Translate the spans json to Stackdriver format.
See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/
projects.traces/batchWrite
:type trace: dict
:param trace: Trace dictionary
:rtype: dict
:returns: Spans in Google Cloud StackDriver Trace format.
"""
set_attributes(trace)
spans_json = trace.get('spans')
trace_id = trace.get('traceId')
for span in spans_json:
span_name = 'projects/{}/traces/{}/spans/{}'.format(
self.project_id, trace_id, span.get('spanId'))
span_json = {
'name': span_name,
'displayName': span.get('displayName'),
'startTime': span.get('startTime'),
'endTime': span.get('endTime'),
'spanId': str(span.get('spanId')),
'attributes': self.map_attributes(span.get('attributes')),
'links': span.get('links'),
'status': span.get('status'),
'stackTrace': span.get('stackTrace'),
'timeEvents': span.get('timeEvents'),
'sameProcessAsParentSpan': span.get('sameProcessAsParentSpan'),
'childSpanCount': span.get('childSpanCount')
}
if span.get('parentSpanId') is not None:
parent_span_id = str(span.get('parentSpanId'))
span_json['parentSpanId'] = parent_span_id
yield span_json | [
"def",
"translate_to_stackdriver",
"(",
"self",
",",
"trace",
")",
":",
"set_attributes",
"(",
"trace",
")",
"spans_json",
"=",
"trace",
".",
"get",
"(",
"'spans'",
")",
"trace_id",
"=",
"trace",
".",
"get",
"(",
"'traceId'",
")",
"for",
"span",
"in",
"s... | Translate the spans json to Stackdriver format.
See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/
projects.traces/batchWrite
:type trace: dict
:param trace: Trace dictionary
:rtype: dict
:returns: Spans in Google Cloud StackDriver Trace format. | [
"Translate",
"the",
"spans",
"json",
"to",
"Stackdriver",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/trace_exporter/__init__.py#L236-L275 | train | 221,057 |
census-instrumentation/opencensus-python | opencensus/common/resource/__init__.py | merge_resources | def merge_resources(resource_list):
"""Merge multiple resources to get a new resource.
Resources earlier in the list take precedence: if multiple resources share
a label key, use the value from the first resource in the list with that
key. The combined resource's type will be the first non-null type in the
list.
:type resource_list: list(:class:`Resource`)
:param resource_list: The list of resources to combine.
:rtype: :class:`Resource`
:return: The new combined resource.
"""
if not resource_list:
raise ValueError
rtype = None
for rr in resource_list:
if rr.type:
rtype = rr.type
break
labels = {}
for rr in reversed(resource_list):
labels.update(rr.labels)
return Resource(rtype, labels) | python | def merge_resources(resource_list):
"""Merge multiple resources to get a new resource.
Resources earlier in the list take precedence: if multiple resources share
a label key, use the value from the first resource in the list with that
key. The combined resource's type will be the first non-null type in the
list.
:type resource_list: list(:class:`Resource`)
:param resource_list: The list of resources to combine.
:rtype: :class:`Resource`
:return: The new combined resource.
"""
if not resource_list:
raise ValueError
rtype = None
for rr in resource_list:
if rr.type:
rtype = rr.type
break
labels = {}
for rr in reversed(resource_list):
labels.update(rr.labels)
return Resource(rtype, labels) | [
"def",
"merge_resources",
"(",
"resource_list",
")",
":",
"if",
"not",
"resource_list",
":",
"raise",
"ValueError",
"rtype",
"=",
"None",
"for",
"rr",
"in",
"resource_list",
":",
"if",
"rr",
".",
"type",
":",
"rtype",
"=",
"rr",
".",
"type",
"break",
"la... | Merge multiple resources to get a new resource.
Resources earlier in the list take precedence: if multiple resources share
a label key, use the value from the first resource in the list with that
key. The combined resource's type will be the first non-null type in the
list.
:type resource_list: list(:class:`Resource`)
:param resource_list: The list of resources to combine.
:rtype: :class:`Resource`
:return: The new combined resource. | [
"Merge",
"multiple",
"resources",
"to",
"get",
"a",
"new",
"resource",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/resource/__init__.py#L52-L76 | train | 221,058 |
census-instrumentation/opencensus-python | opencensus/common/resource/__init__.py | check_ascii_256 | def check_ascii_256(string):
"""Check that `string` is printable ASCII and at most 256 chars.
Raise a `ValueError` if this check fails. Note that `string` itself doesn't
have to be ASCII-encoded.
:type string: str
:param string: The string to check.
"""
if string is None:
return
if len(string) > 256:
raise ValueError("Value is longer than 256 characters")
bad_char = _NON_PRINTABLE_ASCII.search(string)
if bad_char:
raise ValueError(u'Character "{}" at position {} is not printable '
'ASCII'
.format(
string[bad_char.start():bad_char.end()],
bad_char.start())) | python | def check_ascii_256(string):
"""Check that `string` is printable ASCII and at most 256 chars.
Raise a `ValueError` if this check fails. Note that `string` itself doesn't
have to be ASCII-encoded.
:type string: str
:param string: The string to check.
"""
if string is None:
return
if len(string) > 256:
raise ValueError("Value is longer than 256 characters")
bad_char = _NON_PRINTABLE_ASCII.search(string)
if bad_char:
raise ValueError(u'Character "{}" at position {} is not printable '
'ASCII'
.format(
string[bad_char.start():bad_char.end()],
bad_char.start())) | [
"def",
"check_ascii_256",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"if",
"len",
"(",
"string",
")",
">",
"256",
":",
"raise",
"ValueError",
"(",
"\"Value is longer than 256 characters\"",
")",
"bad_char",
"=",
"_NON_PRINTABLE_ASCII",... | Check that `string` is printable ASCII and at most 256 chars.
Raise a `ValueError` if this check fails. Note that `string` itself doesn't
have to be ASCII-encoded.
:type string: str
:param string: The string to check. | [
"Check",
"that",
"string",
"is",
"printable",
"ASCII",
"and",
"at",
"most",
"256",
"chars",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/resource/__init__.py#L79-L98 | train | 221,059 |
census-instrumentation/opencensus-python | opencensus/common/resource/__init__.py | parse_labels | def parse_labels(labels_str):
"""Parse label keys and values following the Resource spec.
>>> parse_labels("k=v")
{'k': 'v'}
>>> parse_labels("k1=v1, k2=v2")
{'k1': 'v1', 'k2': 'v2'}
>>> parse_labels("k1='v1,=z1'")
{'k1': 'v1,=z1'}
"""
if not _LABELS_RE.match(labels_str):
return None
labels = {}
for kv in _KV_RE.finditer(labels_str):
gd = kv.groupdict()
key = unquote(gd['key'])
if key in labels:
logger.warning('Duplicate label key "%s"', key)
labels[key] = unquote(gd['val'])
return labels | python | def parse_labels(labels_str):
"""Parse label keys and values following the Resource spec.
>>> parse_labels("k=v")
{'k': 'v'}
>>> parse_labels("k1=v1, k2=v2")
{'k1': 'v1', 'k2': 'v2'}
>>> parse_labels("k1='v1,=z1'")
{'k1': 'v1,=z1'}
"""
if not _LABELS_RE.match(labels_str):
return None
labels = {}
for kv in _KV_RE.finditer(labels_str):
gd = kv.groupdict()
key = unquote(gd['key'])
if key in labels:
logger.warning('Duplicate label key "%s"', key)
labels[key] = unquote(gd['val'])
return labels | [
"def",
"parse_labels",
"(",
"labels_str",
")",
":",
"if",
"not",
"_LABELS_RE",
".",
"match",
"(",
"labels_str",
")",
":",
"return",
"None",
"labels",
"=",
"{",
"}",
"for",
"kv",
"in",
"_KV_RE",
".",
"finditer",
"(",
"labels_str",
")",
":",
"gd",
"=",
... | Parse label keys and values following the Resource spec.
>>> parse_labels("k=v")
{'k': 'v'}
>>> parse_labels("k1=v1, k2=v2")
{'k1': 'v1', 'k2': 'v2'}
>>> parse_labels("k1='v1,=z1'")
{'k1': 'v1,=z1'} | [
"Parse",
"label",
"keys",
"and",
"values",
"following",
"the",
"Resource",
"spec",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/resource/__init__.py#L180-L199 | train | 221,060 |
census-instrumentation/opencensus-python | opencensus/common/resource/__init__.py | get_from_env | def get_from_env():
"""Get a Resource from environment variables.
:rtype: :class:`Resource`
:return: A resource with type and labels from the environment.
"""
type_env = os.getenv(OC_RESOURCE_TYPE)
if type_env is None:
return None
type_env = type_env.strip()
labels_env = os.getenv(OC_RESOURCE_LABELS)
if labels_env is None:
return Resource(type_env)
labels = parse_labels(labels_env)
return Resource(type_env, labels) | python | def get_from_env():
"""Get a Resource from environment variables.
:rtype: :class:`Resource`
:return: A resource with type and labels from the environment.
"""
type_env = os.getenv(OC_RESOURCE_TYPE)
if type_env is None:
return None
type_env = type_env.strip()
labels_env = os.getenv(OC_RESOURCE_LABELS)
if labels_env is None:
return Resource(type_env)
labels = parse_labels(labels_env)
return Resource(type_env, labels) | [
"def",
"get_from_env",
"(",
")",
":",
"type_env",
"=",
"os",
".",
"getenv",
"(",
"OC_RESOURCE_TYPE",
")",
"if",
"type_env",
"is",
"None",
":",
"return",
"None",
"type_env",
"=",
"type_env",
".",
"strip",
"(",
")",
"labels_env",
"=",
"os",
".",
"getenv",
... | Get a Resource from environment variables.
:rtype: :class:`Resource`
:return: A resource with type and labels from the environment. | [
"Get",
"a",
"Resource",
"from",
"environment",
"variables",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/resource/__init__.py#L202-L219 | train | 221,061 |
census-instrumentation/opencensus-python | context/opencensus-context/opencensus/common/runtime_context/__init__.py | _RuntimeContext.apply | def apply(self, snapshot):
"""Set the current context from a given snapshot dictionary"""
for name in snapshot:
setattr(self, name, snapshot[name]) | python | def apply(self, snapshot):
"""Set the current context from a given snapshot dictionary"""
for name in snapshot:
setattr(self, name, snapshot[name]) | [
"def",
"apply",
"(",
"self",
",",
"snapshot",
")",
":",
"for",
"name",
"in",
"snapshot",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"snapshot",
"[",
"name",
"]",
")"
] | Set the current context from a given snapshot dictionary | [
"Set",
"the",
"current",
"context",
"from",
"a",
"given",
"snapshot",
"dictionary"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/context/opencensus-context/opencensus/common/runtime_context/__init__.py#L48-L52 | train | 221,062 |
census-instrumentation/opencensus-python | context/opencensus-context/opencensus/common/runtime_context/__init__.py | _RuntimeContext.snapshot | def snapshot(self):
"""Return a dictionary of current slots by reference."""
return dict((n, self._slots[n].get()) for n in self._slots.keys()) | python | def snapshot(self):
"""Return a dictionary of current slots by reference."""
return dict((n, self._slots[n].get()) for n in self._slots.keys()) | [
"def",
"snapshot",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"n",
",",
"self",
".",
"_slots",
"[",
"n",
"]",
".",
"get",
"(",
")",
")",
"for",
"n",
"in",
"self",
".",
"_slots",
".",
"keys",
"(",
")",
")"
] | Return a dictionary of current slots by reference. | [
"Return",
"a",
"dictionary",
"of",
"current",
"slots",
"by",
"reference",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/context/opencensus-context/opencensus/common/runtime_context/__init__.py#L54-L57 | train | 221,063 |
census-instrumentation/opencensus-python | context/opencensus-context/opencensus/common/runtime_context/__init__.py | _RuntimeContext.with_current_context | def with_current_context(self, func):
"""Capture the current context and apply it to the provided func"""
caller_context = self.snapshot()
def call_with_current_context(*args, **kwargs):
try:
backup_context = self.snapshot()
self.apply(caller_context)
return func(*args, **kwargs)
finally:
self.apply(backup_context)
return call_with_current_context | python | def with_current_context(self, func):
"""Capture the current context and apply it to the provided func"""
caller_context = self.snapshot()
def call_with_current_context(*args, **kwargs):
try:
backup_context = self.snapshot()
self.apply(caller_context)
return func(*args, **kwargs)
finally:
self.apply(backup_context)
return call_with_current_context | [
"def",
"with_current_context",
"(",
"self",
",",
"func",
")",
":",
"caller_context",
"=",
"self",
".",
"snapshot",
"(",
")",
"def",
"call_with_current_context",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"backup_context",
"=",
"self",... | Capture the current context and apply it to the provided func | [
"Capture",
"the",
"current",
"context",
"and",
"apply",
"it",
"to",
"the",
"provided",
"func"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/context/opencensus-context/opencensus/common/runtime_context/__init__.py#L76-L89 | train | 221,064 |
census-instrumentation/opencensus-python | opencensus/common/monitored_resource/aws_identity_doc_utils.py | AwsIdentityDocumentUtils._initialize_aws_identity_document | def _initialize_aws_identity_document(cls):
"""This method, tries to establish an HTTP connection to AWS instance
identity document url. If the application is running on an EC2
instance, we should be able to get back a valid JSON document. Make a
http get request call and store data in local map.
This method should only be called once.
"""
if cls.inited:
return
content = get_request(_AWS_INSTANCE_IDENTITY_DOCUMENT_URI)
if content is not None:
content = json.loads(content)
for env_var, attribute_key in _AWS_ATTRIBUTES.items():
attribute_value = content.get(env_var)
if attribute_value is not None:
aws_metadata_map[attribute_key] = attribute_value
cls.is_running = True
cls.inited = True | python | def _initialize_aws_identity_document(cls):
"""This method, tries to establish an HTTP connection to AWS instance
identity document url. If the application is running on an EC2
instance, we should be able to get back a valid JSON document. Make a
http get request call and store data in local map.
This method should only be called once.
"""
if cls.inited:
return
content = get_request(_AWS_INSTANCE_IDENTITY_DOCUMENT_URI)
if content is not None:
content = json.loads(content)
for env_var, attribute_key in _AWS_ATTRIBUTES.items():
attribute_value = content.get(env_var)
if attribute_value is not None:
aws_metadata_map[attribute_key] = attribute_value
cls.is_running = True
cls.inited = True | [
"def",
"_initialize_aws_identity_document",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"inited",
":",
"return",
"content",
"=",
"get_request",
"(",
"_AWS_INSTANCE_IDENTITY_DOCUMENT_URI",
")",
"if",
"content",
"is",
"not",
"None",
":",
"content",
"=",
"json",
".",
... | This method, tries to establish an HTTP connection to AWS instance
identity document url. If the application is running on an EC2
instance, we should be able to get back a valid JSON document. Make a
http get request call and store data in local map.
This method should only be called once. | [
"This",
"method",
"tries",
"to",
"establish",
"an",
"HTTP",
"connection",
"to",
"AWS",
"instance",
"identity",
"document",
"url",
".",
"If",
"the",
"application",
"is",
"running",
"on",
"an",
"EC2",
"instance",
"we",
"should",
"be",
"able",
"to",
"get",
"b... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/monitored_resource/aws_identity_doc_utils.py#L53-L74 | train | 221,065 |
census-instrumentation/opencensus-python | opencensus/stats/view.py | View.get_metric_descriptor | def get_metric_descriptor(self):
"""Get a MetricDescriptor for this view.
Lazily creates a MetricDescriptor for metrics conversion.
:rtype: :class:
`opencensus.metrics.export.metric_descriptor.MetricDescriptor`
:return: A converted Metric.
""" # noqa
with self._md_cache_lock:
if self._metric_descriptor is None:
self._metric_descriptor = metric_descriptor.MetricDescriptor(
self.name,
self.description,
self.measure.unit,
metric_utils.get_metric_type(self.measure,
self.aggregation),
# TODO: add label key description
[label_key.LabelKey(tk, "") for tk in self.columns])
return self._metric_descriptor | python | def get_metric_descriptor(self):
"""Get a MetricDescriptor for this view.
Lazily creates a MetricDescriptor for metrics conversion.
:rtype: :class:
`opencensus.metrics.export.metric_descriptor.MetricDescriptor`
:return: A converted Metric.
""" # noqa
with self._md_cache_lock:
if self._metric_descriptor is None:
self._metric_descriptor = metric_descriptor.MetricDescriptor(
self.name,
self.description,
self.measure.unit,
metric_utils.get_metric_type(self.measure,
self.aggregation),
# TODO: add label key description
[label_key.LabelKey(tk, "") for tk in self.columns])
return self._metric_descriptor | [
"def",
"get_metric_descriptor",
"(",
"self",
")",
":",
"# noqa",
"with",
"self",
".",
"_md_cache_lock",
":",
"if",
"self",
".",
"_metric_descriptor",
"is",
"None",
":",
"self",
".",
"_metric_descriptor",
"=",
"metric_descriptor",
".",
"MetricDescriptor",
"(",
"s... | Get a MetricDescriptor for this view.
Lazily creates a MetricDescriptor for metrics conversion.
:rtype: :class:
`opencensus.metrics.export.metric_descriptor.MetricDescriptor`
:return: A converted Metric. | [
"Get",
"a",
"MetricDescriptor",
"for",
"this",
"view",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view.py#L81-L100 | train | 221,066 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py | new_stats_exporter | def new_stats_exporter(service_name,
hostname=None,
endpoint=None,
interval=None):
"""Create a new worker thread and attach the exporter to it.
:type endpoint: str
:param endpoint: address of the opencensus service.
:type service_name: str
:param service_name: name of the service
:type host_name: str
:param host_name: name of the host (machine or host name)
:type interval: int or float
:param interval: Seconds between export calls.
"""
endpoint = utils.DEFAULT_ENDPOINT if endpoint is None else endpoint
exporter = StatsExporter(
ExportRpcHandler(_create_stub(endpoint), service_name, hostname))
transport.get_exporter_thread(stats.stats, exporter, interval)
return exporter | python | def new_stats_exporter(service_name,
hostname=None,
endpoint=None,
interval=None):
"""Create a new worker thread and attach the exporter to it.
:type endpoint: str
:param endpoint: address of the opencensus service.
:type service_name: str
:param service_name: name of the service
:type host_name: str
:param host_name: name of the host (machine or host name)
:type interval: int or float
:param interval: Seconds between export calls.
"""
endpoint = utils.DEFAULT_ENDPOINT if endpoint is None else endpoint
exporter = StatsExporter(
ExportRpcHandler(_create_stub(endpoint), service_name, hostname))
transport.get_exporter_thread(stats.stats, exporter, interval)
return exporter | [
"def",
"new_stats_exporter",
"(",
"service_name",
",",
"hostname",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"interval",
"=",
"None",
")",
":",
"endpoint",
"=",
"utils",
".",
"DEFAULT_ENDPOINT",
"if",
"endpoint",
"is",
"None",
"else",
"endpoint",
"expo... | Create a new worker thread and attach the exporter to it.
:type endpoint: str
:param endpoint: address of the opencensus service.
:type service_name: str
:param service_name: name of the service
:type host_name: str
:param host_name: name of the host (machine or host name)
:type interval: int or float
:param interval: Seconds between export calls. | [
"Create",
"a",
"new",
"worker",
"thread",
"and",
"attach",
"the",
"exporter",
"to",
"it",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py#L238-L261 | train | 221,067 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py | StatsExporter.export_metrics | def export_metrics(self, metrics):
""" Exports given metrics to target metric service.
"""
metric_protos = []
for metric in metrics:
metric_protos.append(_get_metric_proto(metric))
self._rpc_handler.send(
metrics_service_pb2.ExportMetricsServiceRequest(
metrics=metric_protos)) | python | def export_metrics(self, metrics):
""" Exports given metrics to target metric service.
"""
metric_protos = []
for metric in metrics:
metric_protos.append(_get_metric_proto(metric))
self._rpc_handler.send(
metrics_service_pb2.ExportMetricsServiceRequest(
metrics=metric_protos)) | [
"def",
"export_metrics",
"(",
"self",
",",
"metrics",
")",
":",
"metric_protos",
"=",
"[",
"]",
"for",
"metric",
"in",
"metrics",
":",
"metric_protos",
".",
"append",
"(",
"_get_metric_proto",
"(",
"metric",
")",
")",
"self",
".",
"_rpc_handler",
".",
"sen... | Exports given metrics to target metric service. | [
"Exports",
"given",
"metrics",
"to",
"target",
"metric",
"service",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py#L41-L50 | train | 221,068 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py | ExportRpcHandler.send | def send(self, request):
"""Dispatches incoming request on rpc.
Initializes rpc if necessary and dispatches incoming request. If a rpc
error is thrown, this function will attempt to recreate the stream and
retry sending given request once.
:type request: class:
`~.metrics_service_pb2.ExportMetricsServiceRequest`
:param request: incoming export request
"""
if not self._initialized:
self._initialize(request)
return
try:
self._rpc.send(request)
except grpc.RpcError as e:
logging.info('Found rpc error %s', e, exc_info=True)
# If stream has closed due to error, attempt to reopen with the
# incoming request.
self._initialize(request) | python | def send(self, request):
"""Dispatches incoming request on rpc.
Initializes rpc if necessary and dispatches incoming request. If a rpc
error is thrown, this function will attempt to recreate the stream and
retry sending given request once.
:type request: class:
`~.metrics_service_pb2.ExportMetricsServiceRequest`
:param request: incoming export request
"""
if not self._initialized:
self._initialize(request)
return
try:
self._rpc.send(request)
except grpc.RpcError as e:
logging.info('Found rpc error %s', e, exc_info=True)
# If stream has closed due to error, attempt to reopen with the
# incoming request.
self._initialize(request) | [
"def",
"send",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_initialize",
"(",
"request",
")",
"return",
"try",
":",
"self",
".",
"_rpc",
".",
"send",
"(",
"request",
")",
"except",
"grpc",
".",
... | Dispatches incoming request on rpc.
Initializes rpc if necessary and dispatches incoming request. If a rpc
error is thrown, this function will attempt to recreate the stream and
retry sending given request once.
:type request: class:
`~.metrics_service_pb2.ExportMetricsServiceRequest`
:param request: incoming export request | [
"Dispatches",
"incoming",
"request",
"on",
"rpc",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py#L189-L210 | train | 221,069 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py | ExportRpcHandler._initialize | def _initialize(self, request):
"""Initializes the exporter rpc stream."""
# Add node information on the first request dispatched on a stream.
request.node.MergeFrom(self._node)
request.resource.MergeFrom(self._resource)
self._initial_request = request
self._rpc.open()
self._initialized = True | python | def _initialize(self, request):
"""Initializes the exporter rpc stream."""
# Add node information on the first request dispatched on a stream.
request.node.MergeFrom(self._node)
request.resource.MergeFrom(self._resource)
self._initial_request = request
self._rpc.open()
self._initialized = True | [
"def",
"_initialize",
"(",
"self",
",",
"request",
")",
":",
"# Add node information on the first request dispatched on a stream.",
"request",
".",
"node",
".",
"MergeFrom",
"(",
"self",
".",
"_node",
")",
"request",
".",
"resource",
".",
"MergeFrom",
"(",
"self",
... | Initializes the exporter rpc stream. | [
"Initializes",
"the",
"exporter",
"rpc",
"stream",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/stats_exporter/__init__.py#L212-L221 | train | 221,070 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-postgresql/opencensus/ext/postgresql/trace.py | connect | def connect(*args, **kwargs):
"""Create database connection, use TraceCursor as the cursor_factory."""
kwargs['cursor_factory'] = TraceCursor
conn = pg_connect(*args, **kwargs)
return conn | python | def connect(*args, **kwargs):
"""Create database connection, use TraceCursor as the cursor_factory."""
kwargs['cursor_factory'] = TraceCursor
conn = pg_connect(*args, **kwargs)
return conn | [
"def",
"connect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'cursor_factory'",
"]",
"=",
"TraceCursor",
"conn",
"=",
"pg_connect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn"
] | Create database connection, use TraceCursor as the cursor_factory. | [
"Create",
"database",
"connection",
"use",
"TraceCursor",
"as",
"the",
"cursor_factory",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-postgresql/opencensus/ext/postgresql/trace.py#L42-L46 | train | 221,071 |
census-instrumentation/opencensus-python | opencensus/stats/measure_to_view_map.py | MeasureToViewMap.get_view | def get_view(self, view_name, timestamp):
"""get the View Data from the given View name"""
view = self._registered_views.get(view_name)
if view is None:
return None
view_data_list = self._measure_to_view_data_list_map.get(
view.measure.name)
if not view_data_list:
return None
for view_data in view_data_list:
if view_data.view.name == view_name:
break
else:
return None
return self.copy_and_finalize_view_data(view_data) | python | def get_view(self, view_name, timestamp):
"""get the View Data from the given View name"""
view = self._registered_views.get(view_name)
if view is None:
return None
view_data_list = self._measure_to_view_data_list_map.get(
view.measure.name)
if not view_data_list:
return None
for view_data in view_data_list:
if view_data.view.name == view_name:
break
else:
return None
return self.copy_and_finalize_view_data(view_data) | [
"def",
"get_view",
"(",
"self",
",",
"view_name",
",",
"timestamp",
")",
":",
"view",
"=",
"self",
".",
"_registered_views",
".",
"get",
"(",
"view_name",
")",
"if",
"view",
"is",
"None",
":",
"return",
"None",
"view_data_list",
"=",
"self",
".",
"_measu... | get the View Data from the given View name | [
"get",
"the",
"View",
"Data",
"from",
"the",
"given",
"View",
"name"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measure_to_view_map.py#L51-L69 | train | 221,072 |
census-instrumentation/opencensus-python | opencensus/stats/measure_to_view_map.py | MeasureToViewMap.register_view | def register_view(self, view, timestamp):
"""registers the view's measure name to View Datas given a view"""
if len(self.exporters) > 0:
try:
for e in self.exporters:
e.on_register_view(view)
except AttributeError:
pass
self._exported_views = None
existing_view = self._registered_views.get(view.name)
if existing_view is not None:
if existing_view == view:
# ignore the views that are already registered
return
else:
logging.warning(
"A different view with the same name is already registered"
) # pragma: NO COVER
measure = view.measure
registered_measure = self._registered_measures.get(measure.name)
if registered_measure is not None and registered_measure != measure:
logging.warning(
"A different measure with the same name is already registered")
self._registered_views[view.name] = view
if registered_measure is None:
self._registered_measures[measure.name] = measure
self._measure_to_view_data_list_map[view.measure.name].append(
view_data_module.ViewData(view=view, start_time=timestamp,
end_time=timestamp)) | python | def register_view(self, view, timestamp):
"""registers the view's measure name to View Datas given a view"""
if len(self.exporters) > 0:
try:
for e in self.exporters:
e.on_register_view(view)
except AttributeError:
pass
self._exported_views = None
existing_view = self._registered_views.get(view.name)
if existing_view is not None:
if existing_view == view:
# ignore the views that are already registered
return
else:
logging.warning(
"A different view with the same name is already registered"
) # pragma: NO COVER
measure = view.measure
registered_measure = self._registered_measures.get(measure.name)
if registered_measure is not None and registered_measure != measure:
logging.warning(
"A different measure with the same name is already registered")
self._registered_views[view.name] = view
if registered_measure is None:
self._registered_measures[measure.name] = measure
self._measure_to_view_data_list_map[view.measure.name].append(
view_data_module.ViewData(view=view, start_time=timestamp,
end_time=timestamp)) | [
"def",
"register_view",
"(",
"self",
",",
"view",
",",
"timestamp",
")",
":",
"if",
"len",
"(",
"self",
".",
"exporters",
")",
">",
"0",
":",
"try",
":",
"for",
"e",
"in",
"self",
".",
"exporters",
":",
"e",
".",
"on_register_view",
"(",
"view",
")... | registers the view's measure name to View Datas given a view | [
"registers",
"the",
"view",
"s",
"measure",
"name",
"to",
"View",
"Datas",
"given",
"a",
"view"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measure_to_view_map.py#L77-L106 | train | 221,073 |
census-instrumentation/opencensus-python | opencensus/stats/measure_to_view_map.py | MeasureToViewMap.record | def record(self, tags, measurement_map, timestamp, attachments=None):
"""records stats with a set of tags"""
assert all(vv >= 0 for vv in measurement_map.values())
for measure, value in measurement_map.items():
if measure != self._registered_measures.get(measure.name):
return
view_datas = []
for measure_name, view_data_list \
in self._measure_to_view_data_list_map.items():
if measure_name == measure.name:
view_datas.extend(view_data_list)
for view_data in view_datas:
view_data.record(
context=tags, value=value, timestamp=timestamp,
attachments=attachments)
self.export(view_datas) | python | def record(self, tags, measurement_map, timestamp, attachments=None):
"""records stats with a set of tags"""
assert all(vv >= 0 for vv in measurement_map.values())
for measure, value in measurement_map.items():
if measure != self._registered_measures.get(measure.name):
return
view_datas = []
for measure_name, view_data_list \
in self._measure_to_view_data_list_map.items():
if measure_name == measure.name:
view_datas.extend(view_data_list)
for view_data in view_datas:
view_data.record(
context=tags, value=value, timestamp=timestamp,
attachments=attachments)
self.export(view_datas) | [
"def",
"record",
"(",
"self",
",",
"tags",
",",
"measurement_map",
",",
"timestamp",
",",
"attachments",
"=",
"None",
")",
":",
"assert",
"all",
"(",
"vv",
">=",
"0",
"for",
"vv",
"in",
"measurement_map",
".",
"values",
"(",
")",
")",
"for",
"measure",... | records stats with a set of tags | [
"records",
"stats",
"with",
"a",
"set",
"of",
"tags"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measure_to_view_map.py#L108-L123 | train | 221,074 |
census-instrumentation/opencensus-python | opencensus/stats/measure_to_view_map.py | MeasureToViewMap.export | def export(self, view_datas):
"""export view datas to registered exporters"""
view_datas_copy = \
[self.copy_and_finalize_view_data(vd) for vd in view_datas]
if len(self.exporters) > 0:
for e in self.exporters:
try:
e.export(view_datas_copy)
except AttributeError:
pass | python | def export(self, view_datas):
"""export view datas to registered exporters"""
view_datas_copy = \
[self.copy_and_finalize_view_data(vd) for vd in view_datas]
if len(self.exporters) > 0:
for e in self.exporters:
try:
e.export(view_datas_copy)
except AttributeError:
pass | [
"def",
"export",
"(",
"self",
",",
"view_datas",
")",
":",
"view_datas_copy",
"=",
"[",
"self",
".",
"copy_and_finalize_view_data",
"(",
"vd",
")",
"for",
"vd",
"in",
"view_datas",
"]",
"if",
"len",
"(",
"self",
".",
"exporters",
")",
">",
"0",
":",
"f... | export view datas to registered exporters | [
"export",
"view",
"datas",
"to",
"registered",
"exporters"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measure_to_view_map.py#L126-L135 | train | 221,075 |
census-instrumentation/opencensus-python | opencensus/stats/measure_to_view_map.py | MeasureToViewMap.get_metrics | def get_metrics(self, timestamp):
"""Get a Metric for each registered view.
Convert each registered view's associated `ViewData` into a `Metric` to
be exported.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The timestamp to use for metric conversions, usually
the current time.
:rtype: Iterator[:class: `opencensus.metrics.export.metric.Metric`]
"""
for vdl in self._measure_to_view_data_list_map.values():
for vd in vdl:
metric = metric_utils.view_data_to_metric(vd, timestamp)
if metric is not None:
yield metric | python | def get_metrics(self, timestamp):
"""Get a Metric for each registered view.
Convert each registered view's associated `ViewData` into a `Metric` to
be exported.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The timestamp to use for metric conversions, usually
the current time.
:rtype: Iterator[:class: `opencensus.metrics.export.metric.Metric`]
"""
for vdl in self._measure_to_view_data_list_map.values():
for vd in vdl:
metric = metric_utils.view_data_to_metric(vd, timestamp)
if metric is not None:
yield metric | [
"def",
"get_metrics",
"(",
"self",
",",
"timestamp",
")",
":",
"for",
"vdl",
"in",
"self",
".",
"_measure_to_view_data_list_map",
".",
"values",
"(",
")",
":",
"for",
"vd",
"in",
"vdl",
":",
"metric",
"=",
"metric_utils",
".",
"view_data_to_metric",
"(",
"... | Get a Metric for each registered view.
Convert each registered view's associated `ViewData` into a `Metric` to
be exported.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The timestamp to use for metric conversions, usually
the current time.
:rtype: Iterator[:class: `opencensus.metrics.export.metric.Metric`] | [
"Get",
"a",
"Metric",
"for",
"each",
"registered",
"view",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/measure_to_view_map.py#L137-L153 | train | 221,076 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-azure/opencensus/ext/azure/trace_exporter/__init__.py | AzureExporter._transmit | def _transmit(self, envelopes):
"""
Transmit the data envelopes to the ingestion service.
Return a negative value for partial success or non-retryable failure.
Return 0 if all envelopes have been successfully ingested.
Return the next retry time in seconds for retryable failure.
This function should never throw exception.
"""
if not envelopes:
return 0
# TODO: prevent requests being tracked
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames',
)
execution_context.set_opencensus_attr(
'blacklist_hostnames',
['dc.services.visualstudio.com'],
)
try:
response = requests.post(
url=self.options.endpoint,
data=json.dumps(envelopes),
headers={
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
timeout=self.options.timeout,
)
except Exception as ex: # TODO: consider RequestException
logger.warning('Transient client side error %s.', ex)
# client side error (retryable)
return self.options.minimum_retry_interval
finally:
execution_context.set_opencensus_attr(
'blacklist_hostnames',
blacklist_hostnames,
)
text = 'N/A'
data = None
try:
text = response.text
except Exception as ex:
logger.warning('Error while reading response body %s.', ex)
else:
try:
data = json.loads(text)
except Exception:
pass
if response.status_code == 200:
logger.info('Transmission succeeded: %s.', text)
return 0
if response.status_code == 206: # Partial Content
# TODO: store the unsent data
if data:
try:
resend_envelopes = []
for error in data['errors']:
if error['statusCode'] in (
429, # Too Many Requests
500, # Internal Server Error
503, # Service Unavailable
):
resend_envelopes.append(envelopes[error['index']])
else:
logger.error(
'Data drop %s: %s %s.',
error['statusCode'],
error['message'],
envelopes[error['index']],
)
if resend_envelopes:
self.storage.put(resend_envelopes)
except Exception as ex:
logger.error(
'Error while processing %s: %s %s.',
response.status_code,
text,
ex,
)
return -response.status_code
# cannot parse response body, fallback to retry
if response.status_code in (
206, # Partial Content
429, # Too Many Requests
500, # Internal Server Error
503, # Service Unavailable
):
logger.warning(
'Transient server side error %s: %s.',
response.status_code,
text,
)
# server side error (retryable)
return self.options.minimum_retry_interval
logger.error(
'Non-retryable server side error %s: %s.',
response.status_code,
text,
)
# server side error (non-retryable)
return -response.status_code | python | def _transmit(self, envelopes):
"""
Transmit the data envelopes to the ingestion service.
Return a negative value for partial success or non-retryable failure.
Return 0 if all envelopes have been successfully ingested.
Return the next retry time in seconds for retryable failure.
This function should never throw exception.
"""
if not envelopes:
return 0
# TODO: prevent requests being tracked
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames',
)
execution_context.set_opencensus_attr(
'blacklist_hostnames',
['dc.services.visualstudio.com'],
)
try:
response = requests.post(
url=self.options.endpoint,
data=json.dumps(envelopes),
headers={
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
timeout=self.options.timeout,
)
except Exception as ex: # TODO: consider RequestException
logger.warning('Transient client side error %s.', ex)
# client side error (retryable)
return self.options.minimum_retry_interval
finally:
execution_context.set_opencensus_attr(
'blacklist_hostnames',
blacklist_hostnames,
)
text = 'N/A'
data = None
try:
text = response.text
except Exception as ex:
logger.warning('Error while reading response body %s.', ex)
else:
try:
data = json.loads(text)
except Exception:
pass
if response.status_code == 200:
logger.info('Transmission succeeded: %s.', text)
return 0
if response.status_code == 206: # Partial Content
# TODO: store the unsent data
if data:
try:
resend_envelopes = []
for error in data['errors']:
if error['statusCode'] in (
429, # Too Many Requests
500, # Internal Server Error
503, # Service Unavailable
):
resend_envelopes.append(envelopes[error['index']])
else:
logger.error(
'Data drop %s: %s %s.',
error['statusCode'],
error['message'],
envelopes[error['index']],
)
if resend_envelopes:
self.storage.put(resend_envelopes)
except Exception as ex:
logger.error(
'Error while processing %s: %s %s.',
response.status_code,
text,
ex,
)
return -response.status_code
# cannot parse response body, fallback to retry
if response.status_code in (
206, # Partial Content
429, # Too Many Requests
500, # Internal Server Error
503, # Service Unavailable
):
logger.warning(
'Transient server side error %s: %s.',
response.status_code,
text,
)
# server side error (retryable)
return self.options.minimum_retry_interval
logger.error(
'Non-retryable server side error %s: %s.',
response.status_code,
text,
)
# server side error (non-retryable)
return -response.status_code | [
"def",
"_transmit",
"(",
"self",
",",
"envelopes",
")",
":",
"if",
"not",
"envelopes",
":",
"return",
"0",
"# TODO: prevent requests being tracked",
"blacklist_hostnames",
"=",
"execution_context",
".",
"get_opencensus_attr",
"(",
"'blacklist_hostnames'",
",",
")",
"e... | Transmit the data envelopes to the ingestion service.
Return a negative value for partial success or non-retryable failure.
Return 0 if all envelopes have been successfully ingested.
Return the next retry time in seconds for retryable failure.
This function should never throw exception. | [
"Transmit",
"the",
"data",
"envelopes",
"to",
"the",
"ingestion",
"service",
".",
"Return",
"a",
"negative",
"value",
"for",
"partial",
"success",
"or",
"non",
"-",
"retryable",
"failure",
".",
"Return",
"0",
"if",
"all",
"envelopes",
"have",
"been",
"succes... | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-azure/opencensus/ext/azure/trace_exporter/__init__.py#L137-L237 | train | 221,077 |
census-instrumentation/opencensus-python | opencensus/common/monitored_resource/monitored_resource.py | get_instance | def get_instance():
"""Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:return: A `Resource` configured for the current environment.
"""
resources = []
env_resource = resource.get_from_env()
if env_resource is not None:
resources.append(env_resource)
if k8s_utils.is_k8s_environment():
resources.append(resource.Resource(
_K8S_CONTAINER, k8s_utils.get_k8s_metadata()))
if is_gce_environment():
resources.append(resource.Resource(
_GCE_INSTANCE,
gcp_metadata_config.GcpMetadataConfig().get_gce_metadata()))
elif is_aws_environment():
resources.append(resource.Resource(
_AWS_EC2_INSTANCE,
(aws_identity_doc_utils.AwsIdentityDocumentUtils()
.get_aws_metadata())))
if not resources:
return None
return resource.merge_resources(resources) | python | def get_instance():
"""Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:return: A `Resource` configured for the current environment.
"""
resources = []
env_resource = resource.get_from_env()
if env_resource is not None:
resources.append(env_resource)
if k8s_utils.is_k8s_environment():
resources.append(resource.Resource(
_K8S_CONTAINER, k8s_utils.get_k8s_metadata()))
if is_gce_environment():
resources.append(resource.Resource(
_GCE_INSTANCE,
gcp_metadata_config.GcpMetadataConfig().get_gce_metadata()))
elif is_aws_environment():
resources.append(resource.Resource(
_AWS_EC2_INSTANCE,
(aws_identity_doc_utils.AwsIdentityDocumentUtils()
.get_aws_metadata())))
if not resources:
return None
return resource.merge_resources(resources) | [
"def",
"get_instance",
"(",
")",
":",
"resources",
"=",
"[",
"]",
"env_resource",
"=",
"resource",
".",
"get_from_env",
"(",
")",
"if",
"env_resource",
"is",
"not",
"None",
":",
"resources",
".",
"append",
"(",
"env_resource",
")",
"if",
"k8s_utils",
".",
... | Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:return: A `Resource` configured for the current environment. | [
"Get",
"a",
"resource",
"based",
"on",
"the",
"application",
"environment",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/monitored_resource/monitored_resource.py#L37-L67 | train | 221,078 |
census-instrumentation/opencensus-python | nox.py | lint | def lint(session):
"""Run flake8.
Returns a failure if flake8 finds linting errors or sufficiently
serious code quality issues.
"""
session.interpreter = 'python3.6'
session.install('flake8')
# Install dev packages.
_install_dev_packages(session)
session.run(
'flake8',
'--exclude=contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/gen/',
'context/', 'contrib/', 'opencensus/', 'tests/', 'examples/') | python | def lint(session):
"""Run flake8.
Returns a failure if flake8 finds linting errors or sufficiently
serious code quality issues.
"""
session.interpreter = 'python3.6'
session.install('flake8')
# Install dev packages.
_install_dev_packages(session)
session.run(
'flake8',
'--exclude=contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/gen/',
'context/', 'contrib/', 'opencensus/', 'tests/', 'examples/') | [
"def",
"lint",
"(",
"session",
")",
":",
"session",
".",
"interpreter",
"=",
"'python3.6'",
"session",
".",
"install",
"(",
"'flake8'",
")",
"# Install dev packages.",
"_install_dev_packages",
"(",
"session",
")",
"session",
".",
"run",
"(",
"'flake8'",
",",
"... | Run flake8.
Returns a failure if flake8 finds linting errors or sufficiently
serious code quality issues. | [
"Run",
"flake8",
".",
"Returns",
"a",
"failure",
"if",
"flake8",
"finds",
"linting",
"errors",
"or",
"sufficiently",
"serious",
"code",
"quality",
"issues",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/nox.py#L111-L125 | train | 221,079 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-pymongo/opencensus/ext/pymongo/trace.py | trace_integration | def trace_integration(tracer=None):
"""Integrate with pymongo to trace it using event listener."""
log.info('Integrated module: {}'.format(MODULE_NAME))
monitoring.register(MongoCommandListener(tracer=tracer)) | python | def trace_integration(tracer=None):
"""Integrate with pymongo to trace it using event listener."""
log.info('Integrated module: {}'.format(MODULE_NAME))
monitoring.register(MongoCommandListener(tracer=tracer)) | [
"def",
"trace_integration",
"(",
"tracer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Integrated module: {}'",
".",
"format",
"(",
"MODULE_NAME",
")",
")",
"monitoring",
".",
"register",
"(",
"MongoCommandListener",
"(",
"tracer",
"=",
"tracer",
")",
... | Integrate with pymongo to trace it using event listener. | [
"Integrate",
"with",
"pymongo",
"to",
"trace",
"it",
"using",
"event",
"listener",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-pymongo/opencensus/ext/pymongo/trace.py#L30-L33 | train | 221,080 |
census-instrumentation/opencensus-python | opencensus/common/http_handler/__init__.py | get_request | def get_request(request_url, request_headers=dict()):
"""Execute http get request on given request_url with optional headers
"""
request = Request(request_url)
for key, val in request_headers.items():
request.add_header(key, val)
try:
response = urlopen(request, timeout=_REQUEST_TIMEOUT)
response_content = response.read()
except (HTTPError, URLError, socket.timeout):
response_content = None
return response_content | python | def get_request(request_url, request_headers=dict()):
"""Execute http get request on given request_url with optional headers
"""
request = Request(request_url)
for key, val in request_headers.items():
request.add_header(key, val)
try:
response = urlopen(request, timeout=_REQUEST_TIMEOUT)
response_content = response.read()
except (HTTPError, URLError, socket.timeout):
response_content = None
return response_content | [
"def",
"get_request",
"(",
"request_url",
",",
"request_headers",
"=",
"dict",
"(",
")",
")",
":",
"request",
"=",
"Request",
"(",
"request_url",
")",
"for",
"key",
",",
"val",
"in",
"request_headers",
".",
"items",
"(",
")",
":",
"request",
".",
"add_he... | Execute http get request on given request_url with optional headers | [
"Execute",
"http",
"get",
"request",
"on",
"given",
"request_url",
"with",
"optional",
"headers"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/common/http_handler/__init__.py#L30-L43 | train | 221,081 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py | trace_integration | def trace_integration(tracer=None):
"""Wrap the requests library to trace it."""
log.info('Integrated module: {}'.format(MODULE_NAME))
if tracer is not None:
# The execution_context tracer should never be None - if it has not
# been set it returns a no-op tracer. Most code in this library does
# not handle None being used in the execution context.
execution_context.set_opencensus_tracer(tracer)
# Wrap the requests functions
for func in REQUESTS_WRAP_METHODS:
requests_func = getattr(requests, func)
wrapped = wrap_requests(requests_func)
setattr(requests, requests_func.__name__, wrapped)
# Wrap Session class
wrapt.wrap_function_wrapper(
MODULE_NAME, 'Session.request', wrap_session_request) | python | def trace_integration(tracer=None):
"""Wrap the requests library to trace it."""
log.info('Integrated module: {}'.format(MODULE_NAME))
if tracer is not None:
# The execution_context tracer should never be None - if it has not
# been set it returns a no-op tracer. Most code in this library does
# not handle None being used in the execution context.
execution_context.set_opencensus_tracer(tracer)
# Wrap the requests functions
for func in REQUESTS_WRAP_METHODS:
requests_func = getattr(requests, func)
wrapped = wrap_requests(requests_func)
setattr(requests, requests_func.__name__, wrapped)
# Wrap Session class
wrapt.wrap_function_wrapper(
MODULE_NAME, 'Session.request', wrap_session_request) | [
"def",
"trace_integration",
"(",
"tracer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Integrated module: {}'",
".",
"format",
"(",
"MODULE_NAME",
")",
")",
"if",
"tracer",
"is",
"not",
"None",
":",
"# The execution_context tracer should never be None - if it ... | Wrap the requests library to trace it. | [
"Wrap",
"the",
"requests",
"library",
"to",
"trace",
"it",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py#L40-L58 | train | 221,082 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py | wrap_requests | def wrap_requests(requests_func):
"""Wrap the requests function to trace it."""
def call(url, *args, **kwargs):
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
parsed_url = urlparse(url)
if parsed_url.port is None:
dest_url = parsed_url.hostname
else:
dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return requests_func(url, *args, **kwargs)
_tracer = execution_context.get_opencensus_tracer()
_span = _tracer.start_span()
_span.name = '[requests]{}'.format(requests_func.__name__)
_span.span_kind = span_module.SpanKind.CLIENT
# Add the requests url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
result = requests_func(url, *args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status_code))
_tracer.end_span()
return result
return call | python | def wrap_requests(requests_func):
"""Wrap the requests function to trace it."""
def call(url, *args, **kwargs):
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
parsed_url = urlparse(url)
if parsed_url.port is None:
dest_url = parsed_url.hostname
else:
dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return requests_func(url, *args, **kwargs)
_tracer = execution_context.get_opencensus_tracer()
_span = _tracer.start_span()
_span.name = '[requests]{}'.format(requests_func.__name__)
_span.span_kind = span_module.SpanKind.CLIENT
# Add the requests url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
result = requests_func(url, *args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status_code))
_tracer.end_span()
return result
return call | [
"def",
"wrap_requests",
"(",
"requests_func",
")",
":",
"def",
"call",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"blacklist_hostnames",
"=",
"execution_context",
".",
"get_opencensus_attr",
"(",
"'blacklist_hostnames'",
")",
"parsed_url",
... | Wrap the requests function to trace it. | [
"Wrap",
"the",
"requests",
"function",
"to",
"trace",
"it",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py#L61-L91 | train | 221,083 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py | wrap_session_request | def wrap_session_request(wrapped, instance, args, kwargs):
"""Wrap the session function to trace it."""
method = kwargs.get('method') or args[0]
url = kwargs.get('url') or args[1]
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
parsed_url = urlparse(url)
if parsed_url.port is None:
dest_url = parsed_url.hostname
else:
dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return wrapped(*args, **kwargs)
_tracer = execution_context.get_opencensus_tracer()
_span = _tracer.start_span()
_span.name = '[requests]{}'.format(method)
_span.span_kind = span_module.SpanKind.CLIENT
try:
tracer_headers = _tracer.propagator.to_headers(
_tracer.span_context)
kwargs.setdefault('headers', {}).update(
tracer_headers)
except Exception: # pragma: NO COVER
pass
# Add the requests url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
result = wrapped(*args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status_code))
_tracer.end_span()
return result | python | def wrap_session_request(wrapped, instance, args, kwargs):
"""Wrap the session function to trace it."""
method = kwargs.get('method') or args[0]
url = kwargs.get('url') or args[1]
blacklist_hostnames = execution_context.get_opencensus_attr(
'blacklist_hostnames')
parsed_url = urlparse(url)
if parsed_url.port is None:
dest_url = parsed_url.hostname
else:
dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
return wrapped(*args, **kwargs)
_tracer = execution_context.get_opencensus_tracer()
_span = _tracer.start_span()
_span.name = '[requests]{}'.format(method)
_span.span_kind = span_module.SpanKind.CLIENT
try:
tracer_headers = _tracer.propagator.to_headers(
_tracer.span_context)
kwargs.setdefault('headers', {}).update(
tracer_headers)
except Exception: # pragma: NO COVER
pass
# Add the requests url to attributes
_tracer.add_attribute_to_current_span(HTTP_URL, url)
result = wrapped(*args, **kwargs)
# Add the status code to attributes
_tracer.add_attribute_to_current_span(
HTTP_STATUS_CODE, str(result.status_code))
_tracer.end_span()
return result | [
"def",
"wrap_session_request",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"method",
"=",
"kwargs",
".",
"get",
"(",
"'method'",
")",
"or",
"args",
"[",
"0",
"]",
"url",
"=",
"kwargs",
".",
"get",
"(",
"'url'",
")",
"or",
... | Wrap the session function to trace it. | [
"Wrap",
"the",
"session",
"function",
"to",
"trace",
"it",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-requests/opencensus/ext/requests/trace.py#L94-L133 | train | 221,084 |
census-instrumentation/opencensus-python | opencensus/stats/metric_utils.py | get_metric_type | def get_metric_type(measure, aggregation):
"""Get the corresponding metric type for the given stats type.
:type measure: (:class: '~opencensus.stats.measure.BaseMeasure')
:param measure: the measure for which to find a metric type
:type aggregation: (:class:
'~opencensus.stats.aggregation.BaseAggregation')
:param aggregation: the aggregation for which to find a metric type
"""
if aggregation.aggregation_type == aggregation_module.Type.NONE:
raise ValueError("aggregation type must not be NONE")
assert isinstance(aggregation,
AGGREGATION_TYPE_MAP[aggregation.aggregation_type])
if aggregation.aggregation_type == aggregation_module.Type.SUM:
if isinstance(measure, measure_module.MeasureInt):
return metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64
elif isinstance(measure, measure_module.MeasureFloat):
return metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE
else:
raise ValueError
elif aggregation.aggregation_type == aggregation_module.Type.COUNT:
return metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64
elif aggregation.aggregation_type == aggregation_module.Type.DISTRIBUTION:
return metric_descriptor.MetricDescriptorType.CUMULATIVE_DISTRIBUTION
elif aggregation.aggregation_type == aggregation_module.Type.LASTVALUE:
if isinstance(measure, measure_module.MeasureInt):
return metric_descriptor.MetricDescriptorType.GAUGE_INT64
elif isinstance(measure, measure_module.MeasureFloat):
return metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE
else:
raise ValueError
else:
raise AssertionError | python | def get_metric_type(measure, aggregation):
"""Get the corresponding metric type for the given stats type.
:type measure: (:class: '~opencensus.stats.measure.BaseMeasure')
:param measure: the measure for which to find a metric type
:type aggregation: (:class:
'~opencensus.stats.aggregation.BaseAggregation')
:param aggregation: the aggregation for which to find a metric type
"""
if aggregation.aggregation_type == aggregation_module.Type.NONE:
raise ValueError("aggregation type must not be NONE")
assert isinstance(aggregation,
AGGREGATION_TYPE_MAP[aggregation.aggregation_type])
if aggregation.aggregation_type == aggregation_module.Type.SUM:
if isinstance(measure, measure_module.MeasureInt):
return metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64
elif isinstance(measure, measure_module.MeasureFloat):
return metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE
else:
raise ValueError
elif aggregation.aggregation_type == aggregation_module.Type.COUNT:
return metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64
elif aggregation.aggregation_type == aggregation_module.Type.DISTRIBUTION:
return metric_descriptor.MetricDescriptorType.CUMULATIVE_DISTRIBUTION
elif aggregation.aggregation_type == aggregation_module.Type.LASTVALUE:
if isinstance(measure, measure_module.MeasureInt):
return metric_descriptor.MetricDescriptorType.GAUGE_INT64
elif isinstance(measure, measure_module.MeasureFloat):
return metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE
else:
raise ValueError
else:
raise AssertionError | [
"def",
"get_metric_type",
"(",
"measure",
",",
"aggregation",
")",
":",
"if",
"aggregation",
".",
"aggregation_type",
"==",
"aggregation_module",
".",
"Type",
".",
"NONE",
":",
"raise",
"ValueError",
"(",
"\"aggregation type must not be NONE\"",
")",
"assert",
"isin... | Get the corresponding metric type for the given stats type.
:type measure: (:class: '~opencensus.stats.measure.BaseMeasure')
:param measure: the measure for which to find a metric type
:type aggregation: (:class:
'~opencensus.stats.aggregation.BaseAggregation')
:param aggregation: the aggregation for which to find a metric type | [
"Get",
"the",
"corresponding",
"metric",
"type",
"for",
"the",
"given",
"stats",
"type",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/metric_utils.py#L38-L72 | train | 221,085 |
census-instrumentation/opencensus-python | opencensus/stats/metric_utils.py | is_gauge | def is_gauge(md_type):
"""Whether a given MetricDescriptorType value is a gauge.
:type md_type: int
:param md_type: A MetricDescriptorType enum value.
"""
if md_type not in metric_descriptor.MetricDescriptorType:
raise ValueError # pragma: NO COVER
return md_type in {
metric_descriptor.MetricDescriptorType.GAUGE_INT64,
metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE,
metric_descriptor.MetricDescriptorType.GAUGE_DISTRIBUTION
} | python | def is_gauge(md_type):
"""Whether a given MetricDescriptorType value is a gauge.
:type md_type: int
:param md_type: A MetricDescriptorType enum value.
"""
if md_type not in metric_descriptor.MetricDescriptorType:
raise ValueError # pragma: NO COVER
return md_type in {
metric_descriptor.MetricDescriptorType.GAUGE_INT64,
metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE,
metric_descriptor.MetricDescriptorType.GAUGE_DISTRIBUTION
} | [
"def",
"is_gauge",
"(",
"md_type",
")",
":",
"if",
"md_type",
"not",
"in",
"metric_descriptor",
".",
"MetricDescriptorType",
":",
"raise",
"ValueError",
"# pragma: NO COVER",
"return",
"md_type",
"in",
"{",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"GAU... | Whether a given MetricDescriptorType value is a gauge.
:type md_type: int
:param md_type: A MetricDescriptorType enum value. | [
"Whether",
"a",
"given",
"MetricDescriptorType",
"value",
"is",
"a",
"gauge",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/metric_utils.py#L75-L88 | train | 221,086 |
census-instrumentation/opencensus-python | opencensus/stats/metric_utils.py | view_data_to_metric | def view_data_to_metric(view_data, timestamp):
"""Convert a ViewData to a Metric at time `timestamp`.
:type view_data: :class: `opencensus.stats.view_data.ViewData`
:param view_data: The ViewData to convert.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to set on the metric's point's aggregation,
usually the current time.
:rtype: :class: `opencensus.metrics.export.metric.Metric`
:return: A converted Metric.
"""
if not view_data.tag_value_aggregation_data_map:
return None
md = view_data.view.get_metric_descriptor()
# TODO: implement gauges
if is_gauge(md.type):
ts_start = None # pragma: NO COVER
else:
ts_start = view_data.start_time
ts_list = []
for tag_vals, agg_data in view_data.tag_value_aggregation_data_map.items():
label_values = get_label_values(tag_vals)
point = agg_data.to_point(timestamp)
ts_list.append(time_series.TimeSeries(label_values, [point], ts_start))
return metric.Metric(md, ts_list) | python | def view_data_to_metric(view_data, timestamp):
"""Convert a ViewData to a Metric at time `timestamp`.
:type view_data: :class: `opencensus.stats.view_data.ViewData`
:param view_data: The ViewData to convert.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to set on the metric's point's aggregation,
usually the current time.
:rtype: :class: `opencensus.metrics.export.metric.Metric`
:return: A converted Metric.
"""
if not view_data.tag_value_aggregation_data_map:
return None
md = view_data.view.get_metric_descriptor()
# TODO: implement gauges
if is_gauge(md.type):
ts_start = None # pragma: NO COVER
else:
ts_start = view_data.start_time
ts_list = []
for tag_vals, agg_data in view_data.tag_value_aggregation_data_map.items():
label_values = get_label_values(tag_vals)
point = agg_data.to_point(timestamp)
ts_list.append(time_series.TimeSeries(label_values, [point], ts_start))
return metric.Metric(md, ts_list) | [
"def",
"view_data_to_metric",
"(",
"view_data",
",",
"timestamp",
")",
":",
"if",
"not",
"view_data",
".",
"tag_value_aggregation_data_map",
":",
"return",
"None",
"md",
"=",
"view_data",
".",
"view",
".",
"get_metric_descriptor",
"(",
")",
"# TODO: implement gauges... | Convert a ViewData to a Metric at time `timestamp`.
:type view_data: :class: `opencensus.stats.view_data.ViewData`
:param view_data: The ViewData to convert.
:type timestamp: :class: `datetime.datetime`
:param timestamp: The time to set on the metric's point's aggregation,
usually the current time.
:rtype: :class: `opencensus.metrics.export.metric.Metric`
:return: A converted Metric. | [
"Convert",
"a",
"ViewData",
"to",
"a",
"Metric",
"at",
"time",
"timestamp",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/metric_utils.py#L103-L132 | train | 221,087 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-django/opencensus/ext/django/middleware.py | _set_django_attributes | def _set_django_attributes(span, request):
"""Set the django related attributes."""
django_user = getattr(request, 'user', None)
if django_user is None:
return
user_id = django_user.pk
try:
user_name = django_user.get_username()
except AttributeError:
# AnonymousUser in some older versions of Django doesn't implement
# get_username
return
# User id is the django autofield for User model as the primary key
if user_id is not None:
span.add_attribute('django.user.id', str(user_id))
if user_name is not None:
span.add_attribute('django.user.name', str(user_name)) | python | def _set_django_attributes(span, request):
"""Set the django related attributes."""
django_user = getattr(request, 'user', None)
if django_user is None:
return
user_id = django_user.pk
try:
user_name = django_user.get_username()
except AttributeError:
# AnonymousUser in some older versions of Django doesn't implement
# get_username
return
# User id is the django autofield for User model as the primary key
if user_id is not None:
span.add_attribute('django.user.id', str(user_id))
if user_name is not None:
span.add_attribute('django.user.name', str(user_name)) | [
"def",
"_set_django_attributes",
"(",
"span",
",",
"request",
")",
":",
"django_user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"django_user",
"is",
"None",
":",
"return",
"user_id",
"=",
"django_user",
".",
"pk",
"try",
":",
... | Set the django related attributes. | [
"Set",
"the",
"django",
"related",
"attributes",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-django/opencensus/ext/django/middleware.py#L85-L105 | train | 221,088 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-django/opencensus/ext/django/middleware.py | OpencensusMiddleware.process_request | def process_request(self, request):
"""Called on each request, before Django decides which view to execute.
:type request: :class:`~django.http.request.HttpRequest`
:param request: Django http request.
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(request.path, self.blacklist_paths):
return
# Add the request to thread local
execution_context.set_opencensus_attr(
REQUEST_THREAD_LOCAL_KEY,
request)
execution_context.set_opencensus_attr(
'blacklist_hostnames',
self.blacklist_hostnames)
try:
# Start tracing this request
span_context = self.propagator.from_headers(
_DjangoMetaWrapper(_get_django_request().META))
# Reload the tracer with the new span context
tracer = tracer_module.Tracer(
span_context=span_context,
sampler=self.sampler,
exporter=self.exporter,
propagator=self.propagator)
# Span name is being set at process_view
span = tracer.start_span()
span.span_kind = span_module.SpanKind.SERVER
tracer.add_attribute_to_current_span(
attribute_key=HTTP_METHOD,
attribute_value=request.method)
tracer.add_attribute_to_current_span(
attribute_key=HTTP_URL,
attribute_value=str(request.path))
# Add the span to thread local
# in some cases (exceptions, timeouts) currentspan in
# response event will be one of a child spans.
# let's keep reference to 'django' span and
# use it in response event
execution_context.set_opencensus_attr(
SPAN_THREAD_LOCAL_KEY,
span)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | python | def process_request(self, request):
"""Called on each request, before Django decides which view to execute.
:type request: :class:`~django.http.request.HttpRequest`
:param request: Django http request.
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(request.path, self.blacklist_paths):
return
# Add the request to thread local
execution_context.set_opencensus_attr(
REQUEST_THREAD_LOCAL_KEY,
request)
execution_context.set_opencensus_attr(
'blacklist_hostnames',
self.blacklist_hostnames)
try:
# Start tracing this request
span_context = self.propagator.from_headers(
_DjangoMetaWrapper(_get_django_request().META))
# Reload the tracer with the new span context
tracer = tracer_module.Tracer(
span_context=span_context,
sampler=self.sampler,
exporter=self.exporter,
propagator=self.propagator)
# Span name is being set at process_view
span = tracer.start_span()
span.span_kind = span_module.SpanKind.SERVER
tracer.add_attribute_to_current_span(
attribute_key=HTTP_METHOD,
attribute_value=request.method)
tracer.add_attribute_to_current_span(
attribute_key=HTTP_URL,
attribute_value=str(request.path))
# Add the span to thread local
# in some cases (exceptions, timeouts) currentspan in
# response event will be one of a child spans.
# let's keep reference to 'django' span and
# use it in response event
execution_context.set_opencensus_attr(
SPAN_THREAD_LOCAL_KEY,
span)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"# Do not trace if the url is blacklisted",
"if",
"utils",
".",
"disable_tracing_url",
"(",
"request",
".",
"path",
",",
"self",
".",
"blacklist_paths",
")",
":",
"return",
"# Add the request to thread l... | Called on each request, before Django decides which view to execute.
:type request: :class:`~django.http.request.HttpRequest`
:param request: Django http request. | [
"Called",
"on",
"each",
"request",
"before",
"Django",
"decides",
"which",
"view",
"to",
"execute",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-django/opencensus/ext/django/middleware.py#L135-L186 | train | 221,089 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-django/opencensus/ext/django/middleware.py | OpencensusMiddleware.process_view | def process_view(self, request, view_func, *args, **kwargs):
"""Process view is executed before the view function, here we get the
function name add set it as the span name.
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(request.path, self.blacklist_paths):
return
try:
# Get the current span and set the span name to the current
# function name of the request.
tracer = _get_current_tracer()
span = tracer.current_span()
span.name = utils.get_func_name(view_func)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | python | def process_view(self, request, view_func, *args, **kwargs):
"""Process view is executed before the view function, here we get the
function name add set it as the span name.
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(request.path, self.blacklist_paths):
return
try:
# Get the current span and set the span name to the current
# function name of the request.
tracer = _get_current_tracer()
span = tracer.current_span()
span.name = utils.get_func_name(view_func)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Do not trace if the url is blacklisted",
"if",
"utils",
".",
"disable_tracing_url",
"(",
"request",
".",
"path",
",",
"self",
".",
"... | Process view is executed before the view function, here we get the
function name add set it as the span name. | [
"Process",
"view",
"is",
"executed",
"before",
"the",
"view",
"function",
"here",
"we",
"get",
"the",
"function",
"name",
"add",
"set",
"it",
"as",
"the",
"span",
"name",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-django/opencensus/ext/django/middleware.py#L188-L204 | train | 221,090 |
census-instrumentation/opencensus-python | opencensus/trace/span.py | format_span_json | def format_span_json(span):
"""Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span.
"""
span_json = {
'displayName': utils.get_truncatable_str(span.name),
'spanId': span.span_id,
'startTime': span.start_time,
'endTime': span.end_time,
'childSpanCount': len(span._child_spans)
}
parent_span_id = None
if span.parent_span is not None:
parent_span_id = span.parent_span.span_id
if parent_span_id is not None:
span_json['parentSpanId'] = parent_span_id
if span.attributes:
span_json['attributes'] = attributes.Attributes(
span.attributes).format_attributes_json()
if span.stack_trace is not None:
span_json['stackTrace'] = span.stack_trace.format_stack_trace_json()
if span.time_events:
span_json['timeEvents'] = {
'timeEvent': [time_event.format_time_event_json()
for time_event in span.time_events]
}
if span.links:
span_json['links'] = {
'link': [
link.format_link_json() for link in span.links]
}
if span.status is not None:
span_json['status'] = span.status.format_status_json()
if span.same_process_as_parent_span is not None:
span_json['sameProcessAsParentSpan'] = \
span.same_process_as_parent_span
return span_json | python | def format_span_json(span):
"""Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span.
"""
span_json = {
'displayName': utils.get_truncatable_str(span.name),
'spanId': span.span_id,
'startTime': span.start_time,
'endTime': span.end_time,
'childSpanCount': len(span._child_spans)
}
parent_span_id = None
if span.parent_span is not None:
parent_span_id = span.parent_span.span_id
if parent_span_id is not None:
span_json['parentSpanId'] = parent_span_id
if span.attributes:
span_json['attributes'] = attributes.Attributes(
span.attributes).format_attributes_json()
if span.stack_trace is not None:
span_json['stackTrace'] = span.stack_trace.format_stack_trace_json()
if span.time_events:
span_json['timeEvents'] = {
'timeEvent': [time_event.format_time_event_json()
for time_event in span.time_events]
}
if span.links:
span_json['links'] = {
'link': [
link.format_link_json() for link in span.links]
}
if span.status is not None:
span_json['status'] = span.status.format_status_json()
if span.same_process_as_parent_span is not None:
span_json['sameProcessAsParentSpan'] = \
span.same_process_as_parent_span
return span_json | [
"def",
"format_span_json",
"(",
"span",
")",
":",
"span_json",
"=",
"{",
"'displayName'",
":",
"utils",
".",
"get_truncatable_str",
"(",
"span",
".",
"name",
")",
",",
"'spanId'",
":",
"span",
".",
"span_id",
",",
"'startTime'",
":",
"span",
".",
"start_ti... | Helper to format a Span in JSON format.
:type span: :class:`~opencensus.trace.span.Span`
:param span: A Span to be transferred to JSON format.
:rtype: dict
:returns: Formatted Span. | [
"Helper",
"to",
"format",
"a",
"Span",
"in",
"JSON",
"format",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span.py#L258-L309 | train | 221,091 |
census-instrumentation/opencensus-python | opencensus/trace/span.py | Span.add_annotation | def add_annotation(self, description, **attrs):
"""Add an annotation to span.
:type description: str
:param description: A user-supplied message describing the event.
The maximum length for the description is 256 bytes.
:type attrs: kwargs
:param attrs: keyworded arguments e.g. failed=True, name='Caching'
"""
at = attributes.Attributes(attrs)
self.add_time_event(time_event_module.TimeEvent(datetime.utcnow(),
time_event_module.Annotation(description, at))) | python | def add_annotation(self, description, **attrs):
"""Add an annotation to span.
:type description: str
:param description: A user-supplied message describing the event.
The maximum length for the description is 256 bytes.
:type attrs: kwargs
:param attrs: keyworded arguments e.g. failed=True, name='Caching'
"""
at = attributes.Attributes(attrs)
self.add_time_event(time_event_module.TimeEvent(datetime.utcnow(),
time_event_module.Annotation(description, at))) | [
"def",
"add_annotation",
"(",
"self",
",",
"description",
",",
"*",
"*",
"attrs",
")",
":",
"at",
"=",
"attributes",
".",
"Attributes",
"(",
"attrs",
")",
"self",
".",
"add_time_event",
"(",
"time_event_module",
".",
"TimeEvent",
"(",
"datetime",
".",
"utc... | Add an annotation to span.
:type description: str
:param description: A user-supplied message describing the event.
The maximum length for the description is 256 bytes.
:type attrs: kwargs
:param attrs: keyworded arguments e.g. failed=True, name='Caching' | [
"Add",
"an",
"annotation",
"to",
"span",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span.py#L188-L200 | train | 221,092 |
census-instrumentation/opencensus-python | opencensus/trace/span.py | Span.add_time_event | def add_time_event(self, time_event):
"""Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object.
"""
if isinstance(time_event, time_event_module.TimeEvent):
self.time_events.append(time_event)
else:
raise TypeError("Type Error: received {}, but requires TimeEvent.".
format(type(time_event).__name__)) | python | def add_time_event(self, time_event):
"""Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object.
"""
if isinstance(time_event, time_event_module.TimeEvent):
self.time_events.append(time_event)
else:
raise TypeError("Type Error: received {}, but requires TimeEvent.".
format(type(time_event).__name__)) | [
"def",
"add_time_event",
"(",
"self",
",",
"time_event",
")",
":",
"if",
"isinstance",
"(",
"time_event",
",",
"time_event_module",
".",
"TimeEvent",
")",
":",
"self",
".",
"time_events",
".",
"append",
"(",
"time_event",
")",
"else",
":",
"raise",
"TypeErro... | Add a TimeEvent.
:type time_event: :class: `~opencensus.trace.time_event.TimeEvent`
:param time_event: A TimeEvent object. | [
"Add",
"a",
"TimeEvent",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span.py#L202-L212 | train | 221,093 |
census-instrumentation/opencensus-python | opencensus/trace/span.py | Span.add_link | def add_link(self, link):
"""Add a Link.
:type link: :class: `~opencensus.trace.link.Link`
:param link: A Link object.
"""
if isinstance(link, link_module.Link):
self.links.append(link)
else:
raise TypeError("Type Error: received {}, but requires Link.".
format(type(link).__name__)) | python | def add_link(self, link):
"""Add a Link.
:type link: :class: `~opencensus.trace.link.Link`
:param link: A Link object.
"""
if isinstance(link, link_module.Link):
self.links.append(link)
else:
raise TypeError("Type Error: received {}, but requires Link.".
format(type(link).__name__)) | [
"def",
"add_link",
"(",
"self",
",",
"link",
")",
":",
"if",
"isinstance",
"(",
"link",
",",
"link_module",
".",
"Link",
")",
":",
"self",
".",
"links",
".",
"append",
"(",
"link",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Type Error: received {}, ... | Add a Link.
:type link: :class: `~opencensus.trace.link.Link`
:param link: A Link object. | [
"Add",
"a",
"Link",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span.py#L214-L224 | train | 221,094 |
census-instrumentation/opencensus-python | opencensus/metrics/export/metric.py | Metric._check_type | def _check_type(self):
"""Check that point value types match the descriptor type."""
check_type = metric_descriptor.MetricDescriptorType.to_type_class(
self.descriptor.type)
for ts in self.time_series:
if not ts.check_points_type(check_type):
raise ValueError("Invalid point value type") | python | def _check_type(self):
"""Check that point value types match the descriptor type."""
check_type = metric_descriptor.MetricDescriptorType.to_type_class(
self.descriptor.type)
for ts in self.time_series:
if not ts.check_points_type(check_type):
raise ValueError("Invalid point value type") | [
"def",
"_check_type",
"(",
"self",
")",
":",
"check_type",
"=",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"to_type_class",
"(",
"self",
".",
"descriptor",
".",
"type",
")",
"for",
"ts",
"in",
"self",
".",
"time_series",
":",
"if",
"not",
"ts",
... | Check that point value types match the descriptor type. | [
"Check",
"that",
"point",
"value",
"types",
"match",
"the",
"descriptor",
"type",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric.py#L61-L67 | train | 221,095 |
census-instrumentation/opencensus-python | opencensus/metrics/export/metric.py | Metric._check_start_timestamp | def _check_start_timestamp(self):
"""Check that starting timestamp exists for cumulative metrics."""
if self.descriptor.type in (
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DISTRIBUTION,
):
for ts in self.time_series:
if ts.start_timestamp is None:
raise ValueError("time_series.start_timestamp must exist "
"for cumulative metrics") | python | def _check_start_timestamp(self):
"""Check that starting timestamp exists for cumulative metrics."""
if self.descriptor.type in (
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DISTRIBUTION,
):
for ts in self.time_series:
if ts.start_timestamp is None:
raise ValueError("time_series.start_timestamp must exist "
"for cumulative metrics") | [
"def",
"_check_start_timestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"descriptor",
".",
"type",
"in",
"(",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_INT64",
",",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_DOUBLE",... | Check that starting timestamp exists for cumulative metrics. | [
"Check",
"that",
"starting",
"timestamp",
"exists",
"for",
"cumulative",
"metrics",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric.py#L69-L79 | train | 221,096 |
census-instrumentation/opencensus-python | opencensus/stats/bucket_boundaries.py | BucketBoundaries.is_valid_boundaries | def is_valid_boundaries(self, boundaries):
"""checks if the boundaries are in ascending order"""
if boundaries is not None:
min_ = boundaries[0]
for value in boundaries:
if value < min_:
return False
else:
min_ = value
return True
return False | python | def is_valid_boundaries(self, boundaries):
"""checks if the boundaries are in ascending order"""
if boundaries is not None:
min_ = boundaries[0]
for value in boundaries:
if value < min_:
return False
else:
min_ = value
return True
return False | [
"def",
"is_valid_boundaries",
"(",
"self",
",",
"boundaries",
")",
":",
"if",
"boundaries",
"is",
"not",
"None",
":",
"min_",
"=",
"boundaries",
"[",
"0",
"]",
"for",
"value",
"in",
"boundaries",
":",
"if",
"value",
"<",
"min_",
":",
"return",
"False",
... | checks if the boundaries are in ascending order | [
"checks",
"if",
"the",
"boundaries",
"are",
"in",
"ascending",
"order"
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/bucket_boundaries.py#L31-L41 | train | 221,097 |
census-instrumentation/opencensus-python | opencensus/metrics/transport.py | get_exporter_thread | def get_exporter_thread(metric_producer, exporter, interval=None):
"""Get a running task that periodically exports metrics.
Get a `PeriodicTask` that periodically calls:
exporter.export_metrics(metric_producer.get_metrics())
:type metric_producer:
:class:`opencensus.metrics.export.metric_producer.MetricProducer`
:param exporter: The producer to use to get metrics to export.
:type exporter: :class:`opencensus.stats.base_exporter.MetricsExporter`
:param exporter: The exporter to use to export metrics.
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`PeriodicTask`
:return: A running thread responsible calling the exporter.
"""
weak_get = utils.get_weakref(metric_producer.get_metrics)
weak_export = utils.get_weakref(exporter.export_metrics)
def export_all():
get = weak_get()
if get is None:
raise TransportError("Metric producer is not available")
export = weak_export()
if export is None:
raise TransportError("Metric exporter is not available")
export(get())
tt = MetricExporterTask(interval, export_all)
tt.start()
return tt | python | def get_exporter_thread(metric_producer, exporter, interval=None):
"""Get a running task that periodically exports metrics.
Get a `PeriodicTask` that periodically calls:
exporter.export_metrics(metric_producer.get_metrics())
:type metric_producer:
:class:`opencensus.metrics.export.metric_producer.MetricProducer`
:param exporter: The producer to use to get metrics to export.
:type exporter: :class:`opencensus.stats.base_exporter.MetricsExporter`
:param exporter: The exporter to use to export metrics.
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`PeriodicTask`
:return: A running thread responsible calling the exporter.
"""
weak_get = utils.get_weakref(metric_producer.get_metrics)
weak_export = utils.get_weakref(exporter.export_metrics)
def export_all():
get = weak_get()
if get is None:
raise TransportError("Metric producer is not available")
export = weak_export()
if export is None:
raise TransportError("Metric exporter is not available")
export(get())
tt = MetricExporterTask(interval, export_all)
tt.start()
return tt | [
"def",
"get_exporter_thread",
"(",
"metric_producer",
",",
"exporter",
",",
"interval",
"=",
"None",
")",
":",
"weak_get",
"=",
"utils",
".",
"get_weakref",
"(",
"metric_producer",
".",
"get_metrics",
")",
"weak_export",
"=",
"utils",
".",
"get_weakref",
"(",
... | Get a running task that periodically exports metrics.
Get a `PeriodicTask` that periodically calls:
exporter.export_metrics(metric_producer.get_metrics())
:type metric_producer:
:class:`opencensus.metrics.export.metric_producer.MetricProducer`
:param exporter: The producer to use to get metrics to export.
:type exporter: :class:`opencensus.stats.base_exporter.MetricsExporter`
:param exporter: The exporter to use to export metrics.
:type interval: int or float
:param interval: Seconds between export calls.
:rtype: :class:`PeriodicTask`
:return: A running thread responsible calling the exporter. | [
"Get",
"a",
"running",
"task",
"that",
"periodically",
"exports",
"metrics",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/transport.py#L67-L102 | train | 221,098 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py | FlaskMiddleware._before_request | def _before_request(self):
"""A function to be run before each request.
See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
return
try:
span_context = self.propagator.from_headers(flask.request.headers)
tracer = tracer_module.Tracer(
span_context=span_context,
sampler=self.sampler,
exporter=self.exporter,
propagator=self.propagator)
span = tracer.start_span()
span.span_kind = span_module.SpanKind.SERVER
# Set the span name as the name of the current module name
span.name = '[{}]{}'.format(
flask.request.method,
flask.request.url)
tracer.add_attribute_to_current_span(
HTTP_METHOD, flask.request.method)
tracer.add_attribute_to_current_span(
HTTP_URL, str(flask.request.url))
execution_context.set_opencensus_attr(
'blacklist_hostnames',
self.blacklist_hostnames)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | python | def _before_request(self):
"""A function to be run before each request.
See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
"""
# Do not trace if the url is blacklisted
if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
return
try:
span_context = self.propagator.from_headers(flask.request.headers)
tracer = tracer_module.Tracer(
span_context=span_context,
sampler=self.sampler,
exporter=self.exporter,
propagator=self.propagator)
span = tracer.start_span()
span.span_kind = span_module.SpanKind.SERVER
# Set the span name as the name of the current module name
span.name = '[{}]{}'.format(
flask.request.method,
flask.request.url)
tracer.add_attribute_to_current_span(
HTTP_METHOD, flask.request.method)
tracer.add_attribute_to_current_span(
HTTP_URL, str(flask.request.url))
execution_context.set_opencensus_attr(
'blacklist_hostnames',
self.blacklist_hostnames)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True) | [
"def",
"_before_request",
"(",
"self",
")",
":",
"# Do not trace if the url is blacklisted",
"if",
"utils",
".",
"disable_tracing_url",
"(",
"flask",
".",
"request",
".",
"url",
",",
"self",
".",
"blacklist_paths",
")",
":",
"return",
"try",
":",
"span_context",
... | A function to be run before each request.
See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request | [
"A",
"function",
"to",
"be",
"run",
"before",
"each",
"request",
"."
] | 992b223f7e34c5dcb65922b7d5c827e7a1351e7d | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py#L122-L154 | train | 221,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.