Skip to content

Commit 2faa77c

Browse files
authored
Merge pull request #748 from labmonkey/template
swag:auto-uptime-kuma Initial release of the mod
2 parents cc80a43 + 65fb420 commit 2faa77c

File tree

30 files changed

+402
-95
lines changed

30 files changed

+402
-95
lines changed

.github/workflows/BuildImage.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ on: [push, pull_request_target, workflow_dispatch]
55
env:
66
GITHUB_REPO: "linuxserver/docker-mods" #don't modify
77
ENDPOINT: "linuxserver/mods" #don't modify
8-
BASEIMAGE: "replace_baseimage" #replace
9-
MODNAME: "replace_modname" #replace
8+
BASEIMAGE: "swag" #replace
9+
MODNAME: "auto-uptime-kuma" #replace
1010

1111
jobs:
1212
set-vars:

Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
FROM scratch
44

5-
LABEL maintainer="username"
5+
LABEL maintainer="labmonkey"
66

77
# copy local files
88
COPY root/ /

Dockerfile.complex

Lines changed: 0 additions & 25 deletions
This file was deleted.

README.md

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,52 @@
1-
# Rsync - Docker mod for openssh-server
1+
# Auto Uptime Kuma - Docker mod for SWAG
22

3-
This mod adds rsync to openssh-server, to be installed/updated during container start.
3+
This mod gives SWAG the ability to automatically add Uptime Kuma "Monitors" for the running containers. Ultimately it will allow you with a very low effort to setup notifications whenever any of your services goes down etc.
44

5-
In openssh-server docker arguments, set an environment variable `DOCKER_MODS=linuxserver/mods:openssh-server-rsync`
5+
## Requirements
66

7-
If adding multiple mods, enter them in an array separated by `|`, such as `DOCKER_MODS=linuxserver/mods:openssh-server-rsync|linuxserver/mods:openssh-server-mod2`
7+
Running [Uptime Kuma](https://github.com/louislam/uptime-kuma) instance with `username` and `password` configured. The container should be in the same [user defined bridge network](https://docs.linuxserver.io/general/swag#docker-networking) as SWAG.
88

9-
# Mod creation instructions
9+
## Installation
1010

11-
* Fork the repo, create a new branch based on the branch `template`.
12-
* Edit the `Dockerfile` for the mod. `Dockerfile.complex` is only an example and included for reference; it should be deleted when done.
13-
* Inspect the `root` folder contents. Edit, add and remove as necessary.
14-
* After all init scripts and services are created, run `find ./ -path "./.git" -prune -o \( -name "run" -o -name "finish" -o -name "check" \) -not -perm -u=x,g=x,o=x -print -exec chmod +x {} +` to fix permissions.
15-
* Edit this readme with pertinent info, delete these instructions.
16-
* Finally edit the `.github/workflows/BuildImage.yml`. Customize the vars for `BASEIMAGE` and `MODNAME`. Set the versioning logic if needed.
17-
* Ask the team to create a new branch named `<baseimagename>-<modname>`. Baseimage should be the name of the image the mod will be applied to. The new branch will be based on the `template` branch.
18-
* Submit PR against the branch created by the team.
11+
In SWAG docker arguments, set an environment variable `DOCKER_MODS=linuxserver/mods:swag-auto-uptime-kuma`.
1912

13+
Add additional environment variables to the SWAG docker image:
2014

21-
## Tips and tricks
15+
| Name | Required | Example | Description |
16+
| ---------------------- | -------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17+
| `UPTIME_KUMA_URL` | Yes | `http://uptime-kuma:3001/` | The URL to the Uptime Kuma instance. Please note this cannot be the domain that it configured by SWAG as during initialization phase of the container those domains are not yet available. Instead use the docker container name. |
18+
| `UPTIME_KUMA_USERNAME` | Yes | `admin` | Your Uptime Kuma username |
19+
| `UPTIME_KUMA_PASSWORD` | Yes | `password` | Your Uptime Kuma password |
2220

23-
* Some images have helpers built in, these images are currently:
24-
* [Openvscode-server](https://github.com/linuxserver/docker-openvscode-server/pull/10/files)
25-
* [Code-server](https://github.com/linuxserver/docker-code-server/pull/95)
21+
Unfortunately Uptime Kuma does not provide API keys for it's Socket.io API at the moment and Username/Password have to be used.
22+
23+
Finally, add `swag.uptime-kuma.enabled=true` label at minimum to each of your containers that you wish to monitor. More types of labels are listed in next section.
24+
25+
## Labels
26+
27+
This mod is utilizing the wonderful [Uptime Kuma API](https://github.com/lucasheld/uptime-kuma-api) library. It allows you configure nearly every property of the Monitors by defining Docker Labels. For detailed documentation of each of these properties please refer to the `add_monitor` endpoint in the [official documentation](https://uptime-kuma-api.readthedocs.io/en/latest/api.html#uptime_kuma_api.UptimeKumaApi.add_monitor).
28+
29+
| Label | Default Value | Example Value | Description |
30+
| -------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
31+
| `swag.uptime-kuma.enabled` | `false` | `true` | The only required label for the minimal setup. It allows the mod to detect the container and configure monitor. |
32+
| `swag.uptime-kuma.monitor.name` | `{containerName}` | Radarr <br> Jellyfin Public | By default the name of the Monitor will be value of the Docker container name transformed to start with uppercase letter. |
33+
| `swag.uptime-kuma.monitor.url` | `https://{containerName}.{domainName}` | `https://radarr.domain.com/` <br> `https://pihole.domain.com/admin/` | By default the URL of each container if build based of the actual container name (`{containerName}`) defined in docker and the value of `URL` environment variable (`{domainName}`) defined in SWAG (as required by SWAG itself). |
34+
| `swag.uptime-kuma.monitor.type` | http | http | While technically possible to override the monitor type the purpose of this mod is to monitor HTTP endpoints. |
35+
| `swag.uptime-kuma.monitor. description` | Automatically generated by SWAG auto-uptime-kuma | My own description | The description is only for informational purposes and can be freely changed |
36+
| `swag.uptime-kuma.monitor.*` | | `swag.uptime-kuma.monitor. maxretries=5` <br> `swag.uptime-kuma.monitor. accepted_statuscodes= 200-299,404,501` | There are many more properties to configure. The fact that aything can be changed does not mean that it should. Some properties or combinations could not work and should be changed only if you know what you are doing. Please check the [Uptime Kuma API](https://uptime-kuma-api.readthedocs.io/en/latest/api.html#uptime_kuma_api.UptimeKumaApi.add_monitor) for more examples. Properties that are expected to be lists should be separated by comma `,` |
37+
38+
## Notifications
39+
40+
While ultimately this mod makes it easier to setup notifications for your docker containers it does not configure more than Uptime Kuma Monitors. In order to receive Notifications you should configure them manually and then either enable one type to be default for all your Monitors or specify the Notifications by using the `swag.uptime-kuma.monitor.notificationIDList` label.
41+
42+
## Known Limitations
43+
44+
- At the moment this mod does *NOT* monitor your docker containers for changes. This means that whenever you change any of your labels or remove a container and wish to no longer monitor it then the changes will *NOT* be applied to Uptime Kuma in real time. In order to reload the changes you have two options:
45+
- Restart the `swag` container. This will run initialization scripts again and reload all the changes (add/delete/update monitors)
46+
- Run the script manually which is the following command via `ssh`: `docker exec swag python3 /app/auto-uptime-kuma.py` (where `swag` is your container name of the SWAG instance).
47+
48+
- Due to limitations of the Uptime Kuma API whenever you make changes to your container or labels that already have a Monior setup then the **Update** action will be performed by running **Delete** followed by **Add**. What it means that all changes will result in a new Monitor for the same container that will lose history of the heartbeats, all manual changes and get a new 'id' number.
49+
50+
## Purge data
51+
52+
For the purpose of development or simply if you feel that you want to purge all the Monitors and files created by this mod you can run following command via `ssh`: `docker exec swag python3 /app/auto-uptime-kuma.py -purge` (where `swag` is your container name of the SWAG instance).

root/app/auto-uptime-kuma.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
from swagDocker import SwagDocker
2+
from swagUptimeKuma import SwagUptimeKuma
3+
import sys
4+
import argparse
5+
import os
6+
7+
8+
def parseCommandLine():
9+
"""
10+
Different application behavior if executed from CLI
11+
"""
12+
parser = argparse.ArgumentParser()
13+
parser.add_argument('-purge', action='store_true')
14+
args = parser.parse_args()
15+
16+
if (args.purge == True):
17+
swagUptimeKuma.purgeData()
18+
swagUptimeKuma.disconnect()
19+
sys.exit(0)
20+
21+
22+
def addOrUpdateMonitors(domainName, swagContainers):
23+
for swagContainer in swagContainers:
24+
containerConfig = swagDocker.parseContainerLabels(
25+
swagContainer.labels, ".monitor.")
26+
containerName = swagContainer.name
27+
monitorData = swagUptimeKuma.parseMonitorData(
28+
containerName, domainName, containerConfig)
29+
30+
if (not swagUptimeKuma.monitorExists(containerName)):
31+
swagUptimeKuma.addMonitor(containerName, domainName, monitorData)
32+
else:
33+
swagUptimeKuma.updateMonitor(
34+
containerName, domainName, monitorData)
35+
36+
37+
def getMonitorsToBeRemoved(swagContainers, apiMonitors):
38+
# Monitors to be removed are those that no longer have an existing container
39+
# Monitor <-> Container link is done by comparing the container name with the monitor swag tag value
40+
existingMonitorNames = [swagUptimeKuma.getMonitorSwagTagValue(
41+
monitor) for monitor in apiMonitors]
42+
existingContainerNames = [container.name for container in swagContainers]
43+
44+
monitorsToBeRemoved = [
45+
containerName for containerName in existingMonitorNames if containerName not in existingContainerNames]
46+
return monitorsToBeRemoved
47+
48+
49+
if __name__ == "__main__":
50+
url = os.environ['UPTIME_KUMA_URL']
51+
username = os.environ['UPTIME_KUMA_USERNAME']
52+
password = os.environ['UPTIME_KUMA_PASSWORD']
53+
domainName = os.environ['URL']
54+
55+
swagDocker = SwagDocker("swag.uptime-kuma")
56+
swagUptimeKuma = SwagUptimeKuma(url, username, password)
57+
58+
parseCommandLine()
59+
60+
swagContainers = swagDocker.getSwagContainers()
61+
62+
addOrUpdateMonitors(domainName, swagContainers)
63+
64+
monitorsToBeRemoved = getMonitorsToBeRemoved(
65+
swagContainers, swagUptimeKuma.apiMonitors)
66+
swagUptimeKuma.deleteMonitors(monitorsToBeRemoved)
67+
68+
swagUptimeKuma.disconnect()

root/app/helpers.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def has_key_with_value(dictionary, key, value):
2+
return key in dictionary and dictionary[key] == value
3+
4+
5+
def merge_dicts(*dict_args):
6+
result = {}
7+
for dictionary in dict_args:
8+
result.update(dictionary)
9+
return result
10+
11+
12+
def write_file(filename, content):
13+
with open(filename, 'w+') as file:
14+
file.write(content)
15+
16+
17+
def read_file(filename):
18+
with open(filename, 'r') as file:
19+
content = file.read()
20+
return content

root/app/swagDocker.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import docker
2+
3+
4+
class SwagDocker:
5+
"""
6+
A service class for interacting with Docker containers that are used by SWAG mods.
7+
"""
8+
9+
client = None
10+
_containers = None
11+
_labelPrefix = None
12+
13+
def __init__(self, labelPrefix: str):
14+
self._labelPrefix = labelPrefix
15+
self.client = docker.from_env()
16+
17+
def getSwagContainers(self):
18+
"""
19+
Retrieve Docker containers filtered by "swag.my_mod.enabled=true":
20+
>>> swag = SwagDocker("swag.my_mod")
21+
>>> containers = swag.getSwagContainers()
22+
"""
23+
if self._containers is None:
24+
self._containers = self.client.containers.list(
25+
filters={"label": [f"{self._labelPrefix}.enabled=true"]})
26+
return self._containers
27+
28+
def parseContainerLabels(self, containerLabels, extraPrefix=""):
29+
"""
30+
Having following example container labels:
31+
swag.my_mod.enabled: true
32+
swag.my_mod.config.apple: "123"
33+
swag.my_mod.config.orange: "456"
34+
35+
>>> for container in containers:
36+
>>> containerConfigA = swagDocker.parseContainerLabels(container.labels)
37+
# Above will return {"enabled": true, "config.apple": "123", "config.orange": "456"}
38+
>>> containerConfigB = swagDocker.parseContainerLabels(container.labels, ".config.")
39+
# Above will return {"apple": "123", "orange": "456"}
40+
"""
41+
filteredContainerLabels = {}
42+
fullPrefix = f"{self._labelPrefix}{extraPrefix}"
43+
prefix_length = len(fullPrefix)
44+
45+
for label, value in containerLabels.items():
46+
if label.startswith(fullPrefix):
47+
parsedLabel = label[prefix_length:]
48+
filteredContainerLabels[parsedLabel] = value
49+
50+
return filteredContainerLabels

0 commit comments

Comments
 (0)