├── api_demo_server ├── __init__.py ├── app.py └── database.py ├── Dockerfile ├── pyproject.toml ├── .pre-commit-config.yaml ├── .github └── workflows │ └── build.yaml ├── README.md ├── .gitignore └── LICENSE /api_demo_server/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.0.0" 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | from --platform=$BUILDPLATFORM ubuntu:22.04 2 | LABEL org.opencontainers.image.source=https://github.com/canonical/api_demo_server 3 | 4 | RUN apt-get update && apt-get install -y \ 5 | python3.10 \ 6 | python3-pip 7 | COPY ./pyproject.toml . 8 | 9 | # create dummy project folder just to keep the layer with dependencies untouched until pyproject is changed 10 | RUN mkdir api_demo_server && echo "__version__ = '1.0.0.dev0'" > api_demo_server/__init__.py 11 | RUN python3 -m pip install . 12 | COPY ./api_demo_server ./api_demo_server 13 | EXPOSE 8000 14 | ENTRYPOINT ["uvicorn", "api_demo_server.app:app", "--host=0.0.0.0"] 15 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["flit_core >=3.2,<4"] 3 | build-backend = "flit_core.buildapi" 4 | 5 | [project] 6 | name = "api_demo_server" 7 | description = """FastAPI demo server""" 8 | authors = [{name = "Maksim Beliaev", email = "beliaev.m.s@gmail.com"}] 9 | license = {file = "LICENSE"} 10 | classifiers = ["License :: OSI Approved :: MIT License"] 11 | dynamic = ["version"] 12 | 13 | dependencies = [ 14 | "fastapi==0.85", 15 | "uvicorn[standard]==0.18.3", 16 | "python-multipart==0.0.5", 17 | "psycopg2-binary==2.9.9", 18 | "starlette_exporter==0.14.0" 19 | ] 20 | 21 | # development dependencies 22 | [project.optional-dependencies] 23 | test = [ 24 | "pre-commit", 25 | ] 26 | 27 | deploy = [ 28 | "flit==3.7.1", 29 | ] 30 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: ./lib 2 | repos: 3 | - repo: https://github.com/humitos/mirrors-autoflake 4 | rev: v1.1 5 | hooks: 6 | - id: autoflake 7 | args: ["-i", "--remove-all-unused-imports"] 8 | - repo: https://github.com/psf/black 9 | rev: 22.3.0 10 | hooks: 11 | - id: black 12 | language_version: python3 13 | args: ["-l", "100"] 14 | - repo: https://github.com/asottile/blacken-docs 15 | rev: v1.12.1 16 | hooks: 17 | - id: blacken-docs 18 | additional_dependencies: [black] 19 | - repo: https://github.com/pycqa/isort 20 | rev: 5.10.1 21 | hooks: 22 | - id: isort 23 | name: isort (python) 24 | args: ["-sl", "--profile", "black"] 25 | 26 | - repo: https://github.com/pycqa/flake8 27 | rev: 3.9.2 28 | hooks: 29 | - id: flake8 30 | name: flake8-py3 31 | args: ["--max-line-length", "100", "--max-doc-length", "100"] 32 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build and Publish Multi-arch Docker Image 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | build-and-publish: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout Repository 14 | uses: actions/checkout@v4 15 | 16 | - name: Set up QEMU 17 | uses: docker/setup-qemu-action@v3.0.0 18 | 19 | - name: Set up Docker Buildx 20 | uses: docker/setup-buildx-action@v3.1.0 21 | 22 | - name: Login to GitHub Container Registry 23 | uses: docker/login-action@v3.0.0 24 | with: 25 | registry: ghcr.io 26 | username: ${{ github.actor }} 27 | password: ${{ secrets.GITHUB_TOKEN }} 28 | 29 | - name: Build and Push Docker Image 30 | run: | 31 | docker buildx build \ 32 | -t ghcr.io/canonical/api_demo_server:${{ github.ref_name }} \ 33 | --platform linux/amd64,linux/arm64,linux/ppc64le \ 34 | --push . 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Description 2 | This is a demo server based on Python FastAPI. 3 | Server is used to show connections to PostgreSQL and Prometheus. 4 | 5 | To see API reference start the server and open: http://127.0.0.1:8000/docs 6 | To get prometheus metrics: http://127.0.0.1:8000/metrics 7 | 8 | # Usage 9 | Download and start PostgreSQL container: 10 | ``` 11 | docker run --name postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres 12 | ``` 13 | 14 | Get psql container IP: 15 | ``` 16 | docker ps # get postgres container ID 17 | docker inspect | grep IPAddress 18 | ``` 19 | 20 | Build a docker container via: 21 | ``` 22 | docker build -t api_demo_server . 23 | ``` 24 | 25 | Start demo server: 26 | ``` 27 | docker run --rm -e DEMO_SERVER_DB_HOST= -p 8000:8000 api_demo_server 28 | ``` 29 | 30 | # Configuration via environment variables 31 | You can configure application by applying following environment variables: 32 | 33 | | Environment Variable | Value | Description | 34 | |------------------------- |------------------- |------------------------------------------------- | 35 | | DEMO_SERVER_LOGFILE | \ | Path to the file where logs should be written | 36 | | DEMO_SERVER_DB_HOST | \ | IP address of the host where Database is hosted | 37 | | DEMO_SERVER_DB_PORT | \ | Port of the host where Database is hosted | 38 | | DEMO_SERVER_DB_USER | \ | Username that has access to `names` Database | 39 | | DEMO_SERVER_DB_PASSWORD | \ | Password to the `DEMO_SERVER_DB_USER` user | 40 | 41 | # Publish to registry 42 | 43 | ``` 44 | docker buildx build -t ghcr.io/canonical/api_demo_server:1.0.0 --platform linux/amd64,linux/arm64,linux/ppc64le --push . 45 | ``` 46 | -------------------------------------------------------------------------------- /api_demo_server/app.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | from fastapi import FastAPI 5 | from fastapi import Form 6 | from starlette.responses import RedirectResponse 7 | from starlette.responses import Response 8 | from starlette_exporter import PrometheusMiddleware 9 | from starlette_exporter import handle_metrics 10 | 11 | from . import __version__ 12 | from .database import DataBase 13 | 14 | 15 | def define_logger(): 16 | """Define logger to output to the file and to STDOUT.""" 17 | log = logging.getLogger("api-demo-server") 18 | log.setLevel(logging.DEBUG) 19 | formatter = logging.Formatter( 20 | fmt="%(asctime)s (%(levelname)s) %(message)s", datefmt="%d.%m.%Y %H:%M:%S" 21 | ) 22 | stream_handler = logging.StreamHandler() 23 | stream_handler.setFormatter(formatter) 24 | log.addHandler(stream_handler) 25 | 26 | log_file = os.environ.get("DEMO_SERVER_LOGFILE", "demo_server.log") 27 | file_handler = logging.FileHandler(filename=log_file) 28 | file_handler.setFormatter(formatter) 29 | log.addHandler(file_handler) 30 | return log 31 | 32 | 33 | logger = define_logger() 34 | 35 | PSQL_DB = DataBase() 36 | 37 | app = FastAPI() 38 | app.add_middleware(PrometheusMiddleware) 39 | app.add_route("/metrics", handle_metrics) 40 | 41 | 42 | async def catch_exceptions_middleware(request, call_next): 43 | """Middleware to catch all exceptions. 44 | 45 | All exceptions that were raised during handling of the request will be caught 46 | and logged with the traceback, then 500 response will be returned to the user. 47 | """ 48 | try: 49 | return await call_next(request) 50 | except Exception: 51 | logger.exception("Exception occurred") 52 | return Response("Internal server error", status_code=500) 53 | 54 | 55 | app.middleware("http")(catch_exceptions_middleware) 56 | 57 | 58 | @app.get("/") 59 | def root(): 60 | """Just redirect from root path to Swagger UI""" 61 | return RedirectResponse(url="/docs") 62 | 63 | 64 | @app.post("/createtable") 65 | def create_table(): 66 | PSQL_DB.create_table(db_name="names_db", table_name="names") 67 | 68 | 69 | @app.post("/deletetable") 70 | def delete_table(): 71 | PSQL_DB.delete_table(db_name="names_db", table_name="names") 72 | 73 | 74 | @app.post("/addname/") 75 | def add_name(name: str = Form()): 76 | PSQL_DB.add_name(name, db_name="names_db", table_name="names") 77 | return {"name added": name} 78 | 79 | 80 | @app.get("/names") 81 | def get_all_names(): 82 | return {"names": dict(PSQL_DB.all_names(db_name="names_db", table_name="names"))} 83 | 84 | 85 | @app.get("/error") 86 | def cause_error(): 87 | """Intentionally cause a ZeroDivisionError to test logging and prometheus metrics.""" 88 | return 1 / 0 89 | 90 | 91 | @app.get("/version") 92 | def get_version(): 93 | return {"version": __version__} 94 | -------------------------------------------------------------------------------- /api_demo_server/database.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from typing import List 4 | from typing import Tuple 5 | 6 | import psycopg2 7 | from psycopg2 import sql 8 | from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT 9 | 10 | # set logger to be configurable from external 11 | logger = logging.getLogger("api-demo-server") 12 | 13 | DB_HOST = os.environ.get("DEMO_SERVER_DB_HOST", "127.0.0.1") 14 | DB_PORT = os.environ.get("DEMO_SERVER_DB_PORT", "5432") 15 | 16 | DB_USER = os.environ.get("DEMO_SERVER_DB_USER", "postgres") 17 | DB_PASSWORD = os.environ.get("DEMO_SERVER_DB_PASSWORD", "mysecretpassword") 18 | 19 | 20 | class DataBase: 21 | def __init__(self) -> None: 22 | self.db_conn = None 23 | 24 | def connect_to_db(self, db_name: str) -> None: 25 | """Connects to the database, creates if it does not exist.""" 26 | try: 27 | self.db_conn = psycopg2.connect( 28 | dbname=db_name, 29 | user=DB_USER, 30 | password=DB_PASSWORD, 31 | host=DB_HOST, 32 | port=DB_PORT, 33 | ) 34 | self.db_conn.autocommit = True 35 | except psycopg2.OperationalError as exc: 36 | if f'database "{db_name}" does not exist' in str(exc): 37 | logger.error(f"Database {db_name} does not exist. Trying to create.") 38 | self.create_db(db_name) 39 | self.connect_to_db(db_name) 40 | else: 41 | raise 42 | 43 | logger.info(f"Successfully connected to database: {db_name}") 44 | 45 | @property 46 | def can_connect(self): 47 | """Ensure that database connection is alive.""" 48 | return self.db_conn and not self.db_conn.closed 49 | 50 | @staticmethod 51 | def create_db(db_name: str) -> None: 52 | """Creates database if it does not exist. 53 | 54 | Will work only for "postgres" user. 55 | """ 56 | conn = psycopg2.connect(user=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT) 57 | conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) 58 | cursor = conn.cursor() 59 | # Prevent sql injection attack by using sql module instead of string concat 60 | cursor.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(db_name))) 61 | logger.info(f"Database '{db_name}' was created.") 62 | 63 | def _table_exists(self, table_name: str) -> bool: 64 | """Checks if the table already exists.""" 65 | with self.db_conn.cursor() as cursor: 66 | cursor.execute( 67 | "SELECT EXISTS (SELECT relname FROM pg_class WHERE relname=%s);", (table_name,) 68 | ) 69 | if cursor.fetchone()[0]: 70 | logger.info(f"Table '{table_name}' already exists.") 71 | return True 72 | return False 73 | 74 | def delete_table(self, db_name: str, table_name: str) -> None: 75 | """Delete a table in database `db_name`""" 76 | if not self.can_connect: 77 | self.connect_to_db(db_name) 78 | 79 | with self.db_conn.cursor() as cursor: 80 | cursor.execute(sql.SQL("DROP TABLE IF EXISTS {};").format(sql.Identifier(table_name))) 81 | logger.info(f"Table '{table_name}' is deleted") 82 | 83 | def create_table(self, db_name: str, table_name: str) -> None: 84 | """Create a table in database `db_name` if it doesn't already exist.""" 85 | if not self.can_connect: 86 | self.connect_to_db(db_name) 87 | if self._table_exists(table_name): 88 | return 89 | 90 | with self.db_conn.cursor() as cursor: 91 | cursor.execute( 92 | sql.SQL("CREATE TABLE {} (id serial PRIMARY KEY, data varchar);").format( 93 | sql.Identifier(table_name) 94 | ) 95 | ) 96 | logger.info(f"Table '{table_name}' was created in DB '{db_name}'") 97 | 98 | def add_name(self, name: str, db_name: str, table_name: str) -> None: 99 | self.create_table(db_name, table_name) 100 | 101 | with self.db_conn.cursor() as cursor: 102 | cursor.execute( 103 | sql.SQL("INSERT INTO {} (data) VALUES (%s);").format(sql.Identifier(table_name)), 104 | (name,), 105 | ) 106 | 107 | def all_names(self, db_name: str, table_name: str) -> List[Tuple[int, str]]: 108 | self.create_table(db_name, table_name) 109 | with self.db_conn.cursor() as cursor: 110 | cursor.execute(sql.SQL("SELECT * FROM {}").format(sql.Identifier(table_name))) 111 | return cursor.fetchall() 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/pycharm,python,django 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=pycharm,python,django 4 | 5 | /input/ 6 | results*/ 7 | dummy.py 8 | 9 | ### Django ### 10 | *.log 11 | *.pot 12 | *.pyc 13 | __pycache__/ 14 | local_settings.py 15 | db.sqlite3 16 | db.sqlite3-journal 17 | media 18 | venv 19 | admin 20 | grappelli 21 | rest_framework 22 | **/migrations 23 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 24 | # in your Git repository. Update and uncomment the following line accordingly. 25 | # /staticfiles/ 26 | 27 | ### Django.Python Stack ### 28 | # Byte-compiled / optimized / DLL files 29 | *.py[cod] 30 | *$py.class 31 | 32 | # C extensions 33 | *.so 34 | 35 | # Distribution / packaging 36 | .Python 37 | build/ 38 | develop-eggs/ 39 | dist/ 40 | downloads/ 41 | eggs/ 42 | .eggs/ 43 | parts/ 44 | sdist/ 45 | var/ 46 | wheels/ 47 | pip-wheel-metadata/ 48 | share/python-wheels/ 49 | *.egg-info/ 50 | .installed.cfg 51 | *.egg 52 | MANIFEST 53 | 54 | # PyInstaller 55 | # Usually these files are written by a python script from a template 56 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 57 | *.manifest 58 | *.spec 59 | 60 | # Installer logs 61 | pip-log.txt 62 | pip-delete-this-directory.txt 63 | 64 | # Unit test / coverage reports 65 | htmlcov/ 66 | .tox/ 67 | .nox/ 68 | .coverage 69 | .coverage.* 70 | .cache 71 | nosetests.xml 72 | coverage.xml 73 | *.cover 74 | *.py,cover 75 | .hypothesis/ 76 | .pytest_cache/ 77 | pytestdebug.log 78 | 79 | # Translations 80 | *.mo 81 | 82 | # Django stuff: 83 | 84 | # Flask stuff: 85 | instance/ 86 | .webassets-cache 87 | 88 | # Scrapy stuff: 89 | .scrapy 90 | 91 | # Sphinx documentation 92 | docs/_build/ 93 | doc/_build/ 94 | 95 | # PyBuilder 96 | target/ 97 | 98 | # Jupyter Notebook 99 | .ipynb_checkpoints 100 | 101 | # IPython 102 | profile_default/ 103 | ipython_config.py 104 | 105 | # pyenv 106 | .python-version 107 | 108 | # pipenv 109 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 110 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 111 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 112 | # install all needed dependencies. 113 | #Pipfile.lock 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | pythonenv* 134 | 135 | # Spyder project settings 136 | .spyderproject 137 | .spyproject 138 | 139 | # Rope project settings 140 | .ropeproject 141 | 142 | # mkdocs documentation 143 | /site 144 | 145 | # mypy 146 | .mypy_cache/ 147 | .dmypy.json 148 | dmypy.json 149 | 150 | # Pyre type checker 151 | .pyre/ 152 | 153 | # pytype static type analyzer 154 | .pytype/ 155 | 156 | # profiling data 157 | .prof 158 | 159 | ### PyCharm ### 160 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 161 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 162 | 163 | # User-specific stuff 164 | .idea 165 | # CMake 166 | cmake-build-*/ 167 | 168 | 169 | # File-based project format 170 | *.iws 171 | 172 | # IntelliJ 173 | out/ 174 | 175 | # mpeltonen/sbt-idea plugin 176 | .idea_modules/ 177 | 178 | # JIRA plugin 179 | atlassian-ide-plugin.xml 180 | 181 | # Cursive Clojure plugin 182 | .idea/replstate.xml 183 | 184 | # Crashlytics plugin (for Android Studio and IntelliJ) 185 | com_crashlytics_export_strings.xml 186 | crashlytics.properties 187 | crashlytics-build.properties 188 | fabric.properties 189 | 190 | # Editor-based Rest Client 191 | .idea/httpRequests 192 | 193 | # Android studio 3.1+ serialized cache file 194 | .idea/caches/build_file_checksums.ser 195 | 196 | ### PyCharm Patch ### 197 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 198 | 199 | # *.iml 200 | # modules.xml 201 | # .idea/misc.xml 202 | # *.ipr 203 | 204 | # Sonarlint plugin 205 | # https://plugins.jetbrains.com/plugin/7973-sonarlint 206 | .idea/**/sonarlint/ 207 | 208 | # SonarQube Plugin 209 | # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin 210 | .idea/**/sonarIssues.xml 211 | 212 | # Markdown Navigator plugin 213 | # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced 214 | .idea/**/markdown-navigator.xml 215 | .idea/**/markdown-navigator-enh.xml 216 | .idea/**/markdown-navigator/ 217 | 218 | # Cache file creation bug 219 | # See https://youtrack.jetbrains.com/issue/JBR-2257 220 | .idea/$CACHE_FILE$ 221 | 222 | # CodeStream plugin 223 | # https://plugins.jetbrains.com/plugin/12206-codestream 224 | .idea/codestream.xml 225 | 226 | ### Python ### 227 | # Byte-compiled / optimized / DLL files 228 | 229 | # C extensions 230 | 231 | # Distribution / packaging 232 | 233 | # PyInstaller 234 | # Usually these files are written by a python script from a template 235 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 236 | 237 | # Installer logs 238 | 239 | # Unit test / coverage reports 240 | 241 | # Translations 242 | 243 | # Django stuff: 244 | 245 | # Flask stuff: 246 | 247 | # Scrapy stuff: 248 | 249 | # Sphinx documentation 250 | 251 | # PyBuilder 252 | 253 | # Jupyter Notebook 254 | 255 | # IPython 256 | 257 | # pyenv 258 | 259 | # pipenv 260 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 261 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 262 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 263 | # install all needed dependencies. 264 | 265 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 266 | 267 | # Celery stuff 268 | 269 | # SageMath parsed files 270 | 271 | # Environments 272 | 273 | # Spyder project settings 274 | 275 | # Rope project settings 276 | 277 | # mkdocs documentation 278 | 279 | # mypy 280 | 281 | # Pyre type checker 282 | 283 | # pytype static type analyzer 284 | 285 | # profiling data 286 | 287 | # End of https://www.toptal.com/developers/gitignore/api/pycharm,python,django 288 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------