repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
grpc
grpc-master/tools/buildgen/plugins/verify_duplicate_sources.py
# Copyright 2020 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen duplicate source validation plugin.""" def mako_plugin(dictionary): """The exported plugin code for verify_duplicate_sources. This validates that a certain set of libraries don't contain duplicate source files which may cause One Definition Rule (ODR) violation. """ errors = [] target_groups = ( ("gpr", "grpc", "grpc++"), ("gpr", "grpc_unsecure", "grpc++_unsecure"), ) lib_map = {lib["name"]: lib for lib in dictionary.get("libs")} for target_group in target_groups: src_map = {} for target in target_group: for src in lib_map[target]["src"]: if src.endswith(".cc"): if src in src_map: errors.append( "Source {0} is used in both {1} and {2}".format( src, src_map[src], target ) ) else: src_map[src] = target if errors: raise Exception("\n".join(errors))
1,660
35.911111
76
py
grpc
grpc-master/tools/buildgen/plugins/expand_bin_attrs.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen expand binary attributes plugin. This fills in any optional attributes. """ def mako_plugin(dictionary): """The exported plugin code for expand_filegroups. The list of libs in the build.yaml file can contain "filegroups" tags. These refer to the filegroups in the root object. We will expand and merge filegroups on the src, headers and public_headers properties. """ targets = dictionary.get("targets") default_platforms = ["windows", "posix", "linux", "mac"] for tgt in targets: tgt["flaky"] = tgt.get("flaky", False) tgt["platforms"] = sorted(tgt.get("platforms", default_platforms)) tgt["ci_platforms"] = sorted(tgt.get("ci_platforms", tgt["platforms"])) tgt["boringssl"] = tgt.get("boringssl", False) tgt["zlib"] = tgt.get("zlib", False) tgt["ares"] = tgt.get("ares", False) tgt["gtest"] = tgt.get("gtest", False) libs = dictionary.get("libs") for lib in libs: lib["boringssl"] = lib.get("boringssl", False) lib["zlib"] = lib.get("zlib", False) lib["ares"] = lib.get("ares", False)
1,705
35.297872
79
py
grpc
grpc-master/tools/buildgen/plugins/transitive_dependencies.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen transitive dependencies This takes the list of libs, node_modules, and targets from our yaml dictionary, and adds to each the transitive closure of the list of dependencies. """ def transitive_deps(lib_map, node): """Returns a list of transitive dependencies from node. Recursively iterate all dependent node in a depth-first fashion and list a result using a topological sorting. """ result = [] seen = set() start = node def recursive_helper(node): if node is None: return for dep in node.get("deps", []): if dep not in seen: seen.add(dep) next_node = lib_map.get(dep) recursive_helper(next_node) if node is not start: result.insert(0, node["name"]) recursive_helper(node) return result def mako_plugin(dictionary): """The exported plugin code for transitive_dependencies. Iterate over each list and check each item for a deps list. We add a transitive_deps property to each with the transitive closure of those dependency lists. The result list is sorted in a topological ordering. """ lib_map = {lib["name"]: lib for lib in dictionary.get("libs")} for target_name, target_list in list(dictionary.items()): for target in target_list: if isinstance(target, dict): if "deps" in target or target_name == "libs": if not "deps" in target: # make sure all the libs have the "deps" field populated target["deps"] = [] target["transitive_deps"] = transitive_deps(lib_map, target) python_dependencies = dictionary.get("python_dependencies") python_dependencies["transitive_deps"] = transitive_deps( lib_map, python_dependencies )
2,444
34.434783
80
py
grpc
grpc-master/tools/buildgen/plugins/supported_bazel_versions.py
# Copyright 2022 The gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Retrieves supported bazel versions from plaintext file.""" _SUPPORTED_VERSIONS_FILE = "bazel/supported_versions.txt" def _get_supported_bazel_versions(): versions = [] with open(_SUPPORTED_VERSIONS_FILE, "r") as f: for line in f: versions.append(line.strip()) return versions def mako_plugin(dictionary): dictionary["supported_bazel_versions"] = _get_supported_bazel_versions()
1,003
33.62069
76
py
grpc
grpc-master/tools/buildgen/plugins/list_protos.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen .proto files list plugin. This parses the list of targets from the yaml build file, and creates a list called "protos" that contains all of the proto file names. """ import re def mako_plugin(dictionary): """The exported plugin code for list_protos. Some projects generators may want to get the full list of unique .proto files that are being included in a project. This code extracts all files referenced in any library or target that ends in .proto, and builds and exports that as a list called "protos". """ libs = dictionary.get("libs", []) targets = dictionary.get("targets", []) proto_re = re.compile("(.*)\\.proto") protos = set() for lib in libs: for src in lib.get("src", []): m = proto_re.match(src) if m: protos.add(m.group(1)) for tgt in targets: for src in tgt.get("src", []): m = proto_re.match(src) if m: protos.add(m.group(1)) protos = sorted(protos) dictionary["protos"] = protos
1,650
29.574074
81
py
grpc
grpc-master/tools/buildgen/plugins/check_attrs.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen attribute validation plugin.""" def anything(): return lambda v: None def one_of(values): return lambda v: ( "{0} is not in [{1}]".format(v, values) if v not in values else None ) def subset_of(values): return lambda v: ( "{0} is not subset of [{1}]".format(v, values) if not all(e in values for e in v) else None ) VALID_ATTRIBUTE_KEYS_MAP = { "filegroup": { "deps": anything(), "headers": anything(), "plugin": anything(), "public_headers": anything(), "src": anything(), "uses": anything(), }, "lib": { "asm_src": anything(), "baselib": anything(), "boringssl": one_of((True,)), "build_system": anything(), "build": anything(), "cmake_target": anything(), "defaults": anything(), "deps_linkage": one_of(("static",)), "deps": anything(), "dll": one_of((True, "only")), "filegroups": anything(), "generate_plugin_registry": anything(), "headers": anything(), "language": one_of(("c", "c++", "csharp")), "LDFLAGS": anything(), "platforms": subset_of(("linux", "mac", "posix", "windows")), "public_headers": anything(), "secure": one_of(("check", True, False)), "src": anything(), "vs_proj_dir": anything(), "zlib": one_of((True,)), }, "target": { "args": anything(), "benchmark": anything(), "boringssl": one_of((True,)), "build": anything(), "ci_platforms": anything(), "corpus_dirs": anything(), "cpu_cost": anything(), "defaults": anything(), "deps": anything(), "dict": anything(), "exclude_configs": anything(), "exclude_iomgrs": anything(), "excluded_poll_engines": anything(), "filegroups": anything(), "flaky": one_of((True, False)), "gtest": one_of((True, False)), "headers": anything(), "language": one_of(("c", "c89", "c++", "csharp")), "maxlen": anything(), "platforms": subset_of(("linux", "mac", "posix", "windows")), "run": one_of((True, False)), "secure": one_of(("check", True, False)), "src": anything(), "timeout_seconds": anything(), "uses_polling": anything(), "vs_proj_dir": anything(), "zlib": one_of((True,)), }, "external_proto_library": { "destination": anything(), "proto_prefix": anything(), "urls": anything(), "hash": anything(), "strip_prefix": anything(), }, } def check_attributes(entity, kind, errors): attributes = VALID_ATTRIBUTE_KEYS_MAP[kind] name = entity.get("name", anything()) for key, value in list(entity.items()): if key == "name": continue validator = attributes.get(key) if validator: error = validator(value) if error: errors.append( "{0}({1}) has an invalid value for '{2}': {3}".format( name, kind, key, error ) ) else: errors.append( "{0}({1}) has an invalid attribute '{2}'".format( name, kind, key ) ) def mako_plugin(dictionary): """The exported plugin code for check_attr. This validates that filegroups, libs, and target can have only valid attributes. This is mainly for preventing build.yaml from having unnecessary and misleading attributes accidentally. """ errors = [] for filegroup in dictionary.get("filegroups", {}): check_attributes(filegroup, "filegroup", errors) for lib in dictionary.get("libs", {}): check_attributes(lib, "lib", errors) for target in dictionary.get("targets", {}): check_attributes(target, "target", errors) for target in dictionary.get("external_proto_libraries", {}): check_attributes(target, "external_proto_library", errors) if errors: raise Exception("\n".join(errors))
4,756
31.141892
76
py
grpc
grpc-master/tools/buildgen/plugins/expand_version.py
# Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Buildgen package version plugin This parses the list of targets from the yaml build file, and creates a custom version string for each language's package. """ import re LANGUAGES = [ "core", "cpp", "csharp", "node", "objc", "php", "python", "ruby", ] class Version: def __init__(self, version_str, override_major=None): self.tag = None if "-" in version_str: version_str, self.tag = version_str.split("-") self.major, self.minor, self.patch = [ int(x) for x in version_str.split(".") ] if override_major: self.major = override_major def __str__(self): """Version string in a somewhat idiomatic style for most languages""" version_str = "%d.%d.%d" % (self.major, self.minor, self.patch) if self.tag: version_str += "-%s" % self.tag return version_str def pep440(self): """Version string in Python PEP440 style""" s = "%d.%d.%d" % (self.major, self.minor, self.patch) if self.tag: # we need to translate from grpc version tags to pep440 version # tags; this code is likely to be a little ad-hoc if self.tag == "dev": s += ".dev0" elif len(self.tag) >= 3 and self.tag[0:3] == "pre": s += "rc%d" % int(self.tag[3:]) else: raise Exception( 'Don\'t know how to translate version tag "%s" to pep440' % self.tag ) return s def ruby(self): """Version string in Ruby style""" if self.tag: return "%d.%d.%d.%s" % ( self.major, self.minor, self.patch, self.tag, ) else: return "%d.%d.%d" % (self.major, self.minor, self.patch) def php(self): """Version string for PHP PECL package""" s = "%d.%d.%d" % (self.major, self.minor, self.patch) if self.tag: if self.tag == "dev": s += "dev" elif len(self.tag) >= 3 and self.tag[0:3] == "pre": s += "RC%d" % int(self.tag[3:]) else: raise Exception( 'Don\'t know how to translate version tag "%s" to PECL' " version" % self.tag ) return s def php_stability(self): """stability string for PHP PECL package.xml file""" if self.tag: return "beta" else: return "stable" def php_composer(self): """Version string for PHP Composer package""" return "%d.%d.%d" % (self.major, self.minor, self.patch) def php_current_version(self): return "7.4" def php_debian_version(self): return "buster" def mako_plugin(dictionary): """Expand version numbers: - for each language, ensure there's a language_version tag in settings (defaulting to the master version tag) - expand version strings to major, minor, patch, and tag """ settings = dictionary["settings"] version_str = settings["version"] master_version = Version(version_str) settings["version"] = master_version for language in LANGUAGES: version_tag = "%s_version" % language override_major = settings.get("%s_major_version" % language, None) if version_tag in settings: settings[version_tag] = Version( settings[version_tag], override_major=override_major ) else: settings[version_tag] = Version( version_str, override_major=override_major ) settings["protobuf_major_minor_version"] = ".".join( settings["protobuf_version"].split(".")[:2] )
4,440
30.721429
77
py
grpc
grpc-master/tools/buildgen/plugins/list_api.py
#!/usr/bin/env python3 # Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import fnmatch import os import re import sys import yaml _RE_API = r"(?:GPRAPI|GRPCAPI|CENSUSAPI)([^#;]*);" def list_c_apis(filenames): for filename in filenames: with open(filename, "r") as f: text = f.read() for m in re.finditer(_RE_API, text): api_declaration = re.sub("[ \r\n\t]+", " ", m.group(1)) type_and_name, args_and_close = api_declaration.split("(", 1) args = args_and_close[: args_and_close.rfind(")")].strip() last_space = type_and_name.rfind(" ") last_star = type_and_name.rfind("*") type_end = max(last_space, last_star) return_type = type_and_name[0 : type_end + 1].strip() name = type_and_name[type_end + 1 :].strip() yield { "return_type": return_type, "name": name, "arguments": args, "header": filename, } def headers_under(directory): for root, dirnames, filenames in os.walk(directory): for filename in fnmatch.filter(filenames, "*.h"): yield os.path.join(root, filename) def mako_plugin(dictionary): apis = [] headers = [] for lib in dictionary["libs"]: if lib["name"] in ["grpc", "gpr"]: headers.extend(lib["public_headers"]) apis.extend(list_c_apis(sorted(set(headers)))) dictionary["c_apis"] = apis if __name__ == "__main__": print( (yaml.dump([api for api in list_c_apis(headers_under("include/grpc"))])) )
2,165
29.507042
80
py
grpc
grpc-master/tools/release/release_notes.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generate draft and release notes in Markdown from Github PRs. You'll need a github API token to avoid being rate-limited. See https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/ This script collects PRs using "git log X..Y" from local repo where X and Y are tags or release branch names of previous and current releases respectively. Typically, notes are generated before the release branch is labelled so Y is almost always the name of the release branch. X is the previous release branch if this is not a patch release. Otherwise, it is the previous release tag. For example, for release v1.17.0, X will be origin/v1.16.x and for release v1.17.3, X will be v1.17.2. In both cases Y will be origin/v1.17.x. """ from collections import defaultdict import json import logging import urllib3 logging.basicConfig(level=logging.WARNING) content_header = """Draft Release Notes For {version} -- Final release notes will be generated from the PR titles that have *"release notes:yes"* label. If you have any additional notes please add them below. These will be appended to auto generated release notes. Previous release notes are [here](https://github.com/grpc/grpc/releases). **Also, look at the PRs listed below against your name.** Please apply the missing labels and make necessary corrections (like fixing the title) to the PR in Github. Final release notes will be generated just before the release on {date}. Add additional notes not in PRs -- Core - C++ - C# - Objective-C - PHP - Python - Ruby - """ rl_header = """This is release {version} ([{name}](https://github.com/grpc/grpc/blob/master/doc/g_stands_for.md)) of gRPC Core. For gRPC documentation, see [grpc.io](https://grpc.io/). For previous releases, see [Releases](https://github.com/grpc/grpc/releases). This release contains refinements, improvements, and bug fixes, with highlights listed below. """ HTML_URL = "https://github.com/grpc/grpc/pull/" API_URL = "https://api.github.com/repos/grpc/grpc/pulls/" def get_commit_log(prevRelLabel, relBranch): """Return the output of 'git log prevRelLabel..relBranch'""" import subprocess glg_command = [ "git", "log", "--pretty=oneline", "--committer=GitHub", "%s..%s" % (prevRelLabel, relBranch), ] print(("Running ", " ".join(glg_command))) return subprocess.check_output(glg_command).decode("utf-8", "ignore") def get_pr_data(pr_num): """Get the PR data from github. Return 'error' on exception""" http = urllib3.PoolManager( retries=urllib3.Retry(total=7, backoff_factor=1), timeout=4.0 ) url = API_URL + pr_num try: response = http.request( "GET", url, headers={"Authorization": "token %s" % TOKEN} ) except urllib3.exceptions.HTTPError as e: print("Request error:", e.reason) return "error" return json.loads(response.data.decode("utf-8")) def get_pr_titles(gitLogs): import re error_count = 0 # PRs with merge commits match_merge_pr = "Merge pull request #(\d+)" prlist_merge_pr = re.findall(match_merge_pr, gitLogs, re.MULTILINE) print("\nPRs matching 'Merge pull request #<num>':") print(prlist_merge_pr) print("\n") # PRs using Github's squash & merge feature match_sq = "\(#(\d+)\)$" prlist_sq = re.findall(match_sq, gitLogs, re.MULTILINE) print("\nPRs matching '[PR Description](#<num>)$'") print(prlist_sq) print("\n") prlist = prlist_merge_pr + prlist_sq langs_pr = defaultdict(list) for pr_num in prlist: pr_num = str(pr_num) print(("---------- getting data for PR " + pr_num)) pr = get_pr_data(pr_num) if pr == "error": print( ("\n***ERROR*** Error in getting data for PR " + pr_num + "\n") ) error_count += 1 continue rl_no_found = False rl_yes_found = False lang_found = False for label in pr["labels"]: if label["name"] == "release notes: yes": rl_yes_found = True elif label["name"] == "release notes: no": rl_no_found = True elif label["name"].startswith("lang/"): lang_found = True lang = label["name"].split("/")[1].lower() # lang = lang[0].upper() + lang[1:] body = pr["title"] if not body.endswith("."): body = body + "." if not pr["merged_by"]: print(("\n***ERROR***: No merge_by found for PR " + pr_num + "\n")) error_count += 1 continue prline = ( "- " + body + " ([#" + pr_num + "](" + HTML_URL + pr_num + "))" ) detail = "- " + pr["merged_by"]["login"] + "@ " + prline print(detail) # if no RL label if not rl_no_found and not rl_yes_found: print(("Release notes label missing for " + pr_num)) langs_pr["nolabel"].append(detail) elif rl_yes_found and not lang_found: print(("Lang label missing for " + pr_num)) langs_pr["nolang"].append(detail) elif rl_no_found: print(("'Release notes:no' found for " + pr_num)) langs_pr["notinrel"].append(detail) elif rl_yes_found: print( ( "'Release notes:yes' found for " + pr_num + " with lang " + lang ) ) langs_pr["inrel"].append(detail) langs_pr[lang].append(prline) return langs_pr, error_count def write_draft(langs_pr, file, version, date): file.write(content_header.format(version=version, date=date)) file.write("PRs with missing release notes label - please fix in Github\n") file.write("---\n") file.write("\n") if langs_pr["nolabel"]: langs_pr["nolabel"].sort() file.write("\n".join(langs_pr["nolabel"])) else: file.write("- None") file.write("\n") file.write("\n") file.write("PRs with missing lang label - please fix in Github\n") file.write("---\n") file.write("\n") if langs_pr["nolang"]: langs_pr["nolang"].sort() file.write("\n".join(langs_pr["nolang"])) else: file.write("- None") file.write("\n") file.write("\n") file.write( "PRs going into release notes - please check title and fix in Github." " Do not edit here.\n" ) file.write("---\n") file.write("\n") if langs_pr["inrel"]: langs_pr["inrel"].sort() file.write("\n".join(langs_pr["inrel"])) else: file.write("- None") file.write("\n") file.write("\n") file.write("PRs not going into release notes\n") file.write("---\n") file.write("\n") if langs_pr["notinrel"]: langs_pr["notinrel"].sort() file.write("\n".join(langs_pr["notinrel"])) else: file.write("- None") file.write("\n") file.write("\n") def write_rel_notes(langs_pr, file, version, name): file.write(rl_header.format(version=version, name=name)) if langs_pr["core"]: file.write("Core\n---\n\n") file.write("\n".join(langs_pr["core"])) file.write("\n") file.write("\n") if langs_pr["c++"]: file.write("C++\n---\n\n") file.write("\n".join(langs_pr["c++"])) file.write("\n") file.write("\n") if langs_pr["c#"]: file.write("C#\n---\n\n") file.write("\n".join(langs_pr["c#"])) file.write("\n") file.write("\n") if langs_pr["go"]: file.write("Go\n---\n\n") file.write("\n".join(langs_pr["go"])) file.write("\n") file.write("\n") if langs_pr["Java"]: file.write("Java\n---\n\n") file.write("\n".join(langs_pr["Java"])) file.write("\n") file.write("\n") if langs_pr["node"]: file.write("Node\n---\n\n") file.write("\n".join(langs_pr["node"])) file.write("\n") file.write("\n") if langs_pr["objc"]: file.write("Objective-C\n---\n\n") file.write("\n".join(langs_pr["objc"])) file.write("\n") file.write("\n") if langs_pr["php"]: file.write("PHP\n---\n\n") file.write("\n".join(langs_pr["php"])) file.write("\n") file.write("\n") if langs_pr["python"]: file.write("Python\n---\n\n") file.write("\n".join(langs_pr["python"])) file.write("\n") file.write("\n") if langs_pr["ruby"]: file.write("Ruby\n---\n\n") file.write("\n".join(langs_pr["ruby"])) file.write("\n") file.write("\n") if langs_pr["other"]: file.write("Other\n---\n\n") file.write("\n".join(langs_pr["other"])) file.write("\n") file.write("\n") def build_args_parser(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "release_version", type=str, help="New release version e.g. 1.14.0" ) parser.add_argument( "release_name", type=str, help="New release name e.g. gladiolus" ) parser.add_argument( "release_date", type=str, help="Release date e.g. 7/30/18" ) parser.add_argument( "previous_release_label", type=str, help="Previous release branch/tag e.g. v1.13.x", ) parser.add_argument( "release_branch", type=str, help="Current release branch e.g. origin/v1.14.x", ) parser.add_argument( "draft_filename", type=str, help="Name of the draft file e.g. draft.md" ) parser.add_argument( "release_notes_filename", type=str, help="Name of the release notes file e.g. relnotes.md", ) parser.add_argument( "--token", type=str, default="", help="GitHub API token to avoid being rate limited", ) return parser def main(): import os global TOKEN parser = build_args_parser() args = parser.parse_args() version, name, date = ( args.release_version, args.release_name, args.release_date, ) start, end = args.previous_release_label, args.release_branch TOKEN = args.token if TOKEN == "": try: TOKEN = os.environ["GITHUB_TOKEN"] except: pass if TOKEN == "": print( "Error: Github API token required. Either include param" " --token=<your github token> or set environment variable" " GITHUB_TOKEN to your github token" ) return langs_pr, error_count = get_pr_titles(get_commit_log(start, end)) draft_file, rel_file = args.draft_filename, args.release_notes_filename filename = os.path.abspath(draft_file) if os.path.exists(filename): file = open(filename, "r+") else: file = open(filename, "w") file.seek(0) write_draft(langs_pr, file, version, date) file.truncate() file.close() print(("\nDraft notes written to " + filename)) filename = os.path.abspath(rel_file) if os.path.exists(filename): file = open(filename, "r+") else: file = open(filename, "w") file.seek(0) write_rel_notes(langs_pr, file, version, name) file.truncate() file.close() print(("\nRelease notes written to " + filename)) if error_count > 0: print("\n\n*** Errors were encountered. See log. *********\n") if __name__ == "__main__": main()
12,235
29.212346
281
py
grpc
grpc-master/tools/release/verify_python_release.py
#!/usr/bin/env python3 # Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Verifies that all gRPC Python artifacts have been successfully published. This script is intended to be run from a directory containing the artifacts that have been uploaded and only the artifacts that have been uploaded. We use PyPI's JSON API to verify that the proper filenames and checksums are present. Note that PyPI may take several minutes to update its metadata. Don't have a heart attack immediately. This sanity check is a good first step, but ideally, we would automate the entire release process. """ import argparse import collections import hashlib import os import sys import requests _DEFAULT_PACKAGES = [ "grpcio", "grpcio-tools", "grpcio-status", "grpcio-health-checking", "grpcio-reflection", "grpcio-channelz", "grpcio-testing", "grpcio-admin", "grpcio-csds", ] Artifact = collections.namedtuple("Artifact", ("filename", "checksum")) def _get_md5_checksum(filename): """Calculate the md5sum for a file.""" hash_md5 = hashlib.md5() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def _get_local_artifacts(): """Get a set of artifacts representing all files in the cwd.""" return set( Artifact(f, _get_md5_checksum(f)) for f in os.listdir(os.getcwd()) ) def _get_remote_artifacts_for_package(package, version): """Get a list of artifacts based on PyPi's json metadata. Note that this data will not updated immediately after upload. In my experience, it has taken a minute on average to be fresh. """ artifacts = set() payload_resp = requests.get( "https://pypi.org/pypi/{}/{}/json".format(package, version) ) payload_resp.raise_for_status() payload = payload_resp.json() for download_info in payload["urls"]: artifacts.add( Artifact(download_info["filename"], download_info["md5_digest"]) ) return artifacts def _get_remote_artifacts_for_packages(packages, version): artifacts = set() for package in packages: artifacts |= _get_remote_artifacts_for_package(package, version) return artifacts def _verify_release(version, packages): """Compare the local artifacts to the packages uploaded to PyPI.""" local_artifacts = _get_local_artifacts() remote_artifacts = _get_remote_artifacts_for_packages(packages, version) if local_artifacts != remote_artifacts: local_but_not_remote = local_artifacts - remote_artifacts remote_but_not_local = remote_artifacts - local_artifacts if local_but_not_remote: print("The following artifacts exist locally but not remotely.") for artifact in local_but_not_remote: print(artifact) if remote_but_not_local: print("The following artifacts exist remotely but not locally.") for artifact in remote_but_not_local: print(artifact) sys.exit(1) print("Release verified successfully.") if __name__ == "__main__": parser = argparse.ArgumentParser( "Verify a release. Run this from a directory containing only the" "artifacts to be uploaded. Note that PyPI may take several minutes" "after the upload to reflect the proper metadata." ) parser.add_argument("version") parser.add_argument( "packages", nargs="*", type=str, default=_DEFAULT_PACKAGES ) args = parser.parse_args() _verify_release(args.version, args.packages)
4,163
32.312
78
py
grpc
grpc-master/examples/python/multiprocessing/server.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of multiprocess concurrency with gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from concurrent import futures import contextlib import datetime import logging import math import multiprocessing import socket import sys import time import grpc import prime_pb2 import prime_pb2_grpc _LOGGER = logging.getLogger(__name__) _ONE_DAY = datetime.timedelta(days=1) _PROCESS_COUNT = multiprocessing.cpu_count() _THREAD_CONCURRENCY = _PROCESS_COUNT def is_prime(n): for i in range(2, int(math.ceil(math.sqrt(n)))): if n % i == 0: return False else: return True class PrimeChecker(prime_pb2_grpc.PrimeCheckerServicer): def check(self, request, context): _LOGGER.info("Determining primality of %s", request.candidate) return prime_pb2.Primality(isPrime=is_prime(request.candidate)) def _wait_forever(server): try: while True: time.sleep(_ONE_DAY.total_seconds()) except KeyboardInterrupt: server.stop(None) def _run_server(bind_address): """Start a server in a subprocess.""" _LOGGER.info("Starting new server.") options = (("grpc.so_reuseport", 1),) server = grpc.server( futures.ThreadPoolExecutor( max_workers=_THREAD_CONCURRENCY, ), options=options, ) prime_pb2_grpc.add_PrimeCheckerServicer_to_server(PrimeChecker(), server) server.add_insecure_port(bind_address) server.start() _wait_forever(server) @contextlib.contextmanager def _reserve_port(): """Find and reserve a port for all subprocesses to use.""" sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 0: raise RuntimeError("Failed to set SO_REUSEPORT.") sock.bind(("", 0)) try: yield sock.getsockname()[1] finally: sock.close() def main(): with _reserve_port() as port: bind_address = "localhost:{}".format(port) _LOGGER.info("Binding to '%s'", bind_address) sys.stdout.flush() workers = [] for _ in range(_PROCESS_COUNT): # NOTE: It is imperative that the worker subprocesses be forked before # any gRPC servers start up. See # https://github.com/grpc/grpc/issues/16001 for more details. worker = multiprocessing.Process( target=_run_server, args=(bind_address,) ) worker.start() workers.append(worker) for worker in workers: worker.join() if __name__ == "__main__": handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("[PID %(process)d] %(message)s") handler.setFormatter(formatter) _LOGGER.addHandler(handler) _LOGGER.setLevel(logging.INFO) main()
3,540
28.508333
82
py
grpc
grpc-master/examples/python/multiprocessing/client.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of multiprocessing concurrency with gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import atexit import logging import multiprocessing import operator import sys import grpc import prime_pb2 import prime_pb2_grpc _PROCESS_COUNT = 8 _MAXIMUM_CANDIDATE = 10000 # Each worker process initializes a single channel after forking. # It's regrettable, but to ensure that each subprocess only has to instantiate # a single channel to be reused across all RPCs, we use globals. _worker_channel_singleton = None _worker_stub_singleton = None _LOGGER = logging.getLogger(__name__) def _shutdown_worker(): _LOGGER.info("Shutting worker process down.") if _worker_channel_singleton is not None: _worker_channel_singleton.close() def _initialize_worker(server_address): global _worker_channel_singleton # pylint: disable=global-statement global _worker_stub_singleton # pylint: disable=global-statement _LOGGER.info("Initializing worker process.") _worker_channel_singleton = grpc.insecure_channel(server_address) _worker_stub_singleton = prime_pb2_grpc.PrimeCheckerStub( _worker_channel_singleton ) atexit.register(_shutdown_worker) def _run_worker_query(primality_candidate): _LOGGER.info("Checking primality of %s.", primality_candidate) return _worker_stub_singleton.check( prime_pb2.PrimeCandidate(candidate=primality_candidate) ) def _calculate_primes(server_address): worker_pool = multiprocessing.Pool( processes=_PROCESS_COUNT, initializer=_initialize_worker, initargs=(server_address,), ) check_range = range(2, _MAXIMUM_CANDIDATE) primality = worker_pool.map(_run_worker_query, check_range) primes = zip(check_range, map(operator.attrgetter("isPrime"), primality)) return tuple(primes) def main(): msg = "Determine the primality of the first {} integers.".format( _MAXIMUM_CANDIDATE ) parser = argparse.ArgumentParser(description=msg) parser.add_argument( "server_address", help="The address of the server (e.g. localhost:50051)", ) args = parser.parse_args() primes = _calculate_primes(args.server_address) print(primes) if __name__ == "__main__": handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("[PID %(process)d] %(message)s") handler.setFormatter(formatter) _LOGGER.addHandler(handler) _LOGGER.setLevel(logging.INFO) main()
3,149
30.5
78
py
grpc
grpc-master/examples/python/multiprocessing/test/_multiprocessing_example_test.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for multiprocessing example.""" import ast import logging import math import os import re import subprocess import tempfile import unittest _BINARY_DIR = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") ) _SERVER_PATH = os.path.join(_BINARY_DIR, "server") _CLIENT_PATH = os.path.join(_BINARY_DIR, "client") def is_prime(n): for i in range(2, int(math.ceil(math.sqrt(n)))): if n % i == 0: return False else: return True def _get_server_address(server_stream): while True: server_stream.seek(0) line = server_stream.readline() while line: matches = re.search("Binding to '(.+)'", line) if matches is not None: return matches.groups()[0] line = server_stream.readline() class MultiprocessingExampleTest(unittest.TestCase): def test_multiprocessing_example(self): server_stdout = tempfile.TemporaryFile(mode="r") server_process = subprocess.Popen((_SERVER_PATH,), stdout=server_stdout) server_address = _get_server_address(server_stdout) client_stdout = tempfile.TemporaryFile(mode="r") client_process = subprocess.Popen( ( _CLIENT_PATH, server_address, ), stdout=client_stdout, ) client_process.wait() server_process.terminate() client_stdout.seek(0) results = ast.literal_eval(client_stdout.read().strip().split("\n")[-1]) values = tuple(result[0] for result in results) self.assertSequenceEqual(range(2, 10000), values) for result in results: self.assertEqual(is_prime(result[0]), result[1]) if __name__ == "__main__": logging.basicConfig() unittest.main(verbosity=2)
2,414
30.363636
80
py
grpc
grpc-master/examples/python/debug/asyncio_debug_server.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO example of utilizing Channelz feature.""" import argparse import asyncio import logging import random import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) # TODO: Suppress until the macOS segfault fix rolled out from grpc_channelz.v1 import channelz # pylint: disable=wrong-import-position _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _RANDOM_FAILURE_RATE = 0.3 class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self, failure_rate): self._failure_rate = failure_rate async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext, ) -> helloworld_pb2.HelloReply: if random.random() < self._failure_rate: context.abort( grpc.StatusCode.UNAVAILABLE, "Randomly injected failure." ) return helloworld_pb2.HelloReply(message=f"Hello, {request.name}!") def create_server(addr: str, failure_rate: float) -> grpc.aio.Server: server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server( FaultInjectGreeter(failure_rate), server ) # Add Channelz Servicer to the gRPC server channelz.add_channelz_servicer(server) server.add_insecure_port(addr) return server async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to listen on", ) parser.add_argument( "--failure_rate", nargs=1, type=float, default=0.3, help="a float indicates the percentage of failed message injections", ) args = parser.parse_args() server = create_server(addr=args.addr, failure_rate=args.failure_rate) await server.start() await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main())
2,666
28.307692
78
py
grpc
grpc-master/examples/python/debug/send_message.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Send multiple greeting messages to the backend.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) def process(stub, request): try: response = stub.SayHello(request) except grpc.RpcError as rpc_error: print("Received error: %s" % rpc_error) else: print("Received message: %s" % response) def run(addr, n): with grpc.insecure_channel(addr) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) request = helloworld_pb2.HelloRequest(name="you") for _ in range(n): process(stub, request) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to request", ) parser.add_argument( "-n", nargs=1, type=int, default=10, help="an integer for number of messages to sent", ) args = parser.parse_args() run(addr=args.addr, n=args.n) if __name__ == "__main__": logging.basicConfig() main()
1,846
25.385714
74
py
grpc
grpc-master/examples/python/debug/get_stats.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Poll statistics from the server.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import grpc from grpc_channelz.v1 import channelz_pb2 from grpc_channelz.v1 import channelz_pb2_grpc def run(addr): with grpc.insecure_channel(addr) as channel: channelz_stub = channelz_pb2_grpc.ChannelzStub(channel) # This RPC pulls server-level metrics, like sent/received messages, # succeeded/failed RPCs. For more info see: # https://github.com/grpc/grpc/blob/master/src/proto/grpc/channelz/channelz.proto response = channelz_stub.GetServers(channelz_pb2.GetServersRequest()) print(f"Info for all servers: {response}") def main(): parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to request", ) args = parser.parse_args() run(addr=args.addr) if __name__ == "__main__": logging.basicConfig() main()
1,667
29.888889
89
py
grpc
grpc-master/examples/python/debug/debug_server.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python example of utilizing Channelz feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from concurrent import futures import logging import random import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) # TODO: Suppress until the macOS segfault fix rolled out from grpc_channelz.v1 import channelz # pylint: disable=wrong-import-position _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _RANDOM_FAILURE_RATE = 0.3 class FaultInjectGreeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self, failure_rate): self._failure_rate = failure_rate def SayHello(self, request, context): if random.random() < self._failure_rate: context.abort( grpc.StatusCode.UNAVAILABLE, "Randomly injected failure." ) return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def create_server(addr, failure_rate): server = grpc.server(futures.ThreadPoolExecutor()) helloworld_pb2_grpc.add_GreeterServicer_to_server( FaultInjectGreeter(failure_rate), server ) # Add Channelz Servicer to the gRPC server channelz.add_channelz_servicer(server) server.add_insecure_port(addr) return server def main(): parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to listen on", ) parser.add_argument( "--failure_rate", nargs=1, type=float, default=0.3, help="a float indicates the percentage of failed message injections", ) args = parser.parse_args() server = create_server(addr=args.addr, failure_rate=args.failure_rate) server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
2,587
27.43956
78
py
grpc
grpc-master/examples/python/debug/asyncio_send_message.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Send multiple greeting messages to the backend.""" import argparse import asyncio import logging import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) async def process( stub: helloworld_pb2_grpc.GreeterStub, request: helloworld_pb2.HelloRequest ) -> None: try: response = await stub.SayHello(request) except grpc.aio.AioRpcError as rpc_error: print(f"Received error: {rpc_error}") else: print(f"Received message: {response}") async def run(addr: str, n: int) -> None: async with grpc.aio.insecure_channel(addr) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) request = helloworld_pb2.HelloRequest(name="you") for _ in range(n): await process(stub, request) async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to request", ) parser.add_argument( "-n", nargs=1, type=int, default=10, help="an integer for number of messages to sent", ) args = parser.parse_args() await run(addr=args.addr, n=args.n) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main())
1,965
27.492754
79
py
grpc
grpc-master/examples/python/debug/asyncio_get_stats.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Poll statistics from the server.""" import argparse import asyncio import logging import grpc from grpc_channelz.v1 import channelz_pb2 from grpc_channelz.v1 import channelz_pb2_grpc async def run(addr: str) -> None: async with grpc.aio.insecure_channel(addr) as channel: channelz_stub = channelz_pb2_grpc.ChannelzStub(channel) response = await channelz_stub.GetServers( channelz_pb2.GetServersRequest(start_server_id=0) ) print("Info for all servers: %s" % response) async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--addr", nargs=1, type=str, default="[::]:50051", help="the address to request", ) args = parser.parse_args() run(addr=args.addr) if __name__ == "__main__": logging.basicConfig() asyncio.get_event_loop().run_until_complete(main())
1,489
28.8
74
py
grpc
grpc-master/examples/python/debug/test/_debug_example_test.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for gRPC Python debug example.""" import asyncio import logging import unittest from examples.python.debug import asyncio_debug_server from examples.python.debug import asyncio_get_stats from examples.python.debug import asyncio_send_message from examples.python.debug import debug_server from examples.python.debug import get_stats from examples.python.debug import send_message _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _FAILURE_RATE = 0.5 _NUMBER_OF_MESSAGES = 100 _ADDR_TEMPLATE = "localhost:%d" class DebugExampleTest(unittest.TestCase): def test_channelz_example(self): server = debug_server.create_server( addr="[::]:0", failure_rate=_FAILURE_RATE ) port = server.add_insecure_port("[::]:0") server.start() address = _ADDR_TEMPLATE % port send_message.run(addr=address, n=_NUMBER_OF_MESSAGES) get_stats.run(addr=address) server.stop(None) # No unhandled exception raised, test passed! def test_asyncio_channelz_example(self): async def body(): server = asyncio_debug_server.create_server( addr="[::]:0", failure_rate=_FAILURE_RATE ) port = server.add_insecure_port("[::]:0") await server.start() address = _ADDR_TEMPLATE % port await asyncio_send_message.run(addr=address, n=_NUMBER_OF_MESSAGES) await asyncio_get_stats.run(addr=address) await server.stop(None) # No unhandled exception raised, test passed! asyncio.get_event_loop().run_until_complete(body()) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) unittest.main(verbosity=2)
2,330
32.3
79
py
grpc
grpc-master/examples/python/no_codegen/greeter_server.py
# Copyright 2020 The gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import logging import grpc protos, services = grpc.protos_and_services("helloworld.proto") class Greeter(services.GreeterServicer): def SayHello(self, request, context): return protos.HelloReply(message="Hello, %s!" % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) services.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:50051") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
1,241
30.05
74
py
grpc
grpc-master/examples/python/no_codegen/greeter_client.py
# Copyright 2020 The gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Hello World without using protoc. This example parses message and service schemas directly from a .proto file on the filesystem. Several APIs used in this example are in an experimental state. """ from __future__ import print_function import logging import grpc import grpc.experimental # NOTE: The path to the .proto file must be reachable from an entry # on sys.path. Use sys.path.insert or set the $PYTHONPATH variable to # import from files located elsewhere on the filesystem. protos = grpc.protos("helloworld.proto") services = grpc.services("helloworld.proto") logging.basicConfig() response = services.Greeter.SayHello( protos.HelloRequest(name="you"), "localhost:50051", insecure=True ) print("Greeter client received: " + response.message)
1,347
31.095238
74
py
grpc
grpc-master/examples/python/lb_policies/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/lb_policies/greeter_server.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def serve(): port = "50051" server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:" + port) server.start() print("Server started, listening on " + port) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
1,322
30.5
77
py
grpc
grpc-master/examples/python/lb_policies/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/lb_policies/greeter_client.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter client.""" import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): print("Will try to greet world ...") options = (("grpc.lb_policy_name", "round_robin"),) # Load balancing takes effect when the DNS server returns multiple IPs for the DNS hostname. # Replace "localhost" with such hostname to see the round robin LB policy take effect. with grpc.insecure_channel("localhost:50051", options=options) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() run()
1,356
35.675676
96
py
grpc
grpc-master/examples/python/errors/server.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example sends out rich error status from server-side.""" from concurrent import futures import logging import threading from google.protobuf import any_pb2 from google.rpc import code_pb2 from google.rpc import error_details_pb2 from google.rpc import status_pb2 import grpc from grpc_status import rpc_status from examples.protos import helloworld_pb2 from examples.protos import helloworld_pb2_grpc def create_greet_limit_exceed_error_status(name): detail = any_pb2.Any() detail.Pack( error_details_pb2.QuotaFailure( violations=[ error_details_pb2.QuotaFailure.Violation( subject="name: %s" % name, description="Limit one greeting per person", ) ], ) ) return status_pb2.Status( code=code_pb2.RESOURCE_EXHAUSTED, message="Request limit exceeded.", details=[detail], ) class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self): self._lock = threading.RLock() self._greeted = set() def SayHello(self, request, context): with self._lock: if request.name in self._greeted: rich_status = create_greet_limit_exceed_error_status( request.name ) context.abort_with_status(rpc_status.to_status(rich_status)) else: self._greeted.add(request.name) return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def create_server(server_address): server = grpc.server(futures.ThreadPoolExecutor()) helloworld_pb2_grpc.add_GreeterServicer_to_server(LimitedGreeter(), server) port = server.add_insecure_port(server_address) return server, port def serve(server): server.start() server.wait_for_termination() def main(): server, unused_port = create_server("[::]:50051") serve(server) if __name__ == "__main__": logging.basicConfig() main()
2,603
28.931034
79
py
grpc
grpc-master/examples/python/errors/client.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example handles rich error status in client-side.""" from __future__ import print_function import logging from google.rpc import error_details_pb2 import grpc from grpc_status import rpc_status from examples.protos import helloworld_pb2 from examples.protos import helloworld_pb2_grpc _LOGGER = logging.getLogger(__name__) def process(stub): try: response = stub.SayHello(helloworld_pb2.HelloRequest(name="Alice")) _LOGGER.info("Call success: %s", response.message) except grpc.RpcError as rpc_error: _LOGGER.error("Call failure: %s", rpc_error) status = rpc_status.from_call(rpc_error) for detail in status.details: if detail.Is(error_details_pb2.QuotaFailure.DESCRIPTOR): info = error_details_pb2.QuotaFailure() detail.Unpack(info) _LOGGER.error("Quota failure: %s", info) else: raise RuntimeError("Unexpected failure: %s" % detail) def main(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) process(stub) if __name__ == "__main__": logging.basicConfig() main()
1,962
32.844828
78
py
grpc
grpc-master/examples/python/errors/test/_error_handling_example_test.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests of the error handling example.""" # NOTE(lidiz) This module only exists in Bazel BUILD file, for more details # please refer to comments in the "bazel_namespace_package_hack" module. try: from tests import bazel_namespace_package_hack bazel_namespace_package_hack.sys_path_to_site_dir_hack() except ImportError: pass import logging import unittest import grpc from examples.protos import helloworld_pb2_grpc from examples.python.errors import client as error_handling_client from examples.python.errors import server as error_handling_server class ErrorHandlingExampleTest(unittest.TestCase): def setUp(self): self._server, port = error_handling_server.create_server("[::]:0") self._server.start() self._channel = grpc.insecure_channel("localhost:%d" % port) def tearDown(self): self._channel.close() self._server.stop(None) def test_error_handling_example(self): stub = helloworld_pb2_grpc.GreeterStub(self._channel) error_handling_client.process(stub) error_handling_client.process(stub) # No unhandled exception raised, test passed! if __name__ == "__main__": logging.basicConfig() unittest.main(verbosity=2)
1,816
32.036364
75
py
grpc
grpc-master/examples/python/compression/server.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of compression on the server side with gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from concurrent import futures import logging import threading import grpc from examples.protos import helloworld_pb2 from examples.protos import helloworld_pb2_grpc _DESCRIPTION = "A server capable of compression." _COMPRESSION_OPTIONS = { "none": grpc.Compression.NoCompression, "deflate": grpc.Compression.Deflate, "gzip": grpc.Compression.Gzip, } _LOGGER = logging.getLogger(__name__) _SERVER_HOST = "localhost" class Greeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self, no_compress_every_n): super(Greeter, self).__init__() self._no_compress_every_n = 0 self._request_counter = 0 self._counter_lock = threading.RLock() def _should_suppress_compression(self): suppress_compression = False with self._counter_lock: if ( self._no_compress_every_n and self._request_counter % self._no_compress_every_n == 0 ): suppress_compression = True self._request_counter += 1 return suppress_compression def SayHello(self, request, context): if self._should_suppress_compression(): context.set_response_compression(grpc.Compression.NoCompression) return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def run_server(server_compression, no_compress_every_n, port): server = grpc.server( futures.ThreadPoolExecutor(), compression=server_compression, options=(("grpc.so_reuseport", 1),), ) helloworld_pb2_grpc.add_GreeterServicer_to_server( Greeter(no_compress_every_n), server ) address = "{}:{}".format(_SERVER_HOST, port) server.add_insecure_port(address) server.start() print("Server listening at '{}'".format(address)) server.wait_for_termination() def main(): parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument( "--server_compression", default="none", nargs="?", choices=_COMPRESSION_OPTIONS.keys(), help="The default compression method for the server.", ) parser.add_argument( "--no_compress_every_n", type=int, default=0, nargs="?", help="If set, every nth reply will be uncompressed.", ) parser.add_argument( "--port", type=int, default=50051, nargs="?", help="The port on which the server will listen.", ) args = parser.parse_args() run_server( _COMPRESSION_OPTIONS[args.server_compression], args.no_compress_every_n, args.port, ) if __name__ == "__main__": logging.basicConfig() main()
3,476
29.234783
77
py
grpc
grpc-master/examples/python/compression/client.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of compression on the client side with gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import grpc from examples.protos import helloworld_pb2 from examples.protos import helloworld_pb2_grpc _DESCRIPTION = "A client capable of compression." _COMPRESSION_OPTIONS = { "none": grpc.Compression.NoCompression, "deflate": grpc.Compression.Deflate, "gzip": grpc.Compression.Gzip, } _LOGGER = logging.getLogger(__name__) def run_client(channel_compression, call_compression, target): with grpc.insecure_channel( target, compression=channel_compression ) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello( helloworld_pb2.HelloRequest(name="you"), compression=call_compression, wait_for_ready=True, ) print("Response: {}".format(response)) def main(): parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument( "--channel_compression", default="none", nargs="?", choices=_COMPRESSION_OPTIONS.keys(), help="The compression method to use for the channel.", ) parser.add_argument( "--call_compression", default="none", nargs="?", choices=_COMPRESSION_OPTIONS.keys(), help="The compression method to use for an individual call.", ) parser.add_argument( "--server", default="localhost:50051", type=str, nargs="?", help="The host-port pair at which to reach the server.", ) args = parser.parse_args() channel_compression = _COMPRESSION_OPTIONS[args.channel_compression] call_compression = _COMPRESSION_OPTIONS[args.call_compression] run_client(channel_compression, call_compression, args.server) if __name__ == "__main__": logging.basicConfig() main()
2,568
29.951807
74
py
grpc
grpc-master/examples/python/compression/test/compression_example_test.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for compression example.""" import contextlib import os import socket import subprocess import unittest _BINARY_DIR = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") ) _SERVER_PATH = os.path.join(_BINARY_DIR, "server") _CLIENT_PATH = os.path.join(_BINARY_DIR, "client") @contextlib.contextmanager def _get_port(): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 0: raise RuntimeError("Failed to set SO_REUSEPORT.") sock.bind(("", 0)) try: yield sock.getsockname()[1] finally: sock.close() class CompressionExampleTest(unittest.TestCase): def test_compression_example(self): with _get_port() as test_port: server_process = subprocess.Popen( ( _SERVER_PATH, "--port", str(test_port), "--server_compression", "gzip", ) ) try: server_target = "localhost:{}".format(test_port) client_process = subprocess.Popen( ( _CLIENT_PATH, "--server", server_target, "--channel_compression", "gzip", ) ) client_return_code = client_process.wait() self.assertEqual(0, client_return_code) self.assertIsNone(server_process.poll()) finally: server_process.kill() server_process.wait() if __name__ == "__main__": unittest.main(verbosity=2)
2,415
31.213333
74
py
grpc
grpc-master/examples/python/auth/_credentials.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loading SSL credentials for gRPC Python authentication example.""" import os def _load_credential_from_file(filepath): real_path = os.path.join(os.path.dirname(__file__), filepath) with open(real_path, "rb") as f: return f.read() SERVER_CERTIFICATE = _load_credential_from_file("credentials/localhost.crt") SERVER_CERTIFICATE_KEY = _load_credential_from_file("credentials/localhost.key") ROOT_CERTIFICATE = _load_credential_from_file("credentials/root.crt")
1,062
36.964286
80
py
grpc
grpc-master/examples/python/auth/async_customized_auth_server.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Server of the Python AsyncIO example of customizing authentication mechanism.""" import argparse import asyncio import logging from typing import Awaitable, Callable, Tuple import _credentials import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _LISTEN_ADDRESS_TEMPLATE = "localhost:%d" _SIGNATURE_HEADER_KEY = "x-signature" class SignatureValidationInterceptor(grpc.aio.ServerInterceptor): def __init__(self): def abort(ignored_request, context: grpc.aio.ServicerContext) -> None: context.abort(grpc.StatusCode.UNAUTHENTICATED, "Invalid signature") self._abort_handler = grpc.unary_unary_rpc_method_handler(abort) async def intercept_service( self, continuation: Callable[ [grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler] ], handler_call_details: grpc.HandlerCallDetails, ) -> grpc.RpcMethodHandler: # Example HandlerCallDetails object: # _HandlerCallDetails( # method=u'/helloworld.Greeter/SayHello', # invocation_metadata=...) method_name = handler_call_details.method.split("/")[-1] expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1]) if expected_metadata in handler_call_details.invocation_metadata: return await continuation(handler_call_details) else: return self._abort_handler class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, unused_context ) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) async def run_server(port: int) -> Tuple[grpc.aio.Server, int]: # Bind interceptor to server server = grpc.aio.server(interceptors=(SignatureValidationInterceptor(),)) helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server) # Loading credentials server_credentials = grpc.ssl_server_credentials( ( ( _credentials.SERVER_CERTIFICATE_KEY, _credentials.SERVER_CERTIFICATE, ), ) ) # Pass down credentials port = server.add_secure_port( _LISTEN_ADDRESS_TEMPLATE % port, server_credentials ) await server.start() return server, port async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--port", nargs="?", type=int, default=50051, help="the listening port" ) args = parser.parse_args() server, port = await run_server(args.port) logging.info("Server is listening at port :%d", port) await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.run(main())
3,498
31.700935
83
py
grpc
grpc-master/examples/python/auth/async_customized_auth_client.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client of the Python AsyncIO example of customizing authentication mechanism.""" import argparse import asyncio import logging import _credentials import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _SERVER_ADDR_TEMPLATE = "localhost:%d" _SIGNATURE_HEADER_KEY = "x-signature" class AuthGateway(grpc.AuthMetadataPlugin): def __call__( self, context: grpc.AuthMetadataContext, callback: grpc.AuthMetadataPluginCallback, ) -> None: """Implements authentication by passing metadata to a callback. Implementations of this method must not block. Args: context: An AuthMetadataContext providing information on the RPC that the plugin is being called to authenticate. callback: An AuthMetadataPluginCallback to be invoked either synchronously or asynchronously. """ # Example AuthMetadataContext object: # AuthMetadataContext( # service_url=u'https://localhost:50051/helloworld.Greeter', # method_name=u'SayHello') signature = context.method_name[::-1] callback(((_SIGNATURE_HEADER_KEY, signature),), None) def create_client_channel(addr: str) -> grpc.aio.Channel: # Call credential object will be invoked for every single RPC call_credentials = grpc.metadata_call_credentials( AuthGateway(), name="auth gateway" ) # Channel credential will be valid for the entire channel channel_credential = grpc.ssl_channel_credentials( _credentials.ROOT_CERTIFICATE ) # Combining channel credentials and call credentials together composite_credentials = grpc.composite_channel_credentials( channel_credential, call_credentials, ) channel = grpc.aio.secure_channel(addr, composite_credentials) return channel async def send_rpc(channel: grpc.aio.Channel) -> helloworld_pb2.HelloReply: stub = helloworld_pb2_grpc.GreeterStub(channel) request = helloworld_pb2.HelloRequest(name="you") try: response = await stub.SayHello(request) except grpc.RpcError as rpc_error: _LOGGER.error("Received error: %s", rpc_error) return rpc_error else: _LOGGER.info("Received message: %s", response) return response async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument( "--port", nargs="?", type=int, default=50051, help="the address of server", ) args = parser.parse_args() channel = create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) await send_rpc(channel) await channel.close() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.run(main())
3,457
31.018519
83
py
grpc
grpc-master/examples/python/auth/customized_auth_server.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Server of the Python example of customizing authentication mechanism.""" import argparse from concurrent import futures import contextlib import logging import _credentials import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _LISTEN_ADDRESS_TEMPLATE = "localhost:%d" _SIGNATURE_HEADER_KEY = "x-signature" class SignatureValidationInterceptor(grpc.ServerInterceptor): def __init__(self): def abort(ignored_request, context): context.abort(grpc.StatusCode.UNAUTHENTICATED, "Invalid signature") self._abortion = grpc.unary_unary_rpc_method_handler(abort) def intercept_service(self, continuation, handler_call_details): # Example HandlerCallDetails object: # _HandlerCallDetails( # method=u'/helloworld.Greeter/SayHello', # invocation_metadata=...) method_name = handler_call_details.method.split("/")[-1] expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1]) if expected_metadata in handler_call_details.invocation_metadata: return continuation(handler_call_details) else: return self._abortion class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, unused_context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) @contextlib.contextmanager def run_server(port): # Bind interceptor to server server = grpc.server( futures.ThreadPoolExecutor(), interceptors=(SignatureValidationInterceptor(),), ) helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server) # Loading credentials server_credentials = grpc.ssl_server_credentials( ( ( _credentials.SERVER_CERTIFICATE_KEY, _credentials.SERVER_CERTIFICATE, ), ) ) # Pass down credentials port = server.add_secure_port( _LISTEN_ADDRESS_TEMPLATE % port, server_credentials ) server.start() try: yield server, port finally: server.stop(0) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--port", nargs="?", type=int, default=50051, help="the listening port" ) args = parser.parse_args() with run_server(args.port) as (server, port): logging.info("Server is listening at port :%d", port) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
3,220
29.386792
79
py
grpc
grpc-master/examples/python/auth/customized_auth_client.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client of the Python example of customizing authentication mechanism.""" import argparse import contextlib import logging import _credentials import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) _SERVER_ADDR_TEMPLATE = "localhost:%d" _SIGNATURE_HEADER_KEY = "x-signature" class AuthGateway(grpc.AuthMetadataPlugin): def __call__(self, context, callback): """Implements authentication by passing metadata to a callback. Implementations of this method must not block. Args: context: An AuthMetadataContext providing information on the RPC that the plugin is being called to authenticate. callback: An AuthMetadataPluginCallback to be invoked either synchronously or asynchronously. """ # Example AuthMetadataContext object: # AuthMetadataContext( # service_url=u'https://localhost:50051/helloworld.Greeter', # method_name=u'SayHello') signature = context.method_name[::-1] # NOTE: The metadata keys provided to the callback must be lower-cased. callback(((_SIGNATURE_HEADER_KEY, signature),), None) @contextlib.contextmanager def create_client_channel(addr): # Call credential object will be invoked for every single RPC call_credentials = grpc.metadata_call_credentials( AuthGateway(), name="auth gateway" ) # Channel credential will be valid for the entire channel channel_credential = grpc.ssl_channel_credentials( _credentials.ROOT_CERTIFICATE ) # Combining channel credentials and call credentials together composite_credentials = grpc.composite_channel_credentials( channel_credential, call_credentials, ) channel = grpc.secure_channel(addr, composite_credentials) yield channel def send_rpc(channel): stub = helloworld_pb2_grpc.GreeterStub(channel) request = helloworld_pb2.HelloRequest(name="you") try: response = stub.SayHello(request) except grpc.RpcError as rpc_error: _LOGGER.error("Received error: %s", rpc_error) return rpc_error else: _LOGGER.info("Received message: %s", response) return response def main(): parser = argparse.ArgumentParser() parser.add_argument( "--port", nargs="?", type=int, default=50051, help="the address of server", ) args = parser.parse_args() with create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) as channel: send_rpc(channel) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
3,324
30.666667
79
py
grpc
grpc-master/examples/python/auth/test/_auth_example_test.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for gRPC Python authentication example.""" import asyncio import unittest import grpc from examples.python.auth import _credentials from examples.python.auth import async_customized_auth_client from examples.python.auth import async_customized_auth_server from examples.python.auth import customized_auth_client from examples.python.auth import customized_auth_server _SERVER_ADDR_TEMPLATE = "localhost:%d" class AuthExampleTest(unittest.TestCase): def test_successful_call(self): with customized_auth_server.run_server(0) as (_, port): with customized_auth_client.create_client_channel( _SERVER_ADDR_TEMPLATE % port ) as channel: customized_auth_client.send_rpc(channel) # No unhandled exception raised, test passed! def test_no_channel_credential(self): with customized_auth_server.run_server(0) as (_, port): with grpc.insecure_channel(_SERVER_ADDR_TEMPLATE % port) as channel: resp = customized_auth_client.send_rpc(channel) self.assertEqual(resp.code(), grpc.StatusCode.UNAVAILABLE) def test_no_call_credential(self): with customized_auth_server.run_server(0) as (_, port): channel_credential = grpc.ssl_channel_credentials( _credentials.ROOT_CERTIFICATE ) with grpc.secure_channel( _SERVER_ADDR_TEMPLATE % port, channel_credential ) as channel: resp = customized_auth_client.send_rpc(channel) self.assertEqual(resp.code(), grpc.StatusCode.UNAUTHENTICATED) def test_successful_call_asyncio(self): async def test_body(): server, port = await async_customized_auth_server.run_server(0) channel = async_customized_auth_client.create_client_channel( _SERVER_ADDR_TEMPLATE % port ) await async_customized_auth_client.send_rpc(channel) await channel.close() await server.stop(0) # No unhandled exception raised, test passed! asyncio.get_event_loop().run_until_complete(test_body()) if __name__ == "__main__": unittest.main(verbosity=2)
2,815
38.111111
80
py
grpc
grpc-master/examples/python/xds/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/xds/server.py
# Copyright 2020 The gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server.""" import argparse from concurrent import futures import logging import socket import grpc from grpc_health.v1 import health from grpc_health.v1 import health_pb2 from grpc_health.v1 import health_pb2_grpc from grpc_reflection.v1alpha import reflection import helloworld_pb2 import helloworld_pb2_grpc _DESCRIPTION = "A general purpose phony server." _LISTEN_HOST = "0.0.0.0" _THREAD_POOL_SIZE = 256 logger = logging.getLogger() console_handler = logging.StreamHandler() formatter = logging.Formatter(fmt="%(asctime)s: %(levelname)-8s %(message)s") console_handler.setFormatter(formatter) logger.addHandler(console_handler) class Greeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self, hostname: str): self._hostname = hostname if hostname else socket.gethostname() def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.ServicerContext, ) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply( message=f"Hello {request.name} from {self._hostname}!" ) def _configure_maintenance_server( server: grpc.Server, maintenance_port: int ) -> None: listen_address = f"{_LISTEN_HOST}:{maintenance_port}" server.add_insecure_port(listen_address) # Create a health check servicer. We use the non-blocking implementation # to avoid thread starvation. health_servicer = health.HealthServicer( experimental_non_blocking=True, experimental_thread_pool=futures.ThreadPoolExecutor( max_workers=_THREAD_POOL_SIZE ), ) # Create a tuple of all of the services we want to export via reflection. services = tuple( service.full_name for service in helloworld_pb2.DESCRIPTOR.services_by_name.values() ) + (reflection.SERVICE_NAME, health.SERVICE_NAME) # Mark all services as healthy. health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server) for service in services: health_servicer.set(service, health_pb2.HealthCheckResponse.SERVING) reflection.enable_server_reflection(services, server) def _configure_greeter_server( server: grpc.Server, port: int, secure_mode: bool, hostname ) -> None: # Add the application servicer to the server. helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(hostname), server) listen_address = f"{_LISTEN_HOST}:{port}" if not secure_mode: server.add_insecure_port(listen_address) else: # Use xDS credentials. logger.info("Running with xDS Server credentials") # Fall back to insecure credentials. server_fallback_creds = grpc.insecure_server_credentials() server_creds = grpc.xds_server_credentials(server_fallback_creds) server.add_secure_port(listen_address, server_creds) def serve( port: int, hostname: str, maintenance_port: int, secure_mode: bool ) -> None: if port == maintenance_port: # If maintenance port and port are the same, start a single server. server = grpc.server( futures.ThreadPoolExecutor(max_workers=_THREAD_POOL_SIZE) ) _configure_greeter_server(server, port, secure_mode, hostname) _configure_maintenance_server(server, maintenance_port) server.start() logger.info("Greeter server listening on port %d", port) logger.info("Maintenance server listening on port %d", maintenance_port) server.wait_for_termination() else: # Otherwise, start two different servers. greeter_server = grpc.server( futures.ThreadPoolExecutor(max_workers=_THREAD_POOL_SIZE), xds=secure_mode, ) _configure_greeter_server(greeter_server, port, secure_mode, hostname) greeter_server.start() logger.info("Greeter server listening on port %d", port) maintenance_server = grpc.server( futures.ThreadPoolExecutor(max_workers=_THREAD_POOL_SIZE) ) _configure_maintenance_server(maintenance_server, maintenance_port) maintenance_server.start() logger.info("Maintenance server listening on port %d", maintenance_port) greeter_server.wait_for_termination() maintenance_server.wait_for_termination() if __name__ == "__main__": parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument( "port", default=50051, type=int, nargs="?", help="The port on which to listen.", ) parser.add_argument( "hostname", type=str, default=None, nargs="?", help="The name clients will see in responses.", ) parser.add_argument( "--xds-creds", action="store_true", help="If specified, uses xDS credentials to connect to the server.", ) args = parser.parse_args() logging.basicConfig() logger.setLevel(logging.INFO) serve(args.port, args.hostname, args.port + 1, args.xds_creds)
5,647
34.3
80
py
grpc
grpc-master/examples/python/xds/client.py
# Copyright 2020 The gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter client.""" from __future__ import print_function import argparse import logging import grpc import grpc.experimental import helloworld_pb2 import helloworld_pb2_grpc _DESCRIPTION = "Get a greeting from a server." def run(server_address, secure): if secure: fallback_creds = grpc.experimental.insecure_channel_credentials() channel_creds = grpc.xds_channel_credentials(fallback_creds) channel = grpc.secure_channel(server_address, channel_creds) else: channel = grpc.insecure_channel(server_address) with channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument( "server", default=None, help="The address of the server." ) parser.add_argument( "--xds-creds", action="store_true", help="If specified, uses xDS credentials to connect to the server.", ) args = parser.parse_args() logging.basicConfig() run(args.server, args.xds_creds)
1,839
32.454545
76
py
grpc
grpc-master/examples/python/xds/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/timeout/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/timeout/greeter_server.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import logging from time import sleep import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): message = request.name if message.startswith("[delay]"): sleep(5) return helloworld_pb2.HelloReply(message=message) def serve(): port = "50051" server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:" + port) server.start() print("Server started, listening on " + port) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
1,419
29.869565
74
py
grpc
grpc-master/examples/python/timeout/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/timeout/greeter_client.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """gRPC Python helloworld.Greeter client with call timeout parameters.""" import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc def unary_call( stub: helloworld_pb2_grpc.GreeterStub, request_id: int, message: str ): print("call:", request_id) try: response = stub.SayHello( helloworld_pb2.HelloRequest(name=message), timeout=3 ) print(f"Greeter client received: {response.message}") except grpc.RpcError as rpc_error: print(f"Call failed with code: {rpc_error.code()}") def run(): with grpc.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) # Should success unary_call(stub, 1, "you") # Should fail with DEADLINE_EXCEEDED unary_call(stub, 2, "[delay] you") if __name__ == "__main__": logging.basicConfig() run()
1,477
29.791667
74
py
grpc
grpc-master/examples/python/async_streaming/server.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from concurrent.futures import ThreadPoolExecutor import logging import threading import time from typing import Iterable from google.protobuf.json_format import MessageToJson import grpc import phone_pb2 import phone_pb2_grpc def create_state_response( call_state: phone_pb2.CallState.State, ) -> phone_pb2.StreamCallResponse: response = phone_pb2.StreamCallResponse() response.call_state.state = call_state return response class Phone(phone_pb2_grpc.PhoneServicer): def __init__(self): self._id_counter = 0 self._lock = threading.RLock() def _create_call_session(self) -> phone_pb2.CallInfo: call_info = phone_pb2.CallInfo() with self._lock: call_info.session_id = str(self._id_counter) self._id_counter += 1 call_info.media = "https://link.to.audio.resources" logging.info("Created a call session [%s]", MessageToJson(call_info)) return call_info def _clean_call_session(self, call_info: phone_pb2.CallInfo) -> None: logging.info("Call session cleaned [%s]", MessageToJson(call_info)) def StreamCall( self, request_iterator: Iterable[phone_pb2.StreamCallRequest], context: grpc.ServicerContext, ) -> Iterable[phone_pb2.StreamCallResponse]: try: request = next(request_iterator) logging.info( "Received a phone call request for number [%s]", request.phone_number, ) except StopIteration: raise RuntimeError("Failed to receive call request") # Simulate the acceptance of call request time.sleep(1) yield create_state_response(phone_pb2.CallState.NEW) # Simulate the start of the call session time.sleep(1) call_info = self._create_call_session() context.add_callback(lambda: self._clean_call_session(call_info)) response = phone_pb2.StreamCallResponse() response.call_info.session_id = call_info.session_id response.call_info.media = call_info.media yield response yield create_state_response(phone_pb2.CallState.ACTIVE) # Simulate the end of the call time.sleep(2) yield create_state_response(phone_pb2.CallState.ENDED) logging.info("Call finished [%s]", request.phone_number) def serve(address: str) -> None: server = grpc.server(ThreadPoolExecutor()) phone_pb2_grpc.add_PhoneServicer_to_server(Phone(), server) server.add_insecure_port(address) server.start() logging.info("Server serving at %s", address) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) serve("[::]:50051")
3,325
33.645833
77
py
grpc
grpc-master/examples/python/async_streaming/phone_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import phone_pb2 as phone__pb2 class PhoneStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.StreamCall = channel.stream_stream( '/grpc.testing.Phone/StreamCall', request_serializer=phone__pb2.StreamCallRequest.SerializeToString, response_deserializer=phone__pb2.StreamCallResponse.FromString, ) class PhoneServicer(object): """Missing associated documentation comment in .proto file.""" def StreamCall(self, request_iterator, context): """Makes a phone call and communicate states via a stream. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_PhoneServicer_to_server(servicer, server): rpc_method_handlers = { 'StreamCall': grpc.stream_stream_rpc_method_handler( servicer.StreamCall, request_deserializer=phone__pb2.StreamCallRequest.FromString, response_serializer=phone__pb2.StreamCallResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'grpc.testing.Phone', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Phone(object): """Missing associated documentation comment in .proto file.""" @staticmethod def StreamCall(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_stream(request_iterator, target, '/grpc.testing.Phone/StreamCall', phone__pb2.StreamCallRequest.SerializeToString, phone__pb2.StreamCallResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,444
34.955882
106
py
grpc
grpc-master/examples/python/async_streaming/client.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from concurrent.futures import ThreadPoolExecutor import logging import threading from typing import Iterator import grpc import phone_pb2 import phone_pb2_grpc class CallMaker: def __init__( self, executor: ThreadPoolExecutor, channel: grpc.Channel, phone_number: str, ) -> None: self._executor = executor self._channel = channel self._stub = phone_pb2_grpc.PhoneStub(self._channel) self._phone_number = phone_number self._session_id = None self._audio_session_link = None self._call_state = None self._peer_responded = threading.Event() self._call_finished = threading.Event() self._consumer_future = None def _response_watcher( self, response_iterator: Iterator[phone_pb2.StreamCallResponse] ) -> None: try: for response in response_iterator: # NOTE: All fields in Proto3 are optional. This is the recommended way # to check if a field is present or not, or to exam which one-of field is # fulfilled by this message. if response.HasField("call_info"): self._on_call_info(response.call_info) elif response.HasField("call_state"): self._on_call_state(response.call_state.state) else: raise RuntimeError( "Received StreamCallResponse without call_info and" " call_state" ) except Exception as e: self._peer_responded.set() raise def _on_call_info(self, call_info: phone_pb2.CallInfo) -> None: self._session_id = call_info.session_id self._audio_session_link = call_info.media def _on_call_state(self, call_state: phone_pb2.CallState.State) -> None: logging.info( "Call toward [%s] enters [%s] state", self._phone_number, phone_pb2.CallState.State.Name(call_state), ) self._call_state = call_state if call_state == phone_pb2.CallState.State.ACTIVE: self._peer_responded.set() if call_state == phone_pb2.CallState.State.ENDED: self._peer_responded.set() self._call_finished.set() def call(self) -> None: request = phone_pb2.StreamCallRequest() request.phone_number = self._phone_number response_iterator = self._stub.StreamCall(iter((request,))) # Instead of consuming the response on current thread, spawn a consumption thread. self._consumer_future = self._executor.submit( self._response_watcher, response_iterator ) def wait_peer(self) -> bool: logging.info("Waiting for peer to connect [%s]...", self._phone_number) self._peer_responded.wait(timeout=None) if self._consumer_future.done(): # If the future raises, forwards the exception here self._consumer_future.result() return self._call_state == phone_pb2.CallState.State.ACTIVE def audio_session(self) -> None: assert self._audio_session_link is not None logging.info("Consuming audio resource [%s]", self._audio_session_link) self._call_finished.wait(timeout=None) logging.info("Audio session finished [%s]", self._audio_session_link) def process_call( executor: ThreadPoolExecutor, channel: grpc.Channel, phone_number: str ) -> None: call_maker = CallMaker(executor, channel, phone_number) call_maker.call() if call_maker.wait_peer(): call_maker.audio_session() logging.info("Call finished!") else: logging.info("Call failed: peer didn't answer") def run(): executor = ThreadPoolExecutor() with grpc.insecure_channel("localhost:50051") as channel: future = executor.submit( process_call, executor, channel, "555-0100-XXXX" ) future.result() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) run()
4,674
34.961538
90
py
grpc
grpc-master/examples/python/async_streaming/phone_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: phone.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0bphone.proto\x12\x0cgrpc.testing\"-\n\x08\x43\x61llInfo\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12\r\n\x05media\x18\x02 \x01(\t\"q\n\tCallState\x12,\n\x05state\x18\x02 \x01(\x0e\x32\x1d.grpc.testing.CallState.State\"6\n\x05State\x12\r\n\tUNDEFINED\x10\x00\x12\x07\n\x03NEW\x10\x01\x12\n\n\x06\x41\x43TIVE\x10\x06\x12\t\n\x05\x45NDED\x10\x07\")\n\x11StreamCallRequest\x12\x14\n\x0cphone_number\x18\x01 \x01(\t\"\x88\x01\n\x12StreamCallResponse\x12+\n\tcall_info\x18\x01 \x01(\x0b\x32\x16.grpc.testing.CallInfoH\x00\x12-\n\ncall_state\x18\x02 \x01(\x0b\x32\x17.grpc.testing.CallStateH\x00\x42\x16\n\x14stream_call_response2\\\n\x05Phone\x12S\n\nStreamCall\x12\x1f.grpc.testing.StreamCallRequest\x1a .grpc.testing.StreamCallResponse(\x01\x30\x01\x62\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'phone_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None _CALLINFO._serialized_start=29 _CALLINFO._serialized_end=74 _CALLSTATE._serialized_start=76 _CALLSTATE._serialized_end=189 _CALLSTATE_STATE._serialized_start=135 _CALLSTATE_STATE._serialized_end=189 _STREAMCALLREQUEST._serialized_start=191 _STREAMCALLREQUEST._serialized_end=232 _STREAMCALLRESPONSE._serialized_start=235 _STREAMCALLRESPONSE._serialized_end=371 _PHONE._serialized_start=373 _PHONE._serialized_end=465 # @@protoc_insertion_point(module_scope)
1,979
54
822
py
grpc
grpc-master/examples/python/retry/flaky_server.py
# Copyright 2021 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A flaky backend for the gRPC Python retry example.""" import asyncio import collections import logging import random import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) class ErrorInjectingGreeter(helloworld_pb2_grpc.GreeterServicer): def __init__(self): self._counter = collections.defaultdict(int) async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext, ) -> helloworld_pb2.HelloReply: self._counter[context.peer()] += 1 if self._counter[context.peer()] < 5: if random.random() < 0.75: logging.info("Injecting error to RPC from %s", context.peer()) await context.abort( grpc.StatusCode.UNAVAILABLE, "injected error" ) logging.info("Successfully responding to RPC from %s", context.peer()) return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) async def serve() -> None: server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server( ErrorInjectingGreeter(), server ) listen_addr = "[::]:50051" server.add_insecure_port(listen_addr) logging.info("Starting flaky server on %s", listen_addr) await server.start() await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.run(serve())
2,056
31.650794
78
py
grpc
grpc-master/examples/python/retry/async_retry_client.py
# Copyright 2021 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO implementation of the gRPC client-side retry example.""" import asyncio import json import logging import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) async def run() -> None: # The ServiceConfig proto definition can be found: # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377 service_config_json = json.dumps( { "methodConfig": [ { # To apply retry to all methods, put [{}] in the "name" field "name": [ {"service": "helloworld.Greeter", "method": "SayHello"} ], "retryPolicy": { "maxAttempts": 5, "initialBackoff": "0.1s", "maxBackoff": "1s", "backoffMultiplier": 2, "retryableStatusCodes": ["UNAVAILABLE"], }, } ] } ) options = [] # NOTE: the retry feature will be enabled by default >=v1.40.0 options.append(("grpc.enable_retries", 1)) options.append(("grpc.service_config", service_config_json)) async with grpc.aio.insecure_channel( "localhost:50051", options=options ) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = await stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() asyncio.run(run())
2,259
34.3125
132
py
grpc
grpc-master/examples/python/retry/retry_client.py
# Copyright 2021 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the gRPC client-side retry example.""" import json import logging import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) def run(): # The ServiceConfig proto definition can be found: # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377 service_config_json = json.dumps( { "methodConfig": [ { # To apply retry to all methods, put [{}] in the "name" field "name": [ {"service": "helloworld.Greeter", "method": "SayHello"} ], "retryPolicy": { "maxAttempts": 5, "initialBackoff": "0.1s", "maxBackoff": "1s", "backoffMultiplier": 2, "retryableStatusCodes": ["UNAVAILABLE"], }, } ] } ) options = [] # NOTE: the retry feature will be enabled by default >=v1.40.0 options.append(("grpc.enable_retries", 1)) options.append(("grpc.service_config", service_config_json)) with grpc.insecure_channel("localhost:50051", options=options) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() run()
2,179
34.737705
132
py
grpc
grpc-master/examples/python/wait_for_ready/wait_for_ready_with_client_timeout_example_client.py
# Copyright 2023 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of setting a server connection timeout independent from the overall RPC timeout. For stream server, if client set wait_for_ready but server never actually starts, client will wait indefinitely, this example will do the following steps to set a timeout on client side: 1. Set server to return initial_metadata once it receives request. 2. Client will set a timer (customized client timeout) waiting for initial_metadata. 3. Client will timeout if it didn't receive initial_metadata. """ import logging import threading from typing import Sequence, Tuple import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) def wait_for_metadata(response_future, event): metadata: Sequence[Tuple[str, str]] = response_future.initial_metadata() for key, value in metadata: print( "Greeter client received initial metadata: key=%s value=%s" % (key, value) ) event.set() def check_status(response_future, wait_success): if wait_success: print("received initial metadata before time out!") for response in response_future: message = response.message print("Greeter client received: " + message) else: print("Timed out before receiving any initial metadata!") response_future.cancel() def main(): # Create gRPC channel with grpc.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) event_for_delay = threading.Event() # Server will delay send initial metadata back for this RPC response_future_delay = stub.SayHelloStreamReply( helloworld_pb2.HelloRequest(name="you"), wait_for_ready=True ) # Fire RPC and wait for metadata thread_with_delay = threading.Thread( target=wait_for_metadata, args=(response_future_delay, event_for_delay), daemon=True, ) thread_with_delay.start() # Wait on client side with 7 seconds timeout timeout = 7 check_status(response_future_delay, event_for_delay.wait(timeout)) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
2,897
32.310345
84
py
grpc
grpc-master/examples/python/wait_for_ready/asyncio_wait_for_ready_example.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python example of utilizing wait-for-ready flag.""" import asyncio from contextlib import contextmanager import logging import socket from typing import Iterable import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) @contextmanager def get_free_loopback_tcp_port() -> Iterable[str]: if socket.has_ipv6: tcp_socket = socket.socket(socket.AF_INET6) else: tcp_socket = socket.socket(socket.AF_INET) tcp_socket.bind(("", 0)) address_tuple = tcp_socket.getsockname() yield f"localhost:{address_tuple[1]}" tcp_socket.close() class Greeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, unused_context ) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply(message=f"Hello, {request.name}!") def create_server(server_address: str): server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) bound_port = server.add_insecure_port(server_address) assert bound_port == int(server_address.split(":")[-1]) return server async def process( stub: helloworld_pb2_grpc.GreeterStub, wait_for_ready: bool = None ) -> None: try: response = await stub.SayHello( helloworld_pb2.HelloRequest(name="you"), wait_for_ready=wait_for_ready, ) message = response.message except grpc.aio.AioRpcError as rpc_error: assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE assert not wait_for_ready message = rpc_error else: assert wait_for_ready _LOGGER.info( "Wait-for-ready %s, client received: %s", "enabled" if wait_for_ready else "disabled", message, ) async def main() -> None: # Pick a random free port with get_free_loopback_tcp_port() as server_address: # Create gRPC channel channel = grpc.aio.insecure_channel(server_address) stub = helloworld_pb2_grpc.GreeterStub(channel) # Fire an RPC without wait_for_ready fail_fast_task = asyncio.get_event_loop().create_task( process(stub, wait_for_ready=False) ) # Fire an RPC with wait_for_ready wait_for_ready_task = asyncio.get_event_loop().create_task( process(stub, wait_for_ready=True) ) # Wait for the channel entering TRANSIENT FAILURE state. state = channel.get_state() while state != grpc.ChannelConnectivity.TRANSIENT_FAILURE: await channel.wait_for_state_change(state) state = channel.get_state() # Start the server to handle the RPC server = create_server(server_address) await server.start() # Expected to fail with StatusCode.UNAVAILABLE. await fail_fast_task # Expected to success. await wait_for_ready_task await server.stop(None) await channel.close() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main())
3,723
30.294118
75
py
grpc
grpc-master/examples/python/wait_for_ready/wait_for_ready_with_client_timeout_example_server.py
# Copyright 2023 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of setting a server connection timeout independent from the overall RPC timeout. For stream server, if client set wait_for_ready but server never actually starts, client will wait indefinitely, this example will do the following steps to set a timeout on client side: 1. Set server to return initial_metadata once it receives request. 2. Client will set a timer (customized client timeout) waiting for initial_metadata. 3. Client will timeout if it didn't receive initial_metadata. """ from concurrent import futures import logging from time import sleep import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _INITIAL_METADATA = ((b"initial-md", "initial-md-value"),) def starting_up_server(): print("sleeping 5s before sending metadata back") sleep(5) def do_work(): print("server is processing the request") sleep(5) class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHelloStreamReply(self, request, servicer_context): # Suppose server will take some time to setup, client can set the time it willing to wait # for server to up and running. starting_up_server() # Initial metadata will be send back immediately after calling send_initial_metadata. print("sending inital metadata back") servicer_context.send_initial_metadata(_INITIAL_METADATA) # Time for server to process the request. do_work() # Sending actual response. for i in range(3): yield helloworld_pb2.HelloReply( message="Hello %s times %s" % (request.name, i) ) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:50051") print("starting server") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
2,579
31.25
97
py
grpc
grpc-master/examples/python/wait_for_ready/wait_for_ready_example.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python example of utilizing wait-for-ready flag.""" from concurrent import futures from contextlib import contextmanager import logging import socket import threading import grpc helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services( "helloworld.proto" ) _LOGGER = logging.getLogger(__name__) _LOGGER.setLevel(logging.INFO) @contextmanager def get_free_loopback_tcp_port(): if socket.has_ipv6: tcp_socket = socket.socket(socket.AF_INET6) else: tcp_socket = socket.socket(socket.AF_INET) tcp_socket.bind(("", 0)) address_tuple = tcp_socket.getsockname() yield "localhost:%s" % (address_tuple[1]) tcp_socket.close() class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, unused_context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def create_server(server_address): server = grpc.server(futures.ThreadPoolExecutor()) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) bound_port = server.add_insecure_port(server_address) assert bound_port == int(server_address.split(":")[-1]) return server def process(stub, wait_for_ready=None): try: response = stub.SayHello( helloworld_pb2.HelloRequest(name="you"), wait_for_ready=wait_for_ready, ) message = response.message except grpc.RpcError as rpc_error: assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE assert not wait_for_ready message = rpc_error else: assert wait_for_ready _LOGGER.info( "Wait-for-ready %s, client received: %s", "enabled" if wait_for_ready else "disabled", message, ) def main(): # Pick a random free port with get_free_loopback_tcp_port() as server_address: # Register connectivity event to notify main thread transient_failure_event = threading.Event() def wait_for_transient_failure(channel_connectivity): if ( channel_connectivity == grpc.ChannelConnectivity.TRANSIENT_FAILURE ): transient_failure_event.set() # Create gRPC channel channel = grpc.insecure_channel(server_address) channel.subscribe(wait_for_transient_failure) stub = helloworld_pb2_grpc.GreeterStub(channel) # Fire an RPC without wait_for_ready thread_disabled_wait_for_ready = threading.Thread( target=process, args=(stub, False) ) thread_disabled_wait_for_ready.start() # Fire an RPC with wait_for_ready thread_enabled_wait_for_ready = threading.Thread( target=process, args=(stub, True) ) thread_enabled_wait_for_ready.start() # Wait for the channel entering TRANSIENT FAILURE state. transient_failure_event.wait() server = create_server(server_address) server.start() # Expected to fail with StatusCode.UNAVAILABLE. thread_disabled_wait_for_ready.join() # Expected to success. thread_enabled_wait_for_ready.join() server.stop(None) channel.close() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main()
3,826
30.113821
77
py
grpc
grpc-master/examples/python/wait_for_ready/test/_wait_for_ready_example_test.py
# Copyright 2019 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests of the wait-for-ready example.""" import asyncio import logging import unittest from examples.python.wait_for_ready import asyncio_wait_for_ready_example from examples.python.wait_for_ready import wait_for_ready_example class WaitForReadyExampleTest(unittest.TestCase): def test_wait_for_ready_example(self): wait_for_ready_example.main() # No unhandled exception raised, no deadlock, test passed! def test_asyncio_wait_for_ready_example(self): asyncio.get_event_loop().run_until_complete( asyncio_wait_for_ready_example.main() ) # No unhandled exception raised, no deadlock, test passed! if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) unittest.main(verbosity=2)
1,348
33.589744
74
py
grpc
grpc-master/examples/python/multiplex/multiplex_client.py
# Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A client that makes both Greeter and RouteGuide RPCs.""" from __future__ import print_function import logging import random import time import grpc import helloworld_pb2 import helloworld_pb2_grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def make_route_note(message, latitude, longitude): return route_guide_pb2.RouteNote( message=message, location=route_guide_pb2.Point(latitude=latitude, longitude=longitude), ) def guide_get_one_feature(route_guide_stub, point): feature = route_guide_stub.GetFeature(point) if not feature.location: print("Server returned incomplete feature") return if feature.name: print("Feature called %s at %s" % (feature.name, feature.location)) else: print("Found no feature at %s" % feature.location) def guide_get_feature(route_guide_stub): guide_get_one_feature( route_guide_stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906), ) guide_get_one_feature( route_guide_stub, route_guide_pb2.Point(latitude=0, longitude=0) ) def guide_list_features(route_guide_stub): rectangle = route_guide_pb2.Rectangle( lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000), hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000), ) print("Looking for features between 40, -75 and 42, -73") features = route_guide_stub.ListFeatures(rectangle) for feature in features: print("Feature called %s at %s" % (feature.name, feature.location)) def generate_route(feature_list): for _ in range(0, 10): random_feature = feature_list[random.randint(0, len(feature_list) - 1)] print("Visiting point %s" % random_feature.location) yield random_feature.location time.sleep(random.uniform(0.5, 1.5)) def guide_record_route(route_guide_stub): feature_list = route_guide_resources.read_route_guide_database() route_iterator = generate_route(feature_list) route_summary = route_guide_stub.RecordRoute(route_iterator) print("Finished trip with %s points " % route_summary.point_count) print("Passed %s features " % route_summary.feature_count) print("Travelled %s meters " % route_summary.distance) print("It took %s seconds " % route_summary.elapsed_time) def generate_messages(): messages = [ make_route_note("First message", 0, 0), make_route_note("Second message", 0, 1), make_route_note("Third message", 1, 0), make_route_note("Fourth message", 0, 0), make_route_note("Fifth message", 1, 0), ] for msg in messages: print("Sending %s at %s" % (msg.message, msg.location)) yield msg time.sleep(random.uniform(0.5, 1.0)) def guide_route_chat(route_guide_stub): responses = route_guide_stub.RouteChat(generate_messages()) for response in responses: print( "Received message %s at %s" % (response.message, response.location) ) def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel("localhost:50051") as channel: greeter_stub = helloworld_pb2_grpc.GreeterStub(channel) route_guide_stub = route_guide_pb2_grpc.RouteGuideStub(channel) greeter_response = greeter_stub.SayHello( helloworld_pb2.HelloRequest(name="you") ) print("Greeter client received: " + greeter_response.message) print("-------------- GetFeature --------------") guide_get_feature(route_guide_stub) print("-------------- ListFeatures --------------") guide_list_features(route_guide_stub) print("-------------- RecordRoute --------------") guide_record_route(route_guide_stub) print("-------------- RouteChat --------------") guide_route_chat(route_guide_stub) if __name__ == "__main__": logging.basicConfig() run()
4,683
33.189781
79
py
grpc
grpc-master/examples/python/multiplex/route_guide_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: route_guide.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11route_guide.proto\x12\nrouteguide\",\n\x05Point\x12\x10\n\x08latitude\x18\x01 \x01(\x05\x12\x11\n\tlongitude\x18\x02 \x01(\x05\"I\n\tRectangle\x12\x1d\n\x02lo\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x1d\n\x02hi\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"<\n\x07\x46\x65\x61ture\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x08location\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"A\n\tRouteNote\x12#\n\x08location\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x0f\n\x07message\x18\x02 \x01(\t\"b\n\x0cRouteSummary\x12\x13\n\x0bpoint_count\x18\x01 \x01(\x05\x12\x15\n\rfeature_count\x18\x02 \x01(\x05\x12\x10\n\x08\x64istance\x18\x03 \x01(\x05\x12\x14\n\x0c\x65lapsed_time\x18\x04 \x01(\x05\x32\x85\x02\n\nRouteGuide\x12\x36\n\nGetFeature\x12\x11.routeguide.Point\x1a\x13.routeguide.Feature\"\x00\x12>\n\x0cListFeatures\x12\x15.routeguide.Rectangle\x1a\x13.routeguide.Feature\"\x00\x30\x01\x12>\n\x0bRecordRoute\x12\x11.routeguide.Point\x1a\x18.routeguide.RouteSummary\"\x00(\x01\x12?\n\tRouteChat\x12\x15.routeguide.RouteNote\x1a\x15.routeguide.RouteNote\"\x00(\x01\x30\x01\x42\x36\n\x1bio.grpc.examples.routeguideB\x0fRouteGuideProtoP\x01\xa2\x02\x03RTGb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'route_guide_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG' _POINT._serialized_start=33 _POINT._serialized_end=77 _RECTANGLE._serialized_start=79 _RECTANGLE._serialized_end=152 _FEATURE._serialized_start=154 _FEATURE._serialized_end=214 _ROUTENOTE._serialized_start=216 _ROUTENOTE._serialized_end=281 _ROUTESUMMARY._serialized_start=283 _ROUTESUMMARY._serialized_end=381 _ROUTEGUIDE._serialized_start=384 _ROUTEGUIDE._serialized_end=645 # @@protoc_insertion_point(module_scope)
2,478
66
1,237
py
grpc
grpc-master/examples/python/multiplex/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/multiplex/run_codegen.py
# Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates protocol messages and gRPC stubs.""" from grpc_tools import protoc protoc.main( ( "", "-I../../protos", "--python_out=.", "--grpc_python_out=.", "../../protos/helloworld.proto", ) ) protoc.main( ( "", "-I../../protos", "--python_out=.", "--grpc_python_out=.", "../../protos/route_guide.proto", ) )
986
26.416667
74
py
grpc
grpc-master/examples/python/multiplex/multiplex_server.py
# Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A gRPC server servicing both Greeter and RouteGuide RPCs.""" from concurrent import futures import logging import math import time import grpc import helloworld_pb2 import helloworld_pb2_grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def _get_feature(feature_db, point): """Returns Feature at given location or None.""" for feature in feature_db: if feature.location == point: return feature return None def _get_distance(start, end): """Distance between two points.""" coord_factor = 10000000.0 lat_1 = start.latitude / coord_factor lat_2 = end.latitude / coord_factor lon_1 = start.longitude / coord_factor lon_2 = end.longitude / coord_factor lat_rad_1 = math.radians(lat_1) lat_rad_2 = math.radians(lat_2) delta_lat_rad = math.radians(lat_2 - lat_1) delta_lon_rad = math.radians(lon_2 - lon_1) a = pow(math.sin(delta_lat_rad / 2), 2) + ( math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(math.sin(delta_lon_rad / 2), 2) ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) R = 6371000 # metres return R * c class _GreeterServicer(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply( message="Hello, {}!".format(request.name) ) class _RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): """Provides methods that implement functionality of route guide server.""" def __init__(self): self.db = route_guide_resources.read_route_guide_database() def GetFeature(self, request, context): feature = _get_feature(self.db, request) if feature is None: return route_guide_pb2.Feature(name="", location=request) else: return feature def ListFeatures(self, request, context): left = min(request.lo.longitude, request.hi.longitude) right = max(request.lo.longitude, request.hi.longitude) top = max(request.lo.latitude, request.hi.latitude) bottom = min(request.lo.latitude, request.hi.latitude) for feature in self.db: if ( feature.location.longitude >= left and feature.location.longitude <= right and feature.location.latitude >= bottom and feature.location.latitude <= top ): yield feature def RecordRoute(self, request_iterator, context): point_count = 0 feature_count = 0 distance = 0.0 prev_point = None start_time = time.time() for point in request_iterator: point_count += 1 if _get_feature(self.db, point): feature_count += 1 if prev_point: distance += _get_distance(prev_point, point) prev_point = point elapsed_time = time.time() - start_time return route_guide_pb2.RouteSummary( point_count=point_count, feature_count=feature_count, distance=int(distance), elapsed_time=int(elapsed_time), ) def RouteChat(self, request_iterator, context): prev_notes = [] for new_note in request_iterator: for prev_note in prev_notes: if prev_note.location == new_note.location: yield prev_note prev_notes.append(new_note) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server( _GreeterServicer(), server ) route_guide_pb2_grpc.add_RouteGuideServicer_to_server( _RouteGuideServicer(), server ) server.add_insecure_port("[::]:50051") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
4,506
30.739437
78
py
grpc
grpc-master/examples/python/multiplex/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/multiplex/route_guide_resources.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common resources used in the gRPC route guide example.""" import json import route_guide_pb2 def read_route_guide_database(): """Reads the route guide database. Returns: The full contents of the route guide database as a sequence of route_guide_pb2.Features. """ feature_list = [] with open("route_guide_db.json") as route_guide_db_file: for item in json.load(route_guide_db_file): feature = route_guide_pb2.Feature( name=item["name"], location=route_guide_pb2.Point( latitude=item["location"]["latitude"], longitude=item["location"]["longitude"], ), ) feature_list.append(feature) return feature_list
1,357
32.95
74
py
grpc
grpc-master/examples/python/multiplex/route_guide_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import route_guide_pb2 as route__guide__pb2 class RouteGuideStub(object): """Interface exported by the server. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetFeature = channel.unary_unary( '/routeguide.RouteGuide/GetFeature', request_serializer=route__guide__pb2.Point.SerializeToString, response_deserializer=route__guide__pb2.Feature.FromString, ) self.ListFeatures = channel.unary_stream( '/routeguide.RouteGuide/ListFeatures', request_serializer=route__guide__pb2.Rectangle.SerializeToString, response_deserializer=route__guide__pb2.Feature.FromString, ) self.RecordRoute = channel.stream_unary( '/routeguide.RouteGuide/RecordRoute', request_serializer=route__guide__pb2.Point.SerializeToString, response_deserializer=route__guide__pb2.RouteSummary.FromString, ) self.RouteChat = channel.stream_stream( '/routeguide.RouteGuide/RouteChat', request_serializer=route__guide__pb2.RouteNote.SerializeToString, response_deserializer=route__guide__pb2.RouteNote.FromString, ) class RouteGuideServicer(object): """Interface exported by the server. """ def GetFeature(self, request, context): """A simple RPC. Obtains the feature at a given position. A feature with an empty name is returned if there's no feature at the given position. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListFeatures(self, request, context): """A server-to-client streaming RPC. Obtains the Features available within the given Rectangle. Results are streamed rather than returned at once (e.g. in a response message with a repeated field), as the rectangle may cover a large area and contain a huge number of features. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def RecordRoute(self, request_iterator, context): """A client-to-server streaming RPC. Accepts a stream of Points on a route being traversed, returning a RouteSummary when traversal is completed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def RouteChat(self, request_iterator, context): """A Bidirectional streaming RPC. Accepts a stream of RouteNotes sent while a route is being traversed, while receiving other RouteNotes (e.g. from other users). """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_RouteGuideServicer_to_server(servicer, server): rpc_method_handlers = { 'GetFeature': grpc.unary_unary_rpc_method_handler( servicer.GetFeature, request_deserializer=route__guide__pb2.Point.FromString, response_serializer=route__guide__pb2.Feature.SerializeToString, ), 'ListFeatures': grpc.unary_stream_rpc_method_handler( servicer.ListFeatures, request_deserializer=route__guide__pb2.Rectangle.FromString, response_serializer=route__guide__pb2.Feature.SerializeToString, ), 'RecordRoute': grpc.stream_unary_rpc_method_handler( servicer.RecordRoute, request_deserializer=route__guide__pb2.Point.FromString, response_serializer=route__guide__pb2.RouteSummary.SerializeToString, ), 'RouteChat': grpc.stream_stream_rpc_method_handler( servicer.RouteChat, request_deserializer=route__guide__pb2.RouteNote.FromString, response_serializer=route__guide__pb2.RouteNote.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'routeguide.RouteGuide', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class RouteGuide(object): """Interface exported by the server. """ @staticmethod def GetFeature(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/routeguide.RouteGuide/GetFeature', route__guide__pb2.Point.SerializeToString, route__guide__pb2.Feature.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def ListFeatures(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/routeguide.RouteGuide/ListFeatures', route__guide__pb2.Rectangle.SerializeToString, route__guide__pb2.Feature.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def RecordRoute(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_unary(request_iterator, target, '/routeguide.RouteGuide/RecordRoute', route__guide__pb2.Point.SerializeToString, route__guide__pb2.RouteSummary.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def RouteChat(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_stream(request_iterator, target, '/routeguide.RouteGuide/RouteChat', route__guide__pb2.RouteNote.SerializeToString, route__guide__pb2.RouteNote.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
7,560
39.005291
109
py
grpc
grpc-master/examples/python/keep_alive/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/keep_alive/greeter_server.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server with keepAlive options.""" from concurrent import futures import logging from time import sleep import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): message = request.name if message.startswith("[delay]"): sleep(5) return helloworld_pb2.HelloReply(message=message) def serve(): """ grpc.keepalive_time_ms: The period (in milliseconds) after which a keepalive ping is sent on the transport. grpc.keepalive_timeout_ms: The amount of time (in milliseconds) the sender of the keepalive ping waits for an acknowledgement. If it does not receive an acknowledgment within this time, it will close the connection. grpc.http2.min_ping_interval_without_data_ms: Minimum allowed time (in milliseconds) between a server receiving successive ping frames without sending any data/header frame. grpc.max_connection_idle_ms: Maximum time (in milliseconds) that a channel may have no outstanding rpcs, after which the server will close the connection. grpc.max_connection_age_ms: Maximum time (in milliseconds) that a channel may exist. grpc.max_connection_age_grace_ms: Grace period (in milliseconds) after the channel reaches its max age. grpc.http2.max_pings_without_data: How many pings can the client send before needing to send a data/header frame. grpc.keepalive_permit_without_calls: If set to 1 (0 : false; 1 : true), allows keepalive pings to be sent even if there are no calls in flight. For more details, check: https://github.com/grpc/grpc/blob/master/doc/keepalive.md """ server_options = [ ("grpc.keepalive_time_ms", 20000), ("grpc.keepalive_timeout_ms", 10000), ("grpc.http2.min_ping_interval_without_data_ms", 5000), ("grpc.max_connection_idle_ms", 10000), ("grpc.max_connection_age_ms", 30000), ("grpc.max_connection_age_grace_ms", 5000), ("grpc.http2.max_pings_without_data", 5), ("grpc.keepalive_permit_without_calls", 1), ] port = "50051" server = grpc.server( thread_pool=futures.ThreadPoolExecutor(max_workers=10), options=server_options, ) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:" + port) server.start() print("Server started, listening on " + port) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
3,231
40.435897
96
py
grpc
grpc-master/examples/python/keep_alive/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/keep_alive/greeter_client.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """gRPC Python helloworld.Greeter client with keepAlive channel options.""" import logging from time import sleep import grpc import helloworld_pb2 import helloworld_pb2_grpc def unary_call( stub: helloworld_pb2_grpc.GreeterStub, request_id: int, message: str ): print("call:", request_id) try: response = stub.SayHello(helloworld_pb2.HelloRequest(name=message)) print(f"Greeter client received: {response.message}") except grpc.RpcError as rpc_error: print("Call failed with code: ", rpc_error.code()) def run(): """ grpc.keepalive_time_ms: The period (in milliseconds) after which a keepalive ping is sent on the transport. grpc.keepalive_timeout_ms: The amount of time (in milliseconds) the sender of the keepalive ping waits for an acknowledgement. If it does not receive an acknowledgment within this time, it will close the connection. grpc.keepalive_permit_without_calls: If set to 1 (0 : false; 1 : true), allows keepalive pings to be sent even if there are no calls in flight. grpc.http2.max_pings_without_data: How many pings can the client send before needing to send a data/header frame. For more details, check: https://github.com/grpc/grpc/blob/master/doc/keepalive.md """ channel_options = [ ("grpc.keepalive_time_ms", 8000), ("grpc.keepalive_timeout_ms", 5000), ("grpc.http2.max_pings_without_data", 5), ("grpc.keepalive_permit_without_calls", 1), ] with grpc.insecure_channel( target="localhost:50051", options=channel_options ) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) # Should succeed unary_call(stub, 1, "you") # Run 30s, run this with GRPC_VERBOSITY=DEBUG GRPC_TRACE=http_keepalive to observe logs. # Client will be closed after receveing GOAWAY from server. for i in range(30): print(f"{i} seconds paased.") sleep(1) if __name__ == "__main__": logging.basicConfig() run()
2,644
35.736111
96
py
grpc
grpc-master/examples/python/cancellation/server.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of cancelling requests in gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from concurrent import futures import logging import threading import grpc import search from examples.python.cancellation import hash_name_pb2 from examples.python.cancellation import hash_name_pb2_grpc _LOGGER = logging.getLogger(__name__) _SERVER_HOST = "localhost" _DESCRIPTION = "A server for finding hashes similar to names." class HashFinder(hash_name_pb2_grpc.HashFinderServicer): def __init__(self, maximum_hashes): super(HashFinder, self).__init__() self._maximum_hashes = maximum_hashes def Find(self, request, context): stop_event = threading.Event() def on_rpc_done(): _LOGGER.debug("Attempting to regain servicer thread.") stop_event.set() context.add_callback(on_rpc_done) candidates = [] try: candidates = list( search.search( request.desired_name, request.ideal_hamming_distance, stop_event, self._maximum_hashes, ) ) except search.ResourceLimitExceededError: _LOGGER.info("Cancelling RPC due to exhausted resources.") context.cancel() _LOGGER.debug("Servicer thread returning.") if not candidates: return hash_name_pb2.HashNameResponse() return candidates[-1] def FindRange(self, request, context): stop_event = threading.Event() def on_rpc_done(): _LOGGER.debug("Attempting to regain servicer thread.") stop_event.set() context.add_callback(on_rpc_done) secret_generator = search.search( request.desired_name, request.ideal_hamming_distance, stop_event, self._maximum_hashes, interesting_hamming_distance=request.interesting_hamming_distance, ) try: for candidate in secret_generator: yield candidate except search.ResourceLimitExceededError: _LOGGER.info("Cancelling RPC due to exhausted resources.") context.cancel() _LOGGER.debug("Regained servicer thread.") def _running_server(port, maximum_hashes): # We use only a single servicer thread here to demonstrate that, if managed # carefully, cancelled RPCs can need not continue occupying servicers # threads. server = grpc.server( futures.ThreadPoolExecutor(max_workers=1), maximum_concurrent_rpcs=1 ) hash_name_pb2_grpc.add_HashFinderServicer_to_server( HashFinder(maximum_hashes), server ) address = "{}:{}".format(_SERVER_HOST, port) actual_port = server.add_insecure_port(address) server.start() print("Server listening at '{}'".format(address)) return server def main(): parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument( "--port", type=int, default=50051, nargs="?", help="The port on which the server will listen.", ) parser.add_argument( "--maximum-hashes", type=int, default=1000000, nargs="?", help="The maximum number of hashes to search before cancelling.", ) args = parser.parse_args() server = _running_server(args.port, args.maximum_hashes) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() main()
4,198
30.571429
79
py
grpc
grpc-master/examples/python/cancellation/client.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of cancelling requests in gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import signal import sys import grpc from examples.python.cancellation import hash_name_pb2 from examples.python.cancellation import hash_name_pb2_grpc _DESCRIPTION = "A client for finding hashes similar to names." _LOGGER = logging.getLogger(__name__) def run_unary_client(server_target, name, ideal_distance): with grpc.insecure_channel(server_target) as channel: stub = hash_name_pb2_grpc.HashFinderStub(channel) future = stub.Find.future( hash_name_pb2.HashNameRequest( desired_name=name, ideal_hamming_distance=ideal_distance ), wait_for_ready=True, ) def cancel_request(unused_signum, unused_frame): future.cancel() sys.exit(0) signal.signal(signal.SIGINT, cancel_request) result = future.result() print(result) def run_streaming_client( server_target, name, ideal_distance, interesting_distance ): with grpc.insecure_channel(server_target) as channel: stub = hash_name_pb2_grpc.HashFinderStub(channel) result_generator = stub.FindRange( hash_name_pb2.HashNameRequest( desired_name=name, ideal_hamming_distance=ideal_distance, interesting_hamming_distance=interesting_distance, ), wait_for_ready=True, ) def cancel_request(unused_signum, unused_frame): result_generator.cancel() sys.exit(0) signal.signal(signal.SIGINT, cancel_request) for result in result_generator: print(result) def main(): parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument("name", type=str, help="The desired name.") parser.add_argument( "--ideal-distance", default=0, nargs="?", type=int, help="The desired Hamming distance.", ) parser.add_argument( "--server", default="localhost:50051", type=str, nargs="?", help="The host-port pair at which to reach the server.", ) parser.add_argument( "--show-inferior", default=None, type=int, nargs="?", help=( "Also show candidates with a Hamming distance less than this value." ), ) args = parser.parse_args() if args.show_inferior is not None: run_streaming_client( args.server, args.name, args.ideal_distance, args.show_inferior ) else: run_unary_client(args.server, args.name, args.ideal_distance) if __name__ == "__main__": logging.basicConfig() main()
3,434
28.869565
80
py
grpc
grpc-master/examples/python/cancellation/search.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A search algorithm over the space of all bytestrings.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import base64 import hashlib import itertools import logging import struct from examples.python.cancellation import hash_name_pb2 _LOGGER = logging.getLogger(__name__) _BYTE_MAX = 255 def _get_hamming_distance(a, b): """Calculates hamming distance between strings of equal length.""" distance = 0 for char_a, char_b in zip(a, b): if char_a != char_b: distance += 1 return distance def _get_substring_hamming_distance(candidate, target): """Calculates the minimum hamming distance between between the target and any substring of the candidate. Args: candidate: The string whose substrings will be tested. target: The target string. Returns: The minimum Hamming distance between candidate and target. """ min_distance = None if len(target) > len(candidate): raise ValueError("Candidate must be at least as long as target.") for i in range(len(candidate) - len(target) + 1): distance = _get_hamming_distance( candidate[i : i + len(target)].lower(), target.lower() ) if min_distance is None or distance < min_distance: min_distance = distance return min_distance def _get_hash(secret): hasher = hashlib.sha1() hasher.update(secret) return base64.b64encode(hasher.digest()).decode("ascii") class ResourceLimitExceededError(Exception): """Signifies the request has exceeded configured limits.""" def _bytestrings_of_length(length): """Generates a stream containing all bytestrings of a given length. Args: length: A positive integer length. Yields: All bytestrings of length `length`. """ for digits in itertools.product(range(_BYTE_MAX), repeat=length): yield b"".join(struct.pack("B", i) for i in digits) def _all_bytestrings(): """Generates a stream containing all possible bytestrings. This generator does not terminate. Yields: All bytestrings in ascending order of length. """ for bytestring in itertools.chain.from_iterable( _bytestrings_of_length(length) for length in itertools.count() ): yield bytestring def search( target, ideal_distance, stop_event, maximum_hashes, interesting_hamming_distance=None, ): """Find candidate strings. Search through the space of all bytestrings, in order of increasing length, indefinitely, until a hash with a Hamming distance of `maximum_distance` or less has been found. Args: target: The search string. ideal_distance: The desired Hamming distance. stop_event: An event indicating whether the RPC should terminate. maximum_hashes: The maximum number of hashes to check before stopping. interesting_hamming_distance: If specified, strings with a Hamming distance from the target below this value will be yielded. Yields: Instances of HashNameResponse. The final entry in the stream will be of `maximum_distance` Hamming distance or less from the target string, while all others will be of less than `interesting_hamming_distance`. Raises: ResourceLimitExceededError: If the computation exceeds `maximum_hashes` iterations. """ hashes_computed = 0 for secret in _all_bytestrings(): if stop_event.is_set(): return candidate_hash = _get_hash(secret) distance = _get_substring_hamming_distance(candidate_hash, target) if ( interesting_hamming_distance is not None and distance <= interesting_hamming_distance ): # Surface interesting candidates, but don't stop. yield hash_name_pb2.HashNameResponse( secret=base64.b64encode(secret), hashed_name=candidate_hash, hamming_distance=distance, ) elif distance <= ideal_distance: # Yield ideal candidate and end the stream. yield hash_name_pb2.HashNameResponse( secret=base64.b64encode(secret), hashed_name=candidate_hash, hamming_distance=distance, ) return hashes_computed += 1 if hashes_computed == maximum_hashes: raise ResourceLimitExceededError()
5,089
31.21519
79
py
grpc
grpc-master/examples/python/cancellation/test/_cancellation_example_test.py
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for cancellation example.""" import contextlib import os import signal import socket import subprocess import unittest _BINARY_DIR = os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") ) _SERVER_PATH = os.path.join(_BINARY_DIR, "server") _CLIENT_PATH = os.path.join(_BINARY_DIR, "client") @contextlib.contextmanager def _get_port(): sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 0: raise RuntimeError("Failed to set SO_REUSEPORT.") sock.bind(("", 0)) try: yield sock.getsockname()[1] finally: sock.close() def _start_client( server_port, desired_string, ideal_distance, interesting_distance=None ): interesting_distance_args = ( () if interesting_distance is None else ("--show-inferior", interesting_distance) ) return subprocess.Popen( ( _CLIENT_PATH, desired_string, "--server", "localhost:{}".format(server_port), "--ideal-distance", str(ideal_distance), ) + interesting_distance_args ) class CancellationExampleTest(unittest.TestCase): def test_successful_run(self): with _get_port() as test_port: server_process = subprocess.Popen( (_SERVER_PATH, "--port", str(test_port)) ) try: client_process = _start_client(test_port, "aa", 0) client_return_code = client_process.wait() self.assertEqual(0, client_return_code) self.assertIsNone(server_process.poll()) finally: server_process.kill() server_process.wait() def test_graceful_sigint(self): with _get_port() as test_port: server_process = subprocess.Popen( (_SERVER_PATH, "--port", str(test_port)) ) try: client_process1 = _start_client(test_port, "aaaaaaaaaa", 0) client_process1.send_signal(signal.SIGINT) client_process1.wait() client_process2 = _start_client(test_port, "aa", 0) client_return_code = client_process2.wait() self.assertEqual(0, client_return_code) self.assertIsNone(server_process.poll()) finally: server_process.kill() server_process.wait() if __name__ == "__main__": unittest.main(verbosity=2)
3,220
31.535354
75
py
grpc
grpc-master/examples/python/data_transmission/demo_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: demo.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\ndemo.proto\x12\x04\x64\x65mo\"2\n\x07Request\x12\x11\n\tclient_id\x18\x01 \x01(\x03\x12\x14\n\x0crequest_data\x18\x02 \x01(\t\"4\n\x08Response\x12\x11\n\tserver_id\x18\x01 \x01(\x03\x12\x15\n\rresponse_data\x18\x02 \x01(\t2\xf0\x01\n\x08GRPCDemo\x12-\n\x0cSimpleMethod\x12\r.demo.Request\x1a\x0e.demo.Response\x12\x38\n\x15\x43lientStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response(\x01\x12\x38\n\x15ServerStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response0\x01\x12\x41\n\x1c\x42idirectionalStreamingMethod\x12\r.demo.Request\x1a\x0e.demo.Response(\x01\x30\x01\x62\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'demo_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None _REQUEST._serialized_start=20 _REQUEST._serialized_end=70 _RESPONSE._serialized_start=72 _RESPONSE._serialized_end=124 _GRPCDEMO._serialized_start=127 _GRPCDEMO._serialized_end=367 # @@protoc_insertion_point(module_scope)
1,560
51.033333
653
py
grpc
grpc-master/examples/python/data_transmission/server.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The example of four ways of data transmission using gRPC in Python.""" from concurrent import futures from threading import Thread import grpc import demo_pb2 import demo_pb2_grpc __all__ = "DemoServer" SERVER_ADDRESS = "localhost:23333" SERVER_ID = 1 class DemoServer(demo_pb2_grpc.GRPCDemoServicer): # 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应) # unary-unary(In a single call, the client can only send request once, and the server can # only respond once.) def SimpleMethod(self, request, context): print( "SimpleMethod called by client(%d) the message: %s" % (request.client_id, request.request_data) ) response = demo_pb2.Response( server_id=SERVER_ID, response_data="Python server SimpleMethod Ok!!!!", ) return response # 客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应) # stream-unary (In a single call, the client can transfer data to the server several times, # but the server can only return a response once.) def ClientStreamingMethod(self, request_iterator, context): print("ClientStreamingMethod called by client...") for request in request_iterator: print( "recv from client(%d), message= %s" % (request.client_id, request.request_data) ) response = demo_pb2.Response( server_id=SERVER_ID, response_data="Python server ClientStreamingMethod ok", ) return response # 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应) # unary-stream (In a single call, the client can only transmit data to the server at one time, # but the server can return the response many times.) def ServerStreamingMethod(self, request, context): print( "ServerStreamingMethod called by client(%d), message= %s" % (request.client_id, request.request_data) ) # 创建一个生成器 # create a generator def response_messages(): for i in range(5): response = demo_pb2.Response( server_id=SERVER_ID, response_data="send by Python server, message=%d" % i, ) yield response return response_messages() # 双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据) # stream-stream (In a single call, both client and server can send and receive data # to each other multiple times.) def BidirectionalStreamingMethod(self, request_iterator, context): print("BidirectionalStreamingMethod called by client...") # 开启一个子线程去接收数据 # Open a sub thread to receive data def parse_request(): for request in request_iterator: print( "recv from client(%d), message= %s" % (request.client_id, request.request_data) ) t = Thread(target=parse_request) t.start() for i in range(5): yield demo_pb2.Response( server_id=SERVER_ID, response_data="send by Python server, message= %d" % i, ) t.join() def main(): server = grpc.server(futures.ThreadPoolExecutor()) demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), server) server.add_insecure_port(SERVER_ADDRESS) print("------------------start Python GRPC server") server.start() server.wait_for_termination() # If raise Error: # AttributeError: '_Server' object has no attribute 'wait_for_termination' # You can use the following code instead: # import time # while 1: # time.sleep(10) if __name__ == "__main__": main()
4,300
32.601563
98
py
grpc
grpc-master/examples/python/data_transmission/alts_server.py
# Copyright 2020 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The example of using ALTS credentials to setup gRPC server in python. The example would only successfully run in GCP environment.""" from concurrent import futures import grpc import demo_pb2_grpc from server import DemoServer SERVER_ADDRESS = "localhost:23333" def main(): svr = grpc.server(futures.ThreadPoolExecutor()) demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), svr) svr.add_secure_port( SERVER_ADDRESS, server_credentials=grpc.alts_server_credentials() ) print("------------------start Python GRPC server with ALTS encryption") svr.start() svr.wait_for_termination() if __name__ == "__main__": main()
1,250
29.512195
76
py
grpc
grpc-master/examples/python/data_transmission/client.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The example of four ways of data transmission using gRPC in Python.""" import time import grpc import demo_pb2 import demo_pb2_grpc __all__ = [ "simple_method", "client_streaming_method", "server_streaming_method", "bidirectional_streaming_method", ] SERVER_ADDRESS = "localhost:23333" CLIENT_ID = 1 # 中文注释和英文翻译 # Note that this example was contributed by an external user using Chinese comments. # In all cases, the Chinese comment text is translated to English just below it. # 一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应) # unary-unary(In a single call, the client can only send request once, and the server can # only respond once.) def simple_method(stub): print("--------------Call SimpleMethod Begin--------------") request = demo_pb2.Request( client_id=CLIENT_ID, request_data="called by Python client" ) response = stub.SimpleMethod(request) print( "resp from server(%d), the message=%s" % (response.server_id, response.response_data) ) print("--------------Call SimpleMethod Over---------------") # 客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应) # stream-unary (In a single call, the client can transfer data to the server several times, # but the server can only return a response once.) def client_streaming_method(stub): print("--------------Call ClientStreamingMethod Begin--------------") # 创建一个生成器 # create a generator def request_messages(): for i in range(5): request = demo_pb2.Request( client_id=CLIENT_ID, request_data="called by Python client, message:%d" % i, ) yield request response = stub.ClientStreamingMethod(request_messages()) print( "resp from server(%d), the message=%s" % (response.server_id, response.response_data) ) print("--------------Call ClientStreamingMethod Over---------------") # 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应) # unary-stream (In a single call, the client can only transmit data to the server at one time, # but the server can return the response many times.) def server_streaming_method(stub): print("--------------Call ServerStreamingMethod Begin--------------") request = demo_pb2.Request( client_id=CLIENT_ID, request_data="called by Python client" ) response_iterator = stub.ServerStreamingMethod(request) for response in response_iterator: print( "recv from server(%d), message=%s" % (response.server_id, response.response_data) ) print("--------------Call ServerStreamingMethod Over---------------") # 双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据) # stream-stream (In a single call, both client and server can send and receive data # to each other multiple times.) def bidirectional_streaming_method(stub): print( "--------------Call BidirectionalStreamingMethod Begin---------------" ) # 创建一个生成器 # create a generator def request_messages(): for i in range(5): request = demo_pb2.Request( client_id=CLIENT_ID, request_data="called by Python client, message: %d" % i, ) yield request time.sleep(1) response_iterator = stub.BidirectionalStreamingMethod(request_messages()) for response in response_iterator: print( "recv from server(%d), message=%s" % (response.server_id, response.response_data) ) print("--------------Call BidirectionalStreamingMethod Over---------------") def main(): with grpc.insecure_channel(SERVER_ADDRESS) as channel: stub = demo_pb2_grpc.GRPCDemoStub(channel) simple_method(stub) client_streaming_method(stub) server_streaming_method(stub) bidirectional_streaming_method(stub) if __name__ == "__main__": main()
4,481
31.014286
94
py
grpc
grpc-master/examples/python/data_transmission/demo_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import demo_pb2 as demo__pb2 class GRPCDemoStub(object): """`service` 是用来给gRPC服务定义方法的, 格式固定, 类似于Golang中定义一个接口 `service` is used to define methods for gRPC services in a fixed format, similar to defining an interface in Golang """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SimpleMethod = channel.unary_unary( '/demo.GRPCDemo/SimpleMethod', request_serializer=demo__pb2.Request.SerializeToString, response_deserializer=demo__pb2.Response.FromString, ) self.ClientStreamingMethod = channel.stream_unary( '/demo.GRPCDemo/ClientStreamingMethod', request_serializer=demo__pb2.Request.SerializeToString, response_deserializer=demo__pb2.Response.FromString, ) self.ServerStreamingMethod = channel.unary_stream( '/demo.GRPCDemo/ServerStreamingMethod', request_serializer=demo__pb2.Request.SerializeToString, response_deserializer=demo__pb2.Response.FromString, ) self.BidirectionalStreamingMethod = channel.stream_stream( '/demo.GRPCDemo/BidirectionalStreamingMethod', request_serializer=demo__pb2.Request.SerializeToString, response_deserializer=demo__pb2.Response.FromString, ) class GRPCDemoServicer(object): """`service` 是用来给gRPC服务定义方法的, 格式固定, 类似于Golang中定义一个接口 `service` is used to define methods for gRPC services in a fixed format, similar to defining an interface in Golang """ def SimpleMethod(self, request, context): """一元模式(在一次调用中, 客户端只能向服务器传输一次请求数据, 服务器也只能返回一次响应) unary-unary(In a single call, the client can only send request once, and the server can only respond once.) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ClientStreamingMethod(self, request_iterator, context): """客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应) stream-unary (In a single call, the client can transfer data to the server several times, but the server can only return a response once.) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ServerStreamingMethod(self, request, context): """服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应) unary-stream (In a single call, the client can only transmit data to the server at one time, but the server can return the response many times.) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def BidirectionalStreamingMethod(self, request_iterator, context): """双向流模式 (在一次调用中, 客户端和服务器都可以向对方多次收发数据) stream-stream (In a single call, both client and server can send and receive data to each other multiple times.) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GRPCDemoServicer_to_server(servicer, server): rpc_method_handlers = { 'SimpleMethod': grpc.unary_unary_rpc_method_handler( servicer.SimpleMethod, request_deserializer=demo__pb2.Request.FromString, response_serializer=demo__pb2.Response.SerializeToString, ), 'ClientStreamingMethod': grpc.stream_unary_rpc_method_handler( servicer.ClientStreamingMethod, request_deserializer=demo__pb2.Request.FromString, response_serializer=demo__pb2.Response.SerializeToString, ), 'ServerStreamingMethod': grpc.unary_stream_rpc_method_handler( servicer.ServerStreamingMethod, request_deserializer=demo__pb2.Request.FromString, response_serializer=demo__pb2.Response.SerializeToString, ), 'BidirectionalStreamingMethod': grpc.stream_stream_rpc_method_handler( servicer.BidirectionalStreamingMethod, request_deserializer=demo__pb2.Request.FromString, response_serializer=demo__pb2.Response.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'demo.GRPCDemo', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class GRPCDemo(object): """`service` 是用来给gRPC服务定义方法的, 格式固定, 类似于Golang中定义一个接口 `service` is used to define methods for gRPC services in a fixed format, similar to defining an interface in Golang """ @staticmethod def SimpleMethod(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/demo.GRPCDemo/SimpleMethod', demo__pb2.Request.SerializeToString, demo__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def ClientStreamingMethod(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_unary(request_iterator, target, '/demo.GRPCDemo/ClientStreamingMethod', demo__pb2.Request.SerializeToString, demo__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def ServerStreamingMethod(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/demo.GRPCDemo/ServerStreamingMethod', demo__pb2.Request.SerializeToString, demo__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def BidirectionalStreamingMethod(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_stream(request_iterator, target, '/demo.GRPCDemo/BidirectionalStreamingMethod', demo__pb2.Request.SerializeToString, demo__pb2.Response.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
7,898
41.240642
119
py
grpc
grpc-master/examples/python/data_transmission/alts_client.py
# Copyright 2020 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The example of using ALTS credentials to setup gRPC client. The example would only successfully run in GCP environment.""" import grpc from client import bidirectional_streaming_method from client import client_streaming_method from client import server_streaming_method from client import simple_method import demo_pb2_grpc SERVER_ADDRESS = "localhost:23333" def main(): with grpc.secure_channel( SERVER_ADDRESS, credentials=grpc.alts_channel_credentials() ) as channel: stub = demo_pb2_grpc.GRPCDemoStub(channel) simple_method(stub) client_streaming_method(stub) server_streaming_method(stub) bidirectional_streaming_method(stub) if __name__ == "__main__": main()
1,314
30.309524
74
py
grpc
grpc-master/examples/python/helloworld/async_greeter_client.py
# Copyright 2020 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO implementation of the GRPC helloworld.Greeter client.""" import asyncio import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc async def run() -> None: async with grpc.aio.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = await stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() asyncio.run(run())
1,120
31.970588
79
py
grpc
grpc-master/examples/python/helloworld/greeter_client_reflection.py
# Copyright 2023 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter client with reflection.""" import logging from google.protobuf.descriptor_pool import DescriptorPool import grpc from grpc_reflection.v1alpha.proto_reflection_descriptor_database import ( ProtoReflectionDescriptorDatabase, ) def run(): print("Will try to greet world ...") with grpc.insecure_channel("localhost:50051") as channel: reflection_db = ProtoReflectionDescriptorDatabase(channel) services = reflection_db.get_services() print(f"found services: {services}") desc_pool = DescriptorPool(reflection_db) service_desc = desc_pool.FindServiceByName("helloworld.Greeter") print(f"found Greeter service with name: {service_desc.full_name}") for methods in service_desc.methods: print(f"found method name: {methods.full_name}") input_type = methods.input_type print(f"input type for this method: {input_type.full_name}") request_desc = desc_pool.FindMessageTypeByName( "helloworld.HelloRequest" ) print(f"found request name: {request_desc.full_name}") if __name__ == "__main__": logging.basicConfig() run()
1,800
35.755102
86
py
grpc
grpc-master/examples/python/helloworld/greeter_client_with_options.py
# Copyright 2018 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """gRPC Python helloworld.Greeter client with channel options and call timeout parameters.""" from __future__ import print_function import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. # # For more channel options, please see https://grpc.io/grpc/core/group__grpc__arg__keys.html with grpc.insecure_channel( target="localhost:50051", options=[ ("grpc.lb_policy_name", "pick_first"), ("grpc.enable_retries", 0), ("grpc.keepalive_timeout_ms", 10000), ], ) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) # Timeout in seconds. # Please refer gRPC Python documents for more detail. https://grpc.io/grpc/python/grpc.html response = stub.SayHello( helloworld_pb2.HelloRequest(name="you"), timeout=10 ) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() run()
1,751
33.352941
99
py
grpc
grpc-master/examples/python/helloworld/async_greeter_server_with_reflection.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The reflection-enabled version of gRPC AsyncIO helloworld.Greeter server.""" import asyncio import logging import grpc from grpc_reflection.v1alpha import reflection import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext, ) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) async def serve() -> None: server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) SERVICE_NAMES = ( helloworld_pb2.DESCRIPTOR.services_by_name["Greeter"].full_name, reflection.SERVICE_NAME, ) reflection.enable_server_reflection(SERVICE_NAMES, server) server.add_insecure_port("[::]:50051") await server.start() await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() asyncio.run(serve())
1,613
31.28
79
py
grpc
grpc-master/examples/python/helloworld/async_greeter_server_with_graceful_shutdown.py
# Copyright 2021 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The graceful shutdown example for the asyncio Greeter server.""" import asyncio import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc # Coroutines to be invoked when the event loop is shutting down. _cleanup_coroutines = [] class Greeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext, ) -> helloworld_pb2.HelloReply: logging.info("Received request, sleeping for 4 seconds...") await asyncio.sleep(4) logging.info("Sleep completed, responding") return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) async def serve() -> None: server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) listen_addr = "[::]:50051" server.add_insecure_port(listen_addr) logging.info("Starting server on %s", listen_addr) await server.start() async def server_graceful_shutdown(): logging.info("Starting graceful shutdown...") # Shuts down the server with 5 seconds of grace period. During the # grace period, the server won't accept new connections and allow # existing RPCs to continue within the grace period. await server.stop(5) _cleanup_coroutines.append(server_graceful_shutdown()) await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() try: loop.run_until_complete(serve()) finally: loop.run_until_complete(*_cleanup_coroutines) loop.close()
2,247
33.060606
77
py
grpc
grpc-master/examples/python/helloworld/helloworld_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Greeter(object): """The greeting service definition. """ @staticmethod def SayHello(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/helloworld.Greeter/SayHello', helloworld__pb2.HelloRequest.SerializeToString, helloworld__pb2.HelloReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
2,310
31.549296
93
py
grpc
grpc-master/examples/python/helloworld/async_greeter_server.py
# Copyright 2020 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO implementation of the GRPC helloworld.Greeter server.""" import asyncio import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext, ) -> helloworld_pb2.HelloReply: return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) async def serve() -> None: server = grpc.aio.server() helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) listen_addr = "[::]:50051" server.add_insecure_port(listen_addr) logging.info("Starting server on %s", listen_addr) await server.start() await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.run(serve())
1,468
30.934783
78
py
grpc
grpc-master/examples/python/helloworld/async_greeter_client_with_options.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """gRPC Python AsyncIO helloworld.Greeter client with channel options and timeout parameters.""" import asyncio import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc # For more channel options, please see https://grpc.io/grpc/core/group__grpc__arg__keys.html CHANNEL_OPTIONS = [ ("grpc.lb_policy_name", "pick_first"), ("grpc.enable_retries", 0), ("grpc.keepalive_timeout_ms", 10000), ] async def run() -> None: async with grpc.aio.insecure_channel( target="localhost:50051", options=CHANNEL_OPTIONS ) as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) # Timeout in seconds. # Please refer gRPC Python documents for more detail. https://grpc.io/grpc/python/grpc.html response = await stub.SayHello( helloworld_pb2.HelloRequest(name="you"), timeout=10 ) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() asyncio.run(run())
1,584
32.723404
99
py
grpc
grpc-master/examples/python/helloworld/greeter_server.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def serve(): port = "50051" server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port("[::]:" + port) server.start() print("Server started, listening on " + port) server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
1,322
30.5
77
py
grpc
grpc-master/examples/python/helloworld/helloworld_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'helloworld_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW' _HELLOREQUEST._serialized_start=32 _HELLOREQUEST._serialized_end=60 _HELLOREPLY._serialized_start=62 _HELLOREPLY._serialized_end=91 _GREETER._serialized_start=93 _GREETER._serialized_end=166 # @@protoc_insertion_point(module_scope)
1,450
45.806452
409
py
grpc
grpc-master/examples/python/helloworld/greeter_server_with_reflection.py
# Copyright 2018 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The reflection-enabled version of gRPC helloworld.Greeter server.""" from concurrent import futures import logging import grpc from grpc_reflection.v1alpha import reflection import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message="Hello, %s!" % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) SERVICE_NAMES = ( helloworld_pb2.DESCRIPTOR.services_by_name["Greeter"].full_name, reflection.SERVICE_NAME, ) reflection.enable_server_reflection(SERVICE_NAMES, server) server.add_insecure_port("[::]:50051") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
1,499
31.608696
77
py
grpc
grpc-master/examples/python/helloworld/greeter_client.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the GRPC helloworld.Greeter client.""" from __future__ import print_function import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. print("Will try to greet world ...") with grpc.insecure_channel("localhost:50051") as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name="you")) print("Greeter client received: " + response.message) if __name__ == "__main__": logging.basicConfig() run()
1,310
32.615385
78
py
grpc
grpc-master/examples/python/route_guide/route_guide_client.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the gRPC route guide client.""" from __future__ import print_function import logging import random import grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def make_route_note(message, latitude, longitude): return route_guide_pb2.RouteNote( message=message, location=route_guide_pb2.Point(latitude=latitude, longitude=longitude), ) def guide_get_one_feature(stub, point): feature = stub.GetFeature(point) if not feature.location: print("Server returned incomplete feature") return if feature.name: print("Feature called %s at %s" % (feature.name, feature.location)) else: print("Found no feature at %s" % feature.location) def guide_get_feature(stub): guide_get_one_feature( stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906) ) guide_get_one_feature(stub, route_guide_pb2.Point(latitude=0, longitude=0)) def guide_list_features(stub): rectangle = route_guide_pb2.Rectangle( lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000), hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000), ) print("Looking for features between 40, -75 and 42, -73") features = stub.ListFeatures(rectangle) for feature in features: print("Feature called %s at %s" % (feature.name, feature.location)) def generate_route(feature_list): for _ in range(0, 10): random_feature = feature_list[random.randint(0, len(feature_list) - 1)] print("Visiting point %s" % random_feature.location) yield random_feature.location def guide_record_route(stub): feature_list = route_guide_resources.read_route_guide_database() route_iterator = generate_route(feature_list) route_summary = stub.RecordRoute(route_iterator) print("Finished trip with %s points " % route_summary.point_count) print("Passed %s features " % route_summary.feature_count) print("Travelled %s meters " % route_summary.distance) print("It took %s seconds " % route_summary.elapsed_time) def generate_messages(): messages = [ make_route_note("First message", 0, 0), make_route_note("Second message", 0, 1), make_route_note("Third message", 1, 0), make_route_note("Fourth message", 0, 0), make_route_note("Fifth message", 1, 0), ] for msg in messages: print("Sending %s at %s" % (msg.message, msg.location)) yield msg def guide_route_chat(stub): responses = stub.RouteChat(generate_messages()) for response in responses: print( "Received message %s at %s" % (response.message, response.location) ) def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel("localhost:50051") as channel: stub = route_guide_pb2_grpc.RouteGuideStub(channel) print("-------------- GetFeature --------------") guide_get_feature(stub) print("-------------- ListFeatures --------------") guide_list_features(stub) print("-------------- RecordRoute --------------") guide_record_route(stub) print("-------------- RouteChat --------------") guide_route_chat(stub) if __name__ == "__main__": logging.basicConfig() run()
4,075
31.870968
79
py
grpc
grpc-master/examples/python/route_guide/route_guide_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: route_guide.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11route_guide.proto\x12\nrouteguide\",\n\x05Point\x12\x10\n\x08latitude\x18\x01 \x01(\x05\x12\x11\n\tlongitude\x18\x02 \x01(\x05\"I\n\tRectangle\x12\x1d\n\x02lo\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x1d\n\x02hi\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"<\n\x07\x46\x65\x61ture\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x08location\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"A\n\tRouteNote\x12#\n\x08location\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x0f\n\x07message\x18\x02 \x01(\t\"b\n\x0cRouteSummary\x12\x13\n\x0bpoint_count\x18\x01 \x01(\x05\x12\x15\n\rfeature_count\x18\x02 \x01(\x05\x12\x10\n\x08\x64istance\x18\x03 \x01(\x05\x12\x14\n\x0c\x65lapsed_time\x18\x04 \x01(\x05\x32\x85\x02\n\nRouteGuide\x12\x36\n\nGetFeature\x12\x11.routeguide.Point\x1a\x13.routeguide.Feature\"\x00\x12>\n\x0cListFeatures\x12\x15.routeguide.Rectangle\x1a\x13.routeguide.Feature\"\x00\x30\x01\x12>\n\x0bRecordRoute\x12\x11.routeguide.Point\x1a\x18.routeguide.RouteSummary\"\x00(\x01\x12?\n\tRouteChat\x12\x15.routeguide.RouteNote\x1a\x15.routeguide.RouteNote\"\x00(\x01\x30\x01\x42\x36\n\x1bio.grpc.examples.routeguideB\x0fRouteGuideProtoP\x01\xa2\x02\x03RTGb\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'route_guide_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG' _POINT._serialized_start=33 _POINT._serialized_end=77 _RECTANGLE._serialized_start=79 _RECTANGLE._serialized_end=152 _FEATURE._serialized_start=154 _FEATURE._serialized_end=214 _ROUTENOTE._serialized_start=216 _ROUTENOTE._serialized_end=281 _ROUTESUMMARY._serialized_start=283 _ROUTESUMMARY._serialized_end=381 _ROUTEGUIDE._serialized_start=384 _ROUTEGUIDE._serialized_end=645 # @@protoc_insertion_point(module_scope)
2,478
66
1,237
py
grpc
grpc-master/examples/python/route_guide/run_codegen.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Runs protoc with the gRPC plugin to generate messages and gRPC stubs.""" from grpc_tools import protoc protoc.main( ( "", "-I../../protos", "--python_out=.", "--grpc_python_out=.", "../../protos/route_guide.proto", ) )
849
30.481481
75
py
grpc
grpc-master/examples/python/route_guide/asyncio_route_guide_server.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO implementation of the gRPC route guide server.""" import asyncio import logging import math import time from typing import AsyncIterable, Iterable import grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def get_feature( feature_db: Iterable[route_guide_pb2.Feature], point: route_guide_pb2.Point ) -> route_guide_pb2.Feature: """Returns Feature at given location or None.""" for feature in feature_db: if feature.location == point: return feature return None def get_distance( start: route_guide_pb2.Point, end: route_guide_pb2.Point ) -> float: """Distance between two points.""" coord_factor = 10000000.0 lat_1 = start.latitude / coord_factor lat_2 = end.latitude / coord_factor lon_1 = start.longitude / coord_factor lon_2 = end.longitude / coord_factor lat_rad_1 = math.radians(lat_1) lat_rad_2 = math.radians(lat_2) delta_lat_rad = math.radians(lat_2 - lat_1) delta_lon_rad = math.radians(lon_2 - lon_1) # Formula is based on http://mathforum.org/library/drmath/view/51879.html a = pow(math.sin(delta_lat_rad / 2), 2) + ( math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(math.sin(delta_lon_rad / 2), 2) ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) R = 6371000 # metres return R * c class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): """Provides methods that implement functionality of route guide server.""" def __init__(self) -> None: self.db = route_guide_resources.read_route_guide_database() def GetFeature( self, request: route_guide_pb2.Point, unused_context ) -> route_guide_pb2.Feature: feature = get_feature(self.db, request) if feature is None: return route_guide_pb2.Feature(name="", location=request) else: return feature async def ListFeatures( self, request: route_guide_pb2.Rectangle, unused_context ) -> AsyncIterable[route_guide_pb2.Feature]: left = min(request.lo.longitude, request.hi.longitude) right = max(request.lo.longitude, request.hi.longitude) top = max(request.lo.latitude, request.hi.latitude) bottom = min(request.lo.latitude, request.hi.latitude) for feature in self.db: if ( feature.location.longitude >= left and feature.location.longitude <= right and feature.location.latitude >= bottom and feature.location.latitude <= top ): yield feature async def RecordRoute( self, request_iterator: AsyncIterable[route_guide_pb2.Point], unused_context, ) -> route_guide_pb2.RouteSummary: point_count = 0 feature_count = 0 distance = 0.0 prev_point = None start_time = time.time() async for point in request_iterator: point_count += 1 if get_feature(self.db, point): feature_count += 1 if prev_point: distance += get_distance(prev_point, point) prev_point = point elapsed_time = time.time() - start_time return route_guide_pb2.RouteSummary( point_count=point_count, feature_count=feature_count, distance=int(distance), elapsed_time=int(elapsed_time), ) async def RouteChat( self, request_iterator: AsyncIterable[route_guide_pb2.RouteNote], unused_context, ) -> AsyncIterable[route_guide_pb2.RouteNote]: prev_notes = [] async for new_note in request_iterator: for prev_note in prev_notes: if prev_note.location == new_note.location: yield prev_note prev_notes.append(new_note) async def serve() -> None: server = grpc.aio.server() route_guide_pb2_grpc.add_RouteGuideServicer_to_server( RouteGuideServicer(), server ) server.add_insecure_port("[::]:50051") await server.start() await server.wait_for_termination() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(serve())
4,893
32.067568
79
py
grpc
grpc-master/examples/python/route_guide/route_guide_resources.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Common resources used in the gRPC route guide example.""" import json import route_guide_pb2 def read_route_guide_database(): """Reads the route guide database. Returns: The full contents of the route guide database as a sequence of route_guide_pb2.Features. """ feature_list = [] with open("route_guide_db.json") as route_guide_db_file: for item in json.load(route_guide_db_file): feature = route_guide_pb2.Feature( name=item["name"], location=route_guide_pb2.Point( latitude=item["location"]["latitude"], longitude=item["location"]["longitude"], ), ) feature_list.append(feature) return feature_list
1,357
32.95
74
py
grpc
grpc-master/examples/python/route_guide/asyncio_route_guide_client.py
# Copyright 2020 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python AsyncIO implementation of the gRPC route guide client.""" import asyncio import logging import random from typing import Iterable, List import grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def make_route_note( message: str, latitude: int, longitude: int ) -> route_guide_pb2.RouteNote: return route_guide_pb2.RouteNote( message=message, location=route_guide_pb2.Point(latitude=latitude, longitude=longitude), ) # Performs an unary call async def guide_get_one_feature( stub: route_guide_pb2_grpc.RouteGuideStub, point: route_guide_pb2.Point ) -> None: feature = await stub.GetFeature(point) if not feature.location: print("Server returned incomplete feature") return if feature.name: print(f"Feature called {feature.name} at {feature.location}") else: print(f"Found no feature at {feature.location}") async def guide_get_feature(stub: route_guide_pb2_grpc.RouteGuideStub) -> None: # The following two coroutines will be wrapped in a Future object # and scheduled in the event loop so that they can run concurrently task_group = asyncio.gather( guide_get_one_feature( stub, route_guide_pb2.Point(latitude=409146138, longitude=-746188906), ), guide_get_one_feature( stub, route_guide_pb2.Point(latitude=0, longitude=0) ), ) # Wait until the Future is resolved await task_group # Performs a server-streaming call async def guide_list_features( stub: route_guide_pb2_grpc.RouteGuideStub, ) -> None: rectangle = route_guide_pb2.Rectangle( lo=route_guide_pb2.Point(latitude=400000000, longitude=-750000000), hi=route_guide_pb2.Point(latitude=420000000, longitude=-730000000), ) print("Looking for features between 40, -75 and 42, -73") features = stub.ListFeatures(rectangle) async for feature in features: print(f"Feature called {feature.name} at {feature.location}") def generate_route( feature_list: List[route_guide_pb2.Feature], ) -> Iterable[route_guide_pb2.Point]: for _ in range(0, 10): random_feature = random.choice(feature_list) print(f"Visiting point {random_feature.location}") yield random_feature.location # Performs a client-streaming call async def guide_record_route(stub: route_guide_pb2_grpc.RouteGuideStub) -> None: feature_list = route_guide_resources.read_route_guide_database() route_iterator = generate_route(feature_list) # gRPC AsyncIO client-streaming RPC API accepts both synchronous iterables # and async iterables. route_summary = await stub.RecordRoute(route_iterator) print(f"Finished trip with {route_summary.point_count} points") print(f"Passed {route_summary.feature_count} features") print(f"Travelled {route_summary.distance} meters") print(f"It took {route_summary.elapsed_time} seconds") def generate_messages() -> Iterable[route_guide_pb2.RouteNote]: messages = [ make_route_note("First message", 0, 0), make_route_note("Second message", 0, 1), make_route_note("Third message", 1, 0), make_route_note("Fourth message", 0, 0), make_route_note("Fifth message", 1, 0), ] for msg in messages: print(f"Sending {msg.message} at {msg.location}") yield msg # Performs a bidi-streaming call async def guide_route_chat(stub: route_guide_pb2_grpc.RouteGuideStub) -> None: # gRPC AsyncIO bidi-streaming RPC API accepts both synchronous iterables # and async iterables. call = stub.RouteChat(generate_messages()) async for response in call: print(f"Received message {response.message} at {response.location}") async def main() -> None: async with grpc.aio.insecure_channel("localhost:50051") as channel: stub = route_guide_pb2_grpc.RouteGuideStub(channel) print("-------------- GetFeature --------------") await guide_get_feature(stub) print("-------------- ListFeatures --------------") await guide_list_features(stub) print("-------------- RecordRoute --------------") await guide_record_route(stub) print("-------------- RouteChat --------------") await guide_route_chat(stub) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(main())
5,044
34.034722
80
py
grpc
grpc-master/examples/python/route_guide/route_guide_server.py
# Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Python implementation of the gRPC route guide server.""" from concurrent import futures import logging import math import time import grpc import route_guide_pb2 import route_guide_pb2_grpc import route_guide_resources def get_feature(feature_db, point): """Returns Feature at given location or None.""" for feature in feature_db: if feature.location == point: return feature return None def get_distance(start, end): """Distance between two points.""" coord_factor = 10000000.0 lat_1 = start.latitude / coord_factor lat_2 = end.latitude / coord_factor lon_1 = start.longitude / coord_factor lon_2 = end.longitude / coord_factor lat_rad_1 = math.radians(lat_1) lat_rad_2 = math.radians(lat_2) delta_lat_rad = math.radians(lat_2 - lat_1) delta_lon_rad = math.radians(lon_2 - lon_1) # Formula is based on http://mathforum.org/library/drmath/view/51879.html a = pow(math.sin(delta_lat_rad / 2), 2) + ( math.cos(lat_rad_1) * math.cos(lat_rad_2) * pow(math.sin(delta_lon_rad / 2), 2) ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) R = 6371000 # metres return R * c class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): """Provides methods that implement functionality of route guide server.""" def __init__(self): self.db = route_guide_resources.read_route_guide_database() def GetFeature(self, request, context): feature = get_feature(self.db, request) if feature is None: return route_guide_pb2.Feature(name="", location=request) else: return feature def ListFeatures(self, request, context): left = min(request.lo.longitude, request.hi.longitude) right = max(request.lo.longitude, request.hi.longitude) top = max(request.lo.latitude, request.hi.latitude) bottom = min(request.lo.latitude, request.hi.latitude) for feature in self.db: if ( feature.location.longitude >= left and feature.location.longitude <= right and feature.location.latitude >= bottom and feature.location.latitude <= top ): yield feature def RecordRoute(self, request_iterator, context): point_count = 0 feature_count = 0 distance = 0.0 prev_point = None start_time = time.time() for point in request_iterator: point_count += 1 if get_feature(self.db, point): feature_count += 1 if prev_point: distance += get_distance(prev_point, point) prev_point = point elapsed_time = time.time() - start_time return route_guide_pb2.RouteSummary( point_count=point_count, feature_count=feature_count, distance=int(distance), elapsed_time=int(elapsed_time), ) def RouteChat(self, request_iterator, context): prev_notes = [] for new_note in request_iterator: for prev_note in prev_notes: if prev_note.location == new_note.location: yield prev_note prev_notes.append(new_note) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) route_guide_pb2_grpc.add_RouteGuideServicer_to_server( RouteGuideServicer(), server ) server.add_insecure_port("[::]:50051") server.start() server.wait_for_termination() if __name__ == "__main__": logging.basicConfig() serve()
4,221
31.229008
78
py
grpc
grpc-master/examples/python/route_guide/route_guide_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import route_guide_pb2 as route__guide__pb2 class RouteGuideStub(object): """Interface exported by the server. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetFeature = channel.unary_unary( '/routeguide.RouteGuide/GetFeature', request_serializer=route__guide__pb2.Point.SerializeToString, response_deserializer=route__guide__pb2.Feature.FromString, ) self.ListFeatures = channel.unary_stream( '/routeguide.RouteGuide/ListFeatures', request_serializer=route__guide__pb2.Rectangle.SerializeToString, response_deserializer=route__guide__pb2.Feature.FromString, ) self.RecordRoute = channel.stream_unary( '/routeguide.RouteGuide/RecordRoute', request_serializer=route__guide__pb2.Point.SerializeToString, response_deserializer=route__guide__pb2.RouteSummary.FromString, ) self.RouteChat = channel.stream_stream( '/routeguide.RouteGuide/RouteChat', request_serializer=route__guide__pb2.RouteNote.SerializeToString, response_deserializer=route__guide__pb2.RouteNote.FromString, ) class RouteGuideServicer(object): """Interface exported by the server. """ def GetFeature(self, request, context): """A simple RPC. Obtains the feature at a given position. A feature with an empty name is returned if there's no feature at the given position. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListFeatures(self, request, context): """A server-to-client streaming RPC. Obtains the Features available within the given Rectangle. Results are streamed rather than returned at once (e.g. in a response message with a repeated field), as the rectangle may cover a large area and contain a huge number of features. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def RecordRoute(self, request_iterator, context): """A client-to-server streaming RPC. Accepts a stream of Points on a route being traversed, returning a RouteSummary when traversal is completed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def RouteChat(self, request_iterator, context): """A Bidirectional streaming RPC. Accepts a stream of RouteNotes sent while a route is being traversed, while receiving other RouteNotes (e.g. from other users). """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_RouteGuideServicer_to_server(servicer, server): rpc_method_handlers = { 'GetFeature': grpc.unary_unary_rpc_method_handler( servicer.GetFeature, request_deserializer=route__guide__pb2.Point.FromString, response_serializer=route__guide__pb2.Feature.SerializeToString, ), 'ListFeatures': grpc.unary_stream_rpc_method_handler( servicer.ListFeatures, request_deserializer=route__guide__pb2.Rectangle.FromString, response_serializer=route__guide__pb2.Feature.SerializeToString, ), 'RecordRoute': grpc.stream_unary_rpc_method_handler( servicer.RecordRoute, request_deserializer=route__guide__pb2.Point.FromString, response_serializer=route__guide__pb2.RouteSummary.SerializeToString, ), 'RouteChat': grpc.stream_stream_rpc_method_handler( servicer.RouteChat, request_deserializer=route__guide__pb2.RouteNote.FromString, response_serializer=route__guide__pb2.RouteNote.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'routeguide.RouteGuide', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class RouteGuide(object): """Interface exported by the server. """ @staticmethod def GetFeature(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/routeguide.RouteGuide/GetFeature', route__guide__pb2.Point.SerializeToString, route__guide__pb2.Feature.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def ListFeatures(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/routeguide.RouteGuide/ListFeatures', route__guide__pb2.Rectangle.SerializeToString, route__guide__pb2.Feature.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def RecordRoute(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_unary(request_iterator, target, '/routeguide.RouteGuide/RecordRoute', route__guide__pb2.Point.SerializeToString, route__guide__pb2.RouteSummary.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def RouteChat(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_stream(request_iterator, target, '/routeguide.RouteGuide/RouteChat', route__guide__pb2.RouteNote.SerializeToString, route__guide__pb2.RouteNote.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
7,560
39.005291
109
py