docker-sentinel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: docker-sentinel
3
+ Version: 0.1.0
4
+ Summary: Lightweight local tool that detects, diagnoses and recovers failing Docker containers.
5
+ Author: Jairam Hegde
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Jairamhegde/DockerSentinel
8
+ Project-URL: Repository, https://github.com/Jairamhegde/DockerSentinel
9
+ Project-URL: Issues, https://github.com/Jairamhegde/DockerSentinel/issues
10
+ Keywords: docker,containers,monitoring,diagnostics,recovery,ansible
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: System :: Monitoring
22
+ Classifier: Topic :: System :: Systems Administration
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: docker>=7.0
27
+ Dynamic: license-file
28
+
29
+ # DockerSentinel
30
+
31
+ [![unit test](https://github.com/Jairamhegde/DockerSentinel/actions/workflows/tests.yml/badge.svg)](https://github.com/Jairamhegde/DockerSentinel/actions/workflows/tests.yml)
32
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
33
+
34
+ A lightweight tool that runs on your own machine and watches your Docker containers. When one fails, it tells you **what went wrong** and **what changed since it last worked**, recovers it with **Ansible**, and alerts you on **Telegram**.
35
+
36
+ > **Status: alpha.** Tested on Linux (Fedora). By default `sentinel watch` **changes containers** to recover them; use `--no-recover` to only diagnose and notify.
37
+
38
+ ## What it does
39
+
40
+ Docker only says `Exited (1) 3 seconds ago`. Sentinel answers the real question:
41
+
42
+ ```
43
+ ╭─ #5 CRASHED ─────────────────────────────────────────────── 02:03:50 ─╮
44
+ │ demo-app · exit 1 │
45
+ │ ✖ PROBLEM It worked at 02:03. Since then 1 setting changed: │
46
+ │ • Dockerfile step REMOVED: COPY config.txt . │
47
+ │ ✔ SOLUTION Add 'COPY config.txt .' back to your Dockerfile, rebuild. │
48
+ │ LAST LOGS Error: config.txt not found │
49
+ ╰────────────────────────────────────────────────────────────────────────╯
50
+ ```
51
+
52
+ 1. **Detects** failures: crashes, out-of-memory kills, failed starts, unhealthy checks, crash loops, memory leaks.
53
+ 2. **Diagnoses** them: explains how it failed and ranks what changed (env vars, ports, mounts, command, Dockerfile steps) since the last good run.
54
+ 3. **Recovers** (Ansible): restart, raise the memory limit, or roll back to the last good image. Cases that need a human are only reported.
55
+ 4. **Notifies** registered users on Telegram; each user picks alert types and containers, and can mute.
56
+
57
+ ## Install
58
+
59
+ **Requirements:** Python 3.9+, Docker running, and your user in the `docker` group (Linux: `sudo usermod -aG docker $USER`, then log in again). For automatic recovery also install Ansible and its Docker collection:
60
+
61
+ ```bash
62
+ sudo apt install ansible # or: sudo dnf install ansible
63
+ ansible-galaxy collection install community.docker
64
+ ```
65
+
66
+ **Install Sentinel:**
67
+
68
+ ```bash
69
+ pipx install docker-sentinel # or: pip install docker-sentinel
70
+ ```
71
+
72
+ **From source:**
73
+
74
+ ```bash
75
+ git clone https://github.com/Jairamhegde/DockerSentinel.git && cd DockerSentinel
76
+ python3 -m venv .venv && source .venv/bin/activate
77
+ pip install -e .
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ ```bash
83
+ sentinel demo # 10-second demo with a fake app, no setup needed
84
+ sentinel watch # watch, diagnose, recover, notify (main mode)
85
+ sentinel watch --no-recover # diagnose and notify only; never touches containers
86
+ sentinel check # check all containers once
87
+ sentinel history -n 10 # last 10 saved tickets
88
+ ```
89
+
90
+ | Command | Purpose |
91
+ |---|---|
92
+ | `sentinel users add +91... --name N [--admin]` / `list` / `remove <phone>` | Manage who may receive Telegram alerts |
93
+ | `sentinel notify-test` | Check the Telegram setup and send a test message |
94
+ | `sentinel web` | Local sign-up page (http://localhost:8080) |
95
+
96
+ Tickets are stored in `~/.docker-sentinel/sentinel.db`.
97
+
98
+ ### Telegram alerts (optional)
99
+
100
+ 1. Create a bot with **@BotFather** and `export SENTINEL_TELEGRAM_TOKEN="123456:ABC..."`.
101
+ 2. Allow numbers: `sentinel users add +91 98765 43210 --name Jairam --admin`.
102
+ 3. Run `sentinel watch`. Each user opens the printed bot link, presses **Start**, shares their phone number, then uses `/alerts`, `/containers`, `/mute 2h`.
103
+
104
+ Without a token, alerts are printed in the terminal only.
105
+
106
+ ## Tech stack
107
+
108
+ Python 3.9+ (standard library plus the `docker` SDK) · Docker Engine API · Ansible (`community.docker`) · SQLite · Telegram Bot API · pytest and GitHub Actions for tests and releases.
109
+
110
+ ## Architecture
111
+
112
+ ```
113
+ Docker events + 5 s scan ──► collector.py gathers evidence (inspect, logs, image history)
114
+ │
115
+ tracker.py snapshots each run: "good" or "bad"
116
+ │
117
+ rules.py + changes.py HOW it failed + WHAT changed vs last good run
118
+ │
119
+ store.py (SQLite) + ticket.py saves and prints the ticket
120
+ │
121
+ recovery.py picks one fix from the root cause
122
+ │
123
+ automation.py ──► Ansible playbooks (restart / raise_memory / rollback)
124
+ │
125
+ notifier.py ──► Telegram (bot.py, users.py, memory.py)
126
+ ```
127
+
128
+ Sentinel is a normal Docker client: it doesn't sit between you and Docker, so Docker keeps working if Sentinel stops. Env var **values are never stored**, only SHA-256 fingerprints.
129
+
130
+ More detail (algorithm, recovery table, alerts, live tests): [docs/DETAILS.md](docs/DETAILS.md) · demo walkthrough: [docs/DEMO.md](docs/DEMO.md).
131
+
132
+ ## Development
133
+
134
+ ```bash
135
+ pip install -r requirements-dev.txt && pip install -e .
136
+ python -m pytest
137
+ ```
138
+
139
+ ## License
140
+
141
+ [MIT](LICENSE)
@@ -0,0 +1,28 @@
1
+ docker_sentinel-0.1.0.dist-info/licenses/LICENSE,sha256=aNGMn2cnICpK_qI-8kw69Z995LVpYT4tfoeRHbOpPh4,1068
2
+ sentinel/__init__.py,sha256=QQTk7IfOQwkipPrWqHmVQHVTcGGJIqVrk3tvfSoDMWI,127
3
+ sentinel/__main__.py,sha256=rf6c1Hf1hwNdB2ptHKah7jzTi7CuBgYte-pJc1MYI10,97
4
+ sentinel/automation.py,sha256=5hEudFnBxyEL72NeEUIbVNl8JPwhren5Xcag3wGX9R4,6684
5
+ sentinel/bot.py,sha256=Aeybb9mYwQXWnV9Ip-8koafqUQNBiutUduwDkZk0siI,17294
6
+ sentinel/changes.py,sha256=XgmlbtZacLcih4NyLhlXjkmq0qjYzmppJE5VbNua3nc,18244
7
+ sentinel/cli.py,sha256=XOvOH0Eyy_BQC-Yqk0cRv21I-QOY7wv1LzJ81VdOrOc,14397
8
+ sentinel/collector.py,sha256=2iT96oL4eyp5MSK-p4X9elxxqJeU0HYd1dhk1SSlHsU,8298
9
+ sentinel/demo.py,sha256=dL1exrfGxBGYwUgs28tfQp-keBHw8lEP3xEyYKeQvl0,3253
10
+ sentinel/mailer.py,sha256=--xeMGtEkjM5r7djYM8sFch14CygWcodEhFF5myqMP4,1927
11
+ sentinel/memory.py,sha256=egORZYFcke0NgzdAOYodsF-DUFqcl-qoisri7w2MsiQ,5345
12
+ sentinel/notifier.py,sha256=S23uEKPS99K6liFWDw22MVnSuvLD96nM-h-Xk2hT-ks,7753
13
+ sentinel/recovery.py,sha256=ZDT2WQI6HJb6YYnHqSQLOLyuCSW4Uz0O3c-L2b05Phs,19845
14
+ sentinel/rules.py,sha256=paewCVnpoj7bJnb8y3MGa_R4DTguGhakPGRaq_iEACg,7963
15
+ sentinel/store.py,sha256=iPoH-OGlw7DyakdPuy1EJQMOKKogySvHpQTEEUPy218,7496
16
+ sentinel/subscribers.py,sha256=YFF-pQzXTFVUKC71bw7PQ8ImU3s4F5rcFdYskNLTvhI,4021
17
+ sentinel/ticket.py,sha256=mRMLjypdiUdnhn7l35UM8tZwqxycnu1biq5X39vQSJo,6079
18
+ sentinel/tracker.py,sha256=ZzQhYORocZlUY6QYhkP7IkwUWWWlMXqNEURtUxGTCH4,6555
19
+ sentinel/users.py,sha256=Te2OBB5NZ9azJF-f0OmlONibRqQbKf91AJ4AsTopzNo,8731
20
+ sentinel/web.py,sha256=WHfBbMj5OmuWUSE1Bglu2gzhxPulKUwLC-RXdug5zkU,6879
21
+ sentinel/playbooks/raise_memory.yml,sha256=3hxY4kFTqXSogLmPtdB4hJ4M25V6cxEatnL7jXL2cs8,1011
22
+ sentinel/playbooks/restart.yml,sha256=oG4PDySa_82QTv-eE9f-RTjPBkKI8Efqrn2eWFZK6_Q,758
23
+ sentinel/playbooks/rollback.yml,sha256=VjUP5qxpPBCJswo02-bU6mgnW_N02UUzBwvHbDDsNjM,1626
24
+ docker_sentinel-0.1.0.dist-info/METADATA,sha256=kToa7YYKBOvxs1w_kp_kLY6QB9W01Y_sJx2g6sBTjLY,6637
25
+ docker_sentinel-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
26
+ docker_sentinel-0.1.0.dist-info/entry_points.txt,sha256=ocLIRMq9Ouq9WNyGxm5wf_4S_Lg_L_FA3jBcXo9o2kw,47
27
+ docker_sentinel-0.1.0.dist-info/top_level.txt,sha256=tffn0oUCkyTZs6yuGcwFCZJxRUrJi_wFmpKwWBYlzVE,9
28
+ docker_sentinel-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sentinel = sentinel.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jairam Hegde
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ sentinel
sentinel/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """
2
+ DockerSentinel - a lightweight local tool that detects and diagnoses
3
+ failing Docker containers.
4
+ """
5
+
6
+ __version__ = "0.1.0"
sentinel/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """
2
+ Allows running the tool with: python -m sentinel
3
+ """
4
+
5
+ from sentinel.cli import main
6
+
7
+
8
+ main()
sentinel/automation.py ADDED
@@ -0,0 +1,200 @@
1
+ """
2
+ Automation (Ansible).
3
+
4
+ Runs the recovery playbooks in sentinel/playbooks/ with `ansible-playbook`
5
+ on this machine (connection: local), using the community.docker collection.
6
+
7
+ restart.yml restart the container
8
+ raise_memory.yml raise its memory limit and start it
9
+ rollback.yml re-create it from the last good image
10
+
11
+ The functions that build the playbook variables are pure (they only read
12
+ `docker inspect` dictionaries), so they can be tested without Docker.
13
+
14
+ Playbook variables can contain environment values (passwords, API keys),
15
+ so they are written to a private temporary file that is deleted right
16
+ after the playbook has run, and never stored or printed.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+
26
+
27
+ PLAYBOOK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "playbooks")
28
+
29
+ PLAYBOOKS = {
30
+ "restart": "restart.yml",
31
+ "raise_memory": "raise_memory.yml",
32
+ "rollback": "rollback.yml",
33
+ }
34
+
35
+ TIMEOUT_SECONDS = 180
36
+ OUTPUT_LINES_KEPT = 15
37
+
38
+
39
+ def ansible_available():
40
+ return shutil.which("ansible-playbook") is not None
41
+
42
+
43
+ def container_name(attrs):
44
+ return attrs["Name"].lstrip("/")
45
+
46
+
47
+ def restart_vars(attrs):
48
+ return {
49
+ "container_name": container_name(attrs),
50
+ "container_image": attrs["Image"],
51
+ }
52
+
53
+
54
+ def raise_memory_vars(attrs, new_memory):
55
+ variables = {
56
+ "container_name": container_name(attrs),
57
+ "container_image": attrs["Image"],
58
+ "memory": str(new_memory),
59
+ }
60
+ # Docker's default swap limit is twice the memory limit; -1 means unlimited.
61
+ if attrs["HostConfig"].get("MemorySwap", 0) != -1:
62
+ variables["memory_swap"] = str(new_memory * 2)
63
+ return variables
64
+
65
+
66
+ def format_port(container_port, binding):
67
+ """
68
+ ("80/tcp", {"HostIp": "", "HostPort": "8080"}) -> "8080:80"
69
+ """
70
+ port, _, protocol = container_port.partition("/")
71
+ target = port if protocol in ("", "tcp") else port + "/" + protocol
72
+
73
+ host_port = (binding or {}).get("HostPort", "")
74
+ host_ip = (binding or {}).get("HostIp", "")
75
+ if host_port == "":
76
+ return target
77
+ if host_ip not in ("", "0.0.0.0", "::"):
78
+ return host_ip + ":" + host_port + ":" + target
79
+ return host_port + ":" + target
80
+
81
+
82
+ def format_mount(mount):
83
+ mode = "" if mount.get("RW", True) else ":ro"
84
+ if mount["Type"] == "volume":
85
+ return mount["Name"] + ":" + mount["Destination"] + mode
86
+ return mount["Source"] + ":" + mount["Destination"] + mode
87
+
88
+
89
+ def rollback_vars(attrs, current_image_config, good_image_id):
90
+ """
91
+ Variables to re-create a container from an older image.
92
+
93
+ `current_image_config` is the Config section of the image the failing
94
+ container uses. A setting that is the same as that image's default
95
+ (CMD, ENTRYPOINT, ENV, WORKDIR, USER, labels) came from the new image,
96
+ not from the user, so it is left out: the old image's own default
97
+ applies again. Settings the user gave to `docker run` are kept.
98
+ """
99
+ config = attrs["Config"]
100
+ host = attrs["HostConfig"]
101
+ image = current_image_config or {}
102
+
103
+ variables = {
104
+ "container_name": container_name(attrs),
105
+ "image": good_image_id,
106
+ }
107
+
108
+ if config.get("Cmd") and config["Cmd"] != image.get("Cmd"):
109
+ variables["command"] = config["Cmd"]
110
+
111
+ if config.get("Entrypoint") and config["Entrypoint"] != image.get("Entrypoint"):
112
+ variables["entrypoint"] = config["Entrypoint"]
113
+
114
+ image_env = set(image.get("Env") or [])
115
+ env = {}
116
+ for item in config.get("Env") or []:
117
+ if item in image_env:
118
+ continue
119
+ name, _, value = item.partition("=")
120
+ env[name] = value
121
+ if env:
122
+ variables["env"] = env
123
+
124
+ if config.get("WorkingDir") and config["WorkingDir"] != image.get("WorkingDir"):
125
+ variables["working_dir"] = config["WorkingDir"]
126
+
127
+ if config.get("User") and config["User"] != image.get("User"):
128
+ variables["user"] = config["User"]
129
+
130
+ ports = []
131
+ for container_port, bindings in (host.get("PortBindings") or {}).items():
132
+ for binding in bindings or [None]:
133
+ ports.append(format_port(container_port, binding))
134
+ if ports:
135
+ variables["ports"] = ports
136
+
137
+ volumes = [format_mount(mount) for mount in attrs.get("Mounts") or []]
138
+ if volumes:
139
+ variables["volumes"] = volumes
140
+
141
+ policy = (host.get("RestartPolicy") or {}).get("Name", "")
142
+ if policy not in ("", "no"):
143
+ variables["restart_policy"] = policy
144
+
145
+ if host.get("Memory", 0) > 0:
146
+ variables["memory"] = str(host["Memory"])
147
+
148
+ network_mode = host.get("NetworkMode", "")
149
+ if network_mode not in ("", "default", "bridge"):
150
+ variables["network_mode"] = network_mode
151
+
152
+ image_labels = image.get("Labels") or {}
153
+ labels = {}
154
+ for key, value in (config.get("Labels") or {}).items():
155
+ if image_labels.get(key) != value:
156
+ labels[key] = value
157
+ if labels:
158
+ variables["labels"] = labels
159
+
160
+ return variables
161
+
162
+
163
+ def run_playbook(action, variables):
164
+ """
165
+ Run one recovery playbook. Returns (ok, output) where output is the
166
+ last lines of Ansible's output, for the terminal and notifications.
167
+ """
168
+ if not ansible_available():
169
+ return False, "Ansible is not installed (ansible-playbook not found)."
170
+
171
+ playbook = os.path.join(PLAYBOOK_DIR, PLAYBOOKS[action])
172
+
173
+ # The docker modules run with the same Python as Sentinel, which already
174
+ # has the docker library installed.
175
+ variables = dict(variables)
176
+ variables["ansible_python_interpreter"] = sys.executable
177
+
178
+ handle, vars_path = tempfile.mkstemp(prefix="sentinel-", suffix=".json")
179
+ try:
180
+ with os.fdopen(handle, "w") as file:
181
+ json.dump(variables, file)
182
+
183
+ command = ["ansible-playbook", "-i", "localhost,", "-c", "local", playbook, "-e", "@" + vars_path]
184
+ environment = dict(os.environ)
185
+ environment["ANSIBLE_NOCOLOR"] = "1"
186
+ environment["ANSIBLE_LOCALHOST_WARNING"] = "False"
187
+ environment["ANSIBLE_INVENTORY_UNPARSED_WARNING"] = "False"
188
+ environment["ANSIBLE_RETRY_FILES_ENABLED"] = "False"
189
+
190
+ try:
191
+ result = subprocess.run(command, capture_output=True, text=True,
192
+ timeout=TIMEOUT_SECONDS, env=environment)
193
+ except subprocess.TimeoutExpired:
194
+ return False, "Ansible did not finish within " + str(TIMEOUT_SECONDS) + " seconds."
195
+ finally:
196
+ os.remove(vars_path)
197
+
198
+ output = (result.stdout + "\n" + result.stderr).strip().splitlines()
199
+ tail = "\n".join(line for line in output[-OUTPUT_LINES_KEPT:] if line.strip() != "")
200
+ return result.returncode == 0, tail