Skip to content

Commit aa75bb0

Browse files
committed
Initial
1 parent 6360fcf commit aa75bb0

File tree

23 files changed

+188
-100
lines changed

23 files changed

+188
-100
lines changed

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: 63 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,70 @@
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+
## Requirements:
6+
- This mod needs the [universal-docker mod](https://github.com/linuxserver/docker-mods/tree/universal-docker) installed and set up with either mapping `docker.sock` or setting the environment variable `DOCKER_HOST=remoteaddress`.
7+
- On-demand containers must have a label `swag_ondemand=enable` at a minimum.
68

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`
9+
## Setup:
10+
- In SWAG's docker arguments, set an environment variable `DOCKER_MODS=linuxserver/mods:universal-docker|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).
11+
- Add the label `swag_ondemand=enable` to on-demand containers.
12+
```yaml
13+
somecontainer:
14+
container_name: somecontainer
15+
...
16+
labels:
17+
- swag_ondemand=enable
18+
```
19+
- Replace the following line in `/config/nginx/nginx.conf`:
20+
```nginx
21+
access_log /config/log/nginx/access.log;
22+
```
23+
With:
24+
```nginx
25+
log_format main '$remote_addr - $remote_user [$time_local] '
26+
'"$request_method $scheme://$host$request_uri $server_protocol" '
27+
'$status $body_bytes_sent '
28+
'"$http_referer" "$http_user_agent"';
29+
access_log /config/log/nginx/access.log main;
30+
```
31+
- *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 `1800` which is 30 minutes.
32+
```yaml
33+
swag:
34+
container_name: swag
35+
...
36+
environment:
37+
- SWAG_ONDEMAND_STOP_THRESHOLD=1800
38+
```
839

9-
# Mod creation instructions
40+
## Labels:
41+
- `swag_ondemand=enable` - required for on-demand.
42+
- `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.`.
1043

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.
44+
## URLs:
45+
- Accessed URLs need to start with one of `swag_ondemand_urls` to be matched, for example, setting `https://plex.` will apply to `https://plex.domain.com` and `https://plex.domain.com/something`.
46+
- `swag_ondemand_urls` default to `https://somecontainer.,http://somecontainer.`, for example `https://plex.,http://plex.`.
47+
- `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`.
48+
- The same URL can be set on multiple containers and all of them will be started when accessing that URL.
1949

50+
## Security Consideration:
51+
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.
2052

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)
53+
Here's a sample compose yaml snippet for linuxserver/docker-socket-proxy:
54+
```yaml
55+
socket-proxy:
56+
image: lscr.io/linuxserver/socket-proxy:latest
57+
container_name: socket-proxy
58+
environment:
59+
- ALLOW_START=1
60+
- ALLOW_STOP=1
61+
- CONTAINERS=1
62+
- POST=1
63+
volumes:
64+
- /var/run/docker.sock:/var/run/docker.sock:ro
65+
restart: unless-stopped
66+
read_only: true
67+
tmpfs:
68+
- /run
69+
```
70+
Then the env var in SWAG can be set as `DOCKER_HOST=socket-proxy`. This will allow docker cli in SWAG to be able to retrieve info on other containers, but it won't be allowed to spin up new containers.

app/swag-ondemand.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from datetime import datetime
2+
import docker
3+
import os
4+
import threading
5+
import time
6+
7+
last_accessed_urls = set()
8+
last_accessed_urls_lock = threading.Lock()
9+
ondemand_containers = {}
10+
ondemand_containers_lock = threading.Lock()
11+
stop_threshold = int(os.environ.get("SWAG_ONDEMAND_STOP_THRESHOLD", "1800"))
12+
13+
class ContainerThread(threading.Thread):
14+
def process_containers(self, docker_client):
15+
global ondemand_containers
16+
containers = docker_client.containers.list(all=True, filters={ "label": ["swag_ondemand=enable"] })
17+
container_names = {container.name for container in containers}
18+
19+
for container_name in list(ondemand_containers.keys()):
20+
if container_name in container_names:
21+
continue
22+
ondemand_containers.pop(container_name)
23+
print(f"{datetime.now()} - Stopped monitoring {container_name}")
24+
25+
for container in containers:
26+
container_urls = container.labels.get("swag_ondemand_urls", f"https://{container.name}.,http://{container.name}.")
27+
if container.name not in ondemand_containers.keys():
28+
last_accessed = datetime.now()
29+
print(f"{datetime.now()} - Started monitoring {container.name}")
30+
else:
31+
last_accessed = ondemand_containers[container.name]["last_accessed"]
32+
ondemand_containers[container.name] = { "status": container.status, "urls": container_urls, "last_accessed": last_accessed }
33+
34+
def stop_containers(self, docker_client):
35+
global ondemand_containers
36+
37+
for container_name in ondemand_containers.keys():
38+
if ondemand_containers[container_name]["status"] != "running":
39+
continue
40+
inactive_seconds = (datetime.now() - ondemand_containers[container_name]["last_accessed"]).total_seconds()
41+
if inactive_seconds < stop_threshold:
42+
continue
43+
docker_client.containers.get(container_name).stop()
44+
print(f"{datetime.now()} - Stopped {container_name} after {stop_threshold}s of inactivity")
45+
46+
def start_containers(self, docker_client):
47+
global ondemand_containers
48+
last_accessed_urls_lock.acquire()
49+
last_accessed_urls_combined = ",".join(last_accessed_urls)
50+
last_accessed_urls.clear()
51+
last_accessed_urls_lock.release()
52+
53+
for container_name in ondemand_containers.keys():
54+
accessed = False
55+
for ondemand_url in ondemand_containers[container_name]["urls"].split(","):
56+
if ondemand_url not in last_accessed_urls_combined:
57+
continue
58+
ondemand_containers[container_name]["last_accessed"] = datetime.now()
59+
accessed = True
60+
if not accessed or ondemand_containers[container_name]["status"] == "running":
61+
continue
62+
docker_client.containers.get(container_name).start()
63+
print(f"{datetime.now()} - Started {container_name}")
64+
ondemand_containers[container_name]["status"] = "running"
65+
66+
def run(self):
67+
while True:
68+
docker_client = docker.from_env()
69+
with ondemand_containers_lock:
70+
self.process_containers(docker_client)
71+
self.start_containers(docker_client)
72+
self.stop_containers(docker_client)
73+
time.sleep(5)
74+
75+
class LogReaderThread(threading.Thread):
76+
logname = "/config/log/nginx/access.log"
77+
78+
def tail(self, f):
79+
f.seek(0,2)
80+
inode = os.fstat(f.fileno()).st_ino
81+
82+
while True:
83+
line = f.readline()
84+
if not line:
85+
time.sleep(1)
86+
if os.stat(self.logname).st_ino != inode:
87+
f.close()
88+
f = open(self.logname, 'r')
89+
inode = os.fstat(f.fileno()).st_ino
90+
continue
91+
yield line
92+
93+
def run(self):
94+
logfile = open(self.logname, "r")
95+
for line in self.tail(logfile):
96+
for part in line.split():
97+
if not part.startswith("http"):
98+
continue
99+
with last_accessed_urls_lock:
100+
last_accessed_urls.add(part)
101+
print(f"{datetime.now()} - Accessed {part}")
102+
break
103+
104+
ContainerThread().start()
105+
LogReaderThread().start()

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.

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

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

root/etc/s6-overlay/s6-rc.d/init-mod-imagename-modname-add-package/dependencies.d/init-mods renamed to root/etc/s6-overlay/s6-rc.d/init-mod-swag-ondemand-setup/dependencies.d/init-mod-universal-docker-setup

File renamed without changes.

0 commit comments

Comments
 (0)