Merge feature/first-stack-display into dev

This commit is contained in:
2025-08-17 14:05:58 +00:00
18 changed files with 4568 additions and 149 deletions
-104
View File
@@ -1,104 +0,0 @@
# 📦 StackPulse
**StackPulse** ist eine kleine Web-App, die über die Portainer-API deine Docker-Stacks verwaltet und aktualisiert.
Sie besteht aus einem **Backend (Node.js/Express)** und einem **Frontend (React/Tailwind)**.
Ziel:
- Übersicht über alle Stacks in deiner Portainer-Instanz
- Später: Updates, Deployments und Monitoring
- Bereitstellung als **Docker Image**, nutzbar über **docker-compose**
---
## 🚀 Features (0.1 Roadmap)
- [x] Projektstruktur mit Frontend & Backend
- [x] Lokales Startskript (`scripts/start-dev.sh`)
- [ ] Frontend zeigt Stacks an (über Backend)
- [ ] API-Verbindung zu Portainer
- [ ] Docker-Image bauen & per Compose deployen
---
## 🗂️ Projektstruktur
```bash
stackpulse/
├── backend/ # Node.js Backend mit Express
├── frontend/ # React Frontend mit Tailwind
├── scripts/ # Lokale Hilfsskripte (nicht Teil des Images)
│ ├── start-dev.sh
│ └── create-structure.sh
├── Dockerfile # Multi-Stage Build für Frontend + Backend
├── docker-compose.yml
└── README.md
```
---
## 🔧 Lokale Entwicklung
### 1. Dev-Server starten (Frontend + Backend)
```bash
./scripts/start-dev.sh
```
➡️ Danach:
- Frontend → http://localhost:5173
- Backend → http://localhost:3000
---
## 🐳 Docker-Setup
### Image bauen
```bash
docker build -t stackpulse:dev .
```
### Mit Compose starten
```bash
docker-compose up -d
```
---
## 🌳 Git-Workflow
- `master` → Release-Branch
- `dev` → Entwicklung & Integration
- `feature/*` → einzelne Features
**Ablauf:**
1. Feature-Branch anlegen (`git checkout -b feature/...`)
2. Entwicklung & lokaler Test
3. Merge → `dev` (Review/Test)
4. Merge → `master` für Release (z. B. `v0.1`)
---
## 📦 Release
1. Alles auf `master` mergen
2. Tag setzen:
```bash
git tag -a v0.1 -m "First release"
git push origin v0.1
```
3. Docker-Image bauen & pushen (optional GitHub Container Registry / Docker Hub)
---
## 📋 Voraussetzungen
- Node.js >= 20
- Docker & Docker Compose
- Zugang zu einer Portainer-Instanz (API-Key erforderlich)
---
## 🤝 Mitmachen
1. Repo forken
2. Feature-Branch erstellen
3. PR gegen `dev` öffnen
+114 -9
View File
@@ -1,16 +1,121 @@
const express = require("express");
const axios = require("axios");
const app = express();
const PORT = 3000;
import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
app.get("/api/stacks", async (req, res) => {
dotenv.config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 4000;
const PORTAINER_URL = process.env.PORTAINER_URL;
const PORTAINER_API_KEY = process.env.PORTAINER_API_KEY;
console.log("PORTAINER_API_KEY:", PORTAINER_API_KEY);
// Root-Endpoint
app.get('/', (req, res) => {
res.send('StackPulse Backend läuft. Nutze /api/stacks für die Daten.');
});
// Alle Stacks abrufen und Status prüfen
app.get('/api/stacks', async (req, res) => {
try {
res.json([{ name: "stack1" }, { name: "stack2" }]);
const stacksRes = await axios.get(`${PORTAINER_URL}/api/stacks`, {
headers: { 'X-API-Key': PORTAINER_API_KEY }
});
const stacksWithStatus = await Promise.all(
stacksRes.data.map(async (stack) => {
try {
const statusRes = await axios.get(
`${PORTAINER_URL}/api/stacks/${stack.Id}/images_status?refresh=true`,
{ headers: { 'X-API-Key': PORTAINER_API_KEY } }
);
let statusEmoji = '✅';
if (statusRes.data.Status === 'outdated') statusEmoji = '⚠️';
return { ...stack, updateStatus: statusEmoji };
} catch (err) {
console.error(`Fehler beim Abrufen Remote Digest für Stack ${stack.Id}:`, err.message);
return { ...stack, updateStatus: '❌' };
}
})
);
stacksWithStatus.sort((a, b) => a.Name.localeCompare(b.Name));
res.json(stacksWithStatus);
} catch (err) {
res.status(500).json({ error: err.message });
console.error('Fehler beim Abrufen der Stacks:', err.message);
if (err.response) res.status(err.response.status).json(err.response.data);
else res.status(500).json({ error: err.message });
}
});
app.listen(PORT, () => {
console.log(\`Backend läuft auf http://localhost:\${PORT}\`);
// Redeploy eines Stacks (alle Typen)
app.put('/api/stacks/:id/redeploy', async (req, res) => {
const { id } = req.params;
try {
const stackRes = await axios.get(`${PORTAINER_URL}/api/stacks/${id}`, {
headers: { 'X-API-Key': PORTAINER_API_KEY }
});
const stack = stackRes.data;
if (stack.Type === 1) {
await axios.put(
`${PORTAINER_URL}/api/stacks/${id}/git/redeploy?endpointId=${stack.EndpointId}`,
{},
{ headers: { 'X-API-Key': PORTAINER_API_KEY } }
);
return res.json({ success: true, message: 'Git Stack redeployed' });
} else if (stack.Type === 2) {
const fileRes = await axios.get(`${PORTAINER_URL}/api/stacks/${id}/file`, {
headers: { 'X-API-Key': PORTAINER_API_KEY }
});
const stackFileContent = fileRes.data?.StackFileContent;
if (!stackFileContent) return res.status(500).json({ error: 'Stack file konnte nicht geladen werden' });
const services = fileRes.data?.Config?.services || {};
for (const serviceName in services) {
const imageName = services[serviceName].image;
if (!imageName) continue;
try {
await axios.post(
`${PORTAINER_URL}/api/endpoints/${stack.EndpointId}/docker/images/create?fromImage=${encodeURIComponent(imageName)}`,
{},
{ headers: { 'X-API-Key': PORTAINER_API_KEY } }
);
} catch (pullErr) {
console.error(`Fehler beim Pull von ${imageName}:`, pullErr.message);
}
}
await axios.put(
`${PORTAINER_URL}/api/stacks/${id}?endpointId=${stack.EndpointId}`,
{
StackFileContent: stackFileContent,
Prune: false,
PullImage: true
},
{ headers: { 'X-API-Key': PORTAINER_API_KEY } }
);
return res.json({ success: true, message: 'Compose/Local Stack redeployed' });
} else {
return res.status(400).json({ error: 'Unbekannter oder noch nicht unterstützter Stack-Typ' });
}
} catch (err) {
console.error('Redeploy fehlgeschlagen:', err.response?.data || err.message);
res.status(err.response?.status || 500).json({ success: false, error: err.message });
}
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Backend läuft auf http://0.0.0.0:${PORT}`);
});
+33
View File
@@ -0,0 +1,33 @@
import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 4000;
const PORTAINER_URL = process.env.PORTAINER_URL;
const PORTAINER_API_KEY = process.env.PORTAINER_API_KEY;
console.log("PORTAINER_API_KEY:", PORTAINER_API_KEY);
// Root-Endpoint
app.get('/', (req, res) => {
res.send('StackPulse Backend läuft. Nutze /stacks für die Daten.');
});
app.get('/api/stacks', async (req, res) => {
try {
const url = `${PORTAINER_URL}/api/stacks`;
console.log("Request URL:", url);
const response = await axios.get(url,{headers: { 'X-API-Key': PORTAINER_API_KEY}
});
res.json(response.data);
} catch (err) {
console.error('Fehler:', err.message); if (err.response) { console.error('Status:', err.response.status); console.error('Data:', err.response.data); res.status(err.response.status).json(err.response.data);
} else {
res.status(500).json({ error: err.message });
}
}
});
app.listen(PORT, '0.0.0.0', () => { console.log(`Backend läuft auf http://0.0.0.0:${PORT}`);
});
+23
View File
@@ -0,0 +1,23 @@
import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 4000; // <- Port geändert
const PORTAINER_URL = process.env.PORTAINER_URL;
const PORTAINER_TOKEN = process.env.PORTAINER_TOKEN;
app.get('/stacks', async (req, res) => {
try { const response = await axios.get(`${PORTAINER_URL}/stacks`, { headers: {
'Authorization': `Bearer ${PORTAINER_TOKEN}` }
});
res.json(response.data);
} catch (err) {
console.error(err); res.status(500).json({ error: 'Fehler beim Abrufen der Stacks' });
}
});
app.listen(PORT, '0.0.0.0', () => { console.log(`Backend läuft auf
http://0.0.0.0:${PORT}`);
});
+1486
View File
File diff suppressed because it is too large Load Diff
+1 -12
View File
@@ -1,12 +1 @@
{
"name": "stackpulse-backend",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2",
"axios": "^1.7.5"
}
}
{"name":"backend","version":"1.0.0","type":"module","scripts":{"start":"node index.js"},"dependencies":{"axios":"^1.7.0","dockerode":"^4.0.7","dotenv":"^16.0.0","express":"^4.18.0"}}
+2721
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -7,15 +7,15 @@
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"axios": "^1.7.5"
"react-dom": "^18.2.0"
},
"devDependencies": {
"vite": "^4.4.9",
"@vitejs/plugin-react": "^4.0.0",
"tailwindcss": "^3.3.3",
"postcss": "^8.4.26",
"autoprefixer": "^10.4.14"
"autoprefixer": "^10.4.21",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"vite": "^4.4.9"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+4 -14
View File
@@ -1,21 +1,11 @@
import React, { useEffect, useState } from "react";
import axios from "axios";
import React from "react";
import Stacks from "./Stacks";
function App() {
const [stacks, setStacks] = useState([]);
useEffect(() => {
axios.get("/api/stacks").then(res => setStacks(res.data));
}, []);
return (
<div className="p-6">
<div className="min-h-screen bg-gray-100 p-6">
<h1 className="text-2xl font-bold mb-4">StackPulse</h1>
<ul className="list-disc pl-5">
{stacks.map((stack, i) => (
<li key={i}>{stack.name}</li>
))}
</ul>
<Stacks />
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function Stacks() {
const [stacks, setStacks] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const fetchStacks = async () => {
try {
const res = await axios.get("/api/stacks");
const sortedStacks = res.data.sort((a, b) => a.Name.localeCompare(b.Name));
setStacks(sortedStacks);
} catch (err) {
console.error("❌ Fehler beim Abrufen der Stacks:", err);
setError("Fehler beim Laden der Stacks");
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchStacks();
}, []);
const handleRedeploy = async (stackId) => {
try {
const confirmRedeploy = window.confirm("Willst du den Stack wirklich redeployen?");
if (!confirmRedeploy) return;
const res = await axios.put(`/api/stacks/${stackId}/redeploy`);
if (res.data.success) {
alert("✅ Stack erfolgreich redeployed!");
fetchStacks(); // Optional: Stacks neu laden
} else {
alert("⚠️ Redeploy fehlgeschlagen: " + res.data.error);
}
} catch (err) {
console.error("❌ Fehler beim Redeploy:", err);
alert("⚠️ Redeploy fehlgeschlagen: " + err.message);
}
};
if (loading) return <p className="text-gray-600">Lade Stacks...</p>;
if (error) return <p className="text-red-500">{error}</p>;
return (
<ul className="space-y-4">
{stacks.map((stack) => (
<li
key={stack.Id}
className="p-4 bg-white rounded-xl shadow hover:shadow-md transition flex justify-between items-center"
>
<div className="flex items-center space-x-4">
<div className="text-xl">{stack.updateStatus}</div>
<div>
<p className="text-lg font-semibold text-gray-800">{stack.Name}</p>
<p className="text-sm text-gray-500">ID: {stack.Id}</p>
</div>
</div>
<button
onClick={() => handleRedeploy(stack.Id)}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition"
>
Redeploy
</button>
</li>
))}
{stacks.length === 0 && <p className="text-gray-500">Keine Stacks gefunden.</p>}
</ul>
);
}
+48
View File
@@ -0,0 +1,48 @@
import React, { useEffect, useState } from "react";
import axios from "axios";
export default function Stacks() {
const [stacks, setStacks] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const fetchStacks = async () => {
try {
const res = await axios.get("/api/stacks"); // Vite-Proxy auf Backend
const sortedStacks = res.data.sort((a, b) => a.Name.localeCompare(b.Name));
setStacks(sortedStacks);
} catch (err) {
console.error("❌ Fehler beim Abrufen der Stacks:", err);
setError("Fehler beim Laden der Stacks");
} finally {
setLoading(false);
}
};
fetchStacks();
}, []);
if (loading) return <p className="text-gray-600">Lade Stacks...</p>;
if (error) return <p className="text-red-500">{error}</p>;
return (
<ul className="space-y-4">
{stacks.map((stack) => (
<li
key={stack.Id}
className="p-4 bg-white rounded-xl shadow hover:shadow-md transition flex justify-between items-center"
>
<div>
<p className="text-lg font-semibold text-gray-800">{stack.Name}</p>
<p className="text-sm text-gray-500">ID: {stack.Id}</p>
</div>
<div className="text-2xl">
{stack.Updated ? "✅" : "⚠️"}
</div>
</li>
))}
{stacks.length === 0 && <p className="text-gray-500">Keine Stacks gefunden.</p>}
</ul>
);
}
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+1
View File
@@ -1,6 +1,7 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import './index.css' // <-- Tailwind CSS hier einbinden
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
+10
View File
@@ -0,0 +1,10 @@
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
+8 -3
View File
@@ -4,9 +4,14 @@ import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
host: true,
port: 5173,
proxy: {
"/api": "http://localhost:3000"
}
}
"/api": {
target: "http://localhost:4000", // dein Backend
changeOrigin: true,
},
},
},
});
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
set -e
# Aktuellen Branch herausfinden
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Branch bestätigen
read -p "📂 Aktueller Branch: $BRANCH. Ist das korrekt? (y/n): " CONFIRM
if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
echo "❌ Abgebrochen."
exit 1
fi
# Interaktive Eingabe der Commit-Nachricht
read -p "📝 Bitte Commit-Nachricht eingeben (default: 'Update'): " COMMIT_MSG
# Wenn leer, default setzen
if [ -z "$COMMIT_MSG" ]; then
COMMIT_MSG="Update"
fi
echo " Änderungen werden gestaged..."
git add .
echo "📝 Commit wird erstellt..."
git commit -m "$COMMIT_MSG" || echo "⚠️ Nichts zu committen"
echo "🚀 Push nach origin/$BRANCH..."
git push origin "$BRANCH"
echo "✅ Push abgeschlossen!"
+1 -1
View File
@@ -18,7 +18,7 @@ cd ..
echo ""
echo "✅ StackPulse läuft lokal:"
echo "Frontend: http://localhost:5173"
echo "Backend: http://localhost:3000"
echo "Backend: http://localhost:4000"
echo "Beenden mit STRG+C"
wait $BACK_PID $FRONT_PID