Skip to content

Commit f9a8b10

Browse files
committed
Initial
1 parent 6360fcf commit f9a8b10

File tree

25 files changed

+253
-100
lines changed

25 files changed

+253
-100
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: 71 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,78 @@
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.
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* - In SWAG's docker arguments, set an environment variable `SWAG_ONDEMAND_STOP_THRESHOLD` to override the period of inactivity in seconds before stopping the container. Defaults to `600` which is 10 minutes.
28+
```yaml
29+
swag:
30+
container_name: swag
31+
...
32+
environment:
33+
- SWAG_ONDEMAND_STOP_THRESHOLD=600
34+
```
35+
### Loading Page:
636

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`
37+
![loading-page](.assets/loading-page.png)
838

9-
# Mod creation instructions
39+
Instead of showing a 502 error page, it can display a loading page and auto-refresh once the container is up.
40+
41+
Add the following `include` to each proxy-conf where you wish to show the loading page inside the `server` section:
42+
```nginx
43+
server {
44+
...
45+
include /config/nginx/ondemand.conf;
46+
...
47+
```
48+
### Labels:
49+
- `swag_ondemand=enable` - required for on-demand.
50+
- `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.`.
1051

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.
52+
### URLs:
53+
- 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`.
54+
- `swag_ondemand_urls` default to `https://somecontainer.,http://somecontainer.`, for example `https://plex.,http://plex.`.
55+
- `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`.
56+
- The same URL can be set on multiple containers and all of them will be started when accessing that URL.
1957

58+
## Security Consideration:
59+
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.
2060

21-
## Tips and tricks
22-
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)
61+
Here's a sample compose yaml snippet for `linuxserver/docker-socket-proxy`:
62+
```yaml
63+
socket-proxy:
64+
image: lscr.io/linuxserver/socket-proxy:latest
65+
container_name: socket-proxy
66+
environment:
67+
- ALLOW_START=1
68+
- ALLOW_STOP=1
69+
- CONTAINERS=1
70+
- POST=0
71+
volumes:
72+
- /var/run/docker.sock:/var/run/docker.sock:ro
73+
restart: unless-stopped
74+
read_only: true
75+
tmpfs:
76+
- /run
77+
```
78+
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: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
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+
STOP_THRESHOLD = int(os.environ.get("SWAG_ONDEMAND_STOP_THRESHOLD", "600"))
11+
12+
last_accessed_urls = set()
13+
last_accessed_urls_lock = threading.Lock()
14+
15+
class ContainerThread(threading.Thread):
16+
def __init__(self):
17+
super().__init__()
18+
self.daemon = True
19+
self.ondemand_containers = {}
20+
try:
21+
self.docker_client = docker.from_env()
22+
except Exception as e:
23+
logging.exception(e)
24+
25+
def process_containers(self):
26+
containers = self.docker_client.containers.list(all=True, filters={ "label": ["swag_ondemand=enable"] })
27+
container_names = {container.name for container in containers}
28+
29+
for container_name in list(self.ondemand_containers.keys()):
30+
if container_name in container_names:
31+
continue
32+
self.ondemand_containers.pop(container_name)
33+
logging.info(f"Stopped monitoring {container_name}")
34+
35+
for container in containers:
36+
container_urls = container.labels.get("swag_ondemand_urls", f"https://{container.name}.,http://{container.name}.")
37+
if container.name not in self.ondemand_containers.keys():
38+
last_accessed = datetime.now()
39+
logging.info(f"Started monitoring {container.name}")
40+
else:
41+
last_accessed = self.ondemand_containers[container.name]["last_accessed"]
42+
self.ondemand_containers[container.name] = { "status": container.status, "urls": container_urls, "last_accessed": last_accessed }
43+
44+
def stop_containers(self):
45+
for container_name in self.ondemand_containers.keys():
46+
if self.ondemand_containers[container_name]["status"] != "running":
47+
continue
48+
inactive_seconds = (datetime.now() - self.ondemand_containers[container_name]["last_accessed"]).total_seconds()
49+
if inactive_seconds < STOP_THRESHOLD:
50+
continue
51+
self.docker_client.containers.get(container_name).stop()
52+
logging.info(f"Stopped {container_name} after {STOP_THRESHOLD}s of inactivity")
53+
54+
def start_containers(self):
55+
with last_accessed_urls_lock:
56+
last_accessed_urls_combined = ",".join(last_accessed_urls)
57+
last_accessed_urls.clear()
58+
59+
for container_name in self.ondemand_containers.keys():
60+
accessed = False
61+
for ondemand_url in self.ondemand_containers[container_name]["urls"].split(","):
62+
if ondemand_url not in last_accessed_urls_combined:
63+
continue
64+
self.ondemand_containers[container_name]["last_accessed"] = datetime.now()
65+
accessed = True
66+
if not accessed or self.ondemand_containers[container_name]["status"] == "running":
67+
continue
68+
self.docker_client.containers.get(container_name).start()
69+
logging.info(f"Started {container_name}")
70+
self.ondemand_containers[container_name]["status"] = "running"
71+
72+
def run(self):
73+
while True:
74+
try:
75+
self.process_containers()
76+
self.start_containers()
77+
self.stop_containers()
78+
time.sleep(5)
79+
except Exception as e:
80+
logging.exception(e)
81+
82+
class LogReaderThread(threading.Thread):
83+
def __init__(self):
84+
super().__init__()
85+
self.daemon = True
86+
87+
def tail(self, f):
88+
f.seek(0,2)
89+
inode = os.fstat(f.fileno()).st_ino
90+
91+
while True:
92+
line = f.readline()
93+
if not line:
94+
time.sleep(1)
95+
if os.stat(ACCESS_LOG_FILE).st_ino != inode:
96+
f.close()
97+
f = open(ACCESS_LOG_FILE, 'r')
98+
inode = os.fstat(f.fileno()).st_ino
99+
continue
100+
yield line
101+
102+
def run(self):
103+
while True:
104+
try:
105+
if not os.path.exists(ACCESS_LOG_FILE):
106+
time.sleep(1)
107+
continue
108+
109+
logfile = open(ACCESS_LOG_FILE, "r")
110+
for line in self.tail(logfile):
111+
for part in line.split():
112+
if not part.startswith("http"):
113+
continue
114+
with last_accessed_urls_lock:
115+
last_accessed_urls.add(part)
116+
break
117+
except Exception as e:
118+
logging.exception(e)
119+
time.sleep(1)
120+
121+
if __name__ == "__main__":
122+
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
123+
logging.basicConfig(filename=LOG_FILE,
124+
filemode='a',
125+
format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s',
126+
datefmt='%Y-%m-%d %H:%M:%S',
127+
level=logging.INFO)
128+
logging.info("Starting swag-ondemand...")
129+
130+
ContainerThread().start()
131+
LogReaderThread().start()
132+
133+
while True:
134+
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 5 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="5">
11+
<style>body{font-family:sans-serif;text-align:center;padding-top:50px;background-color:#303030;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)