├── .gitignore ├── LICENSE ├── README.md ├── demo └── flask │ ├── .dockerignore │ ├── Dockerfile │ ├── README.md │ ├── app │ ├── __init__.py │ ├── main.py │ └── templates │ │ └── public │ │ └── dynamic.html │ └── requirements.txt └── spec ├── __init__.py ├── config ├── README.md └── micro-config │ ├── microconfig │ └── config.py │ └── setup.py ├── fault-tolerance └── README.md ├── graphql ├── README.md └── src │ ├── __init__.py │ └── graph.py ├── health ├── README.md ├── microhealth │ ├── __init__.py │ ├── api.py │ ├── healthcheck.py │ ├── healthcheck_decorators.py │ ├── healthcheck_response.py │ └── standard_healthchecks.py └── setup.py ├── metrics ├── README.md ├── __init__.py └── src │ ├── __init__.py │ ├── counter.py │ ├── metric.py │ ├── metric_types.py │ ├── metric_units.py │ ├── tag.py │ └── tests │ ├── __init__.py │ ├── test_counter.py │ ├── test_metric_types.py │ ├── test_metric_units.py │ └── test_tag.py ├── open-api └── README.md ├── open-tracing └── README.md └── rest-client └── README.md /.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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .idea/ 132 | 133 | spec/config/micro-config/microconfig/conf.properties -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | Implement microprofile for python language 3 | 4 | ## overview 5 | So what are microframeworks 6 | ------ 7 | So what are microframeworks? Usually, they are a bare framework for a rest server, according to Wikipedia: minimalistic web application frameworks. Each one has its own flavor: some have a reactive patterns for defining endpoints, some added integrated metrics. 8 | Microservice Architecture has become very common in most companies. The big question is of course what is a microservice. 9 | From the site microservices.io, this is the summary: 10 | * Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are 11 | * Highly maintainable and testable 12 | * Loosely coupled 13 | * Independently deployable 14 | * Organized around business capabilities 15 | * Owned by a small team 16 | 17 | The main issue is that up till now, all the discussions of microservices were about the size and the independence of the service (deployment and development). 18 | What was not covered well is the minimum requirement of the service for monitoring and orchestration. Kubernetis gave to docker a standard way of distributed deployment and scale. 19 | A similar framework for viewing all services via a single lense was missing. 20 | 21 | ![](https://chaimturkel.files.wordpress.com/2019/12/screen-shot-2019-11-12-at-13.06.41.png?w=816&h=314&zoom=2) 22 | 23 | ## goal 24 | In this project we try to collect into one place the best practices and implementations of microprofiles for python. 25 | You can see in each spec what we have found to be the best packages that come closest to the microprofile standard. 26 | In cases that there is nothing we try to implement them ourselfs. 27 | 28 | ## Installing Python 3 29 | 30 | For mac install python3 31 | `brew install python3` 32 | 33 | Also check out [How to install python3 on OSX](https://gist.github.com/alfasin/bc88d4eb0217f13cbc7ccef53e8eadb3) 34 | 35 | ### setup env 36 | 37 | ```buildoutcfg 38 | python3 -m pip install --user --upgrade pip 39 | python3 -m pip --version # (test install) 40 | python3 -m pip install --user virtualenv 41 | python3 -m venv env 42 | source env/bin/activate 43 | which python # (test env) 44 | ``` 45 | -------------------------------------------------------------------------------- /demo/flask/.dockerignore: -------------------------------------------------------------------------------- 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 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 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 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .vscode/ 107 | settings.json 108 | -------------------------------------------------------------------------------- /demo/flask/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tiangolo/uwsgi-nginx-flask:python3.7 2 | 3 | COPY ./requirements.txt /app/requirements.txt 4 | WORKDIR /app 5 | RUN pip install -r requirements.txt 6 | 7 | COPY ./app /app 8 | ENTRYPOINT [ "python" ] 9 | CMD [ "main.py" ] 10 | -------------------------------------------------------------------------------- /demo/flask/README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | 3 | ## flask framework 4 | 5 | The module will show an example of how to use the microprofile libraries within a flask context 6 | 7 | to build the docker file run: 8 | 9 | ### build app 10 | * pip install -r requirements.txt 11 | 12 | 13 | ### build docker 14 | docker build -t flask-demo:latest . 15 | 16 | ## run docker 17 | docker run -it --name flask-demo -p 8080:8080 flask-demo:latest -------------------------------------------------------------------------------- /demo/flask/app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/demo/flask/app/__init__.py -------------------------------------------------------------------------------- /demo/flask/app/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify 2 | import sys 3 | sys.path.append("/Users/slavad/dev/python-microprofile") 4 | import spec.health.microhealth.api as health_api 5 | 6 | # sys.path.append("/Users/mottidadison/work/fuse_022020/python-microprofile/spec/graphql/") 7 | # import graph 8 | 9 | app = Flask(__name__) 10 | 11 | 12 | @app.route('/') 13 | def hello_whale(): 14 | app.logger.info('hello_whale') 15 | return 'Whale, Hello there!' 16 | 17 | 18 | @app.route('/health') 19 | def get_health(): 20 | return health_api.get_health() 21 | 22 | 23 | @app.route('/health/ready') 24 | def get_health_ready(): 25 | return health_api.get_health_ready() 26 | 27 | 28 | @app.route('/health/live') 29 | def get_health_live(): 30 | return health_api.get_health_live() 31 | 32 | 33 | if __name__ == '__main__': 34 | app.run(debug=True, host='0.0.0.0', port=8080) 35 | -------------------------------------------------------------------------------- /demo/flask/app/templates/public/dynamic.html: -------------------------------------------------------------------------------- 1 | {% extends "public/templates/public_template.html" %} 2 | 3 | {% block title %}Profile{% endblock %} 4 | 5 | {% block main %} 6 | 7 |
8 |
9 |
10 | 11 |

Profile

12 |
13 | 14 |
15 |
16 |
17 | 18 | {% endblock %} -------------------------------------------------------------------------------- /demo/flask/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==1.1.1 2 | opentracing>=2,<3 3 | jaeger-client 4 | opentracing-utils 5 | basictracer 6 | lightstep 7 | flask_graphql==2.0.1 8 | graphene==2.1.1 9 | dataclasses-json==0.3.8 10 | data -------------------------------------------------------------------------------- /spec/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/__init__.py -------------------------------------------------------------------------------- /spec/config/README.md: -------------------------------------------------------------------------------- 1 | # Microprofile - Config 2 | 3 | Configuration is an essential part of Microprofile specification. 4 | ## Specifications 5 | The full spec can be found here: [1.4 Spec](https://download.eclipse.org/microprofile/microprofile-config-1.4/microprofile-config-spec.pdf). 6 | 7 | Out of the full spec, we are implementing the basics: 8 | * **ConfigSource** abstract class which reads configuration from a single source. 9 | * Each source is defining its ordinal. 10 | * Main configuration that serves values from all sources according to the ordinal. Values from higher ordinal overwrites lower ordinal configuration source. 11 | * Out of the box the default sources includes: 12 | * Command line arguments (default ordinal=400) 13 | * Environment variables (default ordinal=300) 14 | * Properties file (default ordinal=100) 15 | 16 | ## Usage 17 | ### Installation 18 | `pip install microconfig-0.0.1.tar.gz` 19 | 20 | ### Usage 21 | In order to use the default config sources: 22 | ```python 23 | from microconfig.config import Configuration 24 | 25 | conf = Configuration() 26 | val1 = conf.get("key1") 27 | val2 = conf["key2"] 28 | ``` 29 | 30 | To use properties file config source: 31 | 32 | ```python 33 | from microconfig.config import Configuration, PropertiesConfigSource 34 | 35 | prop_conf = PropertiesConfigSource("conf.properties") 36 | conf = Configuration(prop_conf) 37 | val1 = conf.get("com.tikal.key1") # From properties file 38 | val2 = conf.get("PATH") # From environment variable 39 | ``` -------------------------------------------------------------------------------- /spec/config/micro-config/microconfig/config.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class ConfigSource(ABC): 5 | 6 | def __init__(self, ordinal): 7 | self.values = {} 8 | self.ordinal = ordinal 9 | 10 | @abstractmethod 11 | def load(self, *args, **kwargs): 12 | pass 13 | 14 | def get(self, key): 15 | return self.values.get(key) 16 | 17 | def get_ordinal(self): 18 | return self.ordinal 19 | 20 | 21 | class EnvConfigSource(ConfigSource): 22 | 23 | def __init__(self): 24 | super().__init__(500) 25 | 26 | def load(self, *args, **kwargs): 27 | import os 28 | self.values = os.environ.copy() 29 | 30 | 31 | class PropertiesConfigSource(ConfigSource): 32 | 33 | separator = '=' 34 | 35 | def __init__(self, filename): 36 | super().__init__(400) 37 | self.filename = filename 38 | 39 | def load(self, *args, **kwargs): 40 | with open(self.filename) as f: 41 | 42 | for line in f: 43 | if PropertiesConfigSource.separator in line: 44 | # Find the name and value by splitting the string 45 | name, value = line.split(PropertiesConfigSource.separator, 1) 46 | 47 | # Assign key value pair to dict 48 | # strip() removes white space from the ends of strings 49 | self.values[name.strip()] = value.strip() 50 | 51 | 52 | class Configuration: 53 | 54 | def __init__(self, *args): 55 | self.configs = [] 56 | env_config = EnvConfigSource() 57 | local_configs = { 58 | env_config.get_ordinal(): env_config 59 | } 60 | 61 | for _config in args: 62 | if isinstance(_config, ConfigSource): 63 | local_configs[_config.get_ordinal()] = _config 64 | 65 | for key in sorted(local_configs.keys(), reverse=True): 66 | _config = local_configs[key] 67 | _config.load() 68 | self.configs.append(_config) 69 | 70 | def get(self, key): 71 | for _config in self.configs: 72 | value = _config.get(key) 73 | if value is not None: 74 | return value 75 | return None 76 | 77 | def __getitem__(self, item): 78 | return self.get(item) 79 | 80 | 81 | if __name__ == '__main__': 82 | prop_config = PropertiesConfigSource("conf.properties") 83 | config = Configuration(prop_config) 84 | print(config.get('com.tikalk.key1')) 85 | print(config['PATH']) 86 | -------------------------------------------------------------------------------- /spec/config/micro-config/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='microconfig', 5 | version='0.0.1', 6 | packages=['microconfig'], 7 | url='', 8 | license='', 9 | author='haimcohen', 10 | author_email='hcloli@gmail.com', 11 | description='' 12 | ) 13 | -------------------------------------------------------------------------------- /spec/fault-tolerance/README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | 3 | ## fault tolerance 4 | 5 | Fault tolerance allows the developer to define strategies in case of execution failures 6 | 7 | ## retry 8 | Allows the developer to define how many retries will take place before a methiod actually failes. 9 | 10 | ## Fallback 11 | Allows the developer to define a function that will be called in case of failure in the called method. 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spec/graphql/README.md: -------------------------------------------------------------------------------- 1 | 2 | Microprofile Python GraphQL Specification 3 | ========================================== 4 | 5 | 6 | ## Specification: 7 | 8 | GraphiQL is a powerfull graphical UI that enables a smooth and easy API discovery. 9 | 10 | Just navigate to `/graphql` in your browser and you'll see [GraphiQL](https://github.com/graphql/graphiql/) 11 | 12 | ![https://raw.githubusercontent.com/graphql/graphiql/master/packages/graphiql/resources/graphiql.jpg](https://raw.githubusercontent.com/graphql/graphiql/master/packages/graphiql/resources/graphiql.jpg) 13 | 14 | ## About 15 | 16 | GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data. 17 | 18 | It provides an alternative, though not necessarily a replacement for REST. 19 | 20 | GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015. 21 | 22 | ## What is GraphQL? 23 | GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data. [From [graphql.org](https://graphql.org/learn/)] 24 | 25 | GraphQL is used by many large and small customers including Atlassian, Coursera, Facebook, GitHub, PayPal, Twitter, and https://graphql.org/users/[many more]. 26 | 27 | 28 | 29 | * More info: https://en.wikipedia.org/wiki/GraphQL 30 | 31 | * Home page: https://graphql.org/ 32 | 33 | * Specification: https://facebook.github.io/graphql/draft/ 34 | 35 | 36 | 37 | ## Why GraphQL 38 | 39 | The main reasons developers might want to use GraphQL are: 40 | 41 | 42 | 43 | * Improved data consumption for customers (IoS, Android, Web). Allowing for example to be able to retrieve several types of data in a single request or limiting the response data to exactly the specific data requested. 44 | 45 | * Better analysis of the exhaustiveness of data calls (allowing to know the use of each node) and better manage the deletion of deprecated fields. 46 | 47 | * Advanced developer experience: 48 | 49 | ** The schema defines how the data can be accessed and serves as the contract between the client and the server. Developer teams on both sides can work without further communication, 50 | 51 | ** Native schema introspection enabling to discover the API and to refine the queries on the client-side. 52 | 53 | ** On the client-side, the query language provides a lot of flexibility and efficiency enabling developers to adapt to the constraints of their technical environments (IoS, Android, Web). 54 | 55 | 56 | 57 | ## Why MicroProfile 58 | 59 | 60 | The official purpose of MicroProfile is to optimize development for a microservices architecture and delivers application portability across multiple MicroProfile runtimes. 61 | 62 | GraphQL is already widely used in Microservices architectures as the API Endpoint. 63 | 64 | GraphQL continues to grow in popularity, and as such there should be a specification for GraphQL development. 65 | 66 | MicroProfile is the optimal place to host that standard as it is open, ideally suited for incubating technologies, and has broad reach both in terms of the user community and vendor support. 67 | 68 | 69 | 70 | ## What GraphQL is not 71 | 72 | 73 | This specification will focus on making it easy for developers to create a GraphQL Service/Endpoint and publish it as an API. 74 | 75 | Where the data comes from (NoSQL, Relational DB, another service, etc.) is not the concern of this Proposed Specification. 76 | -------------------------------------------------------------------------------- /spec/graphql/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/graphql/src/__init__.py -------------------------------------------------------------------------------- /spec/graphql/src/graph.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_graphql import GraphQLView 3 | import graphene 4 | from main import app 5 | 6 | class Query(graphene.ObjectType): 7 | hello = graphene.String(name=graphene.String(default_value="World")) 8 | 9 | def resolve_hello(self, info, name): 10 | return 'Hello ' + name 11 | 12 | schema = graphene.Schema(query=Query) 13 | 14 | @app.route('/graphql/status') 15 | def graph(): 16 | return "running..." 17 | 18 | app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True)) 19 | 20 | -------------------------------------------------------------------------------- /spec/health/README.md: -------------------------------------------------------------------------------- 1 | # MicroProfile Health 2 | 3 | ## Motivation 4 | 5 | Health checks are used to probe the state of a computing node from another machine (i.e. kubernetes service controller) with the primary target being cloud infrastructure environments where automated processes maintain the state of computing nodes. 6 | 7 | In this scenario, _health checks are used to determine if a computing node needs to be discarded (terminated, shutdown)_ and eventually replaced by another (healthy) instance. 8 | 9 | It’s not intended (although could be used) as a monitoring solution for human operators. 10 | 11 | ## Proposed solution 12 | 13 | The proposed solution breaks down into two parts: 14 | 15 | - A health check protocol and wireformat 16 | - A Python API to implement health check procedures 17 | 18 | ## Detailed design 19 | 20 | #### Protocol 21 | 22 | This project defines a protocol (wireformat, semantics and possible forms of interactions) between system components that need to determine the “liveliness” of computing nodes in a bigger architecture. 23 | A detailed description of the health check protocol can be found in the [companion document](https://github.com/eclipse/microprofile-health/tree/master/spec/src/main/asciidoc/protocol-wireformat.adoc). 24 | 25 | #### API Usage 26 | 27 | The main API to provide health check procedures on the application level is the `HealthCheck` interface: 28 | 29 | ```python 30 | class Healthcheck: 31 | 32 | @abstractmethod 33 | def call(self) -> HealthcheckResponse: 34 | pass 35 | ``` 36 | 37 | Applications are expected to provide health check procedures (implementation of a `HealthCheck`), which will be used by the framework or runtime hosting the application to verify the healthiness of the computing node. 38 | 39 | The runtime will `call()` the `HealthCheck` which in turn creates a `HealthCheckResponse` that signals the health status to a consuming end: 40 | 41 | ```python 42 | @dataclass 43 | class HealthcheckResponse: 44 | status: HealthcheckStatus 45 | checks: List[HealthcheckCheck] 46 | 47 | @staticmethod 48 | def up(checks=None): 49 | return HealthcheckResponse(HealthcheckStatus.UP, checks) 50 | 51 | @staticmethod 52 | def down(checks=None): 53 | return HealthcheckResponse(HealthcheckStatus.DOWN, checks) 54 | ``` 55 | 56 | #### Constructing `HealthCheckResponse`s 57 | 58 | Application level code is expected to use one of static methods on `HealthCheckResponse` to retrieve a `HealthCheckResponse` object: 59 | 60 | ```python 61 | livelinessResponse = HealthcheckResponse.up('liveliness', {'foo', 'bar'}) 62 | ``` 63 | 64 | #### Integration with CDI 65 | 66 | Within CDI contexts, beans that implement `HealthCheck` and annotated with `@Health` are discovered automatically and are invoked by the framework or runtime when the outermost protocol entry point (i.e. `http://HOST:PORT/health`) receives an inbound request. 67 | 68 | ```python 69 | @healthcheck 70 | class CheckDiskSpace(Healthcheck) { 71 | 72 | def call() -> HealtchcheckResponse: 73 | [...] 74 | 75 | ``` 76 | 77 | #### On the wire 78 | 79 | It's the responsibility of the runtime to gather all `HealthCheckResponse` s for `HealthCheck` s known to the runtime. This means an inbound HTTP request will lead to a series of invocations 80 | on health check procedures and the runtime will provide a composite response, with a single overall status, i.e.: 81 | 82 | ```json 83 | { 84 | "status": "UP", 85 | "checks": [ 86 | { 87 | "name": "first-check", 88 | "status": "UP", 89 | "data": { 90 | "key": "foo", 91 | "foo": "bar" 92 | } 93 | }, 94 | { 95 | "name": "second-check", 96 | "status": "UP" 97 | } 98 | ] 99 | } 100 | ``` 101 | 102 | The link: [companion object](https://github.com/eclipse/microprofile-health/tree/master/spec/src/main/asciidoc/protocol-wireformat.adoc) contains further information on forms of interaction and the wireformat. 103 | -------------------------------------------------------------------------------- /spec/health/microhealth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/health/microhealth/__init__.py -------------------------------------------------------------------------------- /spec/health/microhealth/api.py: -------------------------------------------------------------------------------- 1 | import json 2 | from collections import defaultdict 3 | from typing import Dict, List 4 | 5 | from demo.flask.app.main import app 6 | from spec.health.microhealth.healthcheck import Healthcheck 7 | from spec.health.microhealth.healthcheck_response import ( 8 | HealthcheckSummary, 9 | HealthcheckResponse, 10 | HealthcheckStatus, 11 | EMPTY_HEALTHCHECK_SUMMARY_DOWN, 12 | EMPTY_HEALTHCHECK_SUMMARY_UP) 13 | from spec.health.microhealth.standard_healthchecks import LivelinessHealthcheck, DiskSpaceHealthcheck 14 | 15 | healthchecks_registry: Dict = {} 16 | healthchecks_registry_by_type: Dict[str, List[Healthcheck]] = {} 17 | healthchecker = Healthcheck() 18 | 19 | healthchecks_registry['disk'] = DiskSpaceHealthcheck 20 | healthchecks_registry['live'] = LivelinessHealthcheck 21 | healthchecks_registry_by_type['liveliness'] = [LivelinessHealthcheck] 22 | 23 | 24 | def get_health(): 25 | # noinspection PyBroadException 26 | try: 27 | app.logger.debug('/health') 28 | healthcheck_responses = [] 29 | for check in healthchecks_registry.values(): 30 | healthcheck_responses.append(check().call()) 31 | healthcheck_summary = HealthcheckSummary.call(healthcheck_responses) 32 | if healthcheck_summary.status == HealthcheckStatus.DOWN: 33 | return healthcheck_summary.to_json(), 503 34 | else: 35 | return healthcheck_summary.to_json(), 200 36 | except: 37 | app.logger.error('Failed healthcheck', exc_info=True) 38 | return EMPTY_HEALTHCHECK_SUMMARY_DOWN.to_json(), 500 39 | 40 | 41 | def get_health_live(): 42 | # noinspection PyBroadException 43 | try: 44 | app.logger.debug('/health/live') 45 | healthcheck_responses = [] 46 | for check in healthchecks_registry_by_type.get('liveliness', []): 47 | healthcheck_responses.append(check().call()) 48 | healthcheck_summary = HealthcheckSummary.call(healthcheck_responses) 49 | if healthcheck_summary.status == HealthcheckStatus.DOWN: 50 | return healthcheck_summary.to_json(), 503 51 | else: 52 | return healthcheck_summary.to_json(), 200 53 | except: 54 | app.logger.error('Failed healthcheck liveliness', exc_info=True) 55 | return EMPTY_HEALTHCHECK_SUMMARY_DOWN.to_json(), 500 56 | 57 | 58 | def get_health_ready(): 59 | # noinspection PyBroadException 60 | try: 61 | app.logger.debug('/health/ready') 62 | healthcheck_responses = [] 63 | for check in healthchecks_registry_by_type.get('readiness', []): 64 | healthcheck_responses.append(check().call()) 65 | healthcheck_summary = HealthcheckSummary.call(healthcheck_responses) 66 | if healthcheck_summary.status == HealthcheckStatus.DOWN: 67 | return healthcheck_summary.to_json(), 503 68 | else: 69 | return healthcheck_summary.to_json(), 200 70 | except: 71 | app.logger.error('Failed healthcheck ready', exc_info=True) 72 | return EMPTY_HEALTHCHECK_SUMMARY_DOWN.to_json(), 500 73 | -------------------------------------------------------------------------------- /spec/health/microhealth/healthcheck.py: -------------------------------------------------------------------------------- 1 | from abc import abstractmethod 2 | 3 | from spec.health.microhealth.healthcheck_response import HealthcheckResponse 4 | 5 | 6 | class Healthcheck: 7 | 8 | @abstractmethod 9 | def call(self) -> HealthcheckResponse: 10 | pass 11 | -------------------------------------------------------------------------------- /spec/health/microhealth/healthcheck_decorators.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import logging 3 | 4 | from spec.health.microhealth.healthcheck_response import HealthcheckResponse, HealthcheckStatus 5 | 6 | 7 | def healthcheck(func): 8 | @functools.wraps(func) 9 | def wrapper_healthcheck_check(*args, **kwargs) -> HealthcheckResponse: 10 | logging.debug('Running healthcheck check') 11 | res = func(*args, **kwargs) 12 | if res.status == HealthcheckStatus.UP: 13 | logging.debug(f'Healthcheck check {res.name} is UP') 14 | else: 15 | logging.warning(f'Healthcheck check {res.name} is DOWN') 16 | return res 17 | 18 | return wrapper_healthcheck_check 19 | -------------------------------------------------------------------------------- /spec/health/microhealth/healthcheck_response.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from enum import Enum 3 | from typing import List 4 | 5 | from dataclasses_json import dataclass_json 6 | 7 | 8 | class HealthcheckStatus(Enum): 9 | UP = 'UP' 10 | DOWN = 'DOWN' 11 | 12 | 13 | @dataclass_json 14 | @dataclass 15 | class HealthcheckResponse: 16 | name: str 17 | status: HealthcheckStatus 18 | data: dict 19 | 20 | @staticmethod 21 | def up(name, data=None): 22 | return HealthcheckResponse(name, HealthcheckStatus.UP, data) 23 | 24 | @staticmethod 25 | def down(name, data=None): 26 | return HealthcheckResponse(name, HealthcheckStatus.DOWN, data) 27 | 28 | 29 | @dataclass_json 30 | @dataclass 31 | class HealthcheckSummary: 32 | status: HealthcheckStatus 33 | checks: List[HealthcheckResponse] 34 | 35 | @staticmethod 36 | def call(checks: List[HealthcheckResponse] = None): 37 | down = any(True for check in checks if check.status != HealthcheckStatus.UP) 38 | if checks and down: 39 | return HealthcheckSummary(HealthcheckStatus.DOWN, checks) 40 | else: 41 | return HealthcheckSummary(HealthcheckStatus.UP, checks) 42 | 43 | 44 | EMPTY_HEALTHCHECK_SUMMARY_UP = HealthcheckSummary(HealthcheckStatus.UP, []) 45 | EMPTY_HEALTHCHECK_SUMMARY_DOWN = HealthcheckSummary(HealthcheckStatus.DOWN, []) 46 | -------------------------------------------------------------------------------- /spec/health/microhealth/standard_healthchecks.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | 3 | from spec.health.microhealth.healthcheck import Healthcheck 4 | from spec.health.microhealth.healthcheck_response import HealthcheckResponse 5 | 6 | 7 | class LivelinessHealthcheck(Healthcheck): 8 | def call(self): 9 | return HealthcheckResponse.up('liveliness', None) 10 | 11 | 12 | class DiskSpaceHealthcheck(Healthcheck): 13 | def call(self): 14 | total_space, used_space, free_space = shutil.disk_usage('/') 15 | healthy = (used_space / total_space) < 0.9 16 | data = {'total': total_space, 'used': used_space, 'free': free_space} 17 | if healthy: 18 | return HealthcheckResponse.up('disk_space', data) 19 | else: 20 | return HealthcheckResponse.down('disk_space', data) 21 | -------------------------------------------------------------------------------- /spec/health/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='microprofile-health', 5 | version='0.0.1', 6 | packages=['microhealth'], 7 | url='', 8 | license='', 9 | author='slavad', 10 | author_email='slava.demender@tikalk.com', 11 | description='' 12 | ) 13 | -------------------------------------------------------------------------------- /spec/metrics/README.md: -------------------------------------------------------------------------------- 1 | # Python-Microprofile 2 | 3 | Inspired by [Eclipse Microprofile Metrics](https://github.com/eclipse/microprofile-metrics) we want to develop the metrics portion of microprofiling for languages other than Java. 4 | This POC will focus on microprofile-metrics for webservices. 5 | 6 | The metrics will be stored in a local registry and will be exposed to the monitoring server via /metrics route. 7 | Metrics that are exposed need to be configured in the server. On top of the pure metrics, metadata needs to be provided. 8 | 9 | The following three sets of sub-resource (scopes) are exposed. 10 | 11 | base: metrics that all MicroProfile vendors have to provide, these metrics will be exposed under `/metrics/base` 12 | 13 | vendor: vendor specific metrics (optional), these metrics will be exposed under `/metrics/vendor` 14 | 15 | application: application-specific metrics (optional), these metrics will be exposed under `/metrics/application` 16 | 17 | ## Base Metrics 18 | Microprofile divides base-metrics into two categories: [required](https://github.com/eclipse/microprofile-metrics/blob/master/spec/src/main/asciidoc/required-metrics.adoc#required-metrics) and [optional](https://github.com/eclipse/microprofile-metrics/blob/master/spec/src/main/asciidoc/required-metrics.adoc#thread-pool-stats). 19 | As you can see, many of these metrics are Java specific and deal with the JVM. In this POC we will treat all these metrics as optional and instead, try to come up with a broader, more generic set of base-metrics. 20 | 21 | ### CPU Utilization 22 | * CPU usage in percentage 23 | and breakdown by: 24 | * (optional) processes executing in user mode (percentage) 25 | * (optional) processes executing in kernel mode (percentage) 26 | 27 | ### Memory 28 | Two metrics will be published: 29 | * total memory (bytes) 30 | * used memory (bytes) 31 | 32 | ### Disk 33 | Two metrics will be published: 34 | * disk space total (bytes) 35 | * disk space used (bytes) 36 | 37 | ### Network 38 | * packets transmitted, received (count) 39 | * bytes transmitted, received (bytes) 40 | * (optional) packets dropped by the driver on transmit, receive (count) 41 | * (optional) total number of sockets in kernel socket lists (count); 42 | * (optional) TCP sockets currently in use (count); 43 | * (optional) UDP sockets currently in use (count) 44 | 45 | ## Vendor Metrics (Optional) 46 | // TODO 47 | 48 | ## Application Metrics (Optional) 49 | // TODO 50 | 51 | ## Metrics Tags 52 | We want to be able to standartize metric-names, meaning, for an outbound HTTP call we'll want to publish a metric called: 53 | `outbound_http_latency_seconds`. The way to differentiate between different outbound calls will be by tags (labels). 54 | 55 | Tags are also useful to expose: app-name, instance-id, cluster-name, service-name, region/zone and etc. 56 | 57 | Example: `outbound_http_latency_seconds{region="eu-west-1",path="/foo"}` 58 | 59 | ## Metadata 60 | Immutable static Metric information to be provided by the implementor, and which includes: 61 | * metric name 62 | * metric unit 63 | * metric type (counter, gauge, timer, histogram and etc) 64 | * description (optional) 65 | * displayName (optional) 66 | * reusable (optional): If set to true, then it is allowed to register a metric multiple times under the 67 | same MetricID. 68 | 69 | The MetricID consists of the metric’s name and tags (if supplied). This is used by the MetricRegistry 70 | to uniquely identify a metric and its corresponding metadata. -------------------------------------------------------------------------------- /spec/metrics/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/metrics/__init__.py -------------------------------------------------------------------------------- /spec/metrics/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/metrics/src/__init__.py -------------------------------------------------------------------------------- /spec/metrics/src/counter.py: -------------------------------------------------------------------------------- 1 | from spec.metrics.src.metric import Metric 2 | 3 | 4 | class Counter(Metric): 5 | def __init__(self, *args, **kwargs): 6 | super(Counter, self).__init__(*args, **kwargs) 7 | self._counter = 0 8 | 9 | def inc(self, n=1): 10 | self._counter += n 11 | 12 | def get_count(self): 13 | return self._counter 14 | -------------------------------------------------------------------------------- /spec/metrics/src/metric.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import six 3 | 4 | 5 | @six.add_metaclass(abc.ABCMeta) 6 | class Metric: 7 | def __init__(self, name, unit, metric_type, desc='', display_name='', reusable=False): 8 | self.name = name 9 | self.unit = unit 10 | self.type = metric_type 11 | self.desc = desc 12 | self.display_name = display_name 13 | self.reusable = reusable 14 | -------------------------------------------------------------------------------- /spec/metrics/src/metric_types.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class MetricTypes(Enum): 5 | # A concurrent gauge counts the number of parallel invocations of 6 | # a target (method). Upon entering the target the value is increased. 7 | # It is decreased again upon exiting the target. 8 | CONCURRENT_GAUGE = 'concurrent gauge' 9 | 10 | # A Counter monotonically increases its values. 11 | # An example could be the number of Transactions committed. 12 | COUNTER = 'counter' 13 | 14 | # A Gauge has values that 'arbitrarily' goes up/down at each 15 | # sampling. An example could be CPU load 16 | GAUGE = 'gauge' 17 | 18 | # A Meter measures the rate at which a set of events occur. 19 | # An example could be amount of Transactions per Hour. 20 | METERED = 'meter' 21 | 22 | # A Histogram calculates the distribution of a value. 23 | HISTOGRAM = 'histogram' 24 | 25 | # A timer aggregates timing durations and provides duration 26 | # statistics, plus throughput statistics 27 | TIMER = 'timer' 28 | 29 | # A simple timer aggregates timing durations 30 | SIMPLE_TIMER = 'simple timer' 31 | 32 | # Invalid - Placeholder 33 | INVALID = 'invalid' 34 | 35 | @staticmethod 36 | def metric_from(string): 37 | for t in MetricTypes: 38 | if t.value == string: 39 | return t 40 | return MetricTypes.INVALID 41 | -------------------------------------------------------------------------------- /spec/metrics/src/metric_units.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class MetricUnits(Enum): 5 | NONE = "none" 6 | 7 | BITS = "bits" 8 | 9 | KILOBITS = "kilobits" 10 | 11 | MEGABITS = "megabits" 12 | 13 | GIGABITS = "gigabits" 14 | 15 | KIBIBITS = "kibibits" 16 | 17 | MEBIBITS = "mebibits" 18 | 19 | GIBIBITS = "gibibits" 20 | 21 | BYTES = "bytes" 22 | 23 | KILOBYTES = "kilobytes" 24 | 25 | MEGABYTES = "megabytes" 26 | 27 | GIGABYTES = "gigabytes" 28 | 29 | NANOSECONDS = "nanoseconds" 30 | 31 | MICROSECONDS = "microseconds" 32 | 33 | MILLISECONDS = "milliseconds" 34 | 35 | SECONDS = "seconds" 36 | 37 | MINUTES = "minutes" 38 | 39 | HOURS = "hours" 40 | 41 | DAYS = "days" 42 | 43 | PERCENT = "percent" 44 | 45 | PER_SECOND = "per_second" 46 | 47 | @staticmethod 48 | def unit_from(string): 49 | for t in MetricUnits: 50 | if t.value == string: 51 | return t 52 | return MetricUnits.NONE 53 | -------------------------------------------------------------------------------- /spec/metrics/src/tag.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | # Name of the Tag. Must match the regex [a-zA-Z_][a-zA-Z0-9_]# 5 | # A required field which holds the name of the tag. 6 | class Tag: 7 | PATTERN = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]') 8 | 9 | def __init__(self, name, value): 10 | # Constructs the Tag object with the given tag name and tag value 11 | # 12 | # tagName The tag name, must match the regex [a-zA-Z_][a-zA-Z0-9_] 13 | # tagValue The tag value 14 | # raises IllegalArgumentException If the tagName does not match [a-zA-Z_][a-zA-Z0-9_] 15 | if not name or not value: 16 | raise Exception('Invalid arguments. Tag name: [{}], Tag value: [{}]'.format(name, value)) 17 | 18 | if not Tag.PATTERN.match(name): 19 | raise Exception('Invalid Tag name: [{}]'.format(name)) 20 | 21 | self.name = name 22 | self.value = value 23 | 24 | def get_tag_name(self): 25 | return self.name 26 | 27 | def get_tag_value(self): 28 | return self.value 29 | 30 | def __eq__(self, other): 31 | if not isinstance(other, Tag): 32 | return False 33 | 34 | return self.name == other.name and self.value == other.value 35 | -------------------------------------------------------------------------------- /spec/metrics/src/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tikal-fuseday/python-microprofile/3700db5ca0be6a31df7d8aac8a523f9199484e76/spec/metrics/src/tests/__init__.py -------------------------------------------------------------------------------- /spec/metrics/src/tests/test_counter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from spec.metrics.src.counter import Counter 3 | from spec.metrics.src.metric_units import MetricUnits 4 | from spec.metrics.src.metric_types import MetricTypes 5 | 6 | 7 | class TestCounter(unittest.TestCase): 8 | def test_creation(self): 9 | counter = Counter('test_metric', MetricUnits.NONE, MetricTypes.COUNTER) 10 | self.assertEqual(counter.get_count(), 0) 11 | 12 | def test_inc(self): 13 | counter = Counter('test_metric', MetricUnits.NONE, MetricTypes.COUNTER) 14 | counter.inc() 15 | self.assertEqual(counter.get_count(), 1) 16 | counter.inc(10) 17 | self.assertEqual(counter.get_count(), 11) 18 | 19 | 20 | if __name__ == '__main__': 21 | unittest.main() 22 | -------------------------------------------------------------------------------- /spec/metrics/src/tests/test_metric_types.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from spec.metrics.src.metric_types import MetricTypes 3 | 4 | 5 | class TestMetricTypes(unittest.TestCase): 6 | def test_metric_from(self): 7 | self.assertEqual(MetricTypes.CONCURRENT_GAUGE, MetricTypes.metric_from('concurrent gauge')) 8 | 9 | def test_metric_from_not_exists(self): 10 | self.assertEqual(MetricTypes.INVALID, MetricTypes.metric_from('bla')) 11 | 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /spec/metrics/src/tests/test_metric_units.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from spec.metrics.src.metric_units import MetricUnits 3 | 4 | 5 | class TestMetricUnits(unittest.TestCase): 6 | def test_metric_from(self): 7 | self.assertEqual(MetricUnits.GIBIBITS, MetricUnits.unit_from('gibibits')) 8 | 9 | def test_metric_from_not_exists(self): 10 | self.assertEqual(MetricUnits.NONE, MetricUnits.unit_from('bla')) 11 | 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /spec/metrics/src/tests/test_tag.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from spec.metrics.src.tag import Tag 3 | 4 | 5 | class TestTag(unittest.TestCase): 6 | def test_create_instance(self): 7 | tag = Tag('name', 'value') 8 | self.assertEqual(tag.get_tag_name(), 'name') 9 | self.assertEqual(tag.get_tag_value(), 'value') 10 | 11 | def test_create_raises_exception(self): 12 | bad_name = lambda: Tag('_%&$#@', 'value') 13 | self.assertRaises(Exception, bad_name) 14 | 15 | def test_equals(self): 16 | tag1 = Tag('name', 'value') 17 | tag2 = Tag('name', 'value') 18 | self.assertEqual(tag1, tag2) 19 | 20 | 21 | if __name__ == '__main__': 22 | unittest.main() 23 | -------------------------------------------------------------------------------- /spec/open-api/README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | 3 | ## open-api 4 | -------------------------------------------------------------------------------- /spec/open-tracing/README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | 3 | ## open trace 4 | 5 | ## Introduction (from microprofile-opentracing-spec-1.3.3) 6 | Distributed tracing allows you to trace the flow of a request across service boundaries. 7 | This specification specifically addresses the problem of making it easy to instrument services with distributed tracing function, given an existing distributed tracing system in the environment. 8 | This specification specifically does not address the problem of defining, implementing, or configuring the underlying distributed tracing system. The proposal assumes an environment where all services use a common OpenTracing implementation (all Zipkin compatible, all Jaeger compatible, ...). 9 | 10 | ## Rationale (from microprofile-opentracing-spec-1.3.3) 11 | In order for a distributed tracing system to be effective and usable, two things are required 12 | 1. The different services in the environment must agree on the mechanism for transferring correlation ids across services. 13 | 2. The different services in the environment should produce their trace records in format that is consumable by the storage service for distributed trace records. 14 | Without the first, some services will not be included in the trace records associated with a request. Without the second, custom code would need to be written to present the information about a full request flow. 15 | 16 | 17 | There are existing distributed tracing systems that provide a server for distributed trace record storage and viewing, and application libraries for instrumenting microservices. The problem is that the different distributed tracing systems use implementation specific mechanisms for propagating correlation IDs and for formatting trace records, so once a microservice chooses a distributed tracing implementation library to use for its instrumentation, all other microservices in the environment are locked into the same choice. 18 | 19 | 20 | https://github.com/eclipse/microprofile-opentracing/releases 21 | 22 | ## The Challenge 23 | Use the opentrace standard (including python library) and integrate in python with the microprofile standard and annotations 24 | Currently microprofile only supports opentracing, what opentracing will be merging with opencensus to add metrics as well. 25 | 26 | https://opentracing.io/specification/ 27 | 28 | ## Implementation 29 | The implementation will based on https://github.com/opentracing/opentracing-python 30 | 31 | The following library has been found: opentracing-utils 32 | 33 | * No extrenal dependencies, only ![opentracing-python](https://github.com/zalando-zmon/opentracing-utils). 34 | * No threadlocals. Either pass spans explicitly or fallback to callstack frames inspection! 35 | * Context agnostic, so no external context implementation dependency (no Tornado, Flask, Django etc …). 36 | * Try to be less verbose - just add the @trace decorator. 37 | * Could be more verbose when needed, without complexity - just accept **kwargs and get the span passed to your traced functions via @trace(pass_span=True). 38 | * Support asyncio/async-await coroutines. (drop support for py2.7) 39 | * Support gevent 40 | * Ability to add OpenTracing support to external libs/frameworks/clients: 41 | Django (via OpenTracingHttpMiddleware) 42 | Flask (via trace_flask()) 43 | Requests (via trace_requests()) 44 | SQLAlchemy (via trace_sqlalchemy()) 45 | 46 | ## API Examples 47 | ```python 48 | # Normal traced function 49 | @trace() 50 | def trace_me(): 51 | pass 52 | 53 | # Traced function with access to created span in ``kwargs`` 54 | @trace(operation_name='user.operation', pass_span=True) 55 | def user_operation(user, op, **kwargs): 56 | current_span = extract_span_from_kwargs(**kwargs) 57 | 58 | current_span.set_tag('user.id', user.id) 59 | 60 | # Then do stuff ... 61 | 62 | # trace_me will have ``current_span`` as its parent. 63 | trace_me() 64 | 65 | # Traced function using ``follows_from`` instead of ``child_of`` reference. 66 | @trace(use_follows_from=True) 67 | def trace_me_later(): 68 | pass 69 | 70 | 71 | # Start a fresh trace - any parent spans will be ignored 72 | @trace(operation_name='epoch', ignore_parent_span=True) 73 | def start_fresh(): 74 | 75 | user = {'id': 1} 76 | 77 | # trace decorator will handle trace heirarchy 78 | user_operation(user, 'create') 79 | 80 | # trace_me will have ``epoch`` span as its parent. 81 | trace_me() 82 | 83 | ``` 84 | -------------------------------------------------------------------------------- /spec/rest-client/README.md: -------------------------------------------------------------------------------- 1 | # python-microprofile 2 | 3 | ## rest config client 4 | --------------------------------------------------------------------------------