Skip to content

Commit 8cc5fd4

Browse files
authored
Merge pull request #1079 from linuxserver/swag-ondemand-initial
Add swag-ondemand mod
2 parents 6360fcf + 9b7bf8f commit 8cc5fd4

File tree

25 files changed

+262
-99
lines changed

25 files changed

+262
-99
lines changed

.assets/loading-page.png

12.9 KB
Loading

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="quietsy"
66

77
# copy local files
88
COPY root/ /

Dockerfile.complex

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

README.md

Lines changed: 78 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,86 @@
1-
# Rsync - Docker mod for openssh-server
1+
# On-demand - 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 start containers on-demand when accessed through SWAG and stop them after a period of inactivity. It takes a few seconds for containers to start on-demand, you'll need to refresh the tab or add a loading page as detailed below.
44

5-
In openssh-server docker arguments, set an environment variable `DOCKER_MODS=linuxserver/mods:openssh-server-rsync`
5+
## Setup:
6+
- In SWAG's docker arguments, set an environment variable `DOCKER_MODS=linuxserver/mods:swag-ondemand` and either add a volume mapping for `/var/run/docker.sock:/var/run/docker.sock:ro`, or set an environment var `DOCKER_HOST=remoteaddress` (read the security considerations below).
7+
- Add the label `swag_ondemand=enable` to on-demand containers.
8+
```yaml
9+
somecontainer:
10+
container_name: somecontainer
11+
...
12+
labels:
13+
- swag_ondemand=enable
14+
```
15+
- Replace the following line in `/config/nginx/nginx.conf`:
16+
```nginx
17+
access_log /config/log/nginx/access.log;
18+
```
19+
With:
20+
```nginx
21+
log_format main '$remote_addr - $remote_user [$time_local] '
22+
'"$request_method $scheme://$host$request_uri $server_protocol" '
23+
'$status $body_bytes_sent '
24+
'"$http_referer" "$http_user_agent"';
25+
access_log /config/log/nginx/access.log main;
26+
```
27+
- *Optional* - Additional environment variables
28+
- `SWAG_ONDEMAND_STOP_THRESHOLD` - duration of inactivity in seconds before stopping on-demand containers, defaults to `600` (10 minutes).
29+
- `SWAG_ONDEMAND_CONTAINER_QUERY_SLEEP` - sleep time in seconds between querying containers, defaults to `5.0`.
30+
- `SWAG_ONDEMAND_LOG_READER_SLEEP` - sleep time in seconds between log reads, defaults to `1.0`.
631

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`
32+
### Loading Page:
833

9-
# Mod creation instructions
34+
![loading-page](.assets/loading-page.png)
1035

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 and `MULTI_ARCH` 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.
36+
Instead of showing a 502 error page, it can display a loading page and auto-refresh once the container is up.
37+
38+
Add the following `include` to each proxy-conf where you wish to show the loading page inside the `server` section:
39+
```nginx
40+
server {
41+
...
42+
include /config/nginx/ondemand.conf;
43+
...
44+
```
45+
Or set the following label if using `swag-auto-proxy`:
46+
```yaml
47+
somecontainer:
48+
container_name: somecontainer
49+
...
50+
labels:
51+
- swag_server_custom_directive=include /config/nginx/ondemand.conf;
52+
```
53+
### Labels:
54+
- `swag_ondemand=enable` - required for on-demand.
55+
- `swag_ondemand_urls=https://wake.domain.com,https://app.domain.com/up` - *optional* - overrides the monitored URLs for starting the container on-demand. Defaults to `https://somecontainer.,http://somecontainer.`.
1956

57+
### URLs:
58+
- Accessed URLs need to start with one of `swag_ondemand_urls` to be matched, for example, setting `swag_ondemand_urls=https://plex.` will apply to `https://plex.domain.com` and `https://plex.domain.com/something`.
59+
- `swag_ondemand_urls` default to `https://somecontainer.,http://somecontainer.`, for example `https://plex.,http://plex.`.
60+
- `swag_ondemand_urls` don't need to be valid, it will work as long as it reaches swag and gets logged by nginx under `/config/log/nginx/access.log`.
61+
- The same URL can be set on multiple containers and all of them will be started when accessing that URL.
2062

21-
## Tips and tricks
63+
### Logging:
64+
The log file can be found under `/config/log/ondemand/ondemand.log`.
2265

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)
66+
## Security Consideration:
67+
Mapping the `docker.sock`, especially in a publicly accessible container is a security liability. Since this mod only needs read-only access to the docker api, the recommended method is to proxy the `docker.sock` via a solution like [our docker socket proxy](https://github.com/linuxserver/docker-socket-proxy), limit the access, and set `DOCKER_HOST=` to point to the proxy address.
68+
69+
Here's a sample compose yaml snippet for `linuxserver/docker-socket-proxy`:
70+
```yaml
71+
socket-proxy:
72+
image: lscr.io/linuxserver/socket-proxy:latest
73+
container_name: socket-proxy
74+
environment:
75+
- ALLOW_START=1
76+
- ALLOW_STOP=1
77+
- CONTAINERS=1
78+
- POST=0
79+
volumes:
80+
- /var/run/docker.sock:/var/run/docker.sock:ro
81+
restart: unless-stopped
82+
read_only: true
83+
tmpfs:
84+
- /run
85+
```
86+
Then the env var in SWAG can be set as `DOCKER_HOST=tcp://socket-proxy:2375`. This will allow docker in SWAG to be able to start/stop existing containers, but it won't be allowed to spin up new containers.

root/app/swag-ondemand.py

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
from datetime import datetime
2+
import docker
3+
import logging
4+
import os
5+
import threading
6+
import time
7+
8+
ACCESS_LOG_FILE = "/config/log/nginx/access.log"
9+
LOG_FILE = "/config/log/ondemand/ondemand.log"
10+
CONTAINER_QUERY_SLEEP = float(os.environ.get("SWAG_ONDEMAND_CONTAINER_QUERY_SLEEP", "5.0"))
11+
LOG_READER_SLEEP = float(os.environ.get("SWAG_ONDEMAND_LOG_READER_SLEEP", "1.0"))
12+
STOP_THRESHOLD = int(os.environ.get("SWAG_ONDEMAND_STOP_THRESHOLD", "600"))
13+
14+
last_accessed_urls = set()
15+
last_accessed_urls_lock = threading.Lock()
16+
17+
class ContainerThread(threading.Thread):
18+
def __init__(self):
19+
super().__init__()
20+
self.daemon = True
21+
self.ondemand_containers = {}
22+
try:
23+
self.docker_client = docker.from_env()
24+
except Exception as e:
25+
logging.exception(e)
26+
27+
def process_containers(self):
28+
containers = self.docker_client.containers.list(all=True, filters={ "label": ["swag_ondemand=enable"] })
29+
container_names = {container.name for container in containers}
30+
31+
for container_name in list(self.ondemand_containers.keys()):
32+
if container_name in container_names:
33+
continue
34+
self.ondemand_containers.pop(container_name)
35+
logging.info(f"Stopped monitoring {container_name}")
36+
37+
for container in containers:
38+
container_urls = container.labels.get("swag_ondemand_urls", f"https://{container.name}.,http://{container.name}.")
39+
if container.name not in self.ondemand_containers.keys():
40+
last_accessed = datetime.now()
41+
logging.info(f"Started monitoring {container.name}")
42+
else:
43+
last_accessed = self.ondemand_containers[container.name]["last_accessed"]
44+
self.ondemand_containers[container.name] = { "status": container.status, "urls": container_urls, "last_accessed": last_accessed }
45+
46+
def stop_containers(self):
47+
for container_name in self.ondemand_containers.keys():
48+
if self.ondemand_containers[container_name]["status"] != "running":
49+
continue
50+
inactive_seconds = (datetime.now() - self.ondemand_containers[container_name]["last_accessed"]).total_seconds()
51+
if inactive_seconds < STOP_THRESHOLD:
52+
continue
53+
self.docker_client.containers.get(container_name).stop()
54+
logging.info(f"Stopped {container_name} after {STOP_THRESHOLD}s of inactivity")
55+
56+
def start_containers(self):
57+
with last_accessed_urls_lock:
58+
last_accessed_urls_combined = ",".join(last_accessed_urls)
59+
last_accessed_urls.clear()
60+
61+
for container_name in self.ondemand_containers.keys():
62+
accessed = False
63+
for ondemand_url in self.ondemand_containers[container_name]["urls"].split(","):
64+
if ondemand_url not in last_accessed_urls_combined:
65+
continue
66+
self.ondemand_containers[container_name]["last_accessed"] = datetime.now()
67+
accessed = True
68+
if not accessed or self.ondemand_containers[container_name]["status"] == "running":
69+
continue
70+
self.docker_client.containers.get(container_name).start()
71+
logging.info(f"Started {container_name}")
72+
self.ondemand_containers[container_name]["status"] = "running"
73+
74+
def run(self):
75+
while True:
76+
try:
77+
self.process_containers()
78+
self.start_containers()
79+
self.stop_containers()
80+
time.sleep(CONTAINER_QUERY_SLEEP)
81+
except Exception as e:
82+
logging.exception(e)
83+
84+
class LogReaderThread(threading.Thread):
85+
def __init__(self):
86+
super().__init__()
87+
self.daemon = True
88+
89+
def tail(self, f):
90+
f.seek(0,2)
91+
inode = os.fstat(f.fileno()).st_ino
92+
93+
while True:
94+
line = f.readline()
95+
if not line:
96+
time.sleep(LOG_READER_SLEEP)
97+
if os.stat(ACCESS_LOG_FILE).st_ino != inode:
98+
f.close()
99+
f = open(ACCESS_LOG_FILE, 'r')
100+
inode = os.fstat(f.fileno()).st_ino
101+
continue
102+
yield line
103+
104+
def run(self):
105+
while True:
106+
try:
107+
if not os.path.exists(ACCESS_LOG_FILE):
108+
time.sleep(1)
109+
continue
110+
111+
logfile = open(ACCESS_LOG_FILE, "r")
112+
for line in self.tail(logfile):
113+
for part in line.split():
114+
if not part.startswith("http"):
115+
continue
116+
with last_accessed_urls_lock:
117+
last_accessed_urls.add(part)
118+
break
119+
except Exception as e:
120+
logging.exception(e)
121+
time.sleep(1)
122+
123+
if __name__ == "__main__":
124+
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
125+
logging.basicConfig(filename=LOG_FILE,
126+
filemode='a',
127+
format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s',
128+
datefmt='%Y-%m-%d %H:%M:%S',
129+
level=logging.INFO)
130+
logging.info("Starting swag-ondemand...")
131+
132+
ContainerThread().start()
133+
LogReaderThread().start()
134+
135+
while True:
136+
time.sleep(1)

root/defaults/ondemand.conf

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
proxy_intercept_errors on;
2+
error_page 502 = @waking_up;
3+
location @waking_up {
4+
add_header Retry-After 1 always;
5+
default_type text/html;
6+
return 502 '<!DOCTYPE html>
7+
<html>
8+
<head>
9+
<title>Waking Up...</title>
10+
<meta http-equiv="refresh" content="1">
11+
<style>body{font-family:sans-serif;text-align:center;padding-top:50px;background-color:#1d2022;color:#ffffff;}</style>
12+
</head>
13+
<body>
14+
<h1>Application is sleeping</h1>
15+
<p>Please wait while it wakes up...</p>
16+
<p>This page will refresh automatically.</p>
17+
</body>
18+
</html>';
19+
}

root/etc/s6-overlay/s6-rc.d/init-mod-imagename-modname-add-package/run

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

root/etc/s6-overlay/s6-rc.d/init-mod-imagename-modname-add-package/up

Lines changed: 0 additions & 1 deletion
This file was deleted.

root/etc/s6-overlay/s6-rc.d/init-mod-imagename-modname-install/run

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

root/etc/s6-overlay/s6-rc.d/init-mod-imagename-modname-install/type

Lines changed: 0 additions & 1 deletion
This file was deleted.

0 commit comments

Comments
 (0)