├── .editorconfig
├── .flake8
├── .github
└── workflows
│ ├── python.yml
│ └── release.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── README.md
├── kafka_connect_healthcheck
├── __init__.py
├── handler.py
├── health.py
├── helpers.py
├── main.py
├── parser.py
└── version.py
├── requirements-dev.txt
├── scripts
├── build-docker.sh
├── lint.sh
├── test-coverage.sh
└── test.sh
├── setup.cfg
├── setup.py
├── tests
├── __init__.py
├── conftest.py
├── context.py
├── data
│ ├── expected
│ │ ├── 0-healthcheck-server-healthy.json
│ │ ├── 1-healthy.json
│ │ ├── 10-unhealthy-multiple-connectors.json
│ │ ├── 11-healthy-no-connectors.json
│ │ ├── 12-unhealthy-task-with-trace.json
│ │ ├── 13-unhealthy-broker-connection.json
│ │ ├── 14-basic-auth.json
│ │ ├── 15-unhealthy-threshold.json
│ │ ├── 16-healthy-threshold.json
│ │ ├── 17-healthy-container-connector.json
│ │ ├── 18-healthy-container-task.json
│ │ ├── 19-unhealthy-container-task.json
│ │ ├── 2-unhealthy.json
│ │ ├── 3-unhealthy-error.json
│ │ ├── 4-healthy-worker-id-correct.json
│ │ ├── 5-healthy-worker-id-unused.json
│ │ ├── 6-healthy-worker-id-with-other-workers-failing.json
│ │ ├── 7-unhealthy-worker-id-with-other-workers-healthy.json
│ │ ├── 8-healthy-multiple-tasks.json
│ │ └── 9-healthy-multiple-connectors.json
│ └── mocks
│ │ ├── 1-healthy-connector-local-file-source.json
│ │ ├── 1-healthy-connectors.json
│ │ ├── 10-unhealthy-multiple-connectors-connector-s3-sink.json
│ │ ├── 10-unhealthy-multiple-connectors-connector-s3-source.json
│ │ ├── 10-unhealthy-multiple-connectors-connectors.json
│ │ ├── 11-healthy-no-connectors-connectors.json
│ │ ├── 12-unhealthy-task-with-trace-connector-s3-sink.json
│ │ ├── 12-unhealthy-task-with-trace-connectors.json
│ │ ├── 13-unhealthy-broker-connection-connector-s3-sink.json
│ │ ├── 13-unhealthy-broker-connection-connectors.json
│ │ ├── 14-basic-auth-connector-local-file-source.json
│ │ ├── 14-basic-auth-connectors.json
│ │ ├── 15-unhealthy-threshold-connector-s3-sink.json
│ │ ├── 15-unhealthy-threshold-connector-s3-source.json
│ │ ├── 15-unhealthy-threshold-connectors.json
│ │ ├── 16-healthy-threshold-connector-s3-sink.json
│ │ ├── 16-healthy-threshold-connector-s3-source.json
│ │ ├── 16-healthy-threshold-connectors.json
│ │ ├── 17-healthy-container-connector-connector-local-file-source.json
│ │ ├── 17-healthy-container-connector-connectors.json
│ │ ├── 18-healthy-container-task-connector-local-file-source.json
│ │ ├── 18-healthy-container-task-connectors.json
│ │ ├── 19-unhealthy-container-task-connector-local-file-source.json
│ │ ├── 19-unhealthy-container-task-connectors.json
│ │ ├── 2-unhealthy-connector-local-file-source.json
│ │ ├── 2-unhealthy-connectors.json
│ │ ├── 4-healthy-worker-id-correct-connector-jdbc-sink.json
│ │ ├── 4-healthy-worker-id-correct-connectors.json
│ │ ├── 5-healthy-worker-id-unused-connector-jdbc-sink.json
│ │ ├── 5-healthy-worker-id-unused-connectors.json
│ │ ├── 6-healthy-worker-id-with-other-workers-failing-connector-jdbc-sink.json
│ │ ├── 6-healthy-worker-id-with-other-workers-failing-connectors.json
│ │ ├── 7-unhealthy-worker-id-with-other-workers-healthy-connector-jdbc-sink.json
│ │ ├── 7-unhealthy-worker-id-with-other-workers-healthy-connectors.json
│ │ ├── 8-healthy-multiple-tasks-connector-jdbc-source.json
│ │ ├── 8-healthy-multiple-tasks-connectors.json
│ │ ├── 9-healthy-multiple-connectors-connector-s3-sink.json
│ │ ├── 9-healthy-multiple-connectors-connector-s3-source.json
│ │ ├── 9-healthy-multiple-connectors-connectors.json
│ │ └── healthy-connector-details.json
├── mocks.py
├── test_server.py
└── test_version.py
└── tox.ini
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | trim_trailing_whitespace = true
8 |
9 | [{*.py, *.json}]
10 | indent_style = space
11 | indent_size = 4
12 |
--------------------------------------------------------------------------------
/.flake8:
--------------------------------------------------------------------------------
1 | select = Q0
2 |
--------------------------------------------------------------------------------
/.github/workflows/python.yml:
--------------------------------------------------------------------------------
1 | name: Python CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - '**'
7 | tags-ignore:
8 | - '**'
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 | strategy:
14 | max-parallel: 4
15 | matrix:
16 | python-version: [3.5, 3.6, 3.7, 3.8]
17 |
18 | steps:
19 | - uses: actions/checkout@v1
20 | - name: Set up Python ${{ matrix.python-version }}
21 | uses: actions/setup-python@v2
22 | with:
23 | python-version: ${{ matrix.python-version }}
24 | - name: Install dependencies
25 | run: |
26 | python -m pip install --upgrade pip
27 | python -m pip install -r requirements-dev.txt
28 | python -m pip install -e .
29 | pip install tox tox-gh-actions
30 | - name: Test with tox
31 | run: tox
32 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | tags:
4 | - '*'
5 |
6 | name: Release
7 |
8 | jobs:
9 | build:
10 | name: Build Release
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v1
14 |
15 | - name: Create Release
16 | id: create_release
17 | uses: actions/create-release@v1.0.0
18 | env:
19 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
20 | with:
21 | tag_name: ${{ github.ref }}
22 | release_name: Release ${{ github.ref }}
23 | draft: true
24 | prerelease: false
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | venv/
3 | dist/
4 | build/
5 | htmlcov/
6 | .pytest_cache/
7 | /*.egg-info
8 | __pycache__
9 | *.iml
10 | *.pyc
11 | .coverage*
12 | .tox/
13 | examples/
14 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.7-alpine
2 |
3 | COPY setup.py README.md LICENSE /kafka-connect-healthcheck/
4 | COPY kafka_connect_healthcheck/ /kafka-connect-healthcheck/kafka_connect_healthcheck/
5 |
6 | RUN cd /kafka-connect-healthcheck && pip3 install -e .
7 |
8 | CMD ["kafka-connect-healthcheck"]
9 |
--------------------------------------------------------------------------------
/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 2019 Shawn Seymour
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.
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | include README.md
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # kafka-connect-healthcheck
2 |
3 |  [](https://hub.docker.com/r/devshawn/kafka-connect-healthcheck)   [](LICENSE)
4 |
5 |
6 | A simple healthcheck wrapper to monitor Kafka Connect.
7 |
8 |
9 |
10 |
11 |
12 |
13 | Kafka Connect Healthcheck is a server that wraps the Kafka Connect API and provides a singular API endpoint to determine the health of a Kafka Connect instance. This can be used to alert or take action on unhealthy connectors and tasks.
14 |
15 | This can be used in numerous ways. It can sit as a standalone service for monitoring purposes, it can be used as a sidecar container to mark Kafka Connect workers as unhealthy in Kubernetes, or it can be used to provide logs of when connectors/tasks failed and reasons for their failures.
16 |
17 | By default, the root endpoint `/` will return `200 OK` healthy if all connectors and tasks are in a state other than `FAILED`. It will return `503 Service Unavailable` if any connector or tasks are in a `FAILED` state.
18 |
19 | ## Usage
20 |
21 | Kafka Connect Healthcheck can be installed as a command-line tool through `pip` or it can be used as a standalone Docker container. It could also be installed as a part of a custom Kafka Connect docker image.
22 |
23 | ### Command-Line
24 | To use `kafka-connect-healthcheck` from the command-line, you must have `python` and `pip` installed. Currently, only Python 3 is supported.
25 |
26 | You can install `kafka-connect-healthcheck` via pip:
27 |
28 | ```bash
29 | pip install kafka-connect-healthcheck
30 | ```
31 |
32 | To start the healthcheck server, run:
33 |
34 | ```bash
35 | kafka-connect-healthcheck
36 | ```
37 |
38 | The server will now be running on [localhost:18083][localhost].
39 |
40 | ### Docker
41 | The `kafka-connect-healthcheck` image can be found on Docker Hub.
42 |
43 | You can pull down the latest image by running:
44 |
45 | ```bash
46 | docker pull devshawn/kafka-connect-healthcheck
47 | ```
48 |
49 | To start the healthcheck server, run:
50 |
51 | ```bash
52 | docker run --rm -it -p 18083:18083 devshawn/kafka-connect-healthcheck
53 | ```
54 |
55 | The server will now be running on [localhost:18083][localhost].
56 |
57 | ## Configuration
58 | Kafka Connect Healthcheck can be configured via command-line arguments or by environment variables.
59 |
60 | #### Port
61 | The port for the `kafka-connect-healthcheck` API.
62 |
63 | | Usage | Value |
64 | |-----------------------|--------------------|
65 | | Environment Variable | `HEALTHCHECK_PORT` |
66 | | Command-Line Argument | `--port` |
67 | | Default Value | `18083` |
68 |
69 | #### Connect URL
70 | The full URL of the Kafka Connect REST API. This is used to determine the health of the connect instance.
71 |
72 | | Usage | Value |
73 | |-----------------------|---------------------------|
74 | | Environment Variable | `HEALTHCHECK_CONNECT_URL` |
75 | | Command-Line Argument | `--connect-url` |
76 | | Default Value | `http://localhost:8083` |
77 |
78 | #### Connect Worker ID
79 | The worker ID to monitor (usually the IP address of the connect worker). If none is set, all workers will be monitored and any failure will result in an unhealthy response.
80 |
81 | | Usage | Value |
82 | |-----------------------|---------------------------------|
83 | | Environment Variable | `HEALTHCHECK_CONNECT_WORKER_ID` |
84 | | Command-Line Argument | `--connect-worker-id` |
85 | | Default Value | None (all workers monitored) |
86 |
87 | **Note**: It is highly recommended to run an instance of the healthcheck for each worker if you're planning to restart containers based on the health.
88 |
89 | #### Considered Containers
90 | A comma-separated list of which type of kafka connect container to be considered in the healthcheck calculation.
91 |
92 | | Usage | Value |
93 | |-----------------------|---------------------------------------------|
94 | | Environment Variable | `HEALTHCHECK_CONSIDERED_CONTAINERS` |
95 | | Command-Line Argument | `--considered-containers` |
96 | | Default Value | `CONNECTOR,TASK` |
97 | | Valid Values | `CONNECTOR`, `TASK` |
98 |
99 | #### Unhealthy States
100 | A comma-separated list of connector and tasks states to be marked as unhealthy.
101 |
102 | | Usage | Value |
103 | |-----------------------|---------------------------------------------|
104 | | Environment Variable | `HEALTHCHECK_UNHEALTHY_STATES` |
105 | | Command-Line Argument | `--unhealthy-states` |
106 | | Default Value | `FAILED` |
107 | | Valid Values | `FAILED`, `PAUSED`, `UNASSIGNED`, `RUNNING` |
108 |
109 | **Note**: It's recommended to keep this defaulted to `FAILED`, but paused connectors or tasks can be marked as unhealthy by passing `FAILED,PAUSED`.
110 |
111 | #### Failure Threshold Percentage
112 | A number between 1 and 100. If set, this is the percentage of connectors that must fail for the healthcheck to fail.
113 |
114 | | Usage | Value |
115 | |-----------------------|---------------------------------------------|
116 | | Environment Variable | `HEALTHCHECK_FAILURE_THRESHOLD_PERCENTAGE` |
117 | | Command-Line Argument | `--failure-threshold-percentage` |
118 | | Default Value | `0` |
119 | | Valid Values | 1 to 100 |
120 |
121 | By default, **any** failures will cause the healthcheck to fail.
122 |
123 | #### Log Level
124 | The level of logs to be shown by the application.
125 |
126 | | Usage | Value |
127 | |-----------------------|---------------------------------------------|
128 | | Environment Variable | `HEALTHCHECK_LOG_LEVEL` |
129 | | Command-Line Argument | `--log-level` |
130 | | Default Value | `INFO` |
131 | | Valid Values | `DEBUG`, `INFO`, `WARNING`, `ERROR` |
132 |
133 | All healthy connector and task statuses are logged at `INFO`. Unhealthy ones are logged at `WARNING`. Any communication or HTTP errors are logged at `ERROR`.
134 |
135 | ## API
136 | The server provides a very simple HTTP API which can be used for liveness probes and monitoring alerts. We expose two endpoints:
137 |
138 | #### `GET /`
139 | Get the current health status of the Kafka Connect system. This could be used as a sidecar to determine the health of each Kafka Connect worker and their associated connectors and tasks.
140 |
141 | **Example Request**
142 | ```bash
143 | curl http://localhost:18083
144 | ```
145 |
146 | **Example Healthy Response**
147 |
148 | 200 OK
149 | ```json
150 | {
151 | "failures": [],
152 | "failure_states": [
153 | "FAILED"
154 | ],
155 | "healthy": true
156 | }
157 | ```
158 |
159 | **Example Unhealthy Response**
160 |
161 | 503 Service Unavailable
162 | ```json
163 | {
164 | "failures": [
165 | {
166 | "type": "connector",
167 | "connector": "jdbc-source",
168 | "state": "FAILED",
169 | "worker_id": "127.0.0.1:8083"
170 | },
171 | {
172 | "type": "task",
173 | "connector": "jdbc-source",
174 | "id": 0,
175 | "state": "FAILED",
176 | "worker_id": "127.0.0.1:8083",
177 | "trace": "..."
178 | }
179 | ],
180 | "failure_states": [
181 | "FAILED"
182 | ],
183 | "healthy": false
184 | }
185 | ```
186 |
187 | #### `GET /ping`
188 | Get the current health status of the healthcheck server. This will always be successful as long as the server is still able to serve requests. This can be used as a ready or liveness probe in Kubernetes.
189 |
190 | **Example Request**
191 | ```bash
192 | curl http://localhost:18083/ping
193 | ```
194 |
195 | **Example Response**
196 |
197 | 200 OK
198 | ```json
199 | {
200 | "status": "UP"
201 | }
202 | ```
203 |
204 | ## License
205 | Copyright (c) 2019 Shawn Seymour.
206 |
207 | Licensed under the [Apache 2.0 license][license].
208 |
209 | [localhost]: http://localhost:18083
210 | [license]: LICENSE
211 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | from kafka_connect_healthcheck import handler
17 | from kafka_connect_healthcheck import health
18 | from kafka_connect_healthcheck import helpers
19 | from kafka_connect_healthcheck import main
20 | from kafka_connect_healthcheck import version
21 |
22 | name = "kafka_connect_healthcheck"
23 |
24 | __all__ = [
25 | "handler",
26 | "health",
27 | "helpers",
28 | "main",
29 | "version"
30 | ]
31 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/handler.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | import json
17 |
18 | from http.server import BaseHTTPRequestHandler
19 |
20 |
21 | class RequestHandler(BaseHTTPRequestHandler):
22 |
23 | def __init__(self, health, *args, **kwargs):
24 | self.health = health
25 | super().__init__(*args, **kwargs)
26 |
27 | def do_HEAD(self):
28 | self.send_response(200)
29 | self.send_header("Content-type", "text/html")
30 | self.end_headers()
31 |
32 | def do_GET(self):
33 | if self.path in ["/"]:
34 | payload = self.health.get_health_result()
35 | payload_json = json.dumps(payload)
36 | status = 200 if payload["healthy"] else 503
37 | self.respond(status, payload_json)
38 | elif self.path in ["/ping"]:
39 | payload_json = json.dumps({"status": "UP"})
40 | self.respond(200, payload_json)
41 | else:
42 | self.respond(404, "")
43 |
44 | def log_message(self, format, *args):
45 | return
46 |
47 | def handle_http(self, status_code, payload):
48 | self.send_response(status_code)
49 | self.send_header("Content-type", "application/json")
50 | self.end_headers()
51 | return bytes(payload, "UTF-8")
52 |
53 | def respond(self, status, payload):
54 | response = self.handle_http(status, payload)
55 | self.wfile.write(response)
56 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/health.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | import logging
17 |
18 | import requests
19 |
20 | from kafka_connect_healthcheck import helpers
21 |
22 |
23 | class Health:
24 |
25 | def __init__(self, connect_url, worker_id, unhealthy_states, auth, failure_threshold_percentage, considered_containers):
26 | self.connect_url = connect_url
27 | self.worker_id = worker_id
28 | self.unhealthy_states = [x.upper().strip() for x in unhealthy_states]
29 | self.failure_threshold = failure_threshold_percentage * .01
30 | self.considered_containers = [x.lower().strip() for x in considered_containers]
31 | self.kwargs = {}
32 | if auth and ":" in auth:
33 | self.kwargs["auth"] = tuple(auth.split(":"))
34 | self.log_initialization_values()
35 |
36 | def get_health_result(self):
37 | try:
38 | health_result = {"failures": [], "failure_states": self.unhealthy_states}
39 | connector_names = self.get_connector_names()
40 | connector_statuses = self.get_connectors_health(connector_names)
41 | self.handle_healthcheck(connector_statuses, health_result)
42 |
43 | connector_count = len(connector_names)
44 | task_count = sum(len(c["tasks"]) for c in connector_statuses)
45 |
46 | container_count = 0
47 | if "connector" in self.considered_containers:
48 | container_count += connector_count
49 | if "task" in self.considered_containers:
50 | container_count += task_count
51 |
52 | failure_count = len([f for f in health_result["failures"] if f["type"] in self.considered_containers])
53 |
54 | # guards against division by zero. if we have no connectors or tasks we are deciding to pass
55 | if container_count > 0:
56 | health_result["failure_rate"] = failure_count / container_count
57 | else:
58 | health_result["failure_rate"] = 0.0
59 |
60 | health_result["failure_threshold"] = self.failure_threshold
61 | health_result["healthy"] = health_result["failure_rate"] <= health_result["failure_threshold"]
62 |
63 | # broker errors override any failure calculation
64 | if any([f for f in health_result["failures"] if f["type"] == "broker"]):
65 | health_result["healthy"] = False
66 |
67 | except Exception as ex:
68 | logging.error("Error while attempting to calculate health result. Assuming unhealthy. Error: {}".format(ex))
69 | logging.error(ex)
70 | health_result = {
71 | "healthy": False,
72 | "message": "Exception raised while attempting to calculate health result, assuming unhealthy.",
73 | "error": "{}".format(ex),
74 | "failure_states": self.unhealthy_states
75 | }
76 | helpers.log_line_break()
77 | return health_result
78 |
79 | def handle_healthcheck(self, connector_statuses, health_result):
80 | connectors_on_this_worker = False
81 | for connector in connector_statuses:
82 | if self.is_on_this_worker(connector["worker_id"]) and "connector" in self.considered_containers:
83 | connectors_on_this_worker = True
84 | if self.is_in_unhealthy_state(connector["state"]):
85 | logging.warning("Connector '{}' is unhealthy in failure state: {}".format(connector["name"], connector["state"]))
86 | health_result["failures"].append({
87 | "type": "connector",
88 | "connector": connector["name"],
89 | "state": connector["state"],
90 | "worker_id": connector["worker_id"]
91 | })
92 | else:
93 | logging.info("Connector '{}' is healthy in state: {}".format(connector["name"], connector["state"]))
94 | self.handle_task_healthcheck(connector, health_result)
95 | if not connectors_on_this_worker and connector_statuses:
96 | self.handle_broker_healthcheck(health_result, connector_statuses[0]["name"])
97 |
98 | def handle_broker_healthcheck(self, health_result, connector_name):
99 | try:
100 | self.get_connector_details(connector_name)
101 | except Exception as ex:
102 | logging.error("Error while attempting to get details for {}. Assuming unhealthy. Error: {}".format(connector_name, ex))
103 | logging.error(ex)
104 | health_result["failures"].append({
105 | "type": "broker",
106 | "connector": connector_name,
107 | })
108 |
109 | def handle_task_healthcheck(self, connector, health_result):
110 | if "task" in self.considered_containers:
111 | for task in connector["tasks"]:
112 | if self.is_on_this_worker(task["worker_id"]):
113 | if self.is_in_unhealthy_state(task["state"]):
114 | logging.warning("Connector '{}' task '{}' is unhealthy in failure state: {}".format(
115 | connector["name"], task["id"], task["state"]
116 | ))
117 | health_result["failures"].append({
118 | "type": "task",
119 | "connector": connector["name"],
120 | "id": task["id"],
121 | "state": task["state"],
122 | "worker_id": task["worker_id"],
123 | "trace": task.get("trace", None)
124 | })
125 | else:
126 | logging.info("Connector '{}' task '{}' is healthy in state: {}".format(
127 | connector["name"], task["id"], task["state"]
128 | ))
129 |
130 | def get_connectors_health(self, connector_names):
131 | statuses = []
132 | for connector_name in connector_names:
133 | statuses.append(self.get_connector_health(connector_name))
134 | return statuses
135 |
136 | def get_connector_health(self, connector_name):
137 | connector_status = self.get_connector_status(connector_name)
138 | connector_state = connector_status["connector"]["state"].upper()
139 | connector_worker = connector_status["connector"]["worker_id"]
140 | return {
141 | "name": connector_name,
142 | "state": connector_state,
143 | "worker_id": connector_worker,
144 | "tasks": connector_status["tasks"]
145 | }
146 |
147 | def get_connector_names(self):
148 | response = requests.get("{}/connectors".format(self.connect_url), **self.kwargs)
149 | response_json = response.json()
150 | return response_json
151 |
152 | def get_connector_status(self, connector_name):
153 | response = requests.get("{}/connectors/{}/status".format(self.connect_url, connector_name), **self.kwargs)
154 | response_json = response.json()
155 | return response_json
156 |
157 | def get_connector_details(self, connector_name):
158 | response = requests.get("{}/connectors/{}".format(self.connect_url, connector_name), **self.kwargs)
159 | response.raise_for_status()
160 | response_json = response.json()
161 | return response_json
162 |
163 | def is_in_unhealthy_state(self, state):
164 | return state.upper() in self.unhealthy_states
165 |
166 | def is_on_this_worker(self, response_worker_id):
167 | return response_worker_id.lower() == self.worker_id.lower() if self.worker_id is not None else True
168 |
169 | def log_initialization_values(self):
170 | logging.info("Server will report unhealthy for states: '{}'".format(", ".join(self.unhealthy_states)))
171 | logging.info("Server will healthcheck against Kafka Connect at: {}".format(self.connect_url))
172 | if "auth" in self.kwargs:
173 | logging.info("Server will use basic authentication against Kafka Connect")
174 | if self.worker_id is not None:
175 | logging.info("Server will healthcheck connectors and tasks for worker with id '{}'".format(self.worker_id))
176 | else:
177 | logging.warning("No worker id supplied, server will healthcheck all connectors and tasks")
178 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/helpers.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | import logging
17 |
18 |
19 | def log_line_break():
20 | logging.info("------------------------------------------------")
21 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | import logging
17 | import signal
18 | import sys
19 | from functools import partial
20 | from http.server import HTTPServer
21 |
22 | from kafka_connect_healthcheck import health
23 | from kafka_connect_healthcheck import helpers
24 | from kafka_connect_healthcheck import parser
25 | from kafka_connect_healthcheck.handler import RequestHandler
26 |
27 |
28 | def main():
29 | config_parser = parser.get_parser()
30 | args = config_parser.parse_args()
31 |
32 | logging.basicConfig(format="%(asctime)s.%(msecs)03d [%(levelname)7s] - %(message)s",
33 | datefmt="%Y-%m-%d %H:%M:%S",
34 | level=args.log_level)
35 |
36 | logging.info("Initializing healthcheck server...")
37 |
38 | server_class = HTTPServer
39 | health_object = health.Health(args.connect_url, args.connect_worker_id, args.unhealthy_states.split(","),
40 | args.basic_auth, args.failure_threshold_percentage, args.considered_containers.split(","))
41 | handler = partial(RequestHandler, health_object)
42 | httpd = server_class(("0.0.0.0", args.healthcheck_port), handler)
43 | logging.info("Healthcheck server started at: http://localhost:{}".format(args.healthcheck_port))
44 | helpers.log_line_break()
45 |
46 | def stop(status_code, frame):
47 | logging.info("SIGINT/SIGTERM; exiting...")
48 | httpd.server_close()
49 | sys.exit(0)
50 |
51 | signal.signal(signal.SIGINT, stop)
52 | signal.signal(signal.SIGTERM, stop)
53 |
54 | try:
55 | httpd.serve_forever()
56 | except KeyboardInterrupt:
57 | stop(0, None)
58 |
59 |
60 | if __name__ == "__main__":
61 | main()
62 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/parser.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | import argparse
17 | import os
18 |
19 |
20 | def get_parser():
21 | parser = argparse.ArgumentParser(description="A simple healthcheck for Kafka Connect. It can wrap a Kafka Connect "
22 | "process so you can check the health of specific connectors. "
23 | "This can be used as a health check within Kubernetes to automatically "
24 | "restart failed connect instances.")
25 |
26 | parser.add_argument("--port",
27 | default=os.environ.get("HEALTHCHECK_PORT", "18083"),
28 | dest="healthcheck_port",
29 | type=int,
30 | nargs="?",
31 | help="The port for the healthcheck HTTP server."
32 | )
33 |
34 | parser.add_argument("--connect-url",
35 | default=os.environ.get("HEALTHCHECK_CONNECT_URL", "http://localhost:8083"),
36 | dest="connect_url",
37 | nargs="?",
38 | help="The Kafka Connect REST API URL that the health check will be run against."
39 | )
40 |
41 | parser.add_argument("--connect-worker-id",
42 | default=os.environ.get("HEALTHCHECK_CONNECT_WORKER_ID"),
43 | dest="connect_worker_id",
44 | nargs="?",
45 | help="The Kafka Connect REST API URL that the health check will be run against."
46 | )
47 |
48 | parser.add_argument("--unhealthy-states",
49 | default=os.environ.get("HEALTHCHECK_UNHEALTHY_STATES", "FAILED").upper(),
50 | dest="unhealthy_states",
51 | nargs="?",
52 | help="A comma separated lists of connector and task states to be marked as unhealthy. Default: FAILED."
53 | )
54 |
55 | parser.add_argument("--considered-containers",
56 | default=os.environ.get("HEALTHCHECK_CONSIDERED_CONTAINERS", "CONNECTOR,TASK").upper(),
57 | dest="considered_containers",
58 | nargs="?",
59 | help="A comma separated lists of container types to consider for failure calculations. Default: CONNECTOR,TASK."
60 | )
61 |
62 | parser.add_argument("--failure-threshold-percentage",
63 | default=os.environ.get("HEALTHCHECK_FAILURE_THRESHOLD_PERCENTAGE", 0),
64 | dest="failure_threshold_percentage",
65 | type=int,
66 | nargs="?",
67 | help="A number between 1 and 100. If set, this is the percentage of connectors that must fail for the healthcheck to fail."
68 | )
69 |
70 | parser.add_argument("--basic-auth",
71 | default=os.environ.get("HEALTHCHECK_BASIC_AUTH", ""),
72 | dest="basic_auth",
73 | nargs="?",
74 | help="Colon-separated credentials for basic HTTP authentication. Default: empty.")
75 |
76 | parser.add_argument("--log-level",
77 | default=os.environ.get("HEALTHCHECK_LOG_LEVEL", "INFO").upper(),
78 | dest="log_level",
79 | nargs="?",
80 | help="The level of logs to be shown. Default: INFO.")
81 |
82 | return parser
83 |
--------------------------------------------------------------------------------
/kafka_connect_healthcheck/version.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2019 Shawn Seymour. All Rights Reserved.
4 | #
5 | # Licensed under the Apache License, Version 2.0 (the "License"). You
6 | # may not use this file except in compliance with the License. A copy of
7 | # the License is located at
8 | #
9 | # http://www.apache.org/licenses/LICENSE-2.0
10 | #
11 | # or in the "license" file accompanying this file. This file is
12 | # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
13 | # ANY KIND, either express or implied. See the License for the specific
14 | # language governing permissions and limitations under the License.
15 |
16 | __version__ = "0.3.0"
17 |
18 |
19 | def get_version():
20 | return __version__
21 |
--------------------------------------------------------------------------------
/requirements-dev.txt:
--------------------------------------------------------------------------------
1 | pytest>=2.7.0
2 | pytest-cov>=2.4.0,<2.6
3 | mock>=1.0.1
4 | tox>=1.9.2
5 | flake8>=3.7.7
6 | flake8-quotes>=1.0.0
7 | coverage>=4.5.2
8 | requests>=2.21.0
9 |
--------------------------------------------------------------------------------
/scripts/build-docker.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | docker build -t devshawn/kafka-connect-healthcheck .
4 |
--------------------------------------------------------------------------------
/scripts/lint.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | flake8 --max-line-length=135 --inline-quotes '"' --exclude=.tox,htmlcov,build,tests,scratch,docs,venv .
4 |
--------------------------------------------------------------------------------
/scripts/test-coverage.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | python3 -m pytest --cov=kafka_connect_healthcheck -vs --cov-report html
--------------------------------------------------------------------------------
/scripts/test.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | python3 -m pytest
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | description-file = README.md
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools
2 |
3 | meta = {}
4 |
5 | with open("README.md", "r") as fh:
6 | long_description = fh.read()
7 |
8 | with open("kafka_connect_healthcheck/version.py") as f:
9 | exec(f.read(), meta)
10 |
11 | requires = [
12 | "requests>=2.21.0"
13 | ]
14 |
15 | setuptools.setup(
16 | name="kafka-connect-healthcheck",
17 | version=meta["__version__"],
18 | author="Shawn Seymour",
19 | author_email="shawn@devshawn.com",
20 | description="A simple healthcheck wrapper to monitor Kafka Connect.",
21 | long_description=long_description,
22 | long_description_content_type="text/markdown",
23 | url="https://github.com/devshawn/kafka-connect-healthcheck",
24 | license="Apache License 2.0",
25 | packages=["kafka_connect_healthcheck"],
26 | install_requires=requires,
27 | entry_points={
28 | "console_scripts": ["kafka-connect-healthcheck=kafka_connect_healthcheck.main:main"],
29 | },
30 | keywords=("kafka", "connect", "health", "healthcheck", "wrapper", "monitor", "connector"),
31 | classifiers=[
32 | "Development Status :: 4 - Beta",
33 | "Intended Audience :: Developers",
34 | "Intended Audience :: System Administrators",
35 | "License :: OSI Approved :: Apache Software License",
36 | "Natural Language :: English",
37 | "Operating System :: MacOS",
38 | "Operating System :: Unix",
39 | "Programming Language :: Python :: 3",
40 | "Programming Language :: Python :: 3.5",
41 | "Programming Language :: Python :: 3.6",
42 | "Programming Language :: Python :: 3.7",
43 | "Programming Language :: Python :: 3.8",
44 | "Topic :: Software Development",
45 | "Topic :: Software Development :: Libraries :: Python Modules",
46 | ],
47 | )
48 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/devshawn/kafka-connect-healthcheck/03645ba3cf877de69f615a360441b51c6319ffb6/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import os
2 | import signal
3 | import subprocess
4 | import time
5 |
6 | import coverage.data
7 | import pytest
8 | import requests
9 | from requests.exceptions import ConnectionError
10 |
11 | from tests import mocks
12 |
13 |
14 | @pytest.fixture(autouse=True)
15 | def run_backend(cov, request):
16 | env = os.environ.copy()
17 | env['COVERAGE_FILE'] = '.coverage.backend'
18 |
19 | try:
20 | test_environment, mock_name = request.param
21 | kafka_connect_url = None
22 | if test_environment.get("HEALTHCHECK_CONNECT_URL") is None:
23 | kafka_connect_port = setup_mock_kafka_connect_api(mock_name)
24 | kafka_connect_url = "http://localhost:{}".format(kafka_connect_port)
25 | env['HEALTHCHECK_CONNECT_URL'] = kafka_connect_url
26 |
27 | for key, value in test_environment.items():
28 | env[key] = value
29 | print("\nAdding environment variable: {} --> {}".format(key, value))
30 |
31 | process = generate_subprocess(env, request)
32 | wait_for_servers_to_be_up(kafka_connect_url)
33 |
34 | yield
35 |
36 | process.send_signal(signal.SIGINT)
37 | # out, err = process.communicate()
38 | # request.config.cache.set('logs', err.decode("utf-8"))
39 | time.sleep(1)
40 |
41 | if is_coverage_on(request):
42 | write_backend_coverage(cov)
43 |
44 | except AttributeError:
45 | print("\nNo parameters, ignoring fixture.")
46 | yield
47 |
48 |
49 | def generate_subprocess(env, request):
50 | print()
51 | if is_coverage_on(request):
52 | process_args = " ".join(['exec', 'python3', '-m', 'coverage', 'run', '--source', './kafka_connect_healthcheck',
53 | './kafka_connect_healthcheck/main.py']),
54 | else:
55 | process_args = " ".join(['exec', 'python3', './kafka_connect_healthcheck/main.py']),
56 | return subprocess.Popen(
57 | process_args,
58 | env=env,
59 | shell=True,
60 | stdout=None if os.environ.get("TEST_SHOW_SERVER_LOGS", "false") == "true" else subprocess.PIPE,
61 | stderr=None if os.environ.get("TEST_SHOW_SERVER_LOGS", "false") == "true" else subprocess.PIPE,
62 | preexec_fn=os.setsid
63 | )
64 |
65 |
66 | def write_backend_coverage(cov):
67 | backendcov = coverage.data.CoverageData()
68 | with open('.coverage.backend') as fp:
69 | backendcov.read_fileobj(fp)
70 | cov.data.update(backendcov)
71 |
72 |
73 | def setup_mock_kafka_connect_api(mock_name):
74 | kafka_connect_port = mocks.get_free_port()
75 | mocks.start_mock_server(kafka_connect_port, mock_name)
76 | return kafka_connect_port
77 |
78 |
79 | def wait_for_servers_to_be_up(kafka_connect_url):
80 | is_alive = False
81 | while is_alive is False:
82 | is_alive = are_servers_up("http://localhost:18083", kafka_connect_url)
83 | time.sleep(0.2)
84 |
85 |
86 | def are_servers_up(healthcheck_url, kafka_connect_url):
87 | try:
88 | if kafka_connect_url is not None:
89 | response = requests.head(healthcheck_url)
90 | is_mock_server_alive = response.status_code == 200
91 | else:
92 | is_mock_server_alive = True
93 | response = requests.head(healthcheck_url)
94 | return response.status_code == 200 and is_mock_server_alive
95 | except ConnectionError:
96 | return False
97 |
98 |
99 | def is_coverage_on(request):
100 | return len(request.config.getoption('--cov')) != 0
101 |
--------------------------------------------------------------------------------
/tests/context.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 |
4 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../kafka_connect_healthcheck')))
5 |
6 | import kafka_connect_healthcheck
7 |
--------------------------------------------------------------------------------
/tests/data/expected/0-healthcheck-server-healthy.json:
--------------------------------------------------------------------------------
1 | {
2 | "status": "UP"
3 | }
--------------------------------------------------------------------------------
/tests/data/expected/1-healthy.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/10-unhealthy-multiple-connectors.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "connector",
5 | "connector": "s3-source",
6 | "state": "FAILED",
7 | "worker_id": "my.worker.name:8083"
8 | },
9 | {
10 | "type": "task",
11 | "connector": "s3-source",
12 | "id": 3,
13 | "state": "FAILED",
14 | "worker_id": "my.worker.name:8083",
15 | "trace": null
16 | },
17 | {
18 | "type": "task",
19 | "connector": "s3-sink",
20 | "id": 2,
21 | "state": "FAILED",
22 | "worker_id": "my.worker.name:8083",
23 | "trace": null
24 | }
25 | ],
26 | "failure_states": [
27 | "FAILED"
28 | ],
29 | "failure_rate": 0.3,
30 | "failure_threshold": 0.0,
31 | "healthy": false
32 | }
33 |
--------------------------------------------------------------------------------
/tests/data/expected/11-healthy-no-connectors.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/12-unhealthy-task-with-trace.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "task",
5 | "connector": "s3-sink",
6 | "id": 2,
7 | "state": "FAILED",
8 | "worker_id": "my.worker.name:8083",
9 | "trace": "trace message here"
10 | }
11 | ],
12 | "failure_states": [
13 | "FAILED"
14 | ],
15 | "failure_rate": 0.3333333333333333,
16 | "failure_threshold": 0.0,
17 | "healthy": false
18 | }
19 |
--------------------------------------------------------------------------------
/tests/data/expected/13-unhealthy-broker-connection.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "broker",
5 | "connector": "s3-sink"
6 | }
7 | ],
8 | "failure_states": [
9 | "FAILED"
10 | ],
11 | "failure_rate": 0.0,
12 | "failure_threshold": 0.0,
13 | "healthy": false
14 | }
15 |
--------------------------------------------------------------------------------
/tests/data/expected/14-basic-auth.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/15-unhealthy-threshold.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "connector",
5 | "connector": "s3-source",
6 | "state": "FAILED",
7 | "worker_id": "my.worker.name:8083"
8 | },
9 | {
10 | "type": "task",
11 | "connector": "s3-source",
12 | "id": 3,
13 | "state": "FAILED",
14 | "worker_id": "my.worker.name:8083",
15 | "trace": null
16 | },
17 | {
18 | "type": "task",
19 | "connector": "s3-sink",
20 | "id": 2,
21 | "state": "FAILED",
22 | "worker_id": "my.worker.name:8083",
23 | "trace": null
24 | }
25 | ],
26 | "failure_states": [
27 | "FAILED"
28 | ],
29 | "failure_rate": 0.3,
30 | "failure_threshold": 0.1,
31 | "healthy": false
32 | }
33 |
--------------------------------------------------------------------------------
/tests/data/expected/16-healthy-threshold.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "connector",
5 | "connector": "s3-source",
6 | "state": "FAILED",
7 | "worker_id": "my.worker.name:8083"
8 | },
9 | {
10 | "type": "task",
11 | "connector": "s3-source",
12 | "id": 3,
13 | "state": "FAILED",
14 | "worker_id": "my.worker.name:8083",
15 | "trace": null
16 | },
17 | {
18 | "type": "task",
19 | "connector": "s3-sink",
20 | "id": 2,
21 | "state": "FAILED",
22 | "worker_id": "my.worker.name:8083",
23 | "trace": null
24 | }
25 | ],
26 | "failure_states": [
27 | "FAILED"
28 | ],
29 | "failure_rate": 0.3,
30 | "failure_threshold": 0.5,
31 | "healthy": true
32 | }
33 |
--------------------------------------------------------------------------------
/tests/data/expected/17-healthy-container-connector.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/18-healthy-container-task.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/19-unhealthy-container-task.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "task",
5 | "connector": "local-file-source",
6 | "id": 0,
7 | "state": "FAILED",
8 | "worker_id": "kafka-connect:8083",
9 | "trace": null
10 | }
11 | ],
12 | "failure_states": [
13 | "FAILED"
14 | ],
15 | "failure_rate": 1.0,
16 | "failure_threshold": 0.0,
17 | "healthy": false
18 | }
19 |
--------------------------------------------------------------------------------
/tests/data/expected/2-unhealthy.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "connector",
5 | "connector": "local-file-source",
6 | "state": "FAILED",
7 | "worker_id": "kafka-connect:8083"
8 | },
9 | {
10 | "type": "task",
11 | "connector": "local-file-source",
12 | "id": 0,
13 | "state": "FAILED",
14 | "worker_id": "kafka-connect:8083",
15 | "trace": null
16 | }
17 | ],
18 | "failure_states": [
19 | "FAILED"
20 | ],
21 | "failure_rate": 1.0,
22 | "failure_threshold": 0.0,
23 | "healthy": false
24 | }
25 |
--------------------------------------------------------------------------------
/tests/data/expected/3-unhealthy-error.json:
--------------------------------------------------------------------------------
1 | {
2 | "healthy": false,
3 | "message": "Exception raised while attempting to calculate health result, assuming unhealthy.",
4 | "error": "HTTPConnectionPool(host='unknown-hostname', port=8083): Max retries exceeded with url: /connectors",
5 | "failure_states": [
6 | "FAILED"
7 | ]
8 | }
9 |
--------------------------------------------------------------------------------
/tests/data/expected/4-healthy-worker-id-correct.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/5-healthy-worker-id-unused.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/6-healthy-worker-id-with-other-workers-failing.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/7-unhealthy-worker-id-with-other-workers-healthy.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [
3 | {
4 | "type": "task",
5 | "connector": "jdbc-sink",
6 | "id": 0,
7 | "state": "FAILED",
8 | "worker_id": "kafka-connect:8083",
9 | "trace": null
10 | }
11 | ],
12 | "failure_states": [
13 | "FAILED"
14 | ],
15 | "failure_rate": 0.5,
16 | "failure_threshold": 0.0,
17 | "healthy": false
18 | }
19 |
--------------------------------------------------------------------------------
/tests/data/expected/8-healthy-multiple-tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/expected/9-healthy-multiple-connectors.json:
--------------------------------------------------------------------------------
1 | {
2 | "failures": [],
3 | "failure_states": [
4 | "FAILED"
5 | ],
6 | "failure_rate": 0.0,
7 | "failure_threshold": 0.0,
8 | "healthy": true
9 | }
10 |
--------------------------------------------------------------------------------
/tests/data/mocks/1-healthy-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/1-healthy-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/10-unhealthy-multiple-connectors-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "FAILED",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/10-unhealthy-multiple-connectors-connector-s3-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "FAILED",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/10-unhealthy-multiple-connectors-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-source",
3 | "s3-sink"
4 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/11-healthy-no-connectors-connectors.json:
--------------------------------------------------------------------------------
1 | []
2 |
--------------------------------------------------------------------------------
/tests/data/mocks/12-unhealthy-task-with-trace-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "FAILED",
16 | "worker_id": "my.worker.name:8083",
17 | "trace": "trace message here"
18 | }
19 | ],
20 | "type": "source"
21 | }
22 |
--------------------------------------------------------------------------------
/tests/data/mocks/12-unhealthy-task-with-trace-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-sink"
3 | ]
4 |
--------------------------------------------------------------------------------
/tests/data/mocks/13-unhealthy-broker-connection-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "other.worker:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
16 |
--------------------------------------------------------------------------------
/tests/data/mocks/13-unhealthy-broker-connection-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-sink"
3 | ]
4 |
--------------------------------------------------------------------------------
/tests/data/mocks/14-basic-auth-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
16 |
--------------------------------------------------------------------------------
/tests/data/mocks/14-basic-auth-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
4 |
--------------------------------------------------------------------------------
/tests/data/mocks/15-unhealthy-threshold-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "FAILED",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/15-unhealthy-threshold-connector-s3-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "FAILED",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/15-unhealthy-threshold-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-source",
3 | "s3-sink"
4 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/16-healthy-threshold-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "FAILED",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/16-healthy-threshold-connector-s3-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "FAILED",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/16-healthy-threshold-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-source",
3 | "s3-sink"
4 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/17-healthy-container-connector-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "FAILED",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
16 |
--------------------------------------------------------------------------------
/tests/data/mocks/17-healthy-container-connector-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/18-healthy-container-task-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
16 |
--------------------------------------------------------------------------------
/tests/data/mocks/18-healthy-container-task-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/19-unhealthy-container-task-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "FAILED",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
16 |
--------------------------------------------------------------------------------
/tests/data/mocks/19-unhealthy-container-task-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/2-unhealthy-connector-local-file-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "local-file-source",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "FAILED",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/2-unhealthy-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "local-file-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/4-healthy-worker-id-correct-connector-jdbc-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jdbc-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "kafka-connect:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/4-healthy-worker-id-correct-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "jdbc-sink"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/5-healthy-worker-id-unused-connector-jdbc-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jdbc-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "some-other-worker"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "some-other-worker"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/5-healthy-worker-id-unused-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "jdbc-sink"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/6-healthy-worker-id-with-other-workers-failing-connector-jdbc-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jdbc-sink",
3 | "connector": {
4 | "state": "FAILED",
5 | "worker_id": "failing-worker"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "FAILED",
11 | "worker_id": "failing-worker"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/6-healthy-worker-id-with-other-workers-failing-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "jdbc-sink"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/7-unhealthy-worker-id-with-other-workers-healthy-connector-jdbc-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jdbc-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "test-worker"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "FAILED",
11 | "worker_id": "kafka-connect:8083"
12 | }
13 | ],
14 | "type": "source"
15 | }
--------------------------------------------------------------------------------
/tests/data/mocks/7-unhealthy-worker-id-with-other-workers-healthy-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "jdbc-sink"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/8-healthy-multiple-tasks-connector-jdbc-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jdbc-source",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/8-healthy-multiple-tasks-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "jdbc-source"
3 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/9-healthy-multiple-connectors-connector-s3-sink.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-sink",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/9-healthy-multiple-connectors-connector-s3-source.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "s3-source",
3 | "connector": {
4 | "state": "RUNNING",
5 | "worker_id": "my.worker.name:8083"
6 | },
7 | "tasks": [
8 | {
9 | "id": 0,
10 | "state": "RUNNING",
11 | "worker_id": "my.worker.name:8083"
12 | },
13 | {
14 | "id": 2,
15 | "state": "RUNNING",
16 | "worker_id": "my.worker.name:8083"
17 | },
18 | {
19 | "id": 3,
20 | "state": "RUNNING",
21 | "worker_id": "my.worker.name:8083"
22 | },
23 | {
24 | "id": 4,
25 | "state": "RUNNING",
26 | "worker_id": "my.worker.name:8083"
27 | }
28 | ],
29 | "type": "source"
30 | }
--------------------------------------------------------------------------------
/tests/data/mocks/9-healthy-multiple-connectors-connectors.json:
--------------------------------------------------------------------------------
1 | [
2 | "s3-source",
3 | "s3-sink"
4 | ]
--------------------------------------------------------------------------------
/tests/data/mocks/healthy-connector-details.json:
--------------------------------------------------------------------------------
1 | {
2 | }
3 |
--------------------------------------------------------------------------------
/tests/mocks.py:
--------------------------------------------------------------------------------
1 | import os
2 | import socket
3 | from functools import partial
4 | from http.server import BaseHTTPRequestHandler, HTTPServer
5 | from threading import Thread
6 |
7 |
8 | # Mocks Kafka Connect REST API responses for integration tests
9 | class MockServerRequestHandler(BaseHTTPRequestHandler):
10 |
11 | def __init__(self, mock_name, *args, **kwargs):
12 | self.mock_name = mock_name
13 | super().__init__(*args, **kwargs)
14 |
15 | def do_GET(self):
16 | status_code = 503 if "unhealthy" in self.mock_name else 200
17 | try:
18 | if "auth" in self.mock_name:
19 | if "Basic" not in self.headers.get("Authorization"):
20 | self.response(401, payload="{}")
21 |
22 | if self.path == "/connectors":
23 | with open(os.path.join(os.getcwd(), "tests/data/mocks/{}-connectors.json".format(self.mock_name)), "r") as f:
24 | self.response(200, payload=f.read())
25 | else:
26 | split_path = self.path.split("/")
27 | if len(split_path) >= 4 and split_path[3] == "status":
28 | connector_name = split_path[2]
29 | path = os.path.join(os.getcwd(), "./tests/data/mocks/{}-connector-{}.json".format(self.mock_name, connector_name))
30 | with open(path, "r") as f:
31 | self.response(status_code, payload=f.read())
32 | else:
33 | connector_name = split_path[2]
34 | details_status_code = 503 if "unhealthy-broker" in self.mock_name else 200
35 | path = os.path.join(os.getcwd(),
36 | "./tests/data/mocks/healthy-connector-details.json".format(self.mock_name, connector_name))
37 | with open(path, "r") as f:
38 | self.response(details_status_code, payload=f.read())
39 |
40 | except Exception as ex:
41 | print("Error while handling mock GET request: {}".format(ex))
42 | self.response(500, "")
43 |
44 | def response(self, status_code, payload):
45 | self.send_response(status_code)
46 | self.send_header('Content-Type', 'application/json; charset=utf-8')
47 | self.end_headers()
48 | self.wfile.write(payload.encode('utf-8'))
49 |
50 | def log_message(self, format, *args):
51 | return
52 |
53 |
54 | def get_free_port():
55 | s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)
56 | s.bind(('localhost', 0))
57 | address, port = s.getsockname()
58 | s.close()
59 | return port
60 |
61 |
62 | def start_mock_server(port, mock_name):
63 | handler = partial(MockServerRequestHandler, mock_name)
64 | mock_server = HTTPServer(('localhost', port), handler)
65 | mock_server_thread = Thread(target=mock_server.serve_forever)
66 | mock_server_thread.setDaemon(True)
67 | mock_server_thread.start()
68 | print("\nMock Kafka Connect server running on port: {}".format(port))
69 |
--------------------------------------------------------------------------------
/tests/test_server.py:
--------------------------------------------------------------------------------
1 | # tests/test_server.py
2 |
3 | import json
4 |
5 | import pytest
6 | import requests
7 |
8 | scenario_0 = ({}, "0-healthcheck-server-healthy")
9 | scenario_1 = ({"HEALTHCHECK_UNHEALTHY_STATES": "FAILED"}, "1-healthy")
10 | scenario_2 = ({"HEALTHCHECK_UNHEALTHY_STATES": "FAILED"}, "2-unhealthy")
11 | scenario_3 = ({"HEALTHCHECK_CONNECT_URL": "http://unknown-hostname:8083"}, "3-unhealthy-error")
12 | scenario_4 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "kafka-connect:8083"}, "4-healthy-worker-id-correct")
13 | scenario_5 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "kafka-connect:8083"}, "5-healthy-worker-id-unused")
14 | scenario_6 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "kafka-connect:8083"}, "6-healthy-worker-id-with-other-workers-failing")
15 | scenario_7 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "kafka-connect:8083"}, "7-unhealthy-worker-id-with-other-workers-healthy")
16 | scenario_8 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "my.worker.name:8083"}, "8-healthy-multiple-tasks")
17 | scenario_9 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "my.worker.name:8083"}, "9-healthy-multiple-connectors")
18 | scenario_10 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "my.worker.name:8083"}, "10-unhealthy-multiple-connectors")
19 | scenario_11 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "my.worker.name:8083"}, "11-healthy-no-connectors")
20 | scenario_12 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "my.worker.name:8083"}, "12-unhealthy-task-with-trace")
21 | scenario_13 = ({"HEALTHCHECK_CONNECT_WORKER_ID": "unhealthy.worker:8083"}, "13-unhealthy-broker-connection")
22 | scenario_14 = ({"HEALTHCHECK_BASIC_AUTH": "username:password"}, "14-basic-auth")
23 | scenario_15 = ({"HEALTHCHECK_FAILURE_THRESHOLD_PERCENTAGE": "10"}, "15-unhealthy-threshold")
24 | scenario_16 = ({"HEALTHCHECK_FAILURE_THRESHOLD_PERCENTAGE": "50"}, "16-healthy-threshold")
25 | scenario_17 = ({"HEALTHCHECK_CONSIDERED_CONTAINERS": "CONNECTOR"}, "17-healthy-container-connector")
26 | scenario_18 = ({"HEALTHCHECK_CONSIDERED_CONTAINERS": "TASK"}, "18-healthy-container-task")
27 | scenario_19 = ({"HEALTHCHECK_CONSIDERED_CONTAINERS": "TASK"}, "19-unhealthy-container-task")
28 | other_scenarios = ({}, None)
29 |
30 |
31 | @pytest.mark.parametrize("run_backend", [scenario_0], indirect=True)
32 | def test_0_healthcheck_server_healthy(run_backend):
33 | with open("tests/data/expected/0-healthcheck-server-healthy.json", "r") as f:
34 | response = requests.get("http://localhost:18083/ping")
35 | assert response.status_code == 200
36 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
37 |
38 |
39 | @pytest.mark.parametrize("run_backend", [scenario_1], indirect=True)
40 | def test_1_healthy(run_backend, request):
41 | with open("tests/data/expected/1-healthy.json", "r") as f:
42 | response = requests.get("http://localhost:18083")
43 | logs = request.config.cache.get("logs", "") == ""
44 | assert response.status_code == 200
45 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
46 |
47 |
48 | @pytest.mark.parametrize("run_backend", [scenario_2], indirect=True)
49 | def test_2_unhealthy(run_backend):
50 | with open("tests/data/expected/2-unhealthy.json", "r") as f:
51 | response = requests.get("http://localhost:18083")
52 | assert response.status_code == 503
53 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
54 |
55 |
56 | @pytest.mark.parametrize("run_backend", [scenario_3], indirect=True)
57 | def test_3_unhealthy_error(run_backend):
58 | with open("tests/data/expected/3-unhealthy-error.json", "r") as f:
59 | response = requests.get("http://localhost:18083/")
60 | expected_response = json.load(f)
61 | actual_response = json.loads(response.content.decode("utf-8"))
62 | assert response.status_code == 503
63 | assert actual_response["healthy"] == expected_response["healthy"]
64 | assert actual_response["message"] == expected_response["message"]
65 | assert actual_response["failure_states"] == expected_response["failure_states"]
66 | assert expected_response["error"] in actual_response["error"]
67 |
68 |
69 | @pytest.mark.parametrize("run_backend", [scenario_4], indirect=True)
70 | def test_4_healthy_worker_id_correct(run_backend):
71 | with open("tests/data/expected/4-healthy-worker-id-correct.json", "r") as f:
72 | response = requests.get("http://localhost:18083")
73 | assert response.status_code == 200
74 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
75 |
76 |
77 | @pytest.mark.parametrize("run_backend", [scenario_5], indirect=True)
78 | def test_5_healthy_worker_id_unused(run_backend):
79 | with open("tests/data/expected/5-healthy-worker-id-unused.json", "r") as f:
80 | response = requests.get("http://localhost:18083")
81 | assert response.status_code == 200
82 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
83 |
84 |
85 | @pytest.mark.parametrize("run_backend", [scenario_6], indirect=True)
86 | def test_6_healthy_worker_id_with_other_workers_failing(run_backend):
87 | with open("tests/data/expected/6-healthy-worker-id-with-other-workers-failing.json", "r") as f:
88 | response = requests.get("http://localhost:18083")
89 | assert response.status_code == 200
90 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
91 |
92 |
93 | @pytest.mark.parametrize("run_backend", [scenario_7], indirect=True)
94 | def test_7_unhealthy_worker_id_with_other_workers_healthy(run_backend):
95 | with open("tests/data/expected/7-unhealthy-worker-id-with-other-workers-healthy.json", "r") as f:
96 | response = requests.get("http://localhost:18083")
97 | assert response.status_code == 503
98 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
99 |
100 |
101 | @pytest.mark.parametrize("run_backend", [scenario_8], indirect=True)
102 | def test_8_healthy_multiple_tasks(run_backend):
103 | with open("tests/data/expected/8-healthy-multiple-tasks.json", "r") as f:
104 | response = requests.get("http://localhost:18083")
105 | assert response.status_code == 200
106 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
107 |
108 |
109 | @pytest.mark.parametrize("run_backend", [scenario_9], indirect=True)
110 | def test_9_healthy_multiple_connectors(run_backend):
111 | with open("tests/data/expected/9-healthy-multiple-connectors.json", "r") as f:
112 | response = requests.get("http://localhost:18083")
113 | assert response.status_code == 200
114 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
115 |
116 |
117 | @pytest.mark.parametrize("run_backend", [scenario_10], indirect=True)
118 | def test_10_unhealthy_multiple_connectors(run_backend):
119 | with open("tests/data/expected/10-unhealthy-multiple-connectors.json", "r") as f:
120 | response = requests.get("http://localhost:18083")
121 | assert response.status_code == 503
122 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
123 |
124 |
125 | @pytest.mark.parametrize("run_backend", [scenario_11], indirect=True)
126 | def test_11_healthy_no_connectors(run_backend):
127 | with open("tests/data/expected/11-healthy-no-connectors.json", "r") as f:
128 | response = requests.get("http://localhost:18083")
129 | assert response.status_code == 200
130 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
131 |
132 |
133 | @pytest.mark.parametrize("run_backend", [scenario_12], indirect=True)
134 | def test_12_unhealthy_task_with_trace(run_backend):
135 | with open("tests/data/expected/12-unhealthy-task-with-trace.json", "r") as f:
136 | response = requests.get("http://localhost:18083")
137 | assert response.status_code == 503
138 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
139 |
140 |
141 | @pytest.mark.parametrize("run_backend", [scenario_13], indirect=True)
142 | def test_13_unhealthy_broker_connection(run_backend):
143 | with open("tests/data/expected/13-unhealthy-broker-connection.json", "r") as f:
144 | response = requests.get("http://localhost:18083")
145 | assert response.status_code == 503
146 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
147 |
148 |
149 | @pytest.mark.parametrize("run_backend", [scenario_14], indirect=True)
150 | def test_14_basic_auth(run_backend):
151 | with open("tests/data/expected/14-basic-auth.json", "r") as f:
152 | response = requests.get("http://localhost:18083")
153 | assert response.status_code == 200
154 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
155 |
156 |
157 | @pytest.mark.parametrize("run_backend", [scenario_15], indirect=True)
158 | def test_15_unhealthy_threshold(run_backend):
159 | with open("tests/data/expected/15-unhealthy-threshold.json", "r") as f:
160 | response = requests.get("http://localhost:18083")
161 | assert response.status_code == 503
162 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
163 |
164 |
165 | @pytest.mark.parametrize("run_backend", [scenario_16], indirect=True)
166 | def test_16_healthy_threshold(run_backend):
167 | with open("tests/data/expected/16-healthy-threshold.json", "r") as f:
168 | response = requests.get("http://localhost:18083")
169 | assert response.status_code == 200
170 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
171 |
172 |
173 | @pytest.mark.parametrize("run_backend", [scenario_17], indirect=True)
174 | def test_17_healthy_container_connector(run_backend):
175 | with open("tests/data/expected/17-healthy-container-connector.json", "r") as f:
176 | response = requests.get("http://localhost:18083")
177 | assert response.status_code == 200
178 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
179 |
180 |
181 | @pytest.mark.parametrize("run_backend", [scenario_18], indirect=True)
182 | def test_18_healthy_container_task(run_backend):
183 | with open("tests/data/expected/18-healthy-container-task.json", "r") as f:
184 | response = requests.get("http://localhost:18083")
185 | assert response.status_code == 200
186 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
187 |
188 |
189 | @pytest.mark.parametrize("run_backend", [scenario_19], indirect=True)
190 | def test_19_unhealthy_container_task(run_backend):
191 | with open("tests/data/expected/19-unhealthy-container-task.json", "r") as f:
192 | response = requests.get("http://localhost:18083")
193 | assert response.status_code == 503
194 | assert json.loads(response.content.decode("utf-8")) == json.load(f)
195 |
196 |
197 | @pytest.mark.parametrize("test_input", ["test", "does/not/exist", "kafka", "this-is-a-long/url", "connectors"])
198 | @pytest.mark.parametrize("run_backend", [other_scenarios], indirect=True)
199 | def test_for_404s(run_backend, test_input):
200 | response = requests.get("http://localhost:18083/{}".format(test_input))
201 | assert response.status_code == 404
202 | assert response.content == b""
203 |
204 |
205 | @pytest.mark.parametrize("test_input", ["", "test", "does/not/exist"])
206 | @pytest.mark.parametrize("run_backend", [other_scenarios], indirect=True)
207 | def test_head_request(run_backend, test_input):
208 | response = requests.head("http://localhost:18083/{}".format(test_input))
209 | assert response.status_code == 200
210 | assert response.headers.get("Content-type") == "text/html"
211 | assert response.content == b""
212 |
--------------------------------------------------------------------------------
/tests/test_version.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from .context import kafka_connect_healthcheck
4 |
5 | test_data = [
6 | "0.0.1",
7 | ]
8 |
9 |
10 | @pytest.mark.parametrize("test_input", test_data)
11 | def test_get_version(test_input):
12 | old_version = kafka_connect_healthcheck.version.__version__
13 | kafka_connect_healthcheck.version.__version__ = test_input
14 | assert kafka_connect_healthcheck.version.get_version() == test_input
15 | kafka_connect_healthcheck.version.__version__ = old_version
16 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py35,py36,py37,py38
3 |
4 | [gh-actions]
5 | python =
6 | 3.5: py35
7 | 3.6: py36
8 | 3.7: py37
9 | 3.8: py38
10 |
11 | [testenv]
12 | deps =
13 | pytest
14 | pytest-cov
15 | mock
16 | flake8
17 | flake8-quotes
18 | requests
19 | coverage
20 | commands =
21 | flake8 --max-line-length=160 --inline-quotes '"' --exclude=.tox,.git,htmlcov,build,dist,tests,docs,venv .
22 | pytest
23 |
--------------------------------------------------------------------------------