├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.md ├── doge ├── __init__.py ├── cluster │ ├── __init__.py │ ├── endpoint.py │ ├── ha.py │ └── lb.py ├── common │ ├── __init__.py │ ├── context.py │ ├── doge.py │ ├── exceptions.py │ ├── url.py │ └── utils.py ├── config │ ├── __init__.py │ └── config.py ├── filter │ ├── __init__.py │ ├── metrics │ │ ├── __init__.py │ │ ├── client.py │ │ └── server.py │ └── tracing.py ├── gunicorn │ ├── __init__.py │ ├── configs.py │ └── worker.py ├── registry │ ├── __init__.py │ └── registry.py └── rpc │ ├── __init__.py │ ├── client.py │ └── server.py ├── download_etcd.sh ├── examples ├── client.py ├── client.yaml ├── server.py └── server.yaml ├── requirements.txt ├── setup.py └── tests ├── __init__.py ├── client.yaml ├── server.yaml ├── test_client.py ├── test_config.py ├── test_endpoint.py ├── test_ha.py ├── test_lb.py ├── test_registry.py ├── test_server.py └── test_url.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = doge/ 4 | 5 | [report] 6 | exclude_lines = 7 | if self.debug: 8 | pragma: no cover 9 | raise NotImplementedError 10 | if __name__ == .__main__.: 11 | ignore_errors = True 12 | omit = 13 | tests/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | before_install: 5 | - "sudo apt-get install python-dev" 6 | - ./download_etcd.sh 2.3.7 7 | install: 8 | - pip install -r requirements.txt 9 | - pip install pytest pytest-cov codecov flake8 mypy 10 | before_script: 11 | - nohup ./bin/etcd & 12 | script: 13 | - flake8 doge 14 | - mypy doge 15 | - pytest --cov=./ 16 | after_success: 17 | - codecov -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md requirements.txt 2 | recursive-include doge *.* 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Doge 2 | 3 | 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/zhu327/doge/blob/master/LICENSE) 5 | [![Build Status](https://travis-ci.org/zhu327/doge.svg?branch=master)](https://travis-ci.org/zhu327/doge) 6 | [![codecov](https://codecov.io/gh/zhu327/doge/branch/master/graph/badge.svg)](https://codecov.io/gh/zhu327/doge) 7 | [![codebeat badge](https://codebeat.co/badges/1624b195-bbf5-43d0-9f9d-d330ca09ab76)](https://codebeat.co/projects/github-com-zhu327-doge-master) 8 | 9 | Doge is a Python RPC framework like [Alibaba Dubbo](http://dubbo.io/) and [Weibo Motan](https://github.com/weibocom/motan). 10 | 11 | ## Features 12 | 13 | ![doge](https://camo.githubusercontent.com/51ff9a1d5530f269f3074e9172483acf14c73eb8/687474703a2f2f6e2e73696e61696d672e636e2f746563682f7472616e73666f726d2f32303136303531302f4a7458792d66787279686875323338323938372e6a7067) 14 | 15 | - 服务治理, 服务注册, 服务发现 16 | - 高可用策略, failover, backupRequestHA 17 | - 负载均衡策略, RandomLB, RoundrobinLB 18 | - 限流策略, gevent Pool 19 | - 功能扩展, Opentracing, Prometheus 20 | 21 | ## Quick Start 22 | 23 | ### Installation 24 | 25 | ```sh 26 | pip install dogerpc 27 | ``` 28 | 29 | 你可以在[examples](https://github.com/zhu327/doge/tree/master/examples)找到以下实例 30 | 31 | ### Doge server 32 | 33 | 1. 新建server端配置文件 34 | 35 | ```yml 36 | registry: # 注册中心 37 | protocol: etcd # 注册协议, 支持 etcd 与 direct, 默认 etcd 38 | host: 127.0.0.1 # 注册中心 host 39 | port: 2379 # 注册中心 port 40 | # "address": "127.0.0.1:2379,127.0.0.1:4001", # 注册中心地址, 如果有etcd集群, 可配置多个node 41 | ttl: 10 # etcd注册ttl, 用于server的心跳检查, 默认10s 42 | service: 43 | name: test # 服务名称 44 | node: n1 # 节点名称 45 | host: 127.0.0.1 # 服务暴露ip 46 | port: 4399 # 服务暴露port 47 | limitConn: 100 # 服务最大连接数, 可选, 默认不限制 48 | filters: # 服务端扩展中间件 49 | - doge.filter.tracing.TracingServerFilter # opentracing 50 | - doge.filter.metrics.MetricsServerFilter # prometheus 51 | ``` 52 | 53 | 2. 定义RPC methods类, 启动服务 54 | 55 | ```python 56 | # coding: utf-8 57 | 58 | from gevent import monkey 59 | monkey.patch_socket() # 依赖gevent 60 | 61 | import logging 62 | logging.basicConfig(level=logging.DEBUG) 63 | 64 | from doge.rpc.server import new_server 65 | 66 | 67 | # 定义rpc方法类 68 | class Sum(object): 69 | def sum(self, x, y): 70 | return x + y 71 | 72 | 73 | if __name__ == '__main__': 74 | server = new_server('server.yaml') # 基于配置文件实例化server对象 75 | server.load(Sum) # 加载暴露rpc方法类 76 | server.run() # 启动服务并注册节点信息到注册中心 77 | ``` 78 | 79 | ### Doge client 80 | 81 | 1. 新建client端配置文件 82 | 83 | ```yml 84 | registry: # 注册中心 85 | protocol: etcd # 注册协议, 支持 etcd 与 direct, 默认 etcd 86 | host: 127.0.0.1 # 注册中心 host 87 | port: 2379 # 注册中心 port 88 | # "address": "127.0.0.1:2379,127.0.0.1:4001", # 注册中心地址, 如果有etcd集群, 可配置多个node 89 | ttl: 10 # etcd注册ttl, 用于server的心跳检查, 默认10s 90 | refer: 91 | haStrategy: failover # 高可用策略, 支持 failover backupRequestHA, 默认failover 92 | loadBalance: RoundrobinLB # 负载均衡策略, 支持 RandomLB RoundrobinLB, 默认RoundrobinLB 93 | filters: # 客户端扩展中间件 94 | - doge.filter.tracing.TracingClientFilter # opentracing 95 | - doge.filter.metrics.MetricsClientFilter # prometheus 96 | ``` 97 | 98 | 2. 创建client并call远程方法 99 | 100 | ```python 101 | # coding: utf-8 102 | 103 | from __future__ import print_function 104 | 105 | from gevent import monkey 106 | monkey.patch_socket() 107 | 108 | import logging 109 | logging.basicConfig(level=logging.DEBUG) 110 | 111 | from doge.rpc.client import Cluster 112 | 113 | if __name__ == '__main__': 114 | cluster = Cluster('client.yaml') # 基于配置文件实例化Cluster对象 115 | client = cluster.get_client("test") # 获取服务名对应的Client对象 116 | print(client.call('sum', 1, 2)) # 远程调用服务Sum类下的sum方法 117 | ``` 118 | 119 | ### Doge filter 120 | 121 | `filter`是Doge提供的自定义中间件扩展机制, 当前提供了`jaeger`链路跟踪与`Prometheus`的metrics, `filter`分为客户端`filter`与服务端`filter`, 具体的实例可以参考`filter`目录下的`tracing.py` 122 | 123 | #### Metrics 124 | 125 | 在使用`Prometheus`监控时, 需要在服务节点上配置环境变量`prometheus_multiproc_dir`用于存储`Gunicorn`启动多进程时的`metrics`数据, 然后在服务节点启动`Prometheus Python Exporter` 126 | 127 | 128 | 129 | 如何在多进程下使用`Prometheus`请[参考这里]( https://github.com/prometheus/client_python#multiprocess-mode-gunicorn ) 130 | 131 | ## Doge json gateway 132 | 133 | 基于Bottle实现的json rpc gateway 134 | 135 | 136 | 137 | ## Gunicorn server 138 | 139 | 创建`app.py`, 沿用example中的配置文件`server.json` 140 | 141 | ```python 142 | # coding: utf-8 143 | 144 | from doge.rpc.server import new_server 145 | 146 | 147 | # 定义rpc方法类 148 | class Sum(object): 149 | def sum(self, x, y): 150 | return x + y 151 | 152 | 153 | server = new_server('server.yaml') # 基于配置文件实例化server对象 154 | server.load(Sum) # 加载暴露rpc方法类 155 | ``` 156 | 157 | 创建`configs.py`, 填写的bind必须与`server.yaml`配置的监听端口一致 158 | ```python 159 | from doge.gunicorn.configs import * 160 | 161 | bind = "127.0.0.1:4399" 162 | ``` 163 | 164 | 启动Gunicorn 165 | 166 | ```shell 167 | gunicorn app:server -c configs.py 168 | ``` 169 | 170 | ## Requirements 171 | 172 | - [gevent](https://github.com/gevent/gevent) 173 | - [mprpc](https://github.com/studio-ousia/mprpc) 174 | - [python-etcd](https://github.com/jplana/python-etcd) 175 | - [pyformance](https://github.com/omergertel/pyformance) 176 | - [pyyaml](https://github.com/yaml/pyyaml) 177 | - [prometheus_client](https://github.com/prometheus/client_python) 178 | - [jaeger-client](https://github.com/monsterxx03/jaeger-client-python) 179 | 180 | ## License 181 | 182 | Apache License, Version 2.0 183 | -------------------------------------------------------------------------------- /doge/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/__init__.py -------------------------------------------------------------------------------- /doge/cluster/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/cluster/__init__.py -------------------------------------------------------------------------------- /doge/cluster/endpoint.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import time 4 | from typing import Union 5 | 6 | import gevent # type: ignore 7 | from gevent import socket # type: ignore 8 | from gsocketpool.exceptions import PoolExhaustedError # type: ignore 9 | from mprpc import RPCPoolClient # type: ignore 10 | from mprpc.exceptions import RPCError, RPCProtocolError # type: ignore 11 | 12 | from doge.common.doge import Request, Response 13 | from doge.common.exceptions import RemoteError 14 | from doge.common.url import URL 15 | from doge.common.utils import ConnPool 16 | 17 | defaultPoolSize = 3 18 | defaultRequestTimeout = 1 19 | defaultConnectTimeout = 1 20 | defaultKeepaliveInterval = 10 21 | defaultErrorCountThreshold = 10 22 | 23 | 24 | class EndPoint: 25 | def __init__(self, url: URL) -> None: 26 | self.url = url 27 | self.available = True 28 | self.error_count = 0 29 | self.keepalive_count = 0 30 | self.pool = self.pool_factory() 31 | 32 | def pool_factory(self) -> ConnPool: 33 | return ConnPool( 34 | RPCPoolClient, 35 | dict( 36 | host=self.url.host, 37 | port=self.url.port, 38 | timeout=defaultConnectTimeout, 39 | keep_alive=True, 40 | ), 41 | max_connections=defaultPoolSize, 42 | reap_expired_connections=False, 43 | ) 44 | 45 | def call(self, request: Request) -> Response: 46 | try: 47 | with self.pool.connection() as client: 48 | if not client.is_connected(): 49 | client.open() 50 | res = client.call(request.method, request.meta, *request.args) 51 | except PoolExhaustedError: 52 | self.record_error() 53 | return Response(exception=RemoteError("connection pool full")) 54 | except (RPCError, RPCProtocolError) as e: 55 | return Response(exception=RemoteError(str(e))) 56 | except (IOError, socket.timeout): 57 | self.record_error() 58 | return Response(exception=RemoteError("socket error or bad method")) 59 | self.reset_error() 60 | return Response(value=res) 61 | 62 | def record_error(self) -> None: 63 | self.error_count += 1 64 | if self.error_count == defaultErrorCountThreshold: 65 | self.available = False 66 | gevent.spawn(self.keepalive) 67 | 68 | def keepalive(self): 69 | self.keepalive_count += 1 70 | 71 | start = time.time() 72 | while time.time() - start < defaultKeepaliveInterval: 73 | sock = None 74 | try: 75 | sock = socket.create_connection( 76 | (self.url.host, self.url.port), defaultConnectTimeout 77 | ) 78 | except Exception: 79 | pass 80 | else: 81 | self.available = True 82 | self.reset_error() 83 | return 84 | finally: 85 | if sock: 86 | sock.close() 87 | 88 | def reset_error(self) -> None: 89 | self.error_count = 0 90 | 91 | def destroy(self) -> None: 92 | self.available = False 93 | del self.pool 94 | 95 | 96 | def new_endpoint(k: Union[int, str], v: str) -> EndPoint: 97 | host, port = v.split(":") 98 | url = URL(str(host), int(port), k) 99 | return EndPoint(url) 100 | -------------------------------------------------------------------------------- /doge/cluster/ha.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import logging 4 | from typing import Union 5 | 6 | import gevent # type: ignore 7 | from pyformance import MetricsRegistry # type: ignore 8 | 9 | from doge.cluster.endpoint import EndPoint 10 | from doge.cluster.lb import RandomLB, RoundrobinLB 11 | from doge.common.doge import Request, Response 12 | from doge.common.exceptions import RemoteError 13 | from doge.common.url import URL 14 | from doge.common.utils import time_ns 15 | 16 | defaultRetries = 0 17 | 18 | counterRoundCount = 100 # 默认每100次请求为一个计数周期 19 | counterScaleThreshold = 20 * 1e9 # 如果20s都没有经历一个循环周期则重置,防止过度饥饿 20 | defaultBackupRequestDelayRatio = 90 # 默认的请求延迟的水位线,P90 21 | defaultBackupRequestMaxRetryRatio = 15 # 最大重试比例 22 | defaultRequestTimeout = 1000 23 | 24 | logger = logging.getLogger("doge.cluster.ha") 25 | 26 | 27 | class FailOverHA: 28 | def __init__(self, url: URL) -> None: 29 | self.url = url 30 | self.name = "failover" 31 | 32 | def call(self, request: Request, lb: Union[RandomLB, RoundrobinLB]) -> Response: 33 | retries = self.url.get_method_positive_int_value( 34 | request.method, "retries", defaultRetries 35 | ) 36 | 37 | i = 0 38 | while i <= retries: 39 | i += 1 40 | ep = lb.select(request) 41 | if not ep: 42 | return Response(exception=RemoteError("no available endpoint")) 43 | res = ep.call(request) 44 | if not res.exception: 45 | return res 46 | return res 47 | 48 | 49 | class BackupRequestHA: 50 | def __init__(self, url: URL) -> None: 51 | self.url = url 52 | self.name = "backupRequestHA" 53 | 54 | self.curRoundTotalCount = 0 55 | self.curRoundRetryCount = 0 56 | 57 | self.init() 58 | 59 | def init(self) -> None: 60 | self.registry = MetricsRegistry() 61 | self.lastResetTime = time_ns() 62 | 63 | def call(self, request: Request, lb: Union[RandomLB, RoundrobinLB]) -> Response: 64 | ep_list = lb.select_list(request) 65 | if not ep_list: 66 | return Response(exception=RemoteError("no available endpoint")) 67 | retries = self.url.get_method_int_value(request.method, "retries", 0) 68 | if retries == 0: 69 | return self.do_call(request, ep_list[0]) 70 | 71 | backupRequestDelayRatio = self.url.get_method_positive_int_value( 72 | request.method, 73 | "backupRequestDelayRatio", 74 | defaultBackupRequestDelayRatio, 75 | ) 76 | backupRequestMaxRetryRatio = self.url.get_method_positive_int_value( 77 | request.method, 78 | "backupRequestMaxRetryRatio", 79 | defaultBackupRequestMaxRetryRatio, 80 | ) 81 | requestTimeout = self.url.get_method_positive_int_value( 82 | request.method, "requestTimeout", defaultRequestTimeout 83 | ) 84 | 85 | histogram = self.registry.histogram(request.method) 86 | delay = int( 87 | histogram.get_snapshot().get_percentile(backupRequestDelayRatio / 100.0) 88 | ) 89 | if delay < 10: 90 | delay = 10 91 | 92 | logger.debug( 93 | f"service: {request.service} method: {request.method}" 94 | + f" ha delay: {str(delay)}" 95 | ) 96 | 97 | with gevent.Timeout(requestTimeout / 1000.0, False): 98 | i = 0 99 | while i <= retries and i < len(ep_list): 100 | ep = ep_list[i] 101 | if i == 0: 102 | self.update_call_record(counterRoundCount) 103 | if i > 0 and not self.try_acquirePermit(backupRequestMaxRetryRatio): 104 | break 105 | 106 | def func(): 107 | start = time_ns() 108 | res = self.do_call(request, ep) 109 | if not res.exception: 110 | histogram.add(float(time_ns() - start) / 1e6) 111 | return res 112 | 113 | g = gevent.spawn(func) 114 | try: 115 | res = g.get(timeout=(delay / 1000.0)) 116 | if res: 117 | return res 118 | except gevent.timeout.Timeout: 119 | pass 120 | 121 | i += 1 122 | 123 | return Response(exception=RemoteError("request timeout")) 124 | 125 | def do_call(self, request: Request, ep: EndPoint) -> Response: 126 | return ep.call(request) 127 | 128 | def update_call_record(self, threshold_limit: int) -> None: 129 | if ( 130 | self.curRoundTotalCount > threshold_limit 131 | or (time_ns() - self.lastResetTime) >= counterScaleThreshold 132 | ): 133 | self.curRoundTotalCount = 1 134 | self.curRoundRetryCount = 0 135 | self.lastResetTime = time_ns() 136 | else: 137 | self.curRoundTotalCount += 1 138 | 139 | def try_acquirePermit(self, threshold_limit: int) -> bool: 140 | if self.curRoundRetryCount >= threshold_limit: 141 | return False 142 | self.curRoundRetryCount += 1 143 | return True 144 | -------------------------------------------------------------------------------- /doge/cluster/lb.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import random 4 | from typing import List, Optional, Tuple 5 | 6 | from doge.cluster.endpoint import EndPoint 7 | from doge.common.doge import Request 8 | from doge.common.url import URL 9 | 10 | MaxSelectArraySize = 3 11 | defaultWeight = 1 12 | 13 | 14 | class RandomLB: 15 | """随机 Load Balance""" 16 | 17 | def __init__( 18 | self, url: URL, endpoints: List[EndPoint], weight: None = None 19 | ) -> None: 20 | self.url = url 21 | self.endpoints = endpoints 22 | self.weight = None 23 | 24 | def select(self, request: Request) -> Optional[EndPoint]: 25 | _, ep = select_one_random(self.endpoints) 26 | return ep 27 | 28 | def select_list(self, request: Request) -> List[EndPoint]: 29 | index, ep = select_one_random(self.endpoints) 30 | if not ep: 31 | return [] 32 | return select_list_from_index(self.endpoints, index) 33 | 34 | 35 | class RoundrobinLB: 36 | """Roundrobin Load Balance""" 37 | 38 | def __init__( 39 | self, url: URL, endpoints: List[EndPoint], weight: None = None 40 | ) -> None: 41 | self.url = url 42 | self.endpoints = endpoints 43 | self.weight = None 44 | self.index = 0 45 | 46 | def select(self, request: Request) -> Optional[EndPoint]: 47 | _, ep = self.roundrobin_select() 48 | return ep 49 | 50 | def select_list(self, request): 51 | index, ep = self.roundrobin_select() 52 | if not ep: 53 | return ep 54 | return select_list_from_index(self.endpoints, index) 55 | 56 | def roundrobin_select( 57 | self, 58 | ) -> Tuple[int, Optional[EndPoint]]: 59 | eps = self.endpoints 60 | if not eps: 61 | return -1, None 62 | 63 | self.index += 1 64 | idx = self.index % len(eps) 65 | if eps[idx].available: 66 | return idx, eps[idx] 67 | 68 | return select_one_random(self.endpoints) 69 | 70 | 71 | def select_one_random(eps: List[EndPoint]) -> Tuple[int, Optional[EndPoint]]: 72 | eps_len = len(eps) 73 | if eps_len == 0: 74 | return -1, None 75 | 76 | index = random.randint(0, eps_len - 1) 77 | if eps[index].available: 78 | return index, eps[index] 79 | 80 | rd = random.randint(0, eps_len - 1) 81 | for i in range(eps_len): 82 | rdi = (rd + i) % eps_len 83 | if eps[rdi].available: 84 | return rdi, eps[rdi] 85 | 86 | return -1, None 87 | 88 | 89 | def select_list_from_index(eps: List[EndPoint], index: int) -> List[EndPoint]: 90 | if not eps or index < 0: 91 | return [] 92 | 93 | eps_len = len(eps) 94 | ep_list = [] 95 | for i in range(eps_len): 96 | idx = (index + i) % eps_len 97 | if eps[idx].available: 98 | ep_list.append(eps[idx]) 99 | if len(ep_list) == MaxSelectArraySize: 100 | break 101 | return ep_list 102 | -------------------------------------------------------------------------------- /doge/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/common/__init__.py -------------------------------------------------------------------------------- /doge/common/context.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from typing import Dict, List, Union 4 | 5 | from gevent.local import local # type: ignore 6 | 7 | from doge.cluster.endpoint import EndPoint, new_endpoint 8 | from doge.cluster.ha import BackupRequestHA, FailOverHA 9 | from doge.cluster.lb import RandomLB, RoundrobinLB 10 | from doge.common.doge import Executer, Registry 11 | from doge.common.exceptions import ReferCfgError, RegistryCfgError 12 | from doge.common.url import URL 13 | from doge.filter import FilterChain 14 | from doge.registry.registry import DirectRegistry, EtcdRegistry 15 | 16 | rpc_local = local() 17 | 18 | 19 | class Context: 20 | def __init__(self, url: URL, registry_url: URL) -> None: 21 | self.url = url 22 | self.registry_url = registry_url 23 | 24 | def get_registry(self) -> Registry: # TODO 定义Registry 25 | protocol = self.registry_url.get_param("protocol", "etcd") 26 | if protocol == "etcd": 27 | return EtcdRegistry(self.registry_url) 28 | elif protocol == "direct": 29 | return DirectRegistry(self.registry_url) 30 | raise RegistryCfgError 31 | 32 | def get_endpoints( 33 | self, registry: Registry, service: str 34 | ) -> Union[Dict[int, EndPoint], Dict[str, EndPoint]]: 35 | eps = {} 36 | for k, v in registry.discovery(service).items(): 37 | eps[k] = new_endpoint(k, v) 38 | return eps 39 | 40 | def get_ha(self) -> Union[FailOverHA, BackupRequestHA]: 41 | name = self.url.get_param("haStrategy", "failover") 42 | if name == "failover": 43 | return FailOverHA(self.url) 44 | elif name == "backupRequestHA": 45 | return BackupRequestHA(self.url) 46 | raise ReferCfgError 47 | 48 | def get_lb(self, eps: List[EndPoint]) -> Union[RoundrobinLB, RandomLB]: 49 | name = self.url.get_param("loadBalance", "RoundrobinLB") 50 | if name == "RandomLB": 51 | return RandomLB(self.url, eps) 52 | elif name == "RoundrobinLB": 53 | return RoundrobinLB(self.url, eps) 54 | raise ReferCfgError 55 | 56 | def get_filter(self, executer: Executer) -> Executer: 57 | return FilterChain(self).then(executer) 58 | -------------------------------------------------------------------------------- /doge/common/doge.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from abc import ABCMeta, abstractmethod 4 | from typing import Any, Callable, Dict, Optional 5 | 6 | from doge.common.url import URL 7 | 8 | 9 | class Response: 10 | def __init__( 11 | self, 12 | value: Any = None, 13 | exception: Optional[Exception] = None, 14 | ) -> None: 15 | self.value = value 16 | self.exception = exception 17 | self.prosess_time = 0 18 | 19 | 20 | class Request: 21 | def __init__(self, service: Optional[str], method: str, *args, meta=None) -> None: 22 | self.service = service 23 | self.method = method 24 | self.args = args 25 | self.meta = meta or {} 26 | 27 | 28 | class Executer(metaclass=ABCMeta): 29 | @abstractmethod 30 | def execute(self, req: Request) -> Response: 31 | pass 32 | 33 | 34 | class Registry(metaclass=ABCMeta): 35 | @abstractmethod 36 | def __init__(self, url: URL) -> None: 37 | self.url = url 38 | 39 | @abstractmethod 40 | def register(self, service, url): 41 | pass 42 | 43 | @abstractmethod 44 | def deregister(self, service, url): 45 | pass 46 | 47 | @abstractmethod 48 | def discovery(self, service: str) -> Dict[str, str]: 49 | pass 50 | 51 | @abstractmethod 52 | def watch(self, service: str, callback: Callable) -> None: 53 | pass 54 | 55 | @abstractmethod 56 | def destroy(self) -> None: 57 | pass 58 | -------------------------------------------------------------------------------- /doge/common/exceptions.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | 4 | class DogeError(Exception): 5 | pass 6 | 7 | 8 | class ServerLoadError(DogeError): 9 | pass 10 | 11 | 12 | class RemoteError(DogeError): 13 | pass 14 | 15 | 16 | class ClientError(DogeError): 17 | pass 18 | 19 | 20 | class RegistryCfgError(DogeError): 21 | pass 22 | 23 | 24 | class ServiceCfgError(DogeError): 25 | pass 26 | 27 | 28 | class ReferCfgError(DogeError): 29 | pass 30 | -------------------------------------------------------------------------------- /doge/common/url.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | 4 | from typing import Any, Optional, Union 5 | 6 | 7 | class URL: 8 | def __init__( 9 | self, 10 | host: Optional[str], 11 | port: Optional[Union[int, str]], 12 | path: Optional[Union[int, str]] = "", 13 | params: Optional[Any] = None, 14 | ) -> None: 15 | self.host = host 16 | self.port = port 17 | self.path = path 18 | self.params = params or {} 19 | 20 | def get_int(self, key: str) -> Optional[int]: 21 | if key in self.params and isinstance(self.params[key], int): 22 | return self.params[key] 23 | return None 24 | 25 | def get_int_value(self, key: str, default: int) -> int: 26 | value = self.get_int(key) 27 | return value or default 28 | 29 | def get_positive_int_value(self, key: str, default: int) -> int: 30 | value = self.get_int_value(key, default) 31 | return default if value < 1 else value 32 | 33 | def get_param(self, key: str, default: Any = None) -> Any: 34 | if key in self.params and self.params[key]: 35 | return self.params[key] 36 | return default 37 | 38 | def get_method_int_value(self, method: str, key: str, default: int) -> int: 39 | mkey = "".join([method, ".", key]) 40 | value = self.get_int(mkey) 41 | return value or default 42 | 43 | def get_method_positive_int_value(self, method: str, key: str, default: int) -> int: 44 | value = self.get_method_int_value(method, key, default) 45 | return value if value > 0 else default 46 | 47 | def set_param(self, key: str, value: int) -> None: 48 | self.params[key] = value 49 | -------------------------------------------------------------------------------- /doge/common/utils.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import time 4 | from importlib import import_module 5 | from typing import Any, Tuple 6 | 7 | from gsocketpool.pool import Pool # type: ignore 8 | from jaeger_client import Config # type: ignore 9 | from jaeger_client.tracer import Tracer # type: ignore 10 | from mprpc.client import RPCPoolClient # type: ignore 11 | 12 | 13 | def import_string( 14 | dotted_path: str, 15 | ) -> Any: 16 | try: 17 | module_path, class_name = dotted_path.rsplit(".", 1) 18 | except ValueError: 19 | msg = f"{dotted_path} doesn't look like a module path" 20 | raise ImportError(msg) 21 | 22 | module = import_module(module_path) 23 | 24 | try: 25 | return getattr(module, class_name) 26 | except AttributeError: 27 | msg = ( 28 | f'Module "{dotted_path}" does not define' 29 | + f' a "{class_name}" attribute/class' 30 | ) 31 | raise ImportError(msg) 32 | 33 | 34 | def time_ns() -> float: 35 | s, n = ("%.20f" % time.time()).split(".") 36 | return int(s) * 1e9 + int(n[:9]) 37 | 38 | 39 | def str_to_host(s: str) -> Tuple[str, int]: 40 | h, p = s.split(":") 41 | return (str(h), int(p)) 42 | 43 | 44 | class ConnPool(Pool): 45 | def _create_connection(self) -> RPCPoolClient: 46 | conn = self._factory(**self._options) 47 | # conn.open() 48 | 49 | return conn 50 | 51 | 52 | def init_tracer(service: str) -> Tracer: 53 | config = Config( 54 | config={"sampler": {"type": "const", "param": 1}, "logging": True}, 55 | service_name=service, 56 | ) 57 | 58 | # this call also sets opentracing.tracer 59 | return config.initialize_tracer() 60 | -------------------------------------------------------------------------------- /doge/config/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/config/__init__.py -------------------------------------------------------------------------------- /doge/config/config.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from io import open 4 | 5 | import yaml 6 | 7 | from doge.common.exceptions import ( 8 | ReferCfgError, 9 | RegistryCfgError, 10 | ServiceCfgError, 11 | ) 12 | from doge.common.url import URL 13 | 14 | 15 | class Config: 16 | def __init__(self, name: str) -> None: 17 | self.name = name 18 | self.cfg = self.config_from_file(name) 19 | 20 | def config_from_file(self, name: str): 21 | with open(name, "r", encoding="utf8") as f: 22 | return yaml.load(f, Loader=yaml.FullLoader) 23 | 24 | def parse_registry(self) -> URL: 25 | if "registry" not in self.cfg: 26 | raise RegistryCfgError("registry config not exists") 27 | rcfg = self.cfg["registry"] 28 | if ("host" not in rcfg) and ("address" not in rcfg): 29 | raise RegistryCfgError("host or address must be provided") 30 | host = rcfg.get("host", None) 31 | port = rcfg.get("port", None) 32 | return URL(host and str(host) or host, port and int(port) or port, params=rcfg) 33 | 34 | def parse_service(self) -> URL: 35 | if "service" not in self.cfg: 36 | raise ServiceCfgError("service config not exists") 37 | scfg = self.cfg["service"] 38 | if ("host" not in scfg) or ("port" not in scfg): 39 | raise ServiceCfgError("host and port must be provided") 40 | if ("name" not in scfg) or ("node" not in scfg): 41 | raise ServiceCfgError("name and node must be provided") 42 | return URL(str(scfg["host"]), int(scfg["port"]), params=scfg) 43 | 44 | def parse_refer(self) -> URL: 45 | if "refer" not in self.cfg: 46 | raise ReferCfgError("refer config not exists") 47 | rcfg = self.cfg["refer"] 48 | return URL(None, None, params=rcfg) 49 | -------------------------------------------------------------------------------- /doge/filter/__init__.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | from gevent.monkey import patch_thread # type: ignore 4 | 5 | from doge.common.doge import Executer, Request, Response 6 | from doge.common.utils import import_string 7 | 8 | patch_thread() 9 | 10 | 11 | class BaseFilter(Executer): 12 | def __init__(self, context: Any, _next: Executer): 13 | self.next = _next 14 | 15 | def execute(self, req: Request) -> Response: 16 | return self.next.execute(req) 17 | 18 | 19 | class FilterChain: 20 | def __init__(self, context: Any): 21 | self.context = context 22 | 23 | def then(self, executer: Executer) -> Executer: 24 | filters = self.context.url.get_param("filters", []) 25 | for cls in reversed([import_string(f) for f in filters]): 26 | executer = cls(self.context, executer) 27 | return executer 28 | -------------------------------------------------------------------------------- /doge/filter/metrics/__init__.py: -------------------------------------------------------------------------------- 1 | from doge.filter.metrics.client import MetricsClientFilter 2 | from doge.filter.metrics.server import MetricsServerFilter 3 | 4 | __all__ = ["MetricsClientFilter", "MetricsServerFilter"] 5 | -------------------------------------------------------------------------------- /doge/filter/metrics/client.py: -------------------------------------------------------------------------------- 1 | from prometheus_client import Counter, Histogram # type: ignore 2 | 3 | from doge.common.doge import Request, Response 4 | from doge.filter import BaseFilter 5 | 6 | DOGE_CLIENT_STARTED_TOTAL_COUNTER = Counter( 7 | "doge_client_started_total", 8 | "Total number of RPCs started on the client", 9 | ["doge_service", "doge_method"], 10 | ) 11 | 12 | DOGE_CLIENT_COMPLETED_COUNTER = Counter( 13 | "doge_client_completed", 14 | ( 15 | "Total number of RPCs completed on the client, " 16 | + "regardless of success or failure." 17 | ), 18 | ["doge_service", "doge_method", "code"], 19 | ) 20 | 21 | DOGE_CLIENT_COMPLETED_LATENCY_SECONDS_HISTOGRAM = Histogram( 22 | "doge_client_completed_latency_seconds", 23 | "Histogram of rpc response latency (in seconds) for completed rpcs.", 24 | ["doge_service", "doge_method"], 25 | ) 26 | 27 | 28 | class MetricsClientFilter(BaseFilter): 29 | def execute(self, req: Request) -> Response: 30 | doge_service = req.service 31 | doge_method = req.method 32 | 33 | DOGE_CLIENT_STARTED_TOTAL_COUNTER.labels( 34 | doge_service=doge_service, doge_method=doge_method 35 | ).inc() 36 | 37 | with DOGE_CLIENT_COMPLETED_LATENCY_SECONDS_HISTOGRAM.labels( 38 | doge_service=doge_service, doge_method=doge_method 39 | ).time(): 40 | res = self.next.execute(req) 41 | 42 | DOGE_CLIENT_COMPLETED_COUNTER.labels( 43 | doge_service=doge_service, 44 | doge_method=doge_method, 45 | code=0 if not res.exception else 1, 46 | ).inc() 47 | 48 | return res 49 | -------------------------------------------------------------------------------- /doge/filter/metrics/server.py: -------------------------------------------------------------------------------- 1 | from prometheus_client import Counter, Histogram # type: ignore 2 | 3 | from doge.common.doge import Request, Response 4 | from doge.filter import BaseFilter 5 | 6 | DOGE_SERVER_STARTED_TOTAL_COUNTER = Counter( 7 | "doge_server_started_total", 8 | "Total number of RPCs started on the server.", 9 | ["doge_service", "doge_method"], 10 | ) 11 | 12 | DOGE_SERVER_HANDLED_TOTAL_COUNTER = Counter( 13 | "doge_server_handled_total", 14 | ( 15 | "Total number of RPCs completed on the server, " 16 | + "regardless of success or failure." 17 | ), 18 | ["doge_service", "doge_method", "code"], 19 | ) 20 | 21 | DOGE_SERVER_HANDLED_LATENCY_SECONDS = Histogram( 22 | "doge_server_handled_latency_seconds", 23 | ( 24 | "Histogram of response latency (seconds) of gRPC that had been " 25 | + "application-level handled by the server" 26 | ), 27 | ["doge_service", "doge_method"], 28 | ) 29 | 30 | 31 | class MetricsServerFilter(BaseFilter): 32 | def execute(self, req: Request) -> Response: 33 | doge_service = req.service 34 | doge_method = req.method 35 | 36 | DOGE_SERVER_STARTED_TOTAL_COUNTER.labels( 37 | doge_service=doge_service, doge_method=doge_method 38 | ).inc() 39 | 40 | with DOGE_SERVER_HANDLED_LATENCY_SECONDS.labels( 41 | doge_service=doge_service, doge_method=doge_method 42 | ).time(): 43 | res = self.next.execute(req) 44 | 45 | DOGE_SERVER_HANDLED_TOTAL_COUNTER.labels( 46 | doge_service=doge_service, 47 | doge_method=doge_method, 48 | code=0 if not res.exception else 1, 49 | ).inc() 50 | 51 | return res 52 | -------------------------------------------------------------------------------- /doge/filter/tracing.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import opentracing # type: ignore 4 | from opentracing.ext import tags # type: ignore 5 | from opentracing.propagation import Format # type: ignore 6 | 7 | from doge.common.doge import Request, Response 8 | from doge.filter import BaseFilter 9 | 10 | tracer = opentracing.global_tracer() 11 | 12 | 13 | class TracingClientFilter(BaseFilter): 14 | def execute(self, req: Request) -> Response: 15 | span_ctx = tracer.extract(Format.TEXT_MAP, req.meta) if req.meta else None 16 | 17 | with tracer.start_active_span(req.method, child_of=span_ctx) as scope: 18 | scope.span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT) 19 | scope.span.set_tag("doge_service", req.service) 20 | scope.span.set_tag("doge_method", req.method) 21 | 22 | if not span_ctx: 23 | tracer.inject(scope.span, Format.TEXT_MAP, req.meta) 24 | 25 | res = self.next.execute(req) 26 | if res.exception: 27 | scope.span.set_tag("error", True) 28 | scope.span.log_event({"event": "error", "exception": res.exception}) 29 | return res 30 | 31 | 32 | class TracingServerFilter(BaseFilter): 33 | def execute(self, req: Request) -> Response: 34 | span_ctx = tracer.extract(Format.TEXT_MAP, req.meta) 35 | span_tags = {tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER} 36 | 37 | with tracer.start_active_span( 38 | req.method, child_of=span_ctx, tags=span_tags 39 | ) as scope: 40 | scope.span.set_tag("doge_service", req.service) 41 | scope.span.set_tag("doge_method", req.method) 42 | 43 | res = self.next.execute(req) 44 | if res.exception: 45 | scope.span.set_tag("error", True) 46 | scope.span.log_event({"event": "error", "exception": res.exception}) 47 | return res 48 | -------------------------------------------------------------------------------- /doge/gunicorn/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/gunicorn/__init__.py -------------------------------------------------------------------------------- /doge/gunicorn/configs.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from prometheus_client import multiprocess # type: ignore 3 | 4 | reuse_port = True 5 | worker_class = "doge.gunicorn.worker.DogeWorker" 6 | 7 | 8 | def when_ready(server): 9 | from gevent import monkey # type: ignore 10 | 11 | monkey.patch_socket() 12 | 13 | server.app.wsgi().register() 14 | 15 | 16 | def on_exit(server): 17 | app = server.app.wsgi() 18 | app.registry.deregister(app.name, app.url) 19 | 20 | 21 | def child_exit(server, worker): 22 | multiprocess.mark_process_dead(worker.pid) 23 | -------------------------------------------------------------------------------- /doge/gunicorn/worker.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from gunicorn.workers.ggevent import GeventWorker # type: ignore 4 | 5 | 6 | class DogeWorker(GeventWorker): 7 | """适用于Doge的Gunicorn Worker""" 8 | 9 | def handle(self, listener, client, addr): 10 | client.setblocking(1) 11 | self.wsgi.handler(client, addr) 12 | -------------------------------------------------------------------------------- /doge/registry/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/registry/__init__.py -------------------------------------------------------------------------------- /doge/registry/registry.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import logging 4 | from typing import Callable, Dict 5 | 6 | import etcd # type: ignore 7 | import gevent # type: ignore 8 | from etcd.client import Client # type: ignore 9 | 10 | from doge.common.doge import Registry 11 | from doge.common.url import URL 12 | from doge.common.utils import str_to_host 13 | 14 | logger = logging.getLogger("doge.registry.etcd") 15 | 16 | 17 | class EtcdRegistry(Registry): 18 | """Register etcd""" 19 | 20 | def __init__(self, url: URL) -> None: 21 | self.url = url 22 | self.etcd = self.registry_factory(url) 23 | 24 | def registry_factory(self, url: URL) -> Client: 25 | address = url.get_param("address") 26 | if address: 27 | return etcd.Client( 28 | allow_reconnect=True, 29 | host=tuple([str_to_host(add) for add in address.split(",")]), 30 | ) 31 | return etcd.Client(host=url.host, port=url.port) 32 | 33 | def register(self, service: str, url: URL) -> None: 34 | n_key = self._node_key(service, url.get_param("node")) 35 | value = "{}:{}".format(url.host, url.port) 36 | ttl = self.url.get_param("ttl", 10) 37 | 38 | logger.info(f"register key: {n_key} value: {value}") 39 | 40 | self.heartbeat(n_key, value, ttl=ttl) 41 | 42 | def deregister(self, service: str, url: URL) -> None: 43 | n_key = self._node_key(service, url.get_param("node")) 44 | 45 | logger.debug(f"deregister key: {n_key}") 46 | 47 | self.etcd.delete(n_key) 48 | 49 | def discovery(self, service: str) -> Dict[str, str]: 50 | s_key = self._svc_key(service) 51 | res = self.etcd.read(s_key, recursive=True) 52 | 53 | logger.info(f"discovery key: {s_key} length: {len(res._children)}") 54 | 55 | return {child.key: child.value for child in res.children} 56 | 57 | def watch(self, service: str, callback: Callable) -> None: 58 | def watch_loop(): 59 | s_key = self._svc_key(service) 60 | for res in self.etcd.eternal_watch(s_key, recursive=True): 61 | callback( 62 | { 63 | "action": self._proc_action(res.action), 64 | "key": res.key, 65 | "value": res.value, 66 | } 67 | ) 68 | 69 | self.watch_thread = gevent.spawn(watch_loop) 70 | 71 | def _proc_action(self, action: str) -> str: 72 | return "delete" if action == "expire" else action 73 | 74 | def _svc_key(self, service: str) -> str: 75 | return "/doge/rpc/{}".format(service) 76 | 77 | def _node_key(self, service: str, node: str) -> str: 78 | return "/doge/rpc/{}/{}".format(service, node) 79 | 80 | def heartbeat(self, key: str, value: str, ttl: int) -> None: 81 | self.etcd.write(key, value, ttl=ttl) 82 | 83 | def heartbeat_loop(): 84 | sleep = int(ttl / 2) 85 | while 1: 86 | gevent.sleep(sleep) 87 | self.etcd.refresh(key, ttl) 88 | 89 | self.beat_thread = gevent.spawn(heartbeat_loop) 90 | 91 | def destroy(self) -> None: 92 | if hasattr(self, "beat_thread"): 93 | self.beat_thread.kill() 94 | if hasattr(self, "watch_thread"): 95 | self.watch_thread.kill() 96 | 97 | 98 | class DirectRegistry(Registry): 99 | """Fake Registry""" 100 | 101 | def __init__(self, url: URL) -> None: 102 | self.url = url 103 | 104 | def register(self, service, url): 105 | pass 106 | 107 | def deregister(self, service, url): 108 | pass 109 | 110 | def discovery(self, service: str) -> Dict[str, str]: 111 | address = self.url.get_param("address") 112 | if address: 113 | return {str(i): add for i, add in enumerate(address.split(","))} 114 | return {"0": f"{self.url.host}:{str(self.url.port)}"} 115 | 116 | def watch(self, service: str, callback: Callable) -> None: 117 | pass 118 | 119 | def destroy(self) -> None: 120 | pass 121 | -------------------------------------------------------------------------------- /doge/rpc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhu327/doge/253beb6ab30c81a825a1b7efcdaecb7f3f254b87/doge/rpc/__init__.py -------------------------------------------------------------------------------- /doge/rpc/client.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import logging 4 | from typing import Any, Dict 5 | 6 | from gevent.lock import BoundedSemaphore # type: ignore 7 | 8 | from doge.cluster.endpoint import new_endpoint 9 | from doge.common.context import Context, rpc_local 10 | from doge.common.doge import Executer, Request, Response 11 | from doge.common.exceptions import ClientError 12 | from doge.config.config import Config 13 | 14 | logger = logging.getLogger("doge.rpc.client") 15 | 16 | 17 | class Client(Executer): 18 | def __init__(self, context: Context, service: str) -> None: 19 | self.service = service 20 | self.url = context.url 21 | self.context = context 22 | self.registry = context.get_registry() 23 | self.endpoints = context.get_endpoints(self.registry, service) 24 | self.ha = context.get_ha() 25 | self.lb = context.get_lb(list(self.endpoints.values())) 26 | self.filter = context.get_filter(self) 27 | self.available = True 28 | self.closed = False 29 | 30 | self.watch() 31 | 32 | def call(self, method: str, *args) -> Any: 33 | if self.available: 34 | r = Request( 35 | self.service, method, *args, meta=getattr(rpc_local, "meta", None) 36 | ) 37 | res = self.filter.execute(r) 38 | if res.exception: 39 | logger.error(str(res.exception)) 40 | raise res.exception 41 | return res.value 42 | raise ClientError("client not available") 43 | 44 | def execute(self, req: Request) -> Response: 45 | return self.ha.call(req, self.lb) 46 | 47 | def watch(self) -> None: 48 | self.registry.watch(self.service, self.notify) 49 | 50 | def notify(self, event: Dict[str, Any]) -> None: 51 | if event["action"] == "delete": 52 | ep = self.endpoints[event["key"]] 53 | self.lb.endpoints.remove(ep) 54 | del self.endpoints[event["key"]] 55 | elif event["action"] == "set": 56 | ep = new_endpoint(event["key"], event["value"]) 57 | self.endpoints[event["key"]] = ep 58 | self.lb.endpoints.append(ep) 59 | 60 | def destroy(self) -> None: 61 | if not self.closed: 62 | self.closed = True 63 | self.registry.destroy() 64 | for k, v in self.endpoints.items(): 65 | v.destroy() 66 | del self.context 67 | del self.registry 68 | del self.ha 69 | del self.endpoints 70 | del self.lb 71 | self.closed = True 72 | 73 | 74 | class Cluster: 75 | def __init__(self, config_file: str) -> None: 76 | """Cluster 抽象""" 77 | self.config_file = config_file 78 | self.config = Config(config_file) 79 | self.context = Context(self.config.parse_refer(), self.config.parse_registry()) 80 | 81 | self.clients: Dict[str, Client] = {} 82 | self.sem = BoundedSemaphore(1) 83 | 84 | def get_client(self, service: str) -> Client: 85 | if service not in self.clients: 86 | self.sem.acquire() 87 | if service not in self.clients: 88 | self.clients[service] = Client(self.context, service) 89 | self.sem.release() 90 | return self.clients[service] 91 | -------------------------------------------------------------------------------- /doge/rpc/server.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import logging 4 | import signal 5 | from typing import Callable, Optional, Type 6 | 7 | from gevent.server import StreamServer # type: ignore 8 | from mprpc import RPCServer # type: ignore 9 | from mprpc.exceptions import MethodNotFoundError # type: ignore 10 | 11 | from doge.common.context import Context, rpc_local 12 | from doge.common.doge import Executer, Request, Response 13 | from doge.common.exceptions import ServerLoadError 14 | from doge.config.config import Config 15 | 16 | logger = logging.getLogger("doge.rpc.server") 17 | 18 | 19 | class DogeRPCServer(RPCServer, Executer): 20 | def __init__(self, context: Context, cls: Type) -> None: 21 | super().__init__() 22 | self._name = context.url.get_param("name") 23 | self._filter = context.get_filter(self) 24 | self._methods = cls() 25 | 26 | def __getattr__(self, method_name: str) -> Callable: 27 | if not hasattr(self._methods, method_name): 28 | raise MethodNotFoundError("Method not found: %s", method_name) 29 | 30 | def function(*args): 31 | rpc_local.meta = args[0] 32 | 33 | req = Request(self._name, method_name, *args[1:], meta=args[0]) 34 | res = self._filter.execute(req) 35 | if res.exception: 36 | raise res.exception 37 | return res.value 38 | 39 | return function 40 | 41 | def execute(self, req: Request) -> Response: 42 | method = getattr(self._methods, req.method) 43 | try: 44 | value = method(*req.args) 45 | return Response(value=value) 46 | except Exception as e: 47 | return Response(exception=e) 48 | 49 | 50 | class Server: 51 | def __init__(self, context: Context) -> None: 52 | self.name = context.url.get_param("name") 53 | self.url = context.url 54 | self.context = context 55 | self.registry = context.get_registry() 56 | self.handler: Optional[DogeRPCServer] = None 57 | self.limit = context.url.get_param("limitConn", "default") 58 | 59 | def load(self, cls: Type) -> None: 60 | """加载RPC methods类""" 61 | self.handler = DogeRPCServer(self.context, cls) 62 | 63 | def register(self) -> None: 64 | """向registry服务""" 65 | self.registry.register(self.name, self.url) 66 | 67 | def handle_signal(self) -> None: 68 | """注册信号""" 69 | 70 | def handler(signum, frame): 71 | self.registry.deregister(self.name, self.url) 72 | 73 | signal.signal(signal.SIGINT, handler) 74 | signal.signal(signal.SIGTERM, handler) 75 | 76 | def run(self): 77 | """启动RPC服务""" 78 | if not self.handler: 79 | raise ServerLoadError("Methods not exits.") 80 | 81 | logger.info(f"Starting server at {self.url.host}:{str(self.url.port)}") 82 | 83 | self.handle_signal() 84 | 85 | server = StreamServer( 86 | (self.url.host, self.url.port), self.handler, spawn=self.limit 87 | ) 88 | 89 | self.register() 90 | 91 | server.serve_forever() 92 | 93 | def __call__(environ, start_response): 94 | # for gunicorn wsgi app 95 | pass 96 | 97 | 98 | def new_server(config_file: str) -> Server: 99 | """从配置文件生成server""" 100 | config = Config(config_file) 101 | context = Context(config.parse_service(), config.parse_registry()) 102 | return Server(context) 103 | -------------------------------------------------------------------------------- /download_etcd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | VERSION=${1:-2.3.7} 4 | mkdir -p bin 5 | URL="https://github.com/coreos/etcd/releases/download/v${VERSION}/etcd-v${VERSION}-linux-amd64.tar.gz" 6 | curl -L $URL | tar -C ./bin --strip-components=1 -xzvf - "etcd-v${VERSION}-linux-amd64/etcd" -------------------------------------------------------------------------------- /examples/client.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from __future__ import print_function 4 | 5 | import logging 6 | 7 | import gevent 8 | from gevent import monkey 9 | 10 | from doge.common.utils import init_tracer 11 | from doge.rpc.client import Cluster 12 | 13 | monkey.patch_socket() 14 | 15 | 16 | logging.basicConfig(level=logging.DEBUG) 17 | 18 | 19 | init_tracer("client") # 初始化jaeger tracer 20 | 21 | if __name__ == "__main__": 22 | cluster = Cluster("client.yaml") # 基于配置文件实例化Cluster对象 23 | client = cluster.get_client("doge_server") # 获取服务名对应的Client对象 24 | print(client.call("sum", 1, 2)) # 远程调用服务Sum类下的sum方法 25 | gevent.sleep(2) # wait for jaeger report 26 | -------------------------------------------------------------------------------- /examples/client.yaml: -------------------------------------------------------------------------------- 1 | registry: 2 | protocol: etcd 3 | host: 127.0.0.1 4 | port: 2379 5 | ttl: 10 6 | refer: 7 | haStrategy: failover 8 | loadBalance: RoundrobinLB 9 | filters: 10 | - doge.filter.tracing.TracingClientFilter 11 | - doge.filter.metrics.MetricsClientFilter 12 | -------------------------------------------------------------------------------- /examples/server.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import logging 4 | 5 | from gevent import monkey 6 | 7 | from doge.common.utils import init_tracer 8 | from doge.rpc.server import new_server 9 | 10 | monkey.patch_socket() 11 | 12 | 13 | logging.basicConfig(level=logging.DEBUG) 14 | 15 | 16 | init_tracer("server") 17 | 18 | 19 | # 定义rpc方法类 20 | class Sum: 21 | def sum(self, x, y): 22 | return x + y 23 | 24 | 25 | if __name__ == "__main__": 26 | server = new_server("server.yaml") # 基于配置文件实例化server对象 27 | server.load(Sum) # 加载暴露rpc方法类 28 | server.run() # 启动服务并注册节点信息到注册中心 29 | -------------------------------------------------------------------------------- /examples/server.yaml: -------------------------------------------------------------------------------- 1 | registry: 2 | protocol: etcd 3 | host: 127.0.0.1 4 | port: 2379 5 | ttl: 10 6 | service: 7 | name: doge_server 8 | node: n1 9 | host: 127.0.0.1 10 | port: 4399 11 | limitConn: 100 12 | filters: 13 | - doge.filter.tracing.TracingServerFilter 14 | - doge.filter.metrics.MetricsServerFilter -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | mprpc==0.1.17 2 | prometheus-client==0.7.1 3 | pyformance==0.4 4 | python-etcd==0.4.5 5 | pyyaml==5.4 6 | git+https://github.com/monsterxx03/jaeger-client-python.git@gevent 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding: utf8 2 | 3 | import sys 4 | 5 | from setuptools import find_packages, setup 6 | from setuptools.command.test import test as TestCommand 7 | 8 | 9 | class PyTest(TestCommand): 10 | def finalize_options(self): 11 | TestCommand.finalize_options(self) 12 | self.test_args = [] 13 | self.test_suite = True 14 | 15 | def run_tests(self): 16 | import pytest 17 | 18 | errno = pytest.main(self.test_args) 19 | sys.exit(errno) 20 | 21 | 22 | setup( 23 | name="dogerpc", 24 | version="0.1.4", 25 | description="A RPC Framework", 26 | long_description=open("README.md").read(), 27 | long_description_content_type="text/markdown", 28 | author="Timmy", 29 | author_email="zhu327@gmail.com", 30 | url="http://github.com/zhu327/doge", 31 | packages=["doge"] + [f"{'doge'}.{i}" for i in find_packages("doge")], 32 | license="Apache License 2.0", 33 | keywords=["rpc", "etcd", "messagepack", "gevent", "microservices"], 34 | classifiers=[ 35 | "Development Status :: 4 - Beta", 36 | "Intended Audience :: Developers", 37 | "License :: OSI Approved :: Apache Software License", 38 | "Programming Language :: Python", 39 | "Programming Language :: Python :: 3.4", 40 | "Programming Language :: Python :: 3.5", 41 | "Programming Language :: Python :: 3.6", 42 | ], 43 | install_requires=[ 44 | "mprpc", 45 | "pyformance", 46 | "python-etcd", 47 | ], 48 | tests_require=[ 49 | "pytest", 50 | ], 51 | cmdclass={"test": PyTest}, 52 | ) 53 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | from gevent import monkey 2 | 3 | monkey.patch_all() 4 | -------------------------------------------------------------------------------- /tests/client.yaml: -------------------------------------------------------------------------------- 1 | registry: 2 | protocol: etcd 3 | host: 127.0.0.1 4 | port: 2379 5 | ttl: 10 6 | refer: 7 | filters: 8 | - doge.filter.tracing.TracingClientFilter 9 | -------------------------------------------------------------------------------- /tests/server.yaml: -------------------------------------------------------------------------------- 1 | registry: 2 | protocol: etcd 3 | address: 127.0.0.1:2379 4 | ttl: 10 5 | service: 6 | name: test 7 | node: n1 8 | host: 127.0.0.1 9 | port: 4399 10 | filters: 11 | - doge.filter.tracing.TracingServerFilter -------------------------------------------------------------------------------- /tests/test_client.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import gevent 4 | import pytest 5 | from gevent import sleep 6 | 7 | from doge.common.context import Context 8 | from doge.common.exceptions import RemoteError 9 | from doge.common.url import URL 10 | from doge.rpc.client import Client 11 | from doge.rpc.server import Server 12 | 13 | url = URL("127.0.0.1", 4399, params={"name": "test", "node": "n1"}) 14 | rurl = URL("127.0.0.1", 2379, params={"ttl": 10}) 15 | context = Context(url, rurl) 16 | 17 | 18 | class Sum: 19 | def sum(self, x, y): 20 | return x + y 21 | 22 | 23 | @pytest.fixture(scope="module") 24 | def server(): 25 | s = Server(context) 26 | s.load(Sum) 27 | g = gevent.spawn(s.run) 28 | sleep(0.1) 29 | yield s 30 | g.kill() 31 | s.registry.destroy() 32 | 33 | 34 | class TestClient: 35 | def teardown_method(self, method): 36 | self.c.destroy() 37 | del self.c 38 | 39 | def test_client(self, server): 40 | c = Client(context, "test") 41 | self.c = c 42 | assert c.call("sum", 1, 2) == 3 43 | assert c.call("sum", 1, 2) == 3 44 | assert c.call("sum", 1, 2) == 3 45 | c.registry.deregister(c.service, url) 46 | sleep(0.2) 47 | with pytest.raises(RemoteError): 48 | c.call("sum", 1, 2) 49 | 50 | def test_context(self, server): 51 | url = URL( 52 | "127.0.0.1", 53 | 4399, 54 | params={ 55 | "name": "test", 56 | "node": "n1", 57 | "haStrategy": "backupRequestHA", 58 | "loadBalance": "RandomLB", 59 | }, 60 | ) 61 | rurl = URL("127.0.0.1", 4399, params={"protocol": "direct"}) 62 | context = Context(url, rurl) 63 | c = Client(context, "test") 64 | self.c = c 65 | assert c.call("sum", 1, 2) == 3 66 | assert c.call("sum", 1, 2) == 3 67 | assert c.call("sum", 1, 2) == 3 68 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import os 4 | 5 | import gevent 6 | 7 | from doge.rpc.client import Cluster 8 | from doge.rpc.server import new_server 9 | 10 | 11 | class Sum: 12 | def sum(self, x, y): 13 | return x + y 14 | 15 | 16 | class TestConfig: 17 | def teardown_method(self, method): 18 | self.g.kill() 19 | self.server.registry.deregister(self.server.name, self.server.context.url) 20 | self.server.registry.destroy() 21 | self.client.destroy() 22 | 23 | def test_config(self): 24 | cpath = os.path.join(os.path.dirname(__file__), "client.yaml") 25 | spath = os.path.join(os.path.dirname(__file__), "server.yaml") 26 | cluster = Cluster(cpath) 27 | server = new_server(spath) 28 | server.load(Sum) 29 | self.server = server 30 | self.g = gevent.spawn(server.run) 31 | gevent.sleep(0.1) 32 | cluster = Cluster(cpath) 33 | client = cluster.get_client("test") 34 | self.client = client 35 | assert client.call("sum", 1, 2) 36 | -------------------------------------------------------------------------------- /tests/test_endpoint.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import gevent 4 | import pytest 5 | from gevent.server import StreamServer 6 | 7 | from doge.cluster.endpoint import EndPoint 8 | from doge.common.context import Context 9 | from doge.common.doge import Request 10 | from doge.common.url import URL 11 | from doge.rpc.server import DogeRPCServer 12 | 13 | 14 | class SumServer: 15 | def sum(self, x, y): 16 | return x + y 17 | 18 | 19 | @pytest.fixture(scope="function") 20 | def server(): 21 | server = StreamServer( 22 | ("127.0.0.1", 4399), 23 | DogeRPCServer( 24 | Context(URL(None, None, None, {"name": ""}), URL(None, None, None, {})), 25 | SumServer, 26 | ), 27 | ) 28 | g = gevent.spawn(server.serve_forever) 29 | gevent.sleep(0.1) 30 | yield server 31 | g.kill() 32 | 33 | 34 | @pytest.fixture(scope="module") 35 | def url(): 36 | return URL("127.0.0.1", 4399, "") 37 | 38 | 39 | class TestEndpoint: 40 | def teardown_method(self, method): 41 | if hasattr(self, "ep"): 42 | self.ep.destroy() 43 | del self.ep 44 | 45 | def test_endpoint(self, server, url): 46 | ep = EndPoint(url) 47 | self.ep = ep 48 | r = Request("", "sum", 1, 2) 49 | assert ep.call(r).value == 3 50 | 51 | def test_error(self, server, url): 52 | ep = EndPoint(url) 53 | self.ep = ep 54 | availables = [] 55 | r = Request("", "a") 56 | for i in range(11): 57 | ep.call(r) 58 | availables.append(ep.available) 59 | assert False in availables 60 | gevent.sleep(0.2) 61 | assert ep.available 62 | r = Request("", "sum", 1, 2) 63 | assert ep.call(r).value == 3 64 | -------------------------------------------------------------------------------- /tests/test_ha.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import gevent 4 | import pytest 5 | from gevent.server import StreamServer 6 | 7 | from doge.cluster.endpoint import EndPoint 8 | from doge.cluster.ha import BackupRequestHA, FailOverHA 9 | from doge.cluster.lb import RandomLB 10 | from doge.common.context import Context 11 | from doge.common.doge import Request 12 | from doge.common.url import URL 13 | from doge.rpc.server import DogeRPCServer 14 | 15 | 16 | class SumServer: 17 | def sum(self, x, y): 18 | return x + y 19 | 20 | 21 | @pytest.fixture(scope="module") 22 | def lb(): 23 | url = URL("127.0.0.1", 4399, "") 24 | ep = EndPoint(url) 25 | return RandomLB(url, [ep]) 26 | 27 | 28 | @pytest.fixture(scope="function") 29 | def server(): 30 | server = StreamServer( 31 | ("127.0.0.1", 4399), 32 | DogeRPCServer( 33 | Context(URL(None, None, None, {"name": ""}), URL(None, None, None, {})), 34 | SumServer, 35 | ), 36 | ) 37 | g = gevent.spawn(server.serve_forever) 38 | gevent.sleep(0.1) 39 | yield server 40 | g.kill() 41 | 42 | 43 | class TestFailOverHA: 44 | def test_fail_over(self, server, lb): 45 | ha = FailOverHA(lb.url) 46 | r = Request("", "sum", 1, 2) 47 | assert ha.call(r, lb).value == 3 48 | 49 | 50 | class TestBackupRequestHA: 51 | def test_br(self, server, lb): 52 | ha = BackupRequestHA(lb.url) 53 | r = Request("", "sum", 1, 2) 54 | assert ha.call(r, lb).value == 3 55 | lb.url.set_param("sum.retries", 5) 56 | assert ha.call(r, lb).value == 3 57 | -------------------------------------------------------------------------------- /tests/test_lb.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import random 4 | 5 | import pytest 6 | 7 | from doge.cluster.lb import MaxSelectArraySize, RandomLB, RoundrobinLB 8 | 9 | 10 | @pytest.fixture(scope="module") 11 | def eps(): 12 | class C: 13 | pass 14 | 15 | eps = [] 16 | for i in range(10): 17 | o = C() 18 | o.available = random.choice([True, False]) 19 | eps.append(o) 20 | return eps 21 | 22 | 23 | class TestRandomLB: 24 | lb_class = RandomLB 25 | 26 | def test_select(self, eps): 27 | lb = self.lb_class(None, eps) 28 | ep = lb.select(None) 29 | assert ep.available 30 | 31 | def test_list(self, eps): 32 | lb = self.lb_class(None, eps) 33 | eps = lb.select_list(None) 34 | assert eps 35 | assert len(eps) <= MaxSelectArraySize 36 | for ep in eps: 37 | assert ep.available 38 | 39 | 40 | class TestRoundrobinLB(TestRandomLB): 41 | lb_class = RoundrobinLB 42 | -------------------------------------------------------------------------------- /tests/test_registry.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from __future__ import print_function 4 | 5 | import pytest 6 | from gevent import sleep 7 | 8 | from doge.common.url import URL 9 | from doge.registry.registry import DirectRegistry, EtcdRegistry 10 | 11 | url = URL("127.0.0.1", 2379, params={"ttl": 10}) 12 | 13 | 14 | @pytest.fixture(scope="function") 15 | def registry(): 16 | return EtcdRegistry(url) 17 | 18 | 19 | class TestEtcdRegistry: 20 | def teardown_method(self, method): 21 | if hasattr(self, "registry"): 22 | self.registry.deregister(*self.args) 23 | self.registry.destroy() 24 | del self.registry 25 | del self.args 26 | 27 | def test_register(self, registry): 28 | service = "test" 29 | url = URL("locahost", 80, params={"node": "n1"}) 30 | 31 | self.registry = registry 32 | self.args = [service, url] 33 | 34 | registry.register(service, url) 35 | res = registry.discovery(service) 36 | key = registry._node_key(service, url.get_param("node")) 37 | assert key in res 38 | assert res[key] == ":".join((url.host, str(url.port))) 39 | 40 | def test_deregister(self, registry): 41 | service = "test" 42 | url = URL("locahost", 80, params={"node": "n1"}) 43 | 44 | registry.register(service, url) 45 | registry.deregister(service, url) 46 | res = registry.discovery(service) 47 | key = registry._node_key(service, url.get_param("node")) 48 | assert key not in res 49 | 50 | def test_discovery(self, registry): 51 | service = "test" 52 | url = URL("locahost", 80, params={"node": "n1"}) 53 | 54 | self.registry = registry 55 | self.args = [service, url] 56 | 57 | registry.register(service, url) 58 | 59 | key = registry._node_key(service, "n2") 60 | 61 | registry.etcd.write(key, ":".join((url.host, "81"))) 62 | 63 | res = registry.discovery(service) 64 | 65 | registry.etcd.delete(key) 66 | 67 | assert len(res) == 2 68 | 69 | def test_watch(self, registry): 70 | service = "test_watch" 71 | url = URL("locahost", 80, params={"node": "n1"}) 72 | 73 | registry.register(service, url) 74 | 75 | sleep(0.1) 76 | 77 | def callback(res): 78 | print("callback now") 79 | assert res["action"] == "delete" 80 | 81 | registry.watch(service, callback) 82 | 83 | sleep(0.1) 84 | 85 | registry.deregister(service, url) 86 | registry.beat_thread.kill() 87 | sleep(0.1) 88 | 89 | def test_zaddress(self): 90 | service = "test" 91 | url = URL("locahost", 80, params={"node": "n1"}) 92 | 93 | rurl = URL(None, None, params={"ttl": 10, "address": "127.0.0.1:2379"}) 94 | 95 | registry = EtcdRegistry(rurl) 96 | self.registry = registry 97 | self.args = [service, url] 98 | 99 | registry.register(service, url) 100 | res = registry.discovery(service) 101 | key = registry._node_key(service, url.get_param("node")) 102 | assert key in res 103 | assert res[key] == ":".join((url.host, str(url.port))) 104 | 105 | 106 | class TestDirectRegistry: 107 | def test_direct(self): 108 | registry = DirectRegistry(url) 109 | assert registry.discovery("")["0"] == "127.0.0.1:2379" 110 | -------------------------------------------------------------------------------- /tests/test_server.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | import gevent 4 | import pytest 5 | from gevent import sleep 6 | from mprpc import RPCClient 7 | 8 | from doge.common.context import Context 9 | from doge.common.url import URL 10 | from doge.rpc.server import Server 11 | 12 | url = URL("127.0.0.1", 4399, params={"name": "test", "node": "n1"}) 13 | rurl = URL("127.0.0.1", 2379, params={"ttl": 10}) 14 | context = Context(url, rurl) 15 | 16 | 17 | @pytest.fixture(scope="function") 18 | def server(): 19 | s = Server(context) 20 | yield s 21 | s.registry.deregister(s.name, url) 22 | s.registry.destroy() 23 | 24 | 25 | class TestServer: 26 | def teardown_method(self, method): 27 | self.g.kill() 28 | 29 | def test_server(self, server): 30 | class Sum: 31 | def sum(self, x, y): 32 | return x + y 33 | 34 | server.load(Sum) 35 | self.g = gevent.spawn(server.run) 36 | sleep(0.1) 37 | 38 | registry = server.registry 39 | res = registry.discovery(server.name) 40 | key = registry._node_key(server.name, url.get_param("node")) 41 | 42 | host, port = res[key].split(":") 43 | 44 | client = RPCClient(str(host), int(port)) 45 | 46 | assert client.call("sum", {}, 1, 2) == 3 47 | -------------------------------------------------------------------------------- /tests/test_url.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from doge.common.url import URL 4 | 5 | 6 | def test_url(): 7 | url = URL("", "", "") 8 | assert url.get_int_value("a", 1) == 1 9 | url.set_param("a", -1) 10 | assert url.get_positive_int_value("a", 3) == 3 11 | assert url.get_int_value("a", 0) == -1 12 | url.set_param("m.a", 3) 13 | assert url.get_method_int_value("m", "a", 5) == 3 14 | assert url.get_method_int_value("m", "b", 5) == 5 15 | assert url.get_method_positive_int_value("m", "a", 5) == 3 16 | assert url.get_method_positive_int_value("m", "b", 5) == 5 17 | --------------------------------------------------------------------------------