16 changed files with 324 additions and 72 deletions
+3 -3
View File
@@ -1,8 +1,8 @@
API_PORT=3671
MONGO_INITDB_ROOT_PASSWORD=pass
MONGODB_URI=mongodb://theplug:pass@mongodb:27017/theplug?authSource=admin
MONGO_INITDB_ROOT_PASSWORD=change-this-mongo-password
MONGODB_URI=mongodb://theplug:change-this-mongo-password@localhost:27017/theplug?authSource=admin
MONGODB_DB_NAME=theplug
REDIS_URL=redis://redis:6379
REDIS_URL=redis://localhost:6379
JWT_SECRET_KEY=change-this-secret
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=30
-32
View File
@@ -1,32 +0,0 @@
name: Build and Push to Registry
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
container: catthehacker/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Login to Gitea Registry
uses: docker/login-action@v3
with:
registry: git.reloia.uk
username: reloia
password: ${{ secrets.LOGIN_TOKEN }}
- name: Build and Push (Shell)
run: |
IMAGE_NAME="git.reloia.uk/reloia/theplug:latest"
echo "Building $IMAGE_NAME..."
docker build -t "$IMAGE_NAME" .
echo "Pushing $IMAGE_NAME..."
docker push "$IMAGE_NAME"
+26
View File
@@ -0,0 +1,26 @@
FROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONPATH=/app/app
WORKDIR /app
COPY pyproject.toml ./
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir \
"authlib>=1.6.0" \
"fastapi[standard]>=0.135.3" \
"motor>=3.7.1" \
"pwdlib[argon2,bcrypt]>=0.3.0" \
"pydantic>=2.12.5" \
"pydantic-settings>=2.13.1" \
"pyyaml>=6.0.3" \
"redis>=7.4.0"
COPY app ./app
EXPOSE 3671
CMD ["sh", "-c", "fastapi run /app/app/main.py --host 0.0.0.0 --port ${API_PORT:-3671}"]
+7 -1
View File
@@ -8,7 +8,13 @@ icona di una presa della spina idk
FastAPI + MongoDB + Redis
```
### Setup Dev
## Quick Setup (prod)
```bash
bash <(curl -s https://git.reloia.uk/reloia/thePlug/raw/branch/master/setup.sh)
```
## Setup Dev
imposta le variabili d'ambiente
View File
+14
View File
@@ -0,0 +1,14 @@
from fastapi import APIRouter, Depends, Request
from core.security import require_authenticated_user
router = APIRouter(
prefix="/services",
tags=["Services"],
dependencies=[Depends(require_authenticated_user)],
)
@router.get("")
async def get_services(request: Request):
return request.app.state.services
+13 -4
View File
@@ -1,3 +1,4 @@
import os
import sys
from contextlib import asynccontextmanager
from pathlib import Path
@@ -6,6 +7,7 @@ from fastapi import FastAPI
from api.auth.router import router as auth_router
from api.proxy.router import router as proxy_router
from api.services.router import router as services_router
from core.config import settings
from core.mongodb import close_mongodb, init_mongodb
from core.redis import close_redis, init_redis
@@ -30,10 +32,10 @@ async def lifespan(_: FastAPI):
app.state.services = get_all_services(home_dir) or []
if not app.state.services:
warning = (
"\n" + "!" * 60 + "\n"
" WARNING: No services found in home directory!\n"
f" Scanned: {home_dir}\n"
+ "!" * 60 + "\n"
"\n" + "!" * 60 + "\n"
" WARNING: No services found in home directory!\n"
f" Scanned: {home_dir}\n"
+ "!" * 60 + "\n"
)
print(warning, file=sys.stderr)
@@ -43,13 +45,20 @@ async def lifespan(_: FastAPI):
await close_redis()
await close_mongodb()
DEBUG = os.getenv("DEBUG", "false").lower() == "true"
app = FastAPI(
title="thePlugAPI",
lifespan=lifespan,
docs_url="/docs" if DEBUG else None,
redoc_url="/redoc" if DEBUG else None,
openapi_url="/openapi.json" if DEBUG else None,
)
app.include_router(auth_router)
app.include_router(proxy_router)
app.include_router(services_router)
@app.get("/")
+80
View File
@@ -0,0 +1,80 @@
services:
app:
build:
context: .
dockerfile: Dockerfile.test
container_name: theplug-app-test
restart: unless-stopped
env_file:
- .env
environment:
MONGODB_URI: mongodb://theplug:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017/${MONGO_DB:-theplug}?authSource=admin
MONGODB_DB_NAME: ${MONGO_DB:-theplug}
REDIS_URL: redis://redis:6379
API_PORT: ${API_PORT:-3671}
DEBUG: "true"
depends_on:
mongodb:
condition: service_healthy
redis:
condition: service_healthy
ports:
- "${API_PORT:-3671}:${API_PORT:-3671}"
volumes:
- ./example-http-one:/root/example-http-one:ro
- ./example-http-two:/root/example-http-two:ro
mongodb:
image: mongo:8.2
container_name: theplug-mongodb-test
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER:-theplug}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
MONGO_INITDB_DATABASE: ${MONGO_DB:-theplug}
ports:
- "27017:27017"
volumes:
- mongodb_test_data:/data/db
healthcheck:
test: ["CMD-SHELL", "mongosh --quiet --username ${MONGO_USER:-theplug} --password ${MONGO_INITDB_ROOT_PASSWORD} --authenticationDatabase admin --eval \"db.adminCommand({ ping: 1 }).ok\" | grep 1"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
redis:
image: redis:8-alpine
container_name: theplug-redis-test
restart: unless-stopped
command: ["redis-server", "--appendonly", "yes"]
ports:
- "6379:6379"
volumes:
- redis_test_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 5s
example-http-one:
build:
context: ./example-http-one
container_name: theplug-example-http-one
restart: unless-stopped
ports:
- "18081:8080"
example-http-two:
build:
context: ./example-http-two
container_name: theplug-example-http-two
restart: unless-stopped
ports:
- "18082:8080"
volumes:
mongodb_test_data:
redis_test_data:
+2 -31
View File
@@ -1,47 +1,18 @@
services:
api:
build:
context: .
dockerfile: Dockerfile
container_name: theplug-api
restart: unless-stopped
ports:
- "${API_PORT:-3671}:3671"
environment:
MONGODB_URI: mongodb://${MONGO_USER:-theplug}:${MONGO_PASSWORD:-theplug_dev_password}@mongodb:27017/${MONGO_DB:-theplug}?authSource=admin
MONGODB_DB_NAME: ${MONGO_DB:-theplug}
REDIS_URL: redis://redis:6379/0
JWT_SECRET_KEY: ${JWT_SECRET_KEY:-change-this-secret}
JWT_ALGORITHM: ${JWT_ALGORITHM:-HS256}
JWT_EXPIRE_MINUTES: ${JWT_EXPIRE_MINUTES:-30}
AUTH_USERNAME: ${AUTH_USERNAME:-admin}
AUTH_PASSWORD: ${AUTH_PASSWORD:-change-this-password}
depends_on:
mongodb:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:3671/').read()\""]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
mongodb:
image: mongo:8.2
container_name: theplug-mongodb
restart: unless-stopped
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER:-theplug}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD:-pass}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
MONGO_INITDB_DATABASE: ${MONGO_DB:-theplug}
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
healthcheck:
test: ["CMD-SHELL", "mongosh --quiet --username ${MONGO_USER:-theplug} --password ${MONGO_PASSWORD:-theplug_dev_password} --authenticationDatabase admin --eval \"db.adminCommand({ ping: 1 }).ok\" | grep 1"]
test: ["CMD-SHELL", "mongosh --quiet --username ${MONGO_USER:-theplug} --password ${MONGO_INITDB_ROOT_PASSWORD} --authenticationDatabase admin --eval \"db.adminCommand({ ping: 1 }).ok\" | grep 1"]
interval: 10s
timeout: 5s
retries: 5
+9
View File
@@ -0,0 +1,9 @@
FROM python:3.14-slim
WORKDIR /srv/www
COPY index.html ./
EXPOSE 8080
CMD ["python", "-m", "http.server", "8080", "--bind", "0.0.0.0", "--directory", "/srv/www"]
+6
View File
@@ -0,0 +1,6 @@
services:
web:
build: .
container_name: example-http-one
ports:
- "18081:8080"
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example HTTP One</title>
</head>
<body>
<h1>Example HTTP One</h1>
<p>This container serves a static page with Python's http.server.</p>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
FROM python:3.14-slim
WORKDIR /srv/www
COPY index.html ./
EXPOSE 8080
CMD ["python", "-m", "http.server", "8080", "--bind", "0.0.0.0", "--directory", "/srv/www"]
+6
View File
@@ -0,0 +1,6 @@
services:
web:
build: .
container_name: example-http-two
ports:
- "18082:8080"
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example HTTP Two</title>
</head>
<body>
<h1>Example HTTP Two</h1>
<p>This container serves a static page with Python's http.server.</p>
</body>
</html>
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env bash
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
info() { echo -e "${GREEN}[+]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
die() { echo -e "${RED}[✗] FATAL:${NC} $*" >&2; exit 1; }
install_service() {
local uv_bin
uv_bin=$(command -v uv)
local api_port
api_port=$(grep -E '^API_PORT=' .env 2>/dev/null | cut -d '=' -f2)
api_port=${api_port:-3671}
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/theplug.service <<EOF
[Unit]
Description=thePlug service
After=network.target
[Service]
WorkingDirectory=/srv/theplug
EnvironmentFile=/srv/theplug/.env
Environment=PYTHONPATH=app
ExecStartPre=/usr/bin/docker compose -f /srv/theplug/compose.yml up -d redis mongodb
ExecStart=$uv_bin run uvicorn app.main:app --host 0.0.0.0 --port $api_port
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable theplug
info "systemd user service installed (port $api_port)"
}
start_services() {
info "Starting Redis and MongoDB..."
docker compose up -d redis mongodb || die "docker compose failed — are Redis/MongoDB defined in compose.yml?"
info "Starting thePlug via systemctl..."
systemctl --user start theplug
warn "Use 'systemctl --user status theplug' to check / 'journalctl --user -u theplug -f' to follow logs"
}
# ── 1. ensure we're in thePlug ────────────────────────────────────────────────
if [[ -d "/srv/theplug" ]]; then
info "thePlug già presente — avvio diretto..."
cd /srv/theplug
start_services
exit 0
fi
cd /srv
git clone https://git.reloia.uk/reloia/thePlug theplug || die "git clone failed"
cd theplug
chmod +x ./setup.sh
PLUG_DIR="$(pwd)"
if [[ ! -L /usr/bin/theplug ]]; then
info "Creating symlink /usr/bin/theplug..."
sudo ln -sf "$PLUG_DIR/setup.sh" /usr/bin/theplug
sudo chmod +x /usr/bin/theplug
fi
# 2 env
if [[ ! -f .env ]]; then
warn ".env not found — copyinh from .env.example with random stuff..."
cp .env.example .env || die ".env.example not found (impossibile)"
MONGO_PASS=$(openssl rand -hex 8)
JWT_SECRET=$(openssl rand -hex 20)
AUTH_PASS=$(openssl rand -hex 10)
sed -i "s|^MONGO_INITDB_ROOT_PASSWORD=.*|MONGO_INITDB_ROOT_PASSWORD=$MONGO_PASS|" .env
sed -i "s|^MONGODB_URI=.*|MONGODB_URI=mongodb://theplug:$MONGO_PASS@localhost:27017/theplug?authSource=admin|" .env
sed -i "s|^JWT_SECRET_KEY=.*|JWT_SECRET_KEY=$JWT_SECRET|" .env
sed -i "s|^AUTH_PASSWORD=.*|AUTH_PASSWORD=$AUTH_PASS|" .env
info "Resetting docker containers..."
docker compose down -v 2>/dev/null || true
fi
# ── 3. spin up dependencies ───────────────────────────────────────────────────
info "Starting Redis and MongoDB..."
docker compose up -d redis mongodb || die "docker compose failed — are Redis/MongoDB defined in compose.yml?"
# ── 4. ensure uv is available ─────────────────────────────────────────────────
if ! command -v uv &>/dev/null; then
warn "uv not found — installing..."
curl -LsSf https://astral.sh/uv/install.sh | sh || die "uv installation failed"
export PATH="$HOME/.local/bin:$PATH"
command -v uv &>/dev/null || die "uv installed but still not in PATH — open a new shell and retry"
info "uv installed: $(uv --version)"
fi
# ── 5. venv + deps ────────────────────────────────────────────────────────────
info "Pinning Python 3.14..."
uv python pin 3.14
info "Creating venv..."
uv venv
info "Syncing dependencies..."
uv sync
# ── 6. install service + start ────────────────────────────────────────────────
install_service
systemctl --user start theplug
echo -e ""
info "Automatically generated Secrets:"
info " MONGO_PASS: $MONGO_PASS"
info " JWT_SECRET: $JWT_SECRET"
info " AUTH_PASS: $AUTH_PASS - questa è importante"
warn "Save them — these won't be showed again (non è vero basta che leggi $PLUG_DIR/.env)"
echo -e ""
info "Installed thePlug in $PLUG_DIR"
warn "Use 'systemctl --user status theplug' to check / 'journalctl --user -u theplug -f' to follow logs"
echo -e ""