id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
239,900
RedHatInsights/insights-core
insights/core/__init__.py
IniConfigFile.parse_content
def parse_content(self, content, allow_no_value=False): """Parses content of the config file. In child class overload and call super to set flag ``allow_no_values`` and allow keys with no value in config file:: def parse_content(self, content): super(YourClass, self).parse_content(content, allow_no_values=True) """ super(IniConfigFile, self).parse_content(content) config = RawConfigParser(allow_no_value=allow_no_value) fp = io.StringIO(u"\n".join(content)) config.readfp(fp, filename=self.file_name) self.data = config
python
def parse_content(self, content, allow_no_value=False): super(IniConfigFile, self).parse_content(content) config = RawConfigParser(allow_no_value=allow_no_value) fp = io.StringIO(u"\n".join(content)) config.readfp(fp, filename=self.file_name) self.data = config
[ "def", "parse_content", "(", "self", ",", "content", ",", "allow_no_value", "=", "False", ")", ":", "super", "(", "IniConfigFile", ",", "self", ")", ".", "parse_content", "(", "content", ")", "config", "=", "RawConfigParser", "(", "allow_no_value", "=", "all...
Parses content of the config file. In child class overload and call super to set flag ``allow_no_values`` and allow keys with no value in config file:: def parse_content(self, content): super(YourClass, self).parse_content(content, allow_no_values=True)
[ "Parses", "content", "of", "the", "config", "file", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L1315-L1330
239,901
RedHatInsights/insights-core
insights/core/__init__.py
FileListing.path_entry
def path_entry(self, path): """ The parsed data given a path, which is separated into its directory and entry name. """ if path[0] != '/': return None path_parts = path.split('/') # Note that here the first element will be '' because it's before the # first separator. That's OK, the join puts it back together. directory = '/'.join(path_parts[:-1]) name = path_parts[-1] if directory not in self.listings: return None if name not in self.listings[directory]['entries']: return None return self.listings[directory]['entries'][name]
python
def path_entry(self, path): if path[0] != '/': return None path_parts = path.split('/') # Note that here the first element will be '' because it's before the # first separator. That's OK, the join puts it back together. directory = '/'.join(path_parts[:-1]) name = path_parts[-1] if directory not in self.listings: return None if name not in self.listings[directory]['entries']: return None return self.listings[directory]['entries'][name]
[ "def", "path_entry", "(", "self", ",", "path", ")", ":", "if", "path", "[", "0", "]", "!=", "'/'", ":", "return", "None", "path_parts", "=", "path", ".", "split", "(", "'/'", ")", "# Note that here the first element will be '' because it's before the", "# first ...
The parsed data given a path, which is separated into its directory and entry name.
[ "The", "parsed", "data", "given", "a", "path", "which", "is", "separated", "into", "its", "directory", "and", "entry", "name", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L1525-L1541
239,902
RedHatInsights/insights-core
insights/client/util.py
image_by_name
def image_by_name(img_name, images=None): """ Returns a list of image data for images which match img_name. Will optionally take a list of images from a docker.Client.images query to avoid multiple docker queries. """ i_reg, i_rep, i_tag = _decompose(img_name) # Correct for bash-style matching expressions. if not i_reg: i_reg = '*' if not i_tag: i_tag = '*' # If the images were not passed in, go get them. if images is None: c = docker.Client(**kwargs_from_env()) images = c.images(all=False) valid_images = [] for i in images: for t in i['RepoTags']: reg, rep, tag = _decompose(t) if matches(reg, i_reg) \ and matches(rep, i_rep) \ and matches(tag, i_tag): valid_images.append(i) break # Some repo after decompose end up with the img_name # at the end. i.e. rhel7/rsyslog if rep.endswith(img_name): valid_images.append(i) break return valid_images
python
def image_by_name(img_name, images=None): i_reg, i_rep, i_tag = _decompose(img_name) # Correct for bash-style matching expressions. if not i_reg: i_reg = '*' if not i_tag: i_tag = '*' # If the images were not passed in, go get them. if images is None: c = docker.Client(**kwargs_from_env()) images = c.images(all=False) valid_images = [] for i in images: for t in i['RepoTags']: reg, rep, tag = _decompose(t) if matches(reg, i_reg) \ and matches(rep, i_rep) \ and matches(tag, i_tag): valid_images.append(i) break # Some repo after decompose end up with the img_name # at the end. i.e. rhel7/rsyslog if rep.endswith(img_name): valid_images.append(i) break return valid_images
[ "def", "image_by_name", "(", "img_name", ",", "images", "=", "None", ")", ":", "i_reg", ",", "i_rep", ",", "i_tag", "=", "_decompose", "(", "img_name", ")", "# Correct for bash-style matching expressions.", "if", "not", "i_reg", ":", "i_reg", "=", "'*'", "if",...
Returns a list of image data for images which match img_name. Will optionally take a list of images from a docker.Client.images query to avoid multiple docker queries.
[ "Returns", "a", "list", "of", "image", "data", "for", "images", "which", "match", "img_name", ".", "Will", "optionally", "take", "a", "list", "of", "images", "from", "a", "docker", ".", "Client", ".", "images", "query", "to", "avoid", "multiple", "docker",...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L31-L64
239,903
RedHatInsights/insights-core
insights/client/util.py
subp
def subp(cmd): """ Run a command as a subprocess. Return a triple of return code, standard out, standard err. """ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() return ReturnTuple(proc.returncode, stdout=out, stderr=err)
python
def subp(cmd): proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() return ReturnTuple(proc.returncode, stdout=out, stderr=err)
[ "def", "subp", "(", "cmd", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "proc", ".", "communicate", "(", ")...
Run a command as a subprocess. Return a triple of return code, standard out, standard err.
[ "Run", "a", "command", "as", "a", "subprocess", ".", "Return", "a", "triple", "of", "return", "code", "standard", "out", "standard", "err", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L67-L75
239,904
RedHatInsights/insights-core
insights/client/util.py
print_scan_summary
def print_scan_summary(json_data, names=None): ''' Print a summary of the data returned from a CVE scan. ''' max_col_width = 50 min_width = 15 def _max_width(data): max_name = 0 for name in data: max_name = len(data[name]) if len(data[name]) > max_name \ else max_name # If the max name length is less that max_width if max_name < min_width: max_name = min_width # If the man name is greater than the max col leng # we wish to use if max_name > max_col_width: max_name = max_col_width return max_name clean = True if len(names) > 0: max_width = _max_width(names) else: max_width = min_width template = "{0:" + str(max_width) + "} {1:5} {2:5} {3:5} {4:5}" sevs = ['critical', 'important', 'moderate', 'low'] writeOut(template.format("Container/Image", "Cri", "Imp", "Med", "Low")) writeOut(template.format("-" * max_width, "---", "---", "---", "---")) res_summary = json_data['results_summary'] for image in res_summary.keys(): image_res = res_summary[image] if 'msg' in image_res.keys(): tmp_tuple = (image_res['msg'], "", "", "", "") else: if len(names) < 1: image_name = image[:max_width] else: image_name = names[image][-max_width:] if len(image_name) == max_col_width: image_name = '...' + image_name[-(len(image_name) - 3):] tmp_tuple = tuple([image_name] + [str(image_res[sev]) for sev in sevs]) sev_results = [image_res[sev] for sev in sevs if image_res[sev] > 0] if len(sev_results) > 0: clean = False writeOut(template.format(*tmp_tuple)) writeOut("") return clean
python
def print_scan_summary(json_data, names=None): ''' Print a summary of the data returned from a CVE scan. ''' max_col_width = 50 min_width = 15 def _max_width(data): max_name = 0 for name in data: max_name = len(data[name]) if len(data[name]) > max_name \ else max_name # If the max name length is less that max_width if max_name < min_width: max_name = min_width # If the man name is greater than the max col leng # we wish to use if max_name > max_col_width: max_name = max_col_width return max_name clean = True if len(names) > 0: max_width = _max_width(names) else: max_width = min_width template = "{0:" + str(max_width) + "} {1:5} {2:5} {3:5} {4:5}" sevs = ['critical', 'important', 'moderate', 'low'] writeOut(template.format("Container/Image", "Cri", "Imp", "Med", "Low")) writeOut(template.format("-" * max_width, "---", "---", "---", "---")) res_summary = json_data['results_summary'] for image in res_summary.keys(): image_res = res_summary[image] if 'msg' in image_res.keys(): tmp_tuple = (image_res['msg'], "", "", "", "") else: if len(names) < 1: image_name = image[:max_width] else: image_name = names[image][-max_width:] if len(image_name) == max_col_width: image_name = '...' + image_name[-(len(image_name) - 3):] tmp_tuple = tuple([image_name] + [str(image_res[sev]) for sev in sevs]) sev_results = [image_res[sev] for sev in sevs if image_res[sev] > 0] if len(sev_results) > 0: clean = False writeOut(template.format(*tmp_tuple)) writeOut("") return clean
[ "def", "print_scan_summary", "(", "json_data", ",", "names", "=", "None", ")", ":", "max_col_width", "=", "50", "min_width", "=", "15", "def", "_max_width", "(", "data", ")", ":", "max_name", "=", "0", "for", "name", "in", "data", ":", "max_name", "=", ...
Print a summary of the data returned from a CVE scan.
[ "Print", "a", "summary", "of", "the", "data", "returned", "from", "a", "CVE", "scan", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L98-L153
239,905
RedHatInsights/insights-core
insights/client/util.py
print_detail_scan_summary
def print_detail_scan_summary(json_data, names=None): ''' Print a detailed summary of the data returned from a CVE scan. ''' clean = True sevs = ['Critical', 'Important', 'Moderate', 'Low'] cve_summary = json_data['host_results'] image_template = " {0:10}: {1}" cve_template = " {0:10}: {1}" for image in cve_summary.keys(): image_res = cve_summary[image] writeOut("") writeOut(image[:12]) if not image_res['isRHEL']: writeOut(image_template.format("Result", "Not based on Red Hat" "Enterprise Linux")) continue else: writeOut(image_template.format("OS", image_res['os'].rstrip())) scan_results = image_res['cve_summary']['scan_results'] for sev in sevs: if sev in scan_results: clean = False writeOut(image_template.format(sev, str(scan_results[sev]['num']))) for cve in scan_results[sev]['cves']: writeOut(cve_template.format("CVE", cve['cve_title'])) writeOut(cve_template.format("CVE URL", cve['cve_ref_url'])) writeOut(cve_template.format("RHSA ID", cve['rhsa_ref_id'])) writeOut(cve_template.format("RHSA URL", cve['rhsa_ref_url'])) writeOut("") return clean
python
def print_detail_scan_summary(json_data, names=None): ''' Print a detailed summary of the data returned from a CVE scan. ''' clean = True sevs = ['Critical', 'Important', 'Moderate', 'Low'] cve_summary = json_data['host_results'] image_template = " {0:10}: {1}" cve_template = " {0:10}: {1}" for image in cve_summary.keys(): image_res = cve_summary[image] writeOut("") writeOut(image[:12]) if not image_res['isRHEL']: writeOut(image_template.format("Result", "Not based on Red Hat" "Enterprise Linux")) continue else: writeOut(image_template.format("OS", image_res['os'].rstrip())) scan_results = image_res['cve_summary']['scan_results'] for sev in sevs: if sev in scan_results: clean = False writeOut(image_template.format(sev, str(scan_results[sev]['num']))) for cve in scan_results[sev]['cves']: writeOut(cve_template.format("CVE", cve['cve_title'])) writeOut(cve_template.format("CVE URL", cve['cve_ref_url'])) writeOut(cve_template.format("RHSA ID", cve['rhsa_ref_id'])) writeOut(cve_template.format("RHSA URL", cve['rhsa_ref_url'])) writeOut("") return clean
[ "def", "print_detail_scan_summary", "(", "json_data", ",", "names", "=", "None", ")", ":", "clean", "=", "True", "sevs", "=", "[", "'Critical'", ",", "'Important'", ",", "'Moderate'", ",", "'Low'", "]", "cve_summary", "=", "json_data", "[", "'host_results'", ...
Print a detailed summary of the data returned from a CVE scan.
[ "Print", "a", "detailed", "summary", "of", "the", "data", "returned", "from", "a", "CVE", "scan", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L156-L193
239,906
RedHatInsights/insights-core
insights/util/subproc.py
call
def call(cmd, timeout=None, signum=signal.SIGKILL, keep_rc=False, encoding="utf-8", env=os.environ): """ Execute a cmd or list of commands with an optional timeout in seconds. If `timeout` is supplied and expires, the process is killed with SIGKILL (kill -9) and an exception is raised. Otherwise, the command output is returned. Parameters ---------- cmd: str or [[str]] The command(s) to execute timeout: int Seconds before kill is issued to the process signum: int The signal number to issue to the process on timeout keep_rc: bool Whether to return the exit code along with the output encoding: str unicode decoding scheme to use. Default is "utf-8" env: dict The environment in which to execute commands. Default is os.environ Returns ------- str Content of stdout of cmd on success. Raises ------ CalledProcessError Raised when cmd fails """ if not isinstance(cmd, list): cmd = [cmd] p = Pipeline(*cmd, timeout=timeout, signum=signum, env=env) res = p(keep_rc=keep_rc) if keep_rc: rc, output = res output = output.decode(encoding, 'ignore') return rc, output return res.decode(encoding, "ignore")
python
def call(cmd, timeout=None, signum=signal.SIGKILL, keep_rc=False, encoding="utf-8", env=os.environ): if not isinstance(cmd, list): cmd = [cmd] p = Pipeline(*cmd, timeout=timeout, signum=signum, env=env) res = p(keep_rc=keep_rc) if keep_rc: rc, output = res output = output.decode(encoding, 'ignore') return rc, output return res.decode(encoding, "ignore")
[ "def", "call", "(", "cmd", ",", "timeout", "=", "None", ",", "signum", "=", "signal", ".", "SIGKILL", ",", "keep_rc", "=", "False", ",", "encoding", "=", "\"utf-8\"", ",", "env", "=", "os", ".", "environ", ")", ":", "if", "not", "isinstance", "(", ...
Execute a cmd or list of commands with an optional timeout in seconds. If `timeout` is supplied and expires, the process is killed with SIGKILL (kill -9) and an exception is raised. Otherwise, the command output is returned. Parameters ---------- cmd: str or [[str]] The command(s) to execute timeout: int Seconds before kill is issued to the process signum: int The signal number to issue to the process on timeout keep_rc: bool Whether to return the exit code along with the output encoding: str unicode decoding scheme to use. Default is "utf-8" env: dict The environment in which to execute commands. Default is os.environ Returns ------- str Content of stdout of cmd on success. Raises ------ CalledProcessError Raised when cmd fails
[ "Execute", "a", "cmd", "or", "list", "of", "commands", "with", "an", "optional", "timeout", "in", "seconds", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/subproc.py#L165-L214
239,907
RedHatInsights/insights-core
insights/util/subproc.py
Pipeline.write
def write(self, output, mode="w", keep_rc=False): """ Executes the pipeline and writes the results to the supplied output. If output is a filename and the file didn't already exist before trying to write, the file will be removed if an exception is raised. Args: output (str or file like object): will create a new file of this name or overwrite an existing file. If output is already a file like object, it is used. mode (str): mode to use when creating or opening the provided file name if it is a string. Ignored if output is a file like object. Returns: The final output of the pipeline. Raises: CalledProcessError if any return code in the pipeline is nonzero. """ if isinstance(output, six.string_types): already_exists = os.path.exists(output) try: with open(output, mode) as f: p = self._build_pipes(f) rc = p.wait() if keep_rc: return rc if rc: raise CalledProcessError(rc, self.cmds[0], "") except BaseException as be: if not already_exists and os.path.exists(output): os.remove(output) six.reraise(be.__class__, be, sys.exc_info()[2]) else: p = self._build_pipes(output) rc = p.wait() if keep_rc: return rc if rc: raise CalledProcessError(rc, self.cmds[0], "")
python
def write(self, output, mode="w", keep_rc=False): if isinstance(output, six.string_types): already_exists = os.path.exists(output) try: with open(output, mode) as f: p = self._build_pipes(f) rc = p.wait() if keep_rc: return rc if rc: raise CalledProcessError(rc, self.cmds[0], "") except BaseException as be: if not already_exists and os.path.exists(output): os.remove(output) six.reraise(be.__class__, be, sys.exc_info()[2]) else: p = self._build_pipes(output) rc = p.wait() if keep_rc: return rc if rc: raise CalledProcessError(rc, self.cmds[0], "")
[ "def", "write", "(", "self", ",", "output", ",", "mode", "=", "\"w\"", ",", "keep_rc", "=", "False", ")", ":", "if", "isinstance", "(", "output", ",", "six", ".", "string_types", ")", ":", "already_exists", "=", "os", ".", "path", ".", "exists", "(",...
Executes the pipeline and writes the results to the supplied output. If output is a filename and the file didn't already exist before trying to write, the file will be removed if an exception is raised. Args: output (str or file like object): will create a new file of this name or overwrite an existing file. If output is already a file like object, it is used. mode (str): mode to use when creating or opening the provided file name if it is a string. Ignored if output is a file like object. Returns: The final output of the pipeline. Raises: CalledProcessError if any return code in the pipeline is nonzero.
[ "Executes", "the", "pipeline", "and", "writes", "the", "results", "to", "the", "supplied", "output", ".", "If", "output", "is", "a", "filename", "and", "the", "file", "didn", "t", "already", "exist", "before", "trying", "to", "write", "the", "file", "will"...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/subproc.py#L124-L162
239,908
RedHatInsights/insights-core
insights/core/plugins.py
Response.validate_kwargs
def validate_kwargs(self, kwargs): """ Validates expected subclass attributes and constructor keyword arguments. """ if not self.response_type: msg = "response_type must be set on the Response subclass." raise ValidationException(msg) if (self.key_name and self.key_name in kwargs) or "type" in kwargs: name = self.__class__.__name__ msg = "%s is an invalid argument for %s" % (self.key_name, name) raise ValidationException(msg)
python
def validate_kwargs(self, kwargs): if not self.response_type: msg = "response_type must be set on the Response subclass." raise ValidationException(msg) if (self.key_name and self.key_name in kwargs) or "type" in kwargs: name = self.__class__.__name__ msg = "%s is an invalid argument for %s" % (self.key_name, name) raise ValidationException(msg)
[ "def", "validate_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "not", "self", ".", "response_type", ":", "msg", "=", "\"response_type must be set on the Response subclass.\"", "raise", "ValidationException", "(", "msg", ")", "if", "(", "self", ".", "key_nam...
Validates expected subclass attributes and constructor keyword arguments.
[ "Validates", "expected", "subclass", "attributes", "and", "constructor", "keyword", "arguments", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L390-L402
239,909
RedHatInsights/insights-core
insights/core/plugins.py
Response.validate_key
def validate_key(self, key): """ Called if the key_name class attribute is not None. """ if not key: name = self.__class__.__name__ msg = "%s response missing %s" % (name, self.key_name) raise ValidationException(msg, self) elif not isinstance(key, str): msg = "Response contains invalid %s type" % self.key_name raise ValidationException(msg, type(key))
python
def validate_key(self, key): if not key: name = self.__class__.__name__ msg = "%s response missing %s" % (name, self.key_name) raise ValidationException(msg, self) elif not isinstance(key, str): msg = "Response contains invalid %s type" % self.key_name raise ValidationException(msg, type(key))
[ "def", "validate_key", "(", "self", ",", "key", ")", ":", "if", "not", "key", ":", "name", "=", "self", ".", "__class__", ".", "__name__", "msg", "=", "\"%s response missing %s\"", "%", "(", "name", ",", "self", ".", "key_name", ")", "raise", "Validation...
Called if the key_name class attribute is not None.
[ "Called", "if", "the", "key_name", "class", "attribute", "is", "not", "None", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L404-L412
239,910
RedHatInsights/insights-core
insights/core/plugins.py
Response.adjust_for_length
def adjust_for_length(self, key, r, kwargs): """ Converts the response to a string and compares its length to a max length specified in settings. If the response is too long, an error is logged, and an abbreviated response is returned instead. """ length = len(str(kwargs)) if length > settings.defaults["max_detail_length"]: self._log_length_error(key, length) r["max_detail_length_error"] = length return r return kwargs
python
def adjust_for_length(self, key, r, kwargs): length = len(str(kwargs)) if length > settings.defaults["max_detail_length"]: self._log_length_error(key, length) r["max_detail_length_error"] = length return r return kwargs
[ "def", "adjust_for_length", "(", "self", ",", "key", ",", "r", ",", "kwargs", ")", ":", "length", "=", "len", "(", "str", "(", "kwargs", ")", ")", "if", "length", ">", "settings", ".", "defaults", "[", "\"max_detail_length\"", "]", ":", "self", ".", ...
Converts the response to a string and compares its length to a max length specified in settings. If the response is too long, an error is logged, and an abbreviated response is returned instead.
[ "Converts", "the", "response", "to", "a", "string", "and", "compares", "its", "length", "to", "a", "max", "length", "specified", "in", "settings", ".", "If", "the", "response", "is", "too", "long", "an", "error", "is", "logged", "and", "an", "abbreviated",...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L414-L425
239,911
RedHatInsights/insights-core
insights/core/plugins.py
Response._log_length_error
def _log_length_error(self, key, length): """ Helper function for logging a response length error. """ extra = { "max_detail_length": settings.defaults["max_detail_length"], "len": length } if self.key_name: extra[self.key_name] = key msg = "Length of data in %s is too long." % self.__class__.__name__ log.error(msg, extra=extra)
python
def _log_length_error(self, key, length): extra = { "max_detail_length": settings.defaults["max_detail_length"], "len": length } if self.key_name: extra[self.key_name] = key msg = "Length of data in %s is too long." % self.__class__.__name__ log.error(msg, extra=extra)
[ "def", "_log_length_error", "(", "self", ",", "key", ",", "length", ")", ":", "extra", "=", "{", "\"max_detail_length\"", ":", "settings", ".", "defaults", "[", "\"max_detail_length\"", "]", ",", "\"len\"", ":", "length", "}", "if", "self", ".", "key_name", ...
Helper function for logging a response length error.
[ "Helper", "function", "for", "logging", "a", "response", "length", "error", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L427-L436
239,912
RedHatInsights/insights-core
insights/parsers/oracle.py
_parse_oracle
def _parse_oracle(lines): """ Performs the actual file parsing, returning a dict of the config values in a given Oracle DB config file. Despite their differences, the two filetypes are similar enough to allow idential parsing. """ config = {} for line in get_active_lines(lines): # Check for NULL in line to begin control char removal if '\00' in line: line = cleanup.sub('', line) if '=' in line: (key, value) = line.split('=', 1) key = key.strip(whitespace + '"\'').lower() if ',' in line: value = [s.strip(whitespace + '"\'').lower() for s in value.split(',')] else: value = value.strip(whitespace + '"\'').lower() config[key] = value return config
python
def _parse_oracle(lines): config = {} for line in get_active_lines(lines): # Check for NULL in line to begin control char removal if '\00' in line: line = cleanup.sub('', line) if '=' in line: (key, value) = line.split('=', 1) key = key.strip(whitespace + '"\'').lower() if ',' in line: value = [s.strip(whitespace + '"\'').lower() for s in value.split(',')] else: value = value.strip(whitespace + '"\'').lower() config[key] = value return config
[ "def", "_parse_oracle", "(", "lines", ")", ":", "config", "=", "{", "}", "for", "line", "in", "get_active_lines", "(", "lines", ")", ":", "# Check for NULL in line to begin control char removal", "if", "'\\00'", "in", "line", ":", "line", "=", "cleanup", ".", ...
Performs the actual file parsing, returning a dict of the config values in a given Oracle DB config file. Despite their differences, the two filetypes are similar enough to allow idential parsing.
[ "Performs", "the", "actual", "file", "parsing", "returning", "a", "dict", "of", "the", "config", "values", "in", "a", "given", "Oracle", "DB", "config", "file", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/oracle.py#L18-L41
239,913
RedHatInsights/insights-core
insights/parsers/mdstat.py
apply_upstring
def apply_upstring(upstring, component_list): """Update the dictionaries resulting from ``parse_array_start`` with the "up" key based on the upstring returned from ``parse_upstring``. The function assumes that the upstring and component_list parameters passed in are from the same device array stanza of a ``/proc/mdstat`` file. The function modifies component_list in place, adding or updating the value of the "up" key to True if there is a corresponding ``U`` in the upstring string, or to False if there is a corresponding ``_``. If there the number of rows in component_list does not match the number of characters in upstring, an ``AssertionError`` is raised. Parameters ---------- upstring : str String sequence of ``U``s and ``_``s as determined by the ``parse_upstring`` method component_list : list List of dictionaries output from the ``parse_array_start`` method. """ assert len(upstring) == len(component_list) def add_up_key(comp_dict, up_indicator): assert up_indicator == 'U' or up_indicator == "_" comp_dict['up'] = up_indicator == 'U' for comp_dict, up_indicator in zip(component_list, upstring): add_up_key(comp_dict, up_indicator)
python
def apply_upstring(upstring, component_list): assert len(upstring) == len(component_list) def add_up_key(comp_dict, up_indicator): assert up_indicator == 'U' or up_indicator == "_" comp_dict['up'] = up_indicator == 'U' for comp_dict, up_indicator in zip(component_list, upstring): add_up_key(comp_dict, up_indicator)
[ "def", "apply_upstring", "(", "upstring", ",", "component_list", ")", ":", "assert", "len", "(", "upstring", ")", "==", "len", "(", "component_list", ")", "def", "add_up_key", "(", "comp_dict", ",", "up_indicator", ")", ":", "assert", "up_indicator", "==", "...
Update the dictionaries resulting from ``parse_array_start`` with the "up" key based on the upstring returned from ``parse_upstring``. The function assumes that the upstring and component_list parameters passed in are from the same device array stanza of a ``/proc/mdstat`` file. The function modifies component_list in place, adding or updating the value of the "up" key to True if there is a corresponding ``U`` in the upstring string, or to False if there is a corresponding ``_``. If there the number of rows in component_list does not match the number of characters in upstring, an ``AssertionError`` is raised. Parameters ---------- upstring : str String sequence of ``U``s and ``_``s as determined by the ``parse_upstring`` method component_list : list List of dictionaries output from the ``parse_array_start`` method.
[ "Update", "the", "dictionaries", "resulting", "from", "parse_array_start", "with", "the", "up", "key", "based", "on", "the", "upstring", "returned", "from", "parse_upstring", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/mdstat.py#L344-L377
239,914
RedHatInsights/insights-core
insights/util/fs.py
remove
def remove(path, chmod=False): """Remove a file or directory located on the filesystem at path. If chmod is True, chmod -R 755 is executed on the path before rm -rf path is called. Parameters ---------- path : str file system path to an existing file or directory chmod : bool If True, chmod -R 755 is executed on path before it's removed. Raises ------ CalledProcessError If any part of the removal process fails. """ if not os.path.exists(path): return if chmod: cmd = "chmod -R 755 %s" % path subproc.call(cmd) cmd = 'rm -rf "{p}"'.format(p=path) subproc.call(cmd)
python
def remove(path, chmod=False): if not os.path.exists(path): return if chmod: cmd = "chmod -R 755 %s" % path subproc.call(cmd) cmd = 'rm -rf "{p}"'.format(p=path) subproc.call(cmd)
[ "def", "remove", "(", "path", ",", "chmod", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "if", "chmod", ":", "cmd", "=", "\"chmod -R 755 %s\"", "%", "path", "subproc", ".", "call", "(", "cm...
Remove a file or directory located on the filesystem at path. If chmod is True, chmod -R 755 is executed on the path before rm -rf path is called. Parameters ---------- path : str file system path to an existing file or directory chmod : bool If True, chmod -R 755 is executed on path before it's removed. Raises ------ CalledProcessError If any part of the removal process fails.
[ "Remove", "a", "file", "or", "directory", "located", "on", "the", "filesystem", "at", "path", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/fs.py#L41-L69
239,915
RedHatInsights/insights-core
insights/util/fs.py
ensure_path
def ensure_path(path, mode=0o777): """Ensure that path exists in a multiprocessing safe way. If the path does not exist, recursively create it and its parent directories using the provided mode. If the path already exists, do nothing. The umask is cleared to enable the mode to be set, and then reset to the original value after the mode is set. Parameters ---------- path : str file system path to a non-existent directory that should be created. mode : int octal representation of the mode to use when creating the directory. Raises ------ OSError If os.makedirs raises an OSError for any reason other than if the directory already exists. """ if path: try: umask = os.umask(000) os.makedirs(path, mode) os.umask(umask) except OSError as e: if e.errno != errno.EEXIST: raise
python
def ensure_path(path, mode=0o777): if path: try: umask = os.umask(000) os.makedirs(path, mode) os.umask(umask) except OSError as e: if e.errno != errno.EEXIST: raise
[ "def", "ensure_path", "(", "path", ",", "mode", "=", "0o777", ")", ":", "if", "path", ":", "try", ":", "umask", "=", "os", ".", "umask", "(", "000", ")", "os", ".", "makedirs", "(", "path", ",", "mode", ")", "os", ".", "umask", "(", "umask", ")...
Ensure that path exists in a multiprocessing safe way. If the path does not exist, recursively create it and its parent directories using the provided mode. If the path already exists, do nothing. The umask is cleared to enable the mode to be set, and then reset to the original value after the mode is set. Parameters ---------- path : str file system path to a non-existent directory that should be created. mode : int octal representation of the mode to use when creating the directory. Raises ------ OSError If os.makedirs raises an OSError for any reason other than if the directory already exists.
[ "Ensure", "that", "path", "exists", "in", "a", "multiprocessing", "safe", "way", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/fs.py#L72-L103
239,916
RedHatInsights/insights-core
insights/combiners/uptime.py
uptime
def uptime(ut, facter): """Check uptime and facts to get the uptime information. Prefer uptime to facts. Returns: insights.combiners.uptime.Uptime: A named tuple with `currtime`, `updays`, `uphhmm`, `users`, `loadavg` and `uptime` components. Raises: Exception: If no data is available from both of the parsers. """ ut = ut if ut and ut.loadavg: return Uptime(ut.currtime, ut.updays, ut.uphhmm, ut.users, ut.loadavg, ut.uptime) ft = facter if ft and hasattr(ft, 'uptime_seconds'): import datetime secs = int(ft.uptime_seconds) up_dd = secs // (3600 * 24) up_hh = (secs % (3600 * 24)) // 3600 up_mm = (secs % 3600) // 60 updays = str(up_dd) if up_dd > 0 else '' uphhmm = '%02d:%02d' % (up_hh, up_mm) up_time = datetime.timedelta(seconds=secs) return Uptime(None, updays, uphhmm, None, None, up_time) raise Exception("Unable to get uptime information.")
python
def uptime(ut, facter): ut = ut if ut and ut.loadavg: return Uptime(ut.currtime, ut.updays, ut.uphhmm, ut.users, ut.loadavg, ut.uptime) ft = facter if ft and hasattr(ft, 'uptime_seconds'): import datetime secs = int(ft.uptime_seconds) up_dd = secs // (3600 * 24) up_hh = (secs % (3600 * 24)) // 3600 up_mm = (secs % 3600) // 60 updays = str(up_dd) if up_dd > 0 else '' uphhmm = '%02d:%02d' % (up_hh, up_mm) up_time = datetime.timedelta(seconds=secs) return Uptime(None, updays, uphhmm, None, None, up_time) raise Exception("Unable to get uptime information.")
[ "def", "uptime", "(", "ut", ",", "facter", ")", ":", "ut", "=", "ut", "if", "ut", "and", "ut", ".", "loadavg", ":", "return", "Uptime", "(", "ut", ".", "currtime", ",", "ut", ".", "updays", ",", "ut", ".", "uphhmm", ",", "ut", ".", "users", ","...
Check uptime and facts to get the uptime information. Prefer uptime to facts. Returns: insights.combiners.uptime.Uptime: A named tuple with `currtime`, `updays`, `uphhmm`, `users`, `loadavg` and `uptime` components. Raises: Exception: If no data is available from both of the parsers.
[ "Check", "uptime", "and", "facts", "to", "get", "the", "uptime", "information", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/uptime.py#L31-L60
239,917
census-instrumentation/opencensus-python
contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/utils/__init__.py
get_node
def get_node(service_name, host_name): """Generates Node message from params and system information. """ return common_pb2.Node( identifier=common_pb2.ProcessIdentifier( host_name=socket.gethostname() if host_name is None else host_name, pid=os.getpid(), start_timestamp=proto_ts_from_datetime( datetime.datetime.utcnow())), library_info=common_pb2.LibraryInfo( language=common_pb2.LibraryInfo.Language.Value('PYTHON'), exporter_version=EXPORTER_VERSION, core_library_version=opencensus_version), service_info=common_pb2.ServiceInfo(name=service_name))
python
def get_node(service_name, host_name): return common_pb2.Node( identifier=common_pb2.ProcessIdentifier( host_name=socket.gethostname() if host_name is None else host_name, pid=os.getpid(), start_timestamp=proto_ts_from_datetime( datetime.datetime.utcnow())), library_info=common_pb2.LibraryInfo( language=common_pb2.LibraryInfo.Language.Value('PYTHON'), exporter_version=EXPORTER_VERSION, core_library_version=opencensus_version), service_info=common_pb2.ServiceInfo(name=service_name))
[ "def", "get_node", "(", "service_name", ",", "host_name", ")", ":", "return", "common_pb2", ".", "Node", "(", "identifier", "=", "common_pb2", ".", "ProcessIdentifier", "(", "host_name", "=", "socket", ".", "gethostname", "(", ")", "if", "host_name", "is", "...
Generates Node message from params and system information.
[ "Generates", "Node", "message", "from", "params", "and", "system", "information", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/utils/__init__.py#L17-L31
239,918
census-instrumentation/opencensus-python
opencensus/trace/tracers/context_tracer.py
ContextTracer.end_span
def end_span(self, *args, **kwargs): """End a span. Update the span_id in SpanContext to the current span's parent span id; Update the current span. """ cur_span = self.current_span() if cur_span is None and self._spans_list: cur_span = self._spans_list[-1] if cur_span is None: logging.warning('No active span, cannot do end_span.') return cur_span.finish() self.span_context.span_id = cur_span.parent_span.span_id if \ cur_span.parent_span else None if isinstance(cur_span.parent_span, trace_span.Span): execution_context.set_current_span(cur_span.parent_span) else: execution_context.set_current_span(None) with self._spans_list_condition: if cur_span in self._spans_list: span_datas = self.get_span_datas(cur_span) self.exporter.export(span_datas) self._spans_list.remove(cur_span) return cur_span
python
def end_span(self, *args, **kwargs): cur_span = self.current_span() if cur_span is None and self._spans_list: cur_span = self._spans_list[-1] if cur_span is None: logging.warning('No active span, cannot do end_span.') return cur_span.finish() self.span_context.span_id = cur_span.parent_span.span_id if \ cur_span.parent_span else None if isinstance(cur_span.parent_span, trace_span.Span): execution_context.set_current_span(cur_span.parent_span) else: execution_context.set_current_span(None) with self._spans_list_condition: if cur_span in self._spans_list: span_datas = self.get_span_datas(cur_span) self.exporter.export(span_datas) self._spans_list.remove(cur_span) return cur_span
[ "def", "end_span", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cur_span", "=", "self", ".", "current_span", "(", ")", "if", "cur_span", "is", "None", "and", "self", ".", "_spans_list", ":", "cur_span", "=", "self", ".", "_spans...
End a span. Update the span_id in SpanContext to the current span's parent span id; Update the current span.
[ "End", "a", "span", ".", "Update", "the", "span_id", "in", "SpanContext", "to", "the", "current", "span", "s", "parent", "span", "id", ";", "Update", "the", "current", "span", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L99-L126
239,919
census-instrumentation/opencensus-python
opencensus/trace/tracers/context_tracer.py
ContextTracer.add_attribute_to_current_span
def add_attribute_to_current_span(self, attribute_key, attribute_value): """Add attribute to current span. :type attribute_key: str :param attribute_key: Attribute key. :type attribute_value:str :param attribute_value: Attribute value. """ current_span = self.current_span() current_span.add_attribute(attribute_key, attribute_value)
python
def add_attribute_to_current_span(self, attribute_key, attribute_value): current_span = self.current_span() current_span.add_attribute(attribute_key, attribute_value)
[ "def", "add_attribute_to_current_span", "(", "self", ",", "attribute_key", ",", "attribute_value", ")", ":", "current_span", "=", "self", ".", "current_span", "(", ")", "current_span", ".", "add_attribute", "(", "attribute_key", ",", "attribute_value", ")" ]
Add attribute to current span. :type attribute_key: str :param attribute_key: Attribute key. :type attribute_value:str :param attribute_value: Attribute value.
[ "Add", "attribute", "to", "current", "span", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L137-L147
239,920
census-instrumentation/opencensus-python
opencensus/trace/tracers/context_tracer.py
ContextTracer.get_span_datas
def get_span_datas(self, span): """Extracts a list of SpanData tuples from a span :rtype: list of opencensus.trace.span_data.SpanData :return list of SpanData tuples """ span_datas = [ span_data_module.SpanData( name=ss.name, context=self.span_context, span_id=ss.span_id, parent_span_id=ss.parent_span.span_id if ss.parent_span else None, attributes=ss.attributes, start_time=ss.start_time, end_time=ss.end_time, child_span_count=len(ss.children), stack_trace=ss.stack_trace, time_events=ss.time_events, links=ss.links, status=ss.status, same_process_as_parent_span=ss.same_process_as_parent_span, span_kind=ss.span_kind ) for ss in span ] return span_datas
python
def get_span_datas(self, span): span_datas = [ span_data_module.SpanData( name=ss.name, context=self.span_context, span_id=ss.span_id, parent_span_id=ss.parent_span.span_id if ss.parent_span else None, attributes=ss.attributes, start_time=ss.start_time, end_time=ss.end_time, child_span_count=len(ss.children), stack_trace=ss.stack_trace, time_events=ss.time_events, links=ss.links, status=ss.status, same_process_as_parent_span=ss.same_process_as_parent_span, span_kind=ss.span_kind ) for ss in span ] return span_datas
[ "def", "get_span_datas", "(", "self", ",", "span", ")", ":", "span_datas", "=", "[", "span_data_module", ".", "SpanData", "(", "name", "=", "ss", ".", "name", ",", "context", "=", "self", ".", "span_context", ",", "span_id", "=", "ss", ".", "span_id", ...
Extracts a list of SpanData tuples from a span :rtype: list of opencensus.trace.span_data.SpanData :return list of SpanData tuples
[ "Extracts", "a", "list", "of", "SpanData", "tuples", "from", "a", "span" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/tracers/context_tracer.py#L149-L176
239,921
census-instrumentation/opencensus-python
opencensus/metrics/export/metric_producer.py
MetricProducerManager.add
def add(self, metric_producer): """Add a metric producer. :type metric_producer: :class: 'MetricProducer' :param metric_producer: The metric producer to add. """ if metric_producer is None: raise ValueError with self.mp_lock: self.metric_producers.add(metric_producer)
python
def add(self, metric_producer): if metric_producer is None: raise ValueError with self.mp_lock: self.metric_producers.add(metric_producer)
[ "def", "add", "(", "self", ",", "metric_producer", ")", ":", "if", "metric_producer", "is", "None", ":", "raise", "ValueError", "with", "self", ".", "mp_lock", ":", "self", ".", "metric_producers", ".", "add", "(", "metric_producer", ")" ]
Add a metric producer. :type metric_producer: :class: 'MetricProducer' :param metric_producer: The metric producer to add.
[ "Add", "a", "metric", "producer", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric_producer.py#L44-L53
239,922
census-instrumentation/opencensus-python
opencensus/metrics/export/metric_producer.py
MetricProducerManager.remove
def remove(self, metric_producer): """Remove a metric producer. :type metric_producer: :class: 'MetricProducer' :param metric_producer: The metric producer to remove. """ if metric_producer is None: raise ValueError try: with self.mp_lock: self.metric_producers.remove(metric_producer) except KeyError: pass
python
def remove(self, metric_producer): if metric_producer is None: raise ValueError try: with self.mp_lock: self.metric_producers.remove(metric_producer) except KeyError: pass
[ "def", "remove", "(", "self", ",", "metric_producer", ")", ":", "if", "metric_producer", "is", "None", ":", "raise", "ValueError", "try", ":", "with", "self", ".", "mp_lock", ":", "self", ".", "metric_producers", ".", "remove", "(", "metric_producer", ")", ...
Remove a metric producer. :type metric_producer: :class: 'MetricProducer' :param metric_producer: The metric producer to remove.
[ "Remove", "a", "metric", "producer", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric_producer.py#L55-L67
239,923
census-instrumentation/opencensus-python
contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py
add_message_event
def add_message_event(proto_message, span, message_event_type, message_id=1): """Adds a MessageEvent to the span based off of the given protobuf message """ span.add_time_event( time_event=time_event.TimeEvent( datetime.utcnow(), message_event=time_event.MessageEvent( message_id, type=message_event_type, uncompressed_size_bytes=proto_message.ByteSize() ) ) )
python
def add_message_event(proto_message, span, message_event_type, message_id=1): span.add_time_event( time_event=time_event.TimeEvent( datetime.utcnow(), message_event=time_event.MessageEvent( message_id, type=message_event_type, uncompressed_size_bytes=proto_message.ByteSize() ) ) )
[ "def", "add_message_event", "(", "proto_message", ",", "span", ",", "message_event_type", ",", "message_id", "=", "1", ")", ":", "span", ".", "add_time_event", "(", "time_event", "=", "time_event", ".", "TimeEvent", "(", "datetime", ".", "utcnow", "(", ")", ...
Adds a MessageEvent to the span based off of the given protobuf message
[ "Adds", "a", "MessageEvent", "to", "the", "span", "based", "off", "of", "the", "given", "protobuf", "message" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py#L9-L22
239,924
census-instrumentation/opencensus-python
contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py
wrap_iter_with_message_events
def wrap_iter_with_message_events( request_or_response_iter, span, message_event_type ): """Wraps a request or response iterator to add message events to the span for each proto message sent or received """ for message_id, message in enumerate(request_or_response_iter, start=1): add_message_event( proto_message=message, span=span, message_event_type=message_event_type, message_id=message_id ) yield message
python
def wrap_iter_with_message_events( request_or_response_iter, span, message_event_type ): for message_id, message in enumerate(request_or_response_iter, start=1): add_message_event( proto_message=message, span=span, message_event_type=message_event_type, message_id=message_id ) yield message
[ "def", "wrap_iter_with_message_events", "(", "request_or_response_iter", ",", "span", ",", "message_event_type", ")", ":", "for", "message_id", ",", "message", "in", "enumerate", "(", "request_or_response_iter", ",", "start", "=", "1", ")", ":", "add_message_event", ...
Wraps a request or response iterator to add message events to the span for each proto message sent or received
[ "Wraps", "a", "request", "or", "response", "iterator", "to", "add", "message", "events", "to", "the", "span", "for", "each", "proto", "message", "sent", "or", "received" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-grpc/opencensus/ext/grpc/utils.py#L25-L40
239,925
census-instrumentation/opencensus-python
opencensus/trace/stack_trace.py
StackFrame.format_stack_frame_json
def format_stack_frame_json(self): """Convert StackFrame object to json format.""" stack_frame_json = {} stack_frame_json['function_name'] = get_truncatable_str( self.func_name) stack_frame_json['original_function_name'] = get_truncatable_str( self.original_func_name) stack_frame_json['file_name'] = get_truncatable_str(self.file_name) stack_frame_json['line_number'] = self.line_num stack_frame_json['column_number'] = self.col_num stack_frame_json['load_module'] = { 'module': get_truncatable_str(self.load_module), 'build_id': get_truncatable_str(self.build_id), } stack_frame_json['source_version'] = get_truncatable_str( self.source_version) return stack_frame_json
python
def format_stack_frame_json(self): stack_frame_json = {} stack_frame_json['function_name'] = get_truncatable_str( self.func_name) stack_frame_json['original_function_name'] = get_truncatable_str( self.original_func_name) stack_frame_json['file_name'] = get_truncatable_str(self.file_name) stack_frame_json['line_number'] = self.line_num stack_frame_json['column_number'] = self.col_num stack_frame_json['load_module'] = { 'module': get_truncatable_str(self.load_module), 'build_id': get_truncatable_str(self.build_id), } stack_frame_json['source_version'] = get_truncatable_str( self.source_version) return stack_frame_json
[ "def", "format_stack_frame_json", "(", "self", ")", ":", "stack_frame_json", "=", "{", "}", "stack_frame_json", "[", "'function_name'", "]", "=", "get_truncatable_str", "(", "self", ".", "func_name", ")", "stack_frame_json", "[", "'original_function_name'", "]", "="...
Convert StackFrame object to json format.
[ "Convert", "StackFrame", "object", "to", "json", "format", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L86-L103
239,926
census-instrumentation/opencensus-python
opencensus/trace/stack_trace.py
StackTrace.from_traceback
def from_traceback(cls, tb): """Initializes a StackTrace from a python traceback instance""" stack_trace = cls( stack_trace_hash_id=generate_hash_id_from_traceback(tb) ) # use the add_stack_frame so that json formatting is applied for tb_frame_info in traceback.extract_tb(tb): filename, line_num, fn_name, _ = tb_frame_info stack_trace.add_stack_frame( StackFrame( func_name=fn_name, original_func_name=fn_name, file_name=filename, line_num=line_num, col_num=0, # I don't think this is available in python load_module=filename, build_id=BUILD_ID, source_version=SOURCE_VERSION ) ) return stack_trace
python
def from_traceback(cls, tb): stack_trace = cls( stack_trace_hash_id=generate_hash_id_from_traceback(tb) ) # use the add_stack_frame so that json formatting is applied for tb_frame_info in traceback.extract_tb(tb): filename, line_num, fn_name, _ = tb_frame_info stack_trace.add_stack_frame( StackFrame( func_name=fn_name, original_func_name=fn_name, file_name=filename, line_num=line_num, col_num=0, # I don't think this is available in python load_module=filename, build_id=BUILD_ID, source_version=SOURCE_VERSION ) ) return stack_trace
[ "def", "from_traceback", "(", "cls", ",", "tb", ")", ":", "stack_trace", "=", "cls", "(", "stack_trace_hash_id", "=", "generate_hash_id_from_traceback", "(", "tb", ")", ")", "# use the add_stack_frame so that json formatting is applied", "for", "tb_frame_info", "in", "t...
Initializes a StackTrace from a python traceback instance
[ "Initializes", "a", "StackTrace", "from", "a", "python", "traceback", "instance" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L134-L154
239,927
census-instrumentation/opencensus-python
opencensus/trace/stack_trace.py
StackTrace.add_stack_frame
def add_stack_frame(self, stack_frame): """Add StackFrame to frames list.""" if len(self.stack_frames) >= MAX_FRAMES: self.dropped_frames_count += 1 else: self.stack_frames.append(stack_frame.format_stack_frame_json())
python
def add_stack_frame(self, stack_frame): if len(self.stack_frames) >= MAX_FRAMES: self.dropped_frames_count += 1 else: self.stack_frames.append(stack_frame.format_stack_frame_json())
[ "def", "add_stack_frame", "(", "self", ",", "stack_frame", ")", ":", "if", "len", "(", "self", ".", "stack_frames", ")", ">=", "MAX_FRAMES", ":", "self", ".", "dropped_frames_count", "+=", "1", "else", ":", "self", ".", "stack_frames", ".", "append", "(", ...
Add StackFrame to frames list.
[ "Add", "StackFrame", "to", "frames", "list", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L156-L161
239,928
census-instrumentation/opencensus-python
opencensus/trace/stack_trace.py
StackTrace.format_stack_trace_json
def format_stack_trace_json(self): """Convert a StackTrace object to json format.""" stack_trace_json = {} if self.stack_frames: stack_trace_json['stack_frames'] = { 'frame': self.stack_frames, 'dropped_frames_count': self.dropped_frames_count } stack_trace_json['stack_trace_hash_id'] = self.stack_trace_hash_id return stack_trace_json
python
def format_stack_trace_json(self): stack_trace_json = {} if self.stack_frames: stack_trace_json['stack_frames'] = { 'frame': self.stack_frames, 'dropped_frames_count': self.dropped_frames_count } stack_trace_json['stack_trace_hash_id'] = self.stack_trace_hash_id return stack_trace_json
[ "def", "format_stack_trace_json", "(", "self", ")", ":", "stack_trace_json", "=", "{", "}", "if", "self", ".", "stack_frames", ":", "stack_trace_json", "[", "'stack_frames'", "]", "=", "{", "'frame'", ":", "self", ".", "stack_frames", ",", "'dropped_frames_count...
Convert a StackTrace object to json format.
[ "Convert", "a", "StackTrace", "object", "to", "json", "format", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/stack_trace.py#L163-L175
239,929
census-instrumentation/opencensus-python
opencensus/stats/view_manager.py
ViewManager.register_view
def register_view(self, view): """registers the given view""" self.measure_to_view_map.register_view(view=view, timestamp=self.time)
python
def register_view(self, view): self.measure_to_view_map.register_view(view=view, timestamp=self.time)
[ "def", "register_view", "(", "self", ",", "view", ")", ":", "self", ".", "measure_to_view_map", ".", "register_view", "(", "view", "=", "view", ",", "timestamp", "=", "self", ".", "time", ")" ]
registers the given view
[ "registers", "the", "given", "view" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_manager.py#L35-L37
239,930
census-instrumentation/opencensus-python
opencensus/stats/view_manager.py
ViewManager.get_view
def get_view(self, view_name): """gets the view given the view name """ return self.measure_to_view_map.get_view(view_name=view_name, timestamp=self.time)
python
def get_view(self, view_name): return self.measure_to_view_map.get_view(view_name=view_name, timestamp=self.time)
[ "def", "get_view", "(", "self", ",", "view_name", ")", ":", "return", "self", ".", "measure_to_view_map", ".", "get_view", "(", "view_name", "=", "view_name", ",", "timestamp", "=", "self", ".", "time", ")" ]
gets the view given the view name
[ "gets", "the", "view", "given", "the", "view", "name" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_manager.py#L39-L42
239,931
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
new_stats_exporter
def new_stats_exporter(options=None, interval=None): """Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will raise `google.auth.exceptions.DefaultCredentialsError` if default credentials aren't configured. See `opencensus.metrics.transport.get_exporter_thread` for details on the transport thread. :type options: :class:`Options` :param exporter: Options to pass to the exporter :type interval: int or float :param interval: Seconds between export calls. :rtype: :class:`StackdriverStatsExporter` :return: The newly-created exporter. """ if options is None: _, project_id = google.auth.default() options = Options(project_id=project_id) if str(options.project_id).strip() == "": raise ValueError(ERROR_BLANK_PROJECT_ID) ci = client_info.ClientInfo(client_library_version=get_user_agent_slug()) client = monitoring_v3.MetricServiceClient(client_info=ci) exporter = StackdriverStatsExporter(client=client, options=options) transport.get_exporter_thread(stats.stats, exporter, interval=interval) return exporter
python
def new_stats_exporter(options=None, interval=None): if options is None: _, project_id = google.auth.default() options = Options(project_id=project_id) if str(options.project_id).strip() == "": raise ValueError(ERROR_BLANK_PROJECT_ID) ci = client_info.ClientInfo(client_library_version=get_user_agent_slug()) client = monitoring_v3.MetricServiceClient(client_info=ci) exporter = StackdriverStatsExporter(client=client, options=options) transport.get_exporter_thread(stats.stats, exporter, interval=interval) return exporter
[ "def", "new_stats_exporter", "(", "options", "=", "None", ",", "interval", "=", "None", ")", ":", "if", "options", "is", "None", ":", "_", ",", "project_id", "=", "google", ".", "auth", ".", "default", "(", ")", "options", "=", "Options", "(", "project...
Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will raise `google.auth.exceptions.DefaultCredentialsError` if default credentials aren't configured. See `opencensus.metrics.transport.get_exporter_thread` for details on the transport thread. :type options: :class:`Options` :param exporter: Options to pass to the exporter :type interval: int or float :param interval: Seconds between export calls. :rtype: :class:`StackdriverStatsExporter` :return: The newly-created exporter.
[ "Get", "a", "stats", "exporter", "and", "running", "transport", "thread", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L366-L399
239,932
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
namespaced_view_name
def namespaced_view_name(view_name, metric_prefix): """ create string to be used as metric type """ metric_prefix = metric_prefix or "custom.googleapis.com/opencensus" return os.path.join(metric_prefix, view_name).replace('\\', '/')
python
def namespaced_view_name(view_name, metric_prefix): metric_prefix = metric_prefix or "custom.googleapis.com/opencensus" return os.path.join(metric_prefix, view_name).replace('\\', '/')
[ "def", "namespaced_view_name", "(", "view_name", ",", "metric_prefix", ")", ":", "metric_prefix", "=", "metric_prefix", "or", "\"custom.googleapis.com/opencensus\"", "return", "os", ".", "path", ".", "join", "(", "metric_prefix", ",", "view_name", ")", ".", "replace...
create string to be used as metric type
[ "create", "string", "to", "be", "used", "as", "metric", "type" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L412-L416
239,933
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
new_label_descriptors
def new_label_descriptors(defaults, keys): """ create labels for the metric_descriptor that will be sent to Stackdriver Monitoring """ label_descriptors = [] for lk in itertools.chain.from_iterable((defaults.keys(), keys)): label = {} label["key"] = sanitize_label(lk.key) label["description"] = lk.description label_descriptors.append(label) return label_descriptors
python
def new_label_descriptors(defaults, keys): label_descriptors = [] for lk in itertools.chain.from_iterable((defaults.keys(), keys)): label = {} label["key"] = sanitize_label(lk.key) label["description"] = lk.description label_descriptors.append(label) return label_descriptors
[ "def", "new_label_descriptors", "(", "defaults", ",", "keys", ")", ":", "label_descriptors", "=", "[", "]", "for", "lk", "in", "itertools", ".", "chain", ".", "from_iterable", "(", "(", "defaults", ".", "keys", "(", ")", ",", "keys", ")", ")", ":", "la...
create labels for the metric_descriptor that will be sent to Stackdriver Monitoring
[ "create", "labels", "for", "the", "metric_descriptor", "that", "will", "be", "sent", "to", "Stackdriver", "Monitoring" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L419-L430
239,934
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
sanitize_label
def sanitize_label(text): """Remove characters not accepted in labels key This replaces any non-word characters (alphanumeric or underscore), with an underscore. It also ensures that the first character is a letter by prepending with 'key' if necessary, and trims the text to 100 characters. """ if not text: return text text = re.sub('\\W+', '_', text) if text[0] in string.digits: text = "key_" + text elif text[0] == '_': text = "key" + text return text[:100]
python
def sanitize_label(text): if not text: return text text = re.sub('\\W+', '_', text) if text[0] in string.digits: text = "key_" + text elif text[0] == '_': text = "key" + text return text[:100]
[ "def", "sanitize_label", "(", "text", ")", ":", "if", "not", "text", ":", "return", "text", "text", "=", "re", ".", "sub", "(", "'\\\\W+'", ",", "'_'", ",", "text", ")", "if", "text", "[", "0", "]", "in", "string", ".", "digits", ":", "text", "="...
Remove characters not accepted in labels key This replaces any non-word characters (alphanumeric or underscore), with an underscore. It also ensures that the first character is a letter by prepending with 'key' if necessary, and trims the text to 100 characters.
[ "Remove", "characters", "not", "accepted", "in", "labels", "key" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L433-L447
239,935
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
StackdriverStatsExporter._convert_series
def _convert_series(self, metric, ts): """Convert an OC timeseries to a SD series.""" series = monitoring_v3.types.TimeSeries() series.metric.type = self.get_metric_type(metric.descriptor) for lk, lv in self.options.default_monitoring_labels.items(): series.metric.labels[lk.key] = lv.value for key, val in zip(metric.descriptor.label_keys, ts.label_values): if val.value is not None: safe_key = sanitize_label(key.key) series.metric.labels[safe_key] = val.value set_monitored_resource(series, self.options.resource) for point in ts.points: sd_point = series.points.add() # this just modifies points, no return self._convert_point(metric, ts, point, sd_point) return series
python
def _convert_series(self, metric, ts): series = monitoring_v3.types.TimeSeries() series.metric.type = self.get_metric_type(metric.descriptor) for lk, lv in self.options.default_monitoring_labels.items(): series.metric.labels[lk.key] = lv.value for key, val in zip(metric.descriptor.label_keys, ts.label_values): if val.value is not None: safe_key = sanitize_label(key.key) series.metric.labels[safe_key] = val.value set_monitored_resource(series, self.options.resource) for point in ts.points: sd_point = series.points.add() # this just modifies points, no return self._convert_point(metric, ts, point, sd_point) return series
[ "def", "_convert_series", "(", "self", ",", "metric", ",", "ts", ")", ":", "series", "=", "monitoring_v3", ".", "types", ".", "TimeSeries", "(", ")", "series", ".", "metric", ".", "type", "=", "self", ".", "get_metric_type", "(", "metric", ".", "descript...
Convert an OC timeseries to a SD series.
[ "Convert", "an", "OC", "timeseries", "to", "a", "SD", "series", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L172-L191
239,936
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
StackdriverStatsExporter._convert_point
def _convert_point(self, metric, ts, point, sd_point): """Convert an OC metric point to a SD point.""" if (metric.descriptor.type == metric_descriptor.MetricDescriptorType .CUMULATIVE_DISTRIBUTION): sd_dist_val = sd_point.value.distribution_value sd_dist_val.count = point.value.count sd_dist_val.sum_of_squared_deviation =\ point.value.sum_of_squared_deviation assert sd_dist_val.bucket_options.explicit_buckets.bounds == [] sd_dist_val.bucket_options.explicit_buckets.bounds.extend( [0.0] + list(map(float, point.value.bucket_options.type_.bounds)) ) assert sd_dist_val.bucket_counts == [] sd_dist_val.bucket_counts.extend( [0] + [bb.count for bb in point.value.buckets] ) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64): sd_point.value.int64_value = int(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE): sd_point.value.double_value = float(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.GAUGE_INT64): sd_point.value.int64_value = int(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE): sd_point.value.double_value = float(point.value.value) # TODO: handle SUMMARY metrics, #567 else: # pragma: NO COVER raise TypeError("Unsupported metric type: {}" .format(metric.descriptor.type)) end = point.timestamp if ts.start_timestamp is None: start = end else: start = datetime.strptime(ts.start_timestamp, EPOCH_PATTERN) timestamp_start = (start - EPOCH_DATETIME).total_seconds() timestamp_end = (end - EPOCH_DATETIME).total_seconds() sd_point.interval.end_time.seconds = int(timestamp_end) secs = sd_point.interval.end_time.seconds sd_point.interval.end_time.nanos = int((timestamp_end - secs) * 1e9) start_time = sd_point.interval.start_time start_time.seconds = int(timestamp_start) start_time.nanos = int((timestamp_start - start_time.seconds) * 1e9)
python
def _convert_point(self, metric, ts, point, sd_point): if (metric.descriptor.type == metric_descriptor.MetricDescriptorType .CUMULATIVE_DISTRIBUTION): sd_dist_val = sd_point.value.distribution_value sd_dist_val.count = point.value.count sd_dist_val.sum_of_squared_deviation =\ point.value.sum_of_squared_deviation assert sd_dist_val.bucket_options.explicit_buckets.bounds == [] sd_dist_val.bucket_options.explicit_buckets.bounds.extend( [0.0] + list(map(float, point.value.bucket_options.type_.bounds)) ) assert sd_dist_val.bucket_counts == [] sd_dist_val.bucket_counts.extend( [0] + [bb.count for bb in point.value.buckets] ) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64): sd_point.value.int64_value = int(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE): sd_point.value.double_value = float(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.GAUGE_INT64): sd_point.value.int64_value = int(point.value.value) elif (metric.descriptor.type == metric_descriptor.MetricDescriptorType.GAUGE_DOUBLE): sd_point.value.double_value = float(point.value.value) # TODO: handle SUMMARY metrics, #567 else: # pragma: NO COVER raise TypeError("Unsupported metric type: {}" .format(metric.descriptor.type)) end = point.timestamp if ts.start_timestamp is None: start = end else: start = datetime.strptime(ts.start_timestamp, EPOCH_PATTERN) timestamp_start = (start - EPOCH_DATETIME).total_seconds() timestamp_end = (end - EPOCH_DATETIME).total_seconds() sd_point.interval.end_time.seconds = int(timestamp_end) secs = sd_point.interval.end_time.seconds sd_point.interval.end_time.nanos = int((timestamp_end - secs) * 1e9) start_time = sd_point.interval.start_time start_time.seconds = int(timestamp_start) start_time.nanos = int((timestamp_start - start_time.seconds) * 1e9)
[ "def", "_convert_point", "(", "self", ",", "metric", ",", "ts", ",", "point", ",", "sd_point", ")", ":", "if", "(", "metric", ".", "descriptor", ".", "type", "==", "metric_descriptor", ".", "MetricDescriptorType", ".", "CUMULATIVE_DISTRIBUTION", ")", ":", "s...
Convert an OC metric point to a SD point.
[ "Convert", "an", "OC", "metric", "point", "to", "a", "SD", "point", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L193-L252
239,937
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
StackdriverStatsExporter.get_metric_descriptor
def get_metric_descriptor(self, oc_md): """Convert an OC metric descriptor to a SD metric descriptor.""" try: metric_kind, value_type = OC_MD_TO_SD_TYPE[oc_md.type] except KeyError: raise TypeError("Unsupported metric type: {}".format(oc_md.type)) if self.options.metric_prefix: display_name_prefix = self.options.metric_prefix else: display_name_prefix = DEFAULT_DISPLAY_NAME_PREFIX desc_labels = new_label_descriptors( self.options.default_monitoring_labels, oc_md.label_keys) descriptor = monitoring_v3.types.MetricDescriptor(labels=desc_labels) metric_type = self.get_metric_type(oc_md) descriptor.type = metric_type descriptor.metric_kind = metric_kind descriptor.value_type = value_type descriptor.description = oc_md.description descriptor.unit = oc_md.unit descriptor.name = ("projects/{}/metricDescriptors/{}" .format(self.options.project_id, metric_type)) descriptor.display_name = ("{}/{}" .format(display_name_prefix, oc_md.name)) return descriptor
python
def get_metric_descriptor(self, oc_md): try: metric_kind, value_type = OC_MD_TO_SD_TYPE[oc_md.type] except KeyError: raise TypeError("Unsupported metric type: {}".format(oc_md.type)) if self.options.metric_prefix: display_name_prefix = self.options.metric_prefix else: display_name_prefix = DEFAULT_DISPLAY_NAME_PREFIX desc_labels = new_label_descriptors( self.options.default_monitoring_labels, oc_md.label_keys) descriptor = monitoring_v3.types.MetricDescriptor(labels=desc_labels) metric_type = self.get_metric_type(oc_md) descriptor.type = metric_type descriptor.metric_kind = metric_kind descriptor.value_type = value_type descriptor.description = oc_md.description descriptor.unit = oc_md.unit descriptor.name = ("projects/{}/metricDescriptors/{}" .format(self.options.project_id, metric_type)) descriptor.display_name = ("{}/{}" .format(display_name_prefix, oc_md.name)) return descriptor
[ "def", "get_metric_descriptor", "(", "self", ",", "oc_md", ")", ":", "try", ":", "metric_kind", ",", "value_type", "=", "OC_MD_TO_SD_TYPE", "[", "oc_md", ".", "type", "]", "except", "KeyError", ":", "raise", "TypeError", "(", "\"Unsupported metric type: {}\"", "...
Convert an OC metric descriptor to a SD metric descriptor.
[ "Convert", "an", "OC", "metric", "descriptor", "to", "a", "SD", "metric", "descriptor", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L258-L285
239,938
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
StackdriverStatsExporter.register_metric_descriptor
def register_metric_descriptor(self, oc_md): """Register a metric descriptor with stackdriver.""" metric_type = self.get_metric_type(oc_md) with self._md_lock: if metric_type in self._md_cache: return self._md_cache[metric_type] descriptor = self.get_metric_descriptor(oc_md) project_name = self.client.project_path(self.options.project_id) sd_md = self.client.create_metric_descriptor(project_name, descriptor) with self._md_lock: self._md_cache[metric_type] = sd_md return sd_md
python
def register_metric_descriptor(self, oc_md): metric_type = self.get_metric_type(oc_md) with self._md_lock: if metric_type in self._md_cache: return self._md_cache[metric_type] descriptor = self.get_metric_descriptor(oc_md) project_name = self.client.project_path(self.options.project_id) sd_md = self.client.create_metric_descriptor(project_name, descriptor) with self._md_lock: self._md_cache[metric_type] = sd_md return sd_md
[ "def", "register_metric_descriptor", "(", "self", ",", "oc_md", ")", ":", "metric_type", "=", "self", ".", "get_metric_type", "(", "oc_md", ")", "with", "self", ".", "_md_lock", ":", "if", "metric_type", "in", "self", ".", "_md_cache", ":", "return", "self",...
Register a metric descriptor with stackdriver.
[ "Register", "a", "metric", "descriptor", "with", "stackdriver", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L287-L299
239,939
census-instrumentation/opencensus-python
opencensus/trace/propagation/google_cloud_format.py
GoogleCloudFormatPropagator.from_headers
def from_headers(self, headers): """Generate a SpanContext object using the trace context header. :type headers: dict :param headers: HTTP request headers. :rtype: :class:`~opencensus.trace.span_context.SpanContext` :returns: SpanContext generated from the trace context header. """ if headers is None: return SpanContext() header = headers.get(_TRACE_CONTEXT_HEADER_NAME) if header is None: return SpanContext() header = str(header.encode('utf-8')) return self.from_header(header)
python
def from_headers(self, headers): if headers is None: return SpanContext() header = headers.get(_TRACE_CONTEXT_HEADER_NAME) if header is None: return SpanContext() header = str(header.encode('utf-8')) return self.from_header(header)
[ "def", "from_headers", "(", "self", ",", "headers", ")", ":", "if", "headers", "is", "None", ":", "return", "SpanContext", "(", ")", "header", "=", "headers", ".", "get", "(", "_TRACE_CONTEXT_HEADER_NAME", ")", "if", "header", "is", "None", ":", "return", ...
Generate a SpanContext object using the trace context header. :type headers: dict :param headers: HTTP request headers. :rtype: :class:`~opencensus.trace.span_context.SpanContext` :returns: SpanContext generated from the trace context header.
[ "Generate", "a", "SpanContext", "object", "using", "the", "trace", "context", "header", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/google_cloud_format.py#L77-L92
239,940
census-instrumentation/opencensus-python
opencensus/trace/propagation/google_cloud_format.py
GoogleCloudFormatPropagator.to_header
def to_header(self, span_context): """Convert a SpanContext object to header string. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: str :returns: A trace context header string in google cloud format. """ trace_id = span_context.trace_id span_id = span_context.span_id trace_options = span_context.trace_options.trace_options_byte header = '{}/{};o={}'.format( trace_id, span_id, int(trace_options)) return header
python
def to_header(self, span_context): trace_id = span_context.trace_id span_id = span_context.span_id trace_options = span_context.trace_options.trace_options_byte header = '{}/{};o={}'.format( trace_id, span_id, int(trace_options)) return header
[ "def", "to_header", "(", "self", ",", "span_context", ")", ":", "trace_id", "=", "span_context", ".", "trace_id", "span_id", "=", "span_context", ".", "span_id", "trace_options", "=", "span_context", ".", "trace_options", ".", "trace_options_byte", "header", "=", ...
Convert a SpanContext object to header string. :type span_context: :class:`~opencensus.trace.span_context.SpanContext` :param span_context: SpanContext object. :rtype: str :returns: A trace context header string in google cloud format.
[ "Convert", "a", "SpanContext", "object", "to", "header", "string", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/google_cloud_format.py#L94-L112
239,941
census-instrumentation/opencensus-python
contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py
_extract_annotations_from_span
def _extract_annotations_from_span(span): """Extract and convert time event annotations to zipkin annotations""" if span.time_events is None: return [] annotations = [] for time_event in span.time_events: annotation = time_event.annotation if not annotation: continue event_timestamp_mus = timestamp_to_microseconds(time_event.timestamp) annotations.append({'timestamp': int(round(event_timestamp_mus)), 'value': annotation.description}) return annotations
python
def _extract_annotations_from_span(span): if span.time_events is None: return [] annotations = [] for time_event in span.time_events: annotation = time_event.annotation if not annotation: continue event_timestamp_mus = timestamp_to_microseconds(time_event.timestamp) annotations.append({'timestamp': int(round(event_timestamp_mus)), 'value': annotation.description}) return annotations
[ "def", "_extract_annotations_from_span", "(", "span", ")", ":", "if", "span", ".", "time_events", "is", "None", ":", "return", "[", "]", "annotations", "=", "[", "]", "for", "time_event", "in", "span", ".", "time_events", ":", "annotation", "=", "time_event"...
Extract and convert time event annotations to zipkin annotations
[ "Extract", "and", "convert", "time", "event", "annotations", "to", "zipkin", "annotations" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L202-L217
239,942
census-instrumentation/opencensus-python
contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py
ZipkinExporter.emit
def emit(self, span_datas): """Send SpanData tuples to Zipkin server, default using the v2 API. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param list of opencensus.trace.span_data.SpanData span_datas: SpanData tuples to emit """ try: zipkin_spans = self.translate_to_zipkin(span_datas) result = requests.post( url=self.url, data=json.dumps(zipkin_spans), headers=ZIPKIN_HEADERS) if result.status_code not in SUCCESS_STATUS_CODE: logging.error( "Failed to send spans to Zipkin server! Spans are {}" .format(zipkin_spans)) except Exception as e: # pragma: NO COVER logging.error(getattr(e, 'message', e))
python
def emit(self, span_datas): try: zipkin_spans = self.translate_to_zipkin(span_datas) result = requests.post( url=self.url, data=json.dumps(zipkin_spans), headers=ZIPKIN_HEADERS) if result.status_code not in SUCCESS_STATUS_CODE: logging.error( "Failed to send spans to Zipkin server! Spans are {}" .format(zipkin_spans)) except Exception as e: # pragma: NO COVER logging.error(getattr(e, 'message', e))
[ "def", "emit", "(", "self", ",", "span_datas", ")", ":", "try", ":", "zipkin_spans", "=", "self", ".", "translate_to_zipkin", "(", "span_datas", ")", "result", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "url", ",", "data", "=", "json",...
Send SpanData tuples to Zipkin server, default using the v2 API. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param list of opencensus.trace.span_data.SpanData span_datas: SpanData tuples to emit
[ "Send", "SpanData", "tuples", "to", "Zipkin", "server", "default", "using", "the", "v2", "API", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L99-L120
239,943
census-instrumentation/opencensus-python
contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py
ZipkinExporter.translate_to_zipkin
def translate_to_zipkin(self, span_datas): """Translate the opencensus spans to zipkin spans. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit :rtype: list :returns: List of zipkin format spans. """ local_endpoint = { 'serviceName': self.service_name, 'port': self.port, } if self.ipv4 is not None: local_endpoint['ipv4'] = self.ipv4 if self.ipv6 is not None: local_endpoint['ipv6'] = self.ipv6 zipkin_spans = [] for span in span_datas: # Timestamp in zipkin spans is int of microseconds. start_timestamp_mus = timestamp_to_microseconds(span.start_time) end_timestamp_mus = timestamp_to_microseconds(span.end_time) duration_mus = end_timestamp_mus - start_timestamp_mus zipkin_span = { 'traceId': span.context.trace_id, 'id': str(span.span_id), 'name': span.name, 'timestamp': int(round(start_timestamp_mus)), 'duration': int(round(duration_mus)), 'localEndpoint': local_endpoint, 'tags': _extract_tags_from_span(span.attributes), 'annotations': _extract_annotations_from_span(span), } span_kind = span.span_kind parent_span_id = span.parent_span_id if span_kind is not None: kind = SPAN_KIND_MAP.get(span_kind) # Zipkin API for span kind only accept # enum(CLIENT|SERVER|PRODUCER|CONSUMER|Absent) if kind is not None: zipkin_span['kind'] = kind if parent_span_id is not None: zipkin_span['parentId'] = str(parent_span_id) zipkin_spans.append(zipkin_span) return zipkin_spans
python
def translate_to_zipkin(self, span_datas): local_endpoint = { 'serviceName': self.service_name, 'port': self.port, } if self.ipv4 is not None: local_endpoint['ipv4'] = self.ipv4 if self.ipv6 is not None: local_endpoint['ipv6'] = self.ipv6 zipkin_spans = [] for span in span_datas: # Timestamp in zipkin spans is int of microseconds. start_timestamp_mus = timestamp_to_microseconds(span.start_time) end_timestamp_mus = timestamp_to_microseconds(span.end_time) duration_mus = end_timestamp_mus - start_timestamp_mus zipkin_span = { 'traceId': span.context.trace_id, 'id': str(span.span_id), 'name': span.name, 'timestamp': int(round(start_timestamp_mus)), 'duration': int(round(duration_mus)), 'localEndpoint': local_endpoint, 'tags': _extract_tags_from_span(span.attributes), 'annotations': _extract_annotations_from_span(span), } span_kind = span.span_kind parent_span_id = span.parent_span_id if span_kind is not None: kind = SPAN_KIND_MAP.get(span_kind) # Zipkin API for span kind only accept # enum(CLIENT|SERVER|PRODUCER|CONSUMER|Absent) if kind is not None: zipkin_span['kind'] = kind if parent_span_id is not None: zipkin_span['parentId'] = str(parent_span_id) zipkin_spans.append(zipkin_span) return zipkin_spans
[ "def", "translate_to_zipkin", "(", "self", ",", "span_datas", ")", ":", "local_endpoint", "=", "{", "'serviceName'", ":", "self", ".", "service_name", ",", "'port'", ":", "self", ".", "port", ",", "}", "if", "self", ".", "ipv4", "is", "not", "None", ":",...
Translate the opencensus spans to zipkin spans. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit :rtype: list :returns: List of zipkin format spans.
[ "Translate", "the", "opencensus", "spans", "to", "zipkin", "spans", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-zipkin/opencensus/ext/zipkin/trace_exporter/__init__.py#L125-L182
239,944
census-instrumentation/opencensus-python
contrib/opencensus-ext-sqlalchemy/opencensus/ext/sqlalchemy/trace.py
trace_engine
def trace_engine(engine): """Register the event before cursor execute and after cursor execute to the event listner of the engine. """ event.listen(engine, 'before_cursor_execute', _before_cursor_execute) event.listen(engine, 'after_cursor_execute', _after_cursor_execute)
python
def trace_engine(engine): event.listen(engine, 'before_cursor_execute', _before_cursor_execute) event.listen(engine, 'after_cursor_execute', _after_cursor_execute)
[ "def", "trace_engine", "(", "engine", ")", ":", "event", ".", "listen", "(", "engine", ",", "'before_cursor_execute'", ",", "_before_cursor_execute", ")", "event", ".", "listen", "(", "engine", ",", "'after_cursor_execute'", ",", "_after_cursor_execute", ")" ]
Register the event before cursor execute and after cursor execute to the event listner of the engine.
[ "Register", "the", "event", "before", "cursor", "execute", "and", "after", "cursor", "execute", "to", "the", "event", "listner", "of", "the", "engine", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-sqlalchemy/opencensus/ext/sqlalchemy/trace.py#L38-L43
239,945
census-instrumentation/opencensus-python
opencensus/metrics/export/time_series.py
TimeSeries.check_points_type
def check_points_type(self, type_class): """Check that each point's value is an instance of `type_class`. `type_class` should typically be a Value type, i.e. one that extends :class: `opencensus.metrics.export.value.Value`. :type type_class: type :param type_class: Type to check against. :rtype: bool :return: Whether all points are instances of `type_class`. """ for point in self.points: if (point.value is not None and not isinstance(point.value, type_class)): return False return True
python
def check_points_type(self, type_class): for point in self.points: if (point.value is not None and not isinstance(point.value, type_class)): return False return True
[ "def", "check_points_type", "(", "self", ",", "type_class", ")", ":", "for", "point", "in", "self", ".", "points", ":", "if", "(", "point", ".", "value", "is", "not", "None", "and", "not", "isinstance", "(", "point", ".", "value", ",", "type_class", ")...
Check that each point's value is an instance of `type_class`. `type_class` should typically be a Value type, i.e. one that extends :class: `opencensus.metrics.export.value.Value`. :type type_class: type :param type_class: Type to check against. :rtype: bool :return: Whether all points are instances of `type_class`.
[ "Check", "that", "each", "point", "s", "value", "is", "an", "instance", "of", "type_class", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/time_series.py#L74-L90
239,946
census-instrumentation/opencensus-python
opencensus/log/__init__.py
get_log_attrs
def get_log_attrs(): """Get logging attributes from the opencensus context. :rtype: :class:`LogAttrs` :return: The current span's trace ID, span ID, and sampling decision. """ try: tracer = execution_context.get_opencensus_tracer() if tracer is None: raise RuntimeError except Exception: # noqa _meta_logger.error("Failed to get opencensus tracer") return ATTR_DEFAULTS try: trace_id = tracer.span_context.trace_id if trace_id is None: trace_id = ATTR_DEFAULTS.trace_id except Exception: # noqa _meta_logger.error("Failed to get opencensus trace ID") trace_id = ATTR_DEFAULTS.trace_id try: span_id = tracer.span_context.span_id if span_id is None: span_id = ATTR_DEFAULTS.span_id except Exception: # noqa _meta_logger.error("Failed to get opencensus span ID") span_id = ATTR_DEFAULTS.span_id try: sampling_decision = tracer.span_context.trace_options.get_enabled if sampling_decision is None: sampling_decision = ATTR_DEFAULTS.sampling_decision except AttributeError: sampling_decision = ATTR_DEFAULTS.sampling_decision except Exception: # noqa _meta_logger.error("Failed to get opencensus sampling decision") sampling_decision = ATTR_DEFAULTS.sampling_decision return LogAttrs(trace_id, span_id, sampling_decision)
python
def get_log_attrs(): try: tracer = execution_context.get_opencensus_tracer() if tracer is None: raise RuntimeError except Exception: # noqa _meta_logger.error("Failed to get opencensus tracer") return ATTR_DEFAULTS try: trace_id = tracer.span_context.trace_id if trace_id is None: trace_id = ATTR_DEFAULTS.trace_id except Exception: # noqa _meta_logger.error("Failed to get opencensus trace ID") trace_id = ATTR_DEFAULTS.trace_id try: span_id = tracer.span_context.span_id if span_id is None: span_id = ATTR_DEFAULTS.span_id except Exception: # noqa _meta_logger.error("Failed to get opencensus span ID") span_id = ATTR_DEFAULTS.span_id try: sampling_decision = tracer.span_context.trace_options.get_enabled if sampling_decision is None: sampling_decision = ATTR_DEFAULTS.sampling_decision except AttributeError: sampling_decision = ATTR_DEFAULTS.sampling_decision except Exception: # noqa _meta_logger.error("Failed to get opencensus sampling decision") sampling_decision = ATTR_DEFAULTS.sampling_decision return LogAttrs(trace_id, span_id, sampling_decision)
[ "def", "get_log_attrs", "(", ")", ":", "try", ":", "tracer", "=", "execution_context", ".", "get_opencensus_tracer", "(", ")", "if", "tracer", "is", "None", ":", "raise", "RuntimeError", "except", "Exception", ":", "# noqa", "_meta_logger", ".", "error", "(", ...
Get logging attributes from the opencensus context. :rtype: :class:`LogAttrs` :return: The current span's trace ID, span ID, and sampling decision.
[ "Get", "logging", "attributes", "from", "the", "opencensus", "context", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/log/__init__.py#L33-L73
239,947
census-instrumentation/opencensus-python
contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py
trace_integration
def trace_integration(tracer=None): """Trace the Google Cloud Client libraries by integrating with the transport level including HTTP and gRPC. """ log.info('Integrated module: {}'.format(MODULE_NAME)) # Integrate with gRPC trace_grpc(tracer) # Integrate with HTTP trace_http(tracer)
python
def trace_integration(tracer=None): log.info('Integrated module: {}'.format(MODULE_NAME)) # Integrate with gRPC trace_grpc(tracer) # Integrate with HTTP trace_http(tracer)
[ "def", "trace_integration", "(", "tracer", "=", "None", ")", ":", "log", ".", "info", "(", "'Integrated module: {}'", ".", "format", "(", "MODULE_NAME", ")", ")", "# Integrate with gRPC", "trace_grpc", "(", "tracer", ")", "# Integrate with HTTP", "trace_http", "("...
Trace the Google Cloud Client libraries by integrating with the transport level including HTTP and gRPC.
[ "Trace", "the", "Google", "Cloud", "Client", "libraries", "by", "integrating", "with", "the", "transport", "level", "including", "HTTP", "and", "gRPC", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L37-L47
239,948
census-instrumentation/opencensus-python
contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py
trace_grpc
def trace_grpc(tracer=None): """Integrate with gRPC.""" # Wrap google.cloud._helpers.make_secure_channel make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL) make_secure_channel_wrapped = wrap_make_secure_channel( make_secure_channel_func, tracer) setattr( _helpers, MAKE_SECURE_CHANNEL, make_secure_channel_wrapped) # Wrap the grpc.insecure_channel. insecure_channel_func = getattr(grpc, INSECURE_CHANNEL) insecure_channel_wrapped = wrap_insecure_channel( insecure_channel_func, tracer) setattr( grpc, INSECURE_CHANNEL, insecure_channel_wrapped) # Wrap google.api_core.grpc_helpers.create_channel create_channel_func = getattr(grpc_helpers, CREATE_CHANNEL) create_channel_wrapped = wrap_create_channel(create_channel_func, tracer) setattr( grpc_helpers, CREATE_CHANNEL, create_channel_wrapped)
python
def trace_grpc(tracer=None): # Wrap google.cloud._helpers.make_secure_channel make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL) make_secure_channel_wrapped = wrap_make_secure_channel( make_secure_channel_func, tracer) setattr( _helpers, MAKE_SECURE_CHANNEL, make_secure_channel_wrapped) # Wrap the grpc.insecure_channel. insecure_channel_func = getattr(grpc, INSECURE_CHANNEL) insecure_channel_wrapped = wrap_insecure_channel( insecure_channel_func, tracer) setattr( grpc, INSECURE_CHANNEL, insecure_channel_wrapped) # Wrap google.api_core.grpc_helpers.create_channel create_channel_func = getattr(grpc_helpers, CREATE_CHANNEL) create_channel_wrapped = wrap_create_channel(create_channel_func, tracer) setattr( grpc_helpers, CREATE_CHANNEL, create_channel_wrapped)
[ "def", "trace_grpc", "(", "tracer", "=", "None", ")", ":", "# Wrap google.cloud._helpers.make_secure_channel", "make_secure_channel_func", "=", "getattr", "(", "_helpers", ",", "MAKE_SECURE_CHANNEL", ")", "make_secure_channel_wrapped", "=", "wrap_make_secure_channel", "(", ...
Integrate with gRPC.
[ "Integrate", "with", "gRPC", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L50-L76
239,949
census-instrumentation/opencensus-python
contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py
wrap_make_secure_channel
def wrap_make_secure_channel(make_secure_channel_func, tracer=None): """Wrap the google.cloud._helpers.make_secure_channel.""" def call(*args, **kwargs): channel = make_secure_channel_func(*args, **kwargs) try: host = kwargs.get('host') tracer_interceptor = OpenCensusClientInterceptor(tracer, host) intercepted_channel = grpc.intercept_channel( channel, tracer_interceptor) return intercepted_channel # pragma: NO COVER except Exception: log.warning( 'Failed to wrap secure channel, ' 'clientlibs grpc calls not traced.') return channel return call
python
def wrap_make_secure_channel(make_secure_channel_func, tracer=None): def call(*args, **kwargs): channel = make_secure_channel_func(*args, **kwargs) try: host = kwargs.get('host') tracer_interceptor = OpenCensusClientInterceptor(tracer, host) intercepted_channel = grpc.intercept_channel( channel, tracer_interceptor) return intercepted_channel # pragma: NO COVER except Exception: log.warning( 'Failed to wrap secure channel, ' 'clientlibs grpc calls not traced.') return channel return call
[ "def", "wrap_make_secure_channel", "(", "make_secure_channel_func", ",", "tracer", "=", "None", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "channel", "=", "make_secure_channel_func", "(", "*", "args", ",", "*", "*", "kwar...
Wrap the google.cloud._helpers.make_secure_channel.
[ "Wrap", "the", "google", ".", "cloud", ".", "_helpers", ".", "make_secure_channel", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L84-L100
239,950
census-instrumentation/opencensus-python
contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py
wrap_insecure_channel
def wrap_insecure_channel(insecure_channel_func, tracer=None): """Wrap the grpc.insecure_channel.""" def call(*args, **kwargs): channel = insecure_channel_func(*args, **kwargs) try: target = kwargs.get('target') tracer_interceptor = OpenCensusClientInterceptor(tracer, target) intercepted_channel = grpc.intercept_channel( channel, tracer_interceptor) return intercepted_channel # pragma: NO COVER except Exception: log.warning( 'Failed to wrap insecure channel, ' 'clientlibs grpc calls not traced.') return channel return call
python
def wrap_insecure_channel(insecure_channel_func, tracer=None): def call(*args, **kwargs): channel = insecure_channel_func(*args, **kwargs) try: target = kwargs.get('target') tracer_interceptor = OpenCensusClientInterceptor(tracer, target) intercepted_channel = grpc.intercept_channel( channel, tracer_interceptor) return intercepted_channel # pragma: NO COVER except Exception: log.warning( 'Failed to wrap insecure channel, ' 'clientlibs grpc calls not traced.') return channel return call
[ "def", "wrap_insecure_channel", "(", "insecure_channel_func", ",", "tracer", "=", "None", ")", ":", "def", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "channel", "=", "insecure_channel_func", "(", "*", "args", ",", "*", "*", "kwargs", ")...
Wrap the grpc.insecure_channel.
[ "Wrap", "the", "grpc", ".", "insecure_channel", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L103-L119
239,951
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
_convert_reftype_to_jaeger_reftype
def _convert_reftype_to_jaeger_reftype(ref): """Convert opencensus reference types to jaeger reference types.""" if ref == link_module.Type.CHILD_LINKED_SPAN: return jaeger.SpanRefType.CHILD_OF if ref == link_module.Type.PARENT_LINKED_SPAN: return jaeger.SpanRefType.FOLLOWS_FROM return None
python
def _convert_reftype_to_jaeger_reftype(ref): if ref == link_module.Type.CHILD_LINKED_SPAN: return jaeger.SpanRefType.CHILD_OF if ref == link_module.Type.PARENT_LINKED_SPAN: return jaeger.SpanRefType.FOLLOWS_FROM return None
[ "def", "_convert_reftype_to_jaeger_reftype", "(", "ref", ")", ":", "if", "ref", "==", "link_module", ".", "Type", ".", "CHILD_LINKED_SPAN", ":", "return", "jaeger", ".", "SpanRefType", ".", "CHILD_OF", "if", "ref", "==", "link_module", ".", "Type", ".", "PAREN...
Convert opencensus reference types to jaeger reference types.
[ "Convert", "opencensus", "reference", "types", "to", "jaeger", "reference", "types", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L238-L244
239,952
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
_convert_hex_str_to_int
def _convert_hex_str_to_int(val): """Convert hexadecimal formatted ids to signed int64""" if val is None: return None hex_num = int(val, 16) # ensure it fits into 64-bit if hex_num > 0x7FFFFFFFFFFFFFFF: hex_num -= 0x10000000000000000 assert -9223372036854775808 <= hex_num <= 9223372036854775807 return hex_num
python
def _convert_hex_str_to_int(val): if val is None: return None hex_num = int(val, 16) # ensure it fits into 64-bit if hex_num > 0x7FFFFFFFFFFFFFFF: hex_num -= 0x10000000000000000 assert -9223372036854775808 <= hex_num <= 9223372036854775807 return hex_num
[ "def", "_convert_hex_str_to_int", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "None", "hex_num", "=", "int", "(", "val", ",", "16", ")", "# ensure it fits into 64-bit", "if", "hex_num", ">", "0x7FFFFFFFFFFFFFFF", ":", "hex_num", "-=", "0...
Convert hexadecimal formatted ids to signed int64
[ "Convert", "hexadecimal", "formatted", "ids", "to", "signed", "int64" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L247-L258
239,953
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
_convert_attribute_to_tag
def _convert_attribute_to_tag(key, attr): """Convert the attributes to jaeger tags.""" if isinstance(attr, bool): return jaeger.Tag( key=key, vBool=attr, vType=jaeger.TagType.BOOL) if isinstance(attr, str): return jaeger.Tag( key=key, vStr=attr, vType=jaeger.TagType.STRING) if isinstance(attr, int): return jaeger.Tag( key=key, vLong=attr, vType=jaeger.TagType.LONG) if isinstance(attr, float): return jaeger.Tag( key=key, vDouble=attr, vType=jaeger.TagType.DOUBLE) logging.warn('Could not serialize attribute \ {}:{} to tag'.format(key, attr)) return None
python
def _convert_attribute_to_tag(key, attr): if isinstance(attr, bool): return jaeger.Tag( key=key, vBool=attr, vType=jaeger.TagType.BOOL) if isinstance(attr, str): return jaeger.Tag( key=key, vStr=attr, vType=jaeger.TagType.STRING) if isinstance(attr, int): return jaeger.Tag( key=key, vLong=attr, vType=jaeger.TagType.LONG) if isinstance(attr, float): return jaeger.Tag( key=key, vDouble=attr, vType=jaeger.TagType.DOUBLE) logging.warn('Could not serialize attribute \ {}:{} to tag'.format(key, attr)) return None
[ "def", "_convert_attribute_to_tag", "(", "key", ",", "attr", ")", ":", "if", "isinstance", "(", "attr", ",", "bool", ")", ":", "return", "jaeger", ".", "Tag", "(", "key", "=", "key", ",", "vBool", "=", "attr", ",", "vType", "=", "jaeger", ".", "TagTy...
Convert the attributes to jaeger tags.
[ "Convert", "the", "attributes", "to", "jaeger", "tags", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L298-L322
239,954
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
JaegerExporter.translate_to_jaeger
def translate_to_jaeger(self, span_datas): """Translate the spans to Jaeger format. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit """ top_span = span_datas[0] trace_id = top_span.context.trace_id if top_span.context is not None \ else None jaeger_spans = [] for span in span_datas: start_timestamp_ms = timestamp_to_microseconds(span.start_time) end_timestamp_ms = timestamp_to_microseconds(span.end_time) duration_ms = end_timestamp_ms - start_timestamp_ms tags = _extract_tags(span.attributes) status = span.status if status is not None: tags.append(jaeger.Tag( key='status.code', vType=jaeger.TagType.LONG, vLong=status.code)) tags.append(jaeger.Tag( key='status.message', vType=jaeger.TagType.STRING, vStr=status.message)) refs = _extract_refs_from_span(span) logs = _extract_logs_from_span(span) context = span.context flags = None if context is not None: flags = int(context.trace_options.trace_options_byte) span_id = span.span_id parent_span_id = span.parent_span_id jaeger_span = jaeger.Span( traceIdHigh=_convert_hex_str_to_int(trace_id[0:16]), traceIdLow=_convert_hex_str_to_int(trace_id[16:32]), spanId=_convert_hex_str_to_int(span_id), operationName=span.name, startTime=int(round(start_timestamp_ms)), duration=int(round(duration_ms)), tags=tags, logs=logs, references=refs, flags=flags, parentSpanId=_convert_hex_str_to_int(parent_span_id or '0')) jaeger_spans.append(jaeger_span) return jaeger_spans
python
def translate_to_jaeger(self, span_datas): top_span = span_datas[0] trace_id = top_span.context.trace_id if top_span.context is not None \ else None jaeger_spans = [] for span in span_datas: start_timestamp_ms = timestamp_to_microseconds(span.start_time) end_timestamp_ms = timestamp_to_microseconds(span.end_time) duration_ms = end_timestamp_ms - start_timestamp_ms tags = _extract_tags(span.attributes) status = span.status if status is not None: tags.append(jaeger.Tag( key='status.code', vType=jaeger.TagType.LONG, vLong=status.code)) tags.append(jaeger.Tag( key='status.message', vType=jaeger.TagType.STRING, vStr=status.message)) refs = _extract_refs_from_span(span) logs = _extract_logs_from_span(span) context = span.context flags = None if context is not None: flags = int(context.trace_options.trace_options_byte) span_id = span.span_id parent_span_id = span.parent_span_id jaeger_span = jaeger.Span( traceIdHigh=_convert_hex_str_to_int(trace_id[0:16]), traceIdLow=_convert_hex_str_to_int(trace_id[16:32]), spanId=_convert_hex_str_to_int(span_id), operationName=span.name, startTime=int(round(start_timestamp_ms)), duration=int(round(duration_ms)), tags=tags, logs=logs, references=refs, flags=flags, parentSpanId=_convert_hex_str_to_int(parent_span_id or '0')) jaeger_spans.append(jaeger_span) return jaeger_spans
[ "def", "translate_to_jaeger", "(", "self", ",", "span_datas", ")", ":", "top_span", "=", "span_datas", "[", "0", "]", "trace_id", "=", "top_span", ".", "context", ".", "trace_id", "if", "top_span", ".", "context", "is", "not", "None", "else", "None", "jaeg...
Translate the spans to Jaeger format. :type span_datas: list of :class: `~opencensus.trace.span_data.SpanData` :param span_datas: SpanData tuples to emit
[ "Translate", "the", "spans", "to", "Jaeger", "format", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L159-L220
239,955
census-instrumentation/opencensus-python
contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py
Collector.emit
def emit(self, batch): """Submits batches to Thrift HTTP Server through Binary Protocol. :type batch: :class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch` :param batch: Object to emit Jaeger spans. """ try: self.client.submitBatches([batch]) # it will call http_transport.flush() and # status code and message will be updated code = self.http_transport.code msg = self.http_transport.message if code >= 300 or code < 200: logging.error("Traces cannot be uploaded;\ HTTP status code: {}, message {}".format(code, msg)) except Exception as e: # pragma: NO COVER logging.error(getattr(e, 'message', e)) finally: if self.http_transport.isOpen(): self.http_transport.close()
python
def emit(self, batch): try: self.client.submitBatches([batch]) # it will call http_transport.flush() and # status code and message will be updated code = self.http_transport.code msg = self.http_transport.message if code >= 300 or code < 200: logging.error("Traces cannot be uploaded;\ HTTP status code: {}, message {}".format(code, msg)) except Exception as e: # pragma: NO COVER logging.error(getattr(e, 'message', e)) finally: if self.http_transport.isOpen(): self.http_transport.close()
[ "def", "emit", "(", "self", ",", "batch", ")", ":", "try", ":", "self", ".", "client", ".", "submitBatches", "(", "[", "batch", "]", ")", "# it will call http_transport.flush() and", "# status code and message will be updated", "code", "=", "self", ".", "http_tran...
Submits batches to Thrift HTTP Server through Binary Protocol. :type batch: :class:`~opencensus.ext.jaeger.trace_exporter.gen.jaeger.Batch` :param batch: Object to emit Jaeger spans.
[ "Submits", "batches", "to", "Thrift", "HTTP", "Server", "through", "Binary", "Protocol", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-jaeger/opencensus/ext/jaeger/trace_exporter/__init__.py#L369-L390
239,956
census-instrumentation/opencensus-python
opencensus/stats/view_data.py
ViewData.get_tag_values
def get_tag_values(self, tags, columns): """function to get the tag values from tags and columns""" tag_values = [] i = 0 while i < len(columns): tag_key = columns[i] if tag_key in tags: tag_values.append(tags.get(tag_key)) else: tag_values.append(None) i += 1 return tag_values
python
def get_tag_values(self, tags, columns): tag_values = [] i = 0 while i < len(columns): tag_key = columns[i] if tag_key in tags: tag_values.append(tags.get(tag_key)) else: tag_values.append(None) i += 1 return tag_values
[ "def", "get_tag_values", "(", "self", ",", "tags", ",", "columns", ")", ":", "tag_values", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "columns", ")", ":", "tag_key", "=", "columns", "[", "i", "]", "if", "tag_key", "in", "tags", ...
function to get the tag values from tags and columns
[ "function", "to", "get", "the", "tag", "values", "from", "tags", "and", "columns" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_data.py#L72-L83
239,957
census-instrumentation/opencensus-python
opencensus/stats/view_data.py
ViewData.record
def record(self, context, value, timestamp, attachments=None): """records the view data against context""" if context is None: tags = dict() else: tags = context.map tag_values = self.get_tag_values(tags=tags, columns=self.view.columns) tuple_vals = tuple(tag_values) if tuple_vals not in self.tag_value_aggregation_data_map: self.tag_value_aggregation_data_map[tuple_vals] = copy.deepcopy( self.view.aggregation.aggregation_data) self.tag_value_aggregation_data_map.get(tuple_vals).\ add_sample(value, timestamp, attachments)
python
def record(self, context, value, timestamp, attachments=None): if context is None: tags = dict() else: tags = context.map tag_values = self.get_tag_values(tags=tags, columns=self.view.columns) tuple_vals = tuple(tag_values) if tuple_vals not in self.tag_value_aggregation_data_map: self.tag_value_aggregation_data_map[tuple_vals] = copy.deepcopy( self.view.aggregation.aggregation_data) self.tag_value_aggregation_data_map.get(tuple_vals).\ add_sample(value, timestamp, attachments)
[ "def", "record", "(", "self", ",", "context", ",", "value", ",", "timestamp", ",", "attachments", "=", "None", ")", ":", "if", "context", "is", "None", ":", "tags", "=", "dict", "(", ")", "else", ":", "tags", "=", "context", ".", "map", "tag_values",...
records the view data against context
[ "records", "the", "view", "data", "against", "context" ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/stats/view_data.py#L85-L98
239,958
census-instrumentation/opencensus-python
contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py
trace_integration
def trace_integration(tracer=None): """Wrap the httplib to trace.""" log.info('Integrated module: {}'.format(MODULE_NAME)) # Wrap the httplib request function request_func = getattr( httplib.HTTPConnection, HTTPLIB_REQUEST_FUNC) wrapped_request = wrap_httplib_request(request_func) setattr(httplib.HTTPConnection, request_func.__name__, wrapped_request) # Wrap the httplib response function response_func = getattr( httplib.HTTPConnection, HTTPLIB_RESPONSE_FUNC) wrapped_response = wrap_httplib_response(response_func) setattr(httplib.HTTPConnection, response_func.__name__, wrapped_response)
python
def trace_integration(tracer=None): log.info('Integrated module: {}'.format(MODULE_NAME)) # Wrap the httplib request function request_func = getattr( httplib.HTTPConnection, HTTPLIB_REQUEST_FUNC) wrapped_request = wrap_httplib_request(request_func) setattr(httplib.HTTPConnection, request_func.__name__, wrapped_request) # Wrap the httplib response function response_func = getattr( httplib.HTTPConnection, HTTPLIB_RESPONSE_FUNC) wrapped_response = wrap_httplib_response(response_func) setattr(httplib.HTTPConnection, response_func.__name__, wrapped_response)
[ "def", "trace_integration", "(", "tracer", "=", "None", ")", ":", "log", ".", "info", "(", "'Integrated module: {}'", ".", "format", "(", "MODULE_NAME", ")", ")", "# Wrap the httplib request function", "request_func", "=", "getattr", "(", "httplib", ".", "HTTPConn...
Wrap the httplib to trace.
[ "Wrap", "the", "httplib", "to", "trace", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L41-L55
239,959
census-instrumentation/opencensus-python
contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py
wrap_httplib_request
def wrap_httplib_request(request_func): """Wrap the httplib request function to trace. Create a new span and update and close the span in the response later. """ def call(self, method, url, body, headers, *args, **kwargs): _tracer = execution_context.get_opencensus_tracer() blacklist_hostnames = execution_context.get_opencensus_attr( 'blacklist_hostnames') dest_url = '{}:{}'.format(self._dns_host, self.port) if utils.disable_tracing_hostname(dest_url, blacklist_hostnames): return request_func(self, method, url, body, headers, *args, **kwargs) _span = _tracer.start_span() _span.span_kind = span_module.SpanKind.CLIENT _span.name = '[httplib]{}'.format(request_func.__name__) # Add the request url to attributes _tracer.add_attribute_to_current_span(HTTP_URL, url) # Add the request method to attributes _tracer.add_attribute_to_current_span(HTTP_METHOD, method) # Store the current span id to thread local. execution_context.set_opencensus_attr( 'httplib/current_span_id', _span.span_id) try: headers = headers.copy() headers.update(_tracer.propagator.to_headers( _span.context_tracer.span_context)) except Exception: # pragma: NO COVER pass return request_func(self, method, url, body, headers, *args, **kwargs) return call
python
def wrap_httplib_request(request_func): def call(self, method, url, body, headers, *args, **kwargs): _tracer = execution_context.get_opencensus_tracer() blacklist_hostnames = execution_context.get_opencensus_attr( 'blacklist_hostnames') dest_url = '{}:{}'.format(self._dns_host, self.port) if utils.disable_tracing_hostname(dest_url, blacklist_hostnames): return request_func(self, method, url, body, headers, *args, **kwargs) _span = _tracer.start_span() _span.span_kind = span_module.SpanKind.CLIENT _span.name = '[httplib]{}'.format(request_func.__name__) # Add the request url to attributes _tracer.add_attribute_to_current_span(HTTP_URL, url) # Add the request method to attributes _tracer.add_attribute_to_current_span(HTTP_METHOD, method) # Store the current span id to thread local. execution_context.set_opencensus_attr( 'httplib/current_span_id', _span.span_id) try: headers = headers.copy() headers.update(_tracer.propagator.to_headers( _span.context_tracer.span_context)) except Exception: # pragma: NO COVER pass return request_func(self, method, url, body, headers, *args, **kwargs) return call
[ "def", "wrap_httplib_request", "(", "request_func", ")", ":", "def", "call", "(", "self", ",", "method", ",", "url", ",", "body", ",", "headers", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_tracer", "=", "execution_context", ".", "get_opencens...
Wrap the httplib request function to trace. Create a new span and update and close the span in the response later.
[ "Wrap", "the", "httplib", "request", "function", "to", "trace", ".", "Create", "a", "new", "span", "and", "update", "and", "close", "the", "span", "in", "the", "response", "later", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L58-L92
239,960
census-instrumentation/opencensus-python
contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py
wrap_httplib_response
def wrap_httplib_response(response_func): """Wrap the httplib response function to trace. If there is a corresponding httplib request span, update and close it. If not, return the response. """ def call(self, *args, **kwargs): _tracer = execution_context.get_opencensus_tracer() current_span_id = execution_context.get_opencensus_attr( 'httplib/current_span_id') span = _tracer.current_span() # No corresponding request span is found, request not traced. if not span or span.span_id != current_span_id: return response_func(self, *args, **kwargs) result = response_func(self, *args, **kwargs) # Add the status code to attributes _tracer.add_attribute_to_current_span( HTTP_STATUS_CODE, str(result.status)) _tracer.end_span() return result return call
python
def wrap_httplib_response(response_func): def call(self, *args, **kwargs): _tracer = execution_context.get_opencensus_tracer() current_span_id = execution_context.get_opencensus_attr( 'httplib/current_span_id') span = _tracer.current_span() # No corresponding request span is found, request not traced. if not span or span.span_id != current_span_id: return response_func(self, *args, **kwargs) result = response_func(self, *args, **kwargs) # Add the status code to attributes _tracer.add_attribute_to_current_span( HTTP_STATUS_CODE, str(result.status)) _tracer.end_span() return result return call
[ "def", "wrap_httplib_response", "(", "response_func", ")", ":", "def", "call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_tracer", "=", "execution_context", ".", "get_opencensus_tracer", "(", ")", "current_span_id", "=", "execution_con...
Wrap the httplib response function to trace. If there is a corresponding httplib request span, update and close it. If not, return the response.
[ "Wrap", "the", "httplib", "response", "function", "to", "trace", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L95-L122
239,961
census-instrumentation/opencensus-python
opencensus/metrics/export/gauge.py
get_timeseries_list
def get_timeseries_list(points, timestamp): """Convert a list of `GaugePoint`s into a list of `TimeSeries`. Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each measurement in `points`. Each series contains a single :class:`opencensus.metrics.export.point.Point` that represents the last recorded value of the measurement. :type points: list(:class:`GaugePoint`) :param points: The list of measurements to convert. :type timestamp: :class:`datetime.datetime` :param timestamp: Recording time to report, usually the current time. :rtype: list(:class:`opencensus.metrics.export.time_series.TimeSeries`) :return: A list of one `TimeSeries` for each point in `points`. """ ts_list = [] for lv, gp in points.items(): point = point_module.Point(gp.to_point_value(), timestamp) ts_list.append(time_series.TimeSeries(lv, [point], timestamp)) return ts_list
python
def get_timeseries_list(points, timestamp): ts_list = [] for lv, gp in points.items(): point = point_module.Point(gp.to_point_value(), timestamp) ts_list.append(time_series.TimeSeries(lv, [point], timestamp)) return ts_list
[ "def", "get_timeseries_list", "(", "points", ",", "timestamp", ")", ":", "ts_list", "=", "[", "]", "for", "lv", ",", "gp", "in", "points", ".", "items", "(", ")", ":", "point", "=", "point_module", ".", "Point", "(", "gp", ".", "to_point_value", "(", ...
Convert a list of `GaugePoint`s into a list of `TimeSeries`. Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each measurement in `points`. Each series contains a single :class:`opencensus.metrics.export.point.Point` that represents the last recorded value of the measurement. :type points: list(:class:`GaugePoint`) :param points: The list of measurements to convert. :type timestamp: :class:`datetime.datetime` :param timestamp: Recording time to report, usually the current time. :rtype: list(:class:`opencensus.metrics.export.time_series.TimeSeries`) :return: A list of one `TimeSeries` for each point in `points`.
[ "Convert", "a", "list", "of", "GaugePoint", "s", "into", "a", "list", "of", "TimeSeries", "." ]
992b223f7e34c5dcb65922b7d5c827e7a1351e7d
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L29-L50
239,962
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): 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
239,963
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): 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
239,964
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): 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
239,965
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): 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
239,966
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): 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
239,967
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): 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
239,968
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): 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
239,969
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): 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
239,970
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): 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
239,971
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): 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
239,972
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): 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
239,973
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): 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
239,974
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): 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
239,975
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): 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
239,976
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): 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
239,977
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): 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
239,978
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): 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
239,979
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): 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
239,980
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): 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
239,981
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): 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
239,982
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): 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
239,983
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): 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
239,984
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): 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
239,985
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): 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
239,986
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): 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
239,987
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): 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
239,988
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): 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
239,989
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): 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
239,990
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): 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
239,991
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): 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
239,992
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): 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
239,993
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): 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
239,994
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): 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
239,995
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): 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
239,996
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): 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
239,997
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): # 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
239,998
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): # 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
239,999
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): 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