├── .github └── workflows │ └── release.yml ├── .gitignore ├── .vscode └── settings.json ├── CHANGELOG.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── chaosk6 ├── __init__.py ├── actions.py ├── probes.py └── scripts │ ├── probe.js │ └── single-endpoint.js ├── examples ├── experiment.json └── experiment.yaml ├── pytest.ini ├── requirements-dev.txt ├── requirements.txt ├── setup.cfg ├── setup.py └── tests └── __init__.py /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | workflow_dispatch: {} 8 | release: 9 | types: [created] 10 | 11 | jobs: 12 | deploy: 13 | 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: autopep8 22 | id: autopep8 23 | uses: peter-evans/autopep8@v1 24 | with: 25 | args: --recursive --in-place --aggressive --aggressive . 26 | - name: Fail if autopep8 made changes 27 | if: steps.autopep8.outputs.exit-code == 2 28 | run: exit 1 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install setuptools wheel twine build 33 | - name: Build and publish 34 | env: 35 | TWINE_USERNAME: ${{ secrets.K6_CTK_PYPI_USERNAME }} 36 | TWINE_PASSWORD: ${{ secrets.K6_CTK_PYPI_PASSWORD }} 37 | run: | 38 | python -m build 39 | twine upload dist/* 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | .DS_Store 104 | junit-test-results.xml 105 | journal.json 106 | 107 | # Generated by execution 108 | k6.log -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [Unreleased][] 4 | 5 | [Unreleased]: https://github.com/k6io/chaostoolkit-k6/compare/0.3.3...HEAD 6 | 7 | ### Changed 8 | 9 | - Fix Python minimal version requirements as per https://github.com/pypa/packaging/issues/673 10 | 11 | ## [0.3.0][] - 2021-04-23 12 | 13 | [0.3.0]: https://github.com/k6io/chaostoolkit-k6/tree/0.3.0 14 | 15 | ### Changed 16 | 17 | - Format code according to pep8 18 | 19 | ## [0.2.0][] - 2021-01-25 20 | 21 | [0.2.0]: https://github.com/k6io/chaostoolkit-k6/tree/0.2.0 22 | 23 | ### Added 24 | 25 | - Initial release 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include chaosk6/scripts/*.js 2 | include README.md 3 | include requirements.txt 4 | include requirements-dev.txt 5 | include LICENSE 6 | include CHANGELOG.md 7 | include pytest.ini -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chaos Toolkit Extension for k6. 2 | 3 | [![Python versions](https://img.shields.io/pypi/pyversions/chaostoolkit-k6.svg)](https://www.python.org/) 4 | 5 | This project is a collection of [actions][] and [probes][], gathered as an 6 | extension to the [Chaos Toolkit][chaostoolkit]. 7 | 8 | [actions]: http://chaostoolkit.org/reference/api/experiment/#action 9 | [probes]: http://chaostoolkit.org/reference/api/experiment/#probe 10 | [chaostoolkit]: http://chaostoolkit.org 11 | 12 | ## Install 13 | 14 | This package requires Python 3.5+ 15 | 16 | To be used from your experiment, this package must be installed in the Python 17 | environment where [chaostoolkit][] already lives. 18 | 19 | ``` 20 | $ pip install -U chaostoolkit-k6 21 | ``` 22 | 23 | ## Usage 24 | 25 | Please explore the code to see existing probes and actions. 26 | ## Configuration 27 | 28 | ## Contribute 29 | 30 | If you wish to contribute more functions to this package, you are more than 31 | welcome to do so. Please, fork this project, make your changes following the 32 | usual [PEP 8][pep8] code style, sprinkling with tests and submit a PR for 33 | review. 34 | 35 | [pep8]: https://pycodestyle.readthedocs.io/en/latest/ 36 | 37 | The Chaos Toolkit projects require all contributors must sign a 38 | [Developer Certificate of Origin][dco] on each commit they would like to merge 39 | into the master branch of the repository. Please, make sure you can abide by 40 | the rules of the DCO before submitting a PR. 41 | 42 | [dco]: https://github.com/probot/dco#how-it-works 43 | 44 | ### Develop 45 | 46 | If you wish to develop on this project, make sure to install the development 47 | dependencies. But first, [create a virtual environment][venv] and then install 48 | those dependencies. 49 | 50 | [venv]: http://chaostoolkit.org/reference/usage/install/#create-a-virtual-environment 51 | 52 | ```console 53 | $ pip install -r requirements-dev.txt -r requirements.txt 54 | ``` 55 | 56 | Then, point your environment to this directory: 57 | 58 | ```console 59 | $ pip install -e . 60 | ``` 61 | 62 | Now, you can edit the files and they will be automatically be seen by your 63 | environment, even when running from the `chaos` command locally. 64 | 65 | ### Test 66 | 67 | To run the tests for the project execute the following: 68 | 69 | ``` 70 | $ pytest 71 | ``` 72 | -------------------------------------------------------------------------------- /chaosk6/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from typing import List 4 | from logzero import logger 5 | from chaoslib.discovery.discover import ( 6 | discover_actions, 7 | discover_probes, 8 | initialize_discovery_result, 9 | ) 10 | from chaoslib.types import Discovery, DiscoveredActivities 11 | 12 | """Top-level package for chaostoolkit-k6.""" 13 | 14 | __all__ = ["discover"] 15 | __version__ = "0.3.4" 16 | 17 | 18 | def discover(discover_system: bool = True) -> Discovery: 19 | """ 20 | Discover k6 capabilities offered by this extension. 21 | """ 22 | logger.info("Discovering capabilities from chaostoolkit-k6") 23 | 24 | discovery = initialize_discovery_result( 25 | "chaostoolkit-k6", __version__, "k6") 26 | discovery["activities"].extend(load_exported_activities()) 27 | return discovery 28 | 29 | 30 | def load_exported_activities() -> List[DiscoveredActivities]: 31 | activities = [] 32 | activities.extend(discover_actions("chaosk6.actions")) 33 | activities.extend(discover_probes("chaosk6.probes")) 34 | return activities 35 | -------------------------------------------------------------------------------- /chaosk6/actions.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | 4 | from chaoslib.deprecation import warn_about_moved_function 5 | from logzero import logger 6 | from pathlib import Path 7 | 8 | __all__ = ["run_script", "stress_endpoint"] 9 | 10 | 11 | def run_script(script_path: str = None, vus: int = 1, duration: str = "1s", log_file: str = None, debug: bool = False): 12 | """ 13 | Run an arbitrary k6 script with a configurable amount of VUs and duration. 14 | Depending on the specs of the attacking machine, possible VU amount may 15 | vary. 16 | For a non-customized 2019 Macbook Pro, it will cap around 250 +/- 50. 17 | 18 | Parameters 19 | ---------- 20 | script_path : str 21 | Full path to the k6 test script 22 | vus : int 23 | Amount of virtual users to run the test with 24 | duration : str 25 | Duration, written as a string, ie: `1h2m3s` etc 26 | log_file: str 27 | (Optional) Relative path to the file where output should be logged. 28 | """ 29 | logger.info("Running " + script_path) 30 | _runScript( 31 | script=script_path, 32 | vus=vus, 33 | duration=duration, 34 | log_file=log_file, 35 | debug=debug 36 | ) 37 | 38 | 39 | def stress_endpoint(endpoint: str = None, vus: int = 1, duration: str = "1s", log_file: str = None, debug: bool = False): 40 | """ 41 | Stress a single endpoint with a configurable amount of VUs and duration. 42 | Depending on the specs of the attacking machine, possible VU amount may 43 | vary. 44 | For a non-customized 2019 Macbook Pro, it will cap around 250 +/- 50. 45 | 46 | Parameters 47 | ---------- 48 | endpoint : str 49 | The URL to the endpoint you want to stress, including the scheme prefix. 50 | vus : int 51 | Amount of virtual users to run the test with 52 | duration : str 53 | Duration, written as a string, ie: `1h2m3s` etc 54 | log_file: str 55 | (Optional) Relative path to the file where output should be logged. 56 | """ 57 | basePath = Path(__file__).parent 58 | jsPath = str(basePath.parent) + "/chaosk6/scripts" 59 | 60 | logger.info( 61 | 'Stressing the endpoint "{}" with {} VUs for {}.'.format( 62 | endpoint, vus, duration 63 | ) 64 | ) 65 | 66 | env = dict(**os.environ, CHAOS_K6_URL=endpoint) 67 | r = _runScript( 68 | script=jsPath + "/single-endpoint.js", 69 | vus=vus, 70 | duration=duration, 71 | log_file=log_file, 72 | environ=env, 73 | debug=debug) 74 | 75 | logger.info("Stressing completed.") 76 | if log_file != None: 77 | logger.info("Logged K6 output to {}.".format(log_file)) 78 | return r 79 | 80 | 81 | def _runScript( 82 | script: str, 83 | vus: int, 84 | duration: str, 85 | log_file: str, 86 | environ: dict = None, 87 | debug: bool = False 88 | ): 89 | 90 | if not environ: 91 | environ = dict(os.environ) 92 | command = [ 93 | "k6", 94 | "run", 95 | "--quiet", 96 | script, 97 | "--vus", str(vus), 98 | "--duration", 99 | str(duration) 100 | ] 101 | 102 | # Default output to the void 103 | pipeoutput = subprocess.DEVNULL 104 | # Use log file location if provided 105 | if log_file != None: 106 | pipeoutput = open(log_file, "w") 107 | 108 | with subprocess.Popen( 109 | command, stderr=subprocess.STDOUT, stdout=None if debug is True else pipeoutput, env=environ 110 | ) as p: 111 | return p.returncode is None 112 | 113 | 114 | def runScript(script_path: str = None, vus: int = 1, duration: str = "1s", debug: bool = False): 115 | warn_about_moved_function( 116 | "The action `runScript` is now called `run_script`." 117 | "Please consider updating your experiments accordingly.") 118 | return run_script(script_path, vus, duration) 119 | 120 | 121 | def stressEndpoint(endpoint: str = None, vus: int = 1, duration: str = "1s", debug: bool = False): 122 | warn_about_moved_function( 123 | "The action `stressEndpoint` is now called `stress_endpoint`." 124 | "Please consider updating your experiments accordingly.") 125 | return run_script(endpoint, vus, duration) 126 | -------------------------------------------------------------------------------- /chaosk6/probes.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | import json 4 | 5 | __all__ = ["http"] 6 | 7 | 8 | def http( 9 | endpoint: str, 10 | method: str = "GET", 11 | status: int = 200, 12 | body: str = "", 13 | headers: dict = {}, 14 | vus: int = 1, 15 | duration: str = "", 16 | debug: bool = False, 17 | timeout: int = 1, 18 | ) -> bool: 19 | """ 20 | Probe an endpoint to make sure it responds to an http request 21 | with the expected HTTP status code. Depending on the endpoint and your 22 | payload, this action might be destructive. Use with caution. 23 | 24 | Parameters 25 | ---------- 26 | endpoint : str 27 | The URL to the endpoint to probe 28 | method : str 29 | A valid http request method name, like GET, POST, PUT, DELETE, OPTIONS, or PATCH 30 | status : int 31 | The expected HTTP Response status code. 32 | vus : int 33 | The amount of concurrent virtual users accessing the endpoint 34 | duration : str 35 | How long to probe the endpoint. Expressed as a duration string, 36 | i.e "20s", "1m", "1h" etc. 37 | timeout : int 38 | Timeout duration for http requests. Defaults to 1 second 39 | """ # noqa: E501 40 | if status < 100 or status > 999: 41 | raise ValueError("Invalid HTTP Response status code expection") 42 | if method.lower() not in [ 43 | "get", "post", "put", "patch", "delete", "options"]: 44 | raise ValueError("Invalid HTTP Request method") 45 | if endpoint is None: 46 | raise ValueError("Endpoint is a required argument") 47 | 48 | env = dict( 49 | **os.environ, 50 | CHAOS_K6_URL=endpoint, 51 | CHAOS_K6_METHOD=method, 52 | CHAOS_K6_STATUS=str(status), 53 | CHAOS_K6_BODY=body, 54 | CHAOS_K6_HEADERS=json.dumps(headers), 55 | CHAOS_K6_VUS=str(vus), 56 | CHAOS_K6_DURATION=duration, 57 | CHAOS_K6_HTTP_TIMEOUT=str(timeout), 58 | ) 59 | 60 | scriptDir = os.path.dirname(os.path.realpath(__file__)) 61 | 62 | cmd = ["k6", "run", "{}/scripts/probe.js".format(scriptDir)] 63 | 64 | with subprocess.Popen( 65 | cmd, 66 | env=env, 67 | stderr=subprocess.STDOUT, 68 | stdout=None if debug is True else subprocess.PIPE, 69 | ) as p: 70 | return p.returncode is None 71 | -------------------------------------------------------------------------------- /chaosk6/scripts/probe.js: -------------------------------------------------------------------------------- 1 | import { Counter, Rate } from 'k6/metrics'; 2 | import http from 'k6/http'; 3 | 4 | const defaults = { 5 | vus: 1, 6 | duration: '1s', 7 | headers: '{}', 8 | }; 9 | 10 | const env = getEnvs(); 11 | const failures = new Rate('failures'); 12 | const completed = new Counter('completed'); 13 | 14 | export const options = { 15 | discardResponseBodies: true, 16 | vus: env.vus, 17 | duration: env.duration, 18 | thresholds: { 19 | completed: [ 20 | { 21 | threshold: 'count>0', 22 | }, 23 | ], 24 | failures: [ 25 | { 26 | threshold: 'rate<=0', 27 | abortOnFail: true, 28 | }, 29 | ], 30 | }, 31 | }; 32 | 33 | export default function () { 34 | completed.add(0); 35 | const r = doRequest(env); 36 | completed.add(1); 37 | failures.add(r.status !== env.status); 38 | } 39 | 40 | function getEnvs() { 41 | return { 42 | method: __ENV.CHAOS_K6_METHOD.toLowerCase(), 43 | url: __ENV.CHAOS_K6_URL, 44 | status: parseInt(__ENV.CHAOS_K6_STATUS, 10), 45 | body: __ENV.CHAOS_K6_BODY, 46 | vus: __ENV.CHAOS_K6_VUS || defaults.vus, 47 | duration: __ENV.CHAOS_K6_DURATION || defaults.duration, 48 | headers: JSON.parse(__ENV.CHAOS_K6_HEADERS || defaults.headers), 49 | timeout: parseInt(__ENV.CHAOS_K6_HTTP_TIMEOUT, 10), 50 | }; 51 | } 52 | 53 | function doRequest(env) { 54 | if (env.method === 'get') { 55 | return http.get(env.url, { 56 | headers: env.headers, 57 | timeout: env.timeout * 1000, 58 | }); 59 | } 60 | 61 | return (env.method === 'delete' ? http.delete : http[env.method])( 62 | env.url, 63 | env.body, 64 | { headers: env.headers, timeout: env.timeout * 1000 } 65 | ); 66 | } 67 | -------------------------------------------------------------------------------- /chaosk6/scripts/single-endpoint.js: -------------------------------------------------------------------------------- 1 | import { Rate } from 'k6/metrics'; 2 | import http from 'k6/http'; 3 | 4 | const failures = new Rate('failures'); 5 | 6 | export const options = { 7 | thresholds: { 8 | failures: [{ threshold: 'rate<=0', abortOnFail: true }], 9 | }, 10 | }; 11 | 12 | export default function () { 13 | const r = http.get(__ENV.CHAOS_K6_URL); 14 | console.log(`Status: ${r.status_text}`) 15 | failures.add(r.status !== 200); 16 | } 17 | -------------------------------------------------------------------------------- /examples/experiment.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0", 3 | "title": "Google Incident JSON Example", 4 | "description": "Retrieve all of Google's incidents reapeatedly as an example.", 5 | "tags": [], 6 | "configuration": {}, 7 | "steady-state-hypothesis": { 8 | "title": "The enpoint will continue to respond.", 9 | "probes": [ 10 | { 11 | "name": "Retrieve incidents.", 12 | "type": "probe", 13 | "tolerance": 200, 14 | "provider": { 15 | "type": "http", 16 | "url": "https://status.cloud.google.com/incidents.json" 17 | } 18 | } 19 | ] 20 | }, 21 | "method": [ 22 | { 23 | "name": "Retrieve all incidents repeatedly.", 24 | "type": "action", 25 | "provider": { 26 | "type": "python", 27 | "module": "chaosk6.actions", 28 | "func": "stress_endpoint", 29 | "arguments": { 30 | "endpoint": "https://status.cloud.google.com/incidents.json", 31 | "vus": 10, 32 | "duration": "5s", 33 | "log_file": "k6.log" 34 | } 35 | } 36 | } 37 | ], 38 | "rollbacks": [] 39 | } -------------------------------------------------------------------------------- /examples/experiment.yaml: -------------------------------------------------------------------------------- 1 | version: 1.0.0 2 | title: k6 test 3 | description: | 4 | When terminating a random pod from a replicaset containing API servers, 5 | there should not be any dropped, or erroring, request while the service recovers. 6 | tags: 7 | - kubernetes 8 | - pods 9 | - replicaset 10 | - error rates 11 | - http 12 | contributions: 13 | reliability: medium 14 | security: none 15 | scalability: medium 16 | steady-state-hypothesis: 17 | title: api is alive and healthy 18 | probes: 19 | - type: probe 20 | name: api-is-responding-with-http-status-200 21 | tolerance: true 22 | provider: 23 | type: python 24 | module: chaosk6.probes 25 | func: http 26 | arguments: 27 | endpoint: http://chaos.example.com 28 | method: get 29 | status: 200 30 | vus: 10 31 | duration: 5s 32 | debug: true 33 | headers: 34 | Content-Type: application/json 35 | - name: count-pods 36 | type: probe 37 | tolerance: 5 38 | provider: 39 | type: python 40 | module: chaosk8s.pod.probes 41 | func: count_pods 42 | arguments: 43 | ns: chaos-demo 44 | label_selector: run=chaos-nginx 45 | phase: Running 46 | method: 47 | - type: action 48 | name: terminate-webserver-pod 49 | provider: 50 | type: python 51 | module: chaosk8s.pod.actions 52 | func: terminate_pods 53 | arguments: 54 | ns: chaos-demo 55 | label_selector: run=chaos-nginx 56 | name_pattern: '^chaos-webserver-.*$' 57 | grace_period: 2 58 | rand: true -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | norecursedirs=dist build htmlcov docs .eggs 3 | addopts=-v -rxs --junitxml=junit-test-results.xml --cov=chaostoolkit_k6 --cov-report term-missing:skip-covered --cov-report xml 4 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | requests-mock 2 | coverage 3 | pycodestyle 4 | pytest>=6.0 5 | pytest-cov 6 | pytest-sugar -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | chaostoolkit-lib>=1.1.2 2 | logzero 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | release = sdist bdist_wheel 3 | test = pytest 4 | 5 | [wheel] 6 | universal = 0 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """chaostoolkit-k6 extension builder and installer""" 3 | 4 | import sys 5 | import io 6 | 7 | import setuptools 8 | 9 | name = "chaostoolkit-k6" 10 | desc = "Chaos Toolkit Extension for k6." 11 | 12 | with io.open("README.md", encoding="utf-8") as strm: 13 | long_desc = strm.read() 14 | 15 | classifiers = [ 16 | "Development Status :: 3 - Alpha", 17 | "Intended Audience :: Developers", 18 | "License :: Freely Distributable", 19 | "Operating System :: OS Independent", 20 | "License :: OSI Approved :: Apache Software License", 21 | "Programming Language :: Python", 22 | "Programming Language :: Python :: 3", 23 | "Programming Language :: Python :: 3.7", 24 | "Programming Language :: Python :: 3.8", 25 | "Programming Language :: Python :: 3.9", 26 | "Programming Language :: Python :: 3.10", 27 | "Programming Language :: Python :: Implementation", 28 | "Programming Language :: Python :: Implementation :: CPython", 29 | ] 30 | author = "k6" 31 | author_email = "avocados@k6.io" 32 | url = "http://chaostoolkit.org" 33 | license = "Apache License Version 2.0" 34 | packages = ["chaosk6"] 35 | 36 | needs_pytest = set(["pytest", "test"]).intersection(sys.argv) 37 | pytest_runner = ["pytest_runner"] if needs_pytest else [] 38 | 39 | test_require = [] 40 | with io.open('requirements-dev.txt') as f: 41 | test_require = [l.strip() for l in f if not l.startswith('#')] 42 | 43 | install_require = [] 44 | with io.open("requirements.txt") as f: 45 | install_require = [l.strip() for l in f if not l.startswith("#")] 46 | 47 | setup_params = dict( 48 | name=name, 49 | version="0.3.4", 50 | description=desc, 51 | long_description=long_desc, 52 | classifiers=classifiers, 53 | author=author, 54 | author_email=author_email, 55 | url=url, 56 | license=license, 57 | packages=packages, 58 | include_package_data=True, 59 | install_requires=install_require, 60 | tests_require=test_require, 61 | setup_requires=pytest_runner, 62 | python_requires=">=3.7", 63 | ) 64 | 65 | 66 | def main(): 67 | """Package installation entry point.""" 68 | setuptools.setup(**setup_params) 69 | 70 | 71 | if __name__ == "__main__": 72 | main() 73 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Unit test package for chaostoolkit-k6.""" 4 | --------------------------------------------------------------------------------