Compare commits
6 Commits
fix/correc
...
fix/status
| Author | SHA1 | Date | |
|---|---|---|---|
| cb0d2c80cf | |||
| d593d3f0e2 | |||
| 66a6a8caf0 | |||
| 6aa85ac683 | |||
| 403bc91f33 | |||
| 0a73c5cb37 |
12
.env.example
12
.env.example
@@ -11,12 +11,12 @@ BACKUPS_REMOTE_ROOT=
|
||||
BACKUPS_MAX_FILES=
|
||||
|
||||
# Paramètres utilisés pour construire les commandes disque et backup
|
||||
DISK_REMOTE_HOST=malio-b
|
||||
DISK_LOCAL_SCRIPT_DIR=/home/malio/Malio-ops/CheckStorage
|
||||
DISK_REMOTE_SCRIPT_DIR=/home/malio-b/Malio-ops/CheckStorage
|
||||
RECETTE_SCRIPTS_DIR=/home/malio/Malio-ops/RecetteScripts
|
||||
VAULTWARDEN_SSH_HOST=bitwarden
|
||||
VAULTWARDEN_SCRIPTS_DIR=/home/matt/vaultwarden/Malio-ops/BackupVaultWarden
|
||||
DISK_REMOTE_HOST=
|
||||
DISK_LOCAL_SCRIPT_DIR=
|
||||
DISK_REMOTE_SCRIPT_DIR=
|
||||
RECETTE_SCRIPTS_DIR=
|
||||
VAULTWARDEN_SSH_HOST=
|
||||
VAULTWARDEN_SCRIPTS_DIR=
|
||||
|
||||
# A quelle heure les backups doivent être effectués (format 24h)
|
||||
BACKUPS_HOUR=19
|
||||
|
||||
4
.github/workflows/release.yml
vendored
4
.github/workflows/release.yml
vendored
@@ -21,4 +21,8 @@ jobs:
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- run: npm run lint
|
||||
|
||||
- run: npm run build
|
||||
|
||||
- run: npx semantic-release
|
||||
|
||||
15
README.md
15
README.md
@@ -22,7 +22,6 @@ Sur Linux, installer Docker et nvm.
|
||||
Suivre la documentation suivante :
|
||||
https://wiki.malio.fr/bookstack/books/environnement-de-dev/chapter/linux
|
||||
|
||||
### Installation du projet
|
||||
Une fois les prérequis installés, cloner le dépôt puis installer les dépendances.
|
||||
|
||||
Les étapes ci-dessous sont celles qui sont réellement supportées par le depot.
|
||||
@@ -63,11 +62,9 @@ Les variables visibles dans le depot sont :
|
||||
- `BACKUPS_REMOTE_HOST` : hôte SSH cible pour les operations distantes
|
||||
- `BACKUPS_REMOTE_ROOT` : dossier racine des sauvegardes sur l'hôte distant
|
||||
- `BACKUPS_MAX_FILES` : nombre maximal de fichiers retournés par dossier de backup
|
||||
- `DISK_COMMAND_REMOTE` : commande shell utilisée pour la verification disque distante
|
||||
- `DISK_COMMAND_LOCAL` : commande shell utilisée pour la verification disque locale
|
||||
- `BACKUP_SCRIPT_COMMAND_BACKUP_BDD_RECETTE` : commande a exécuter pour le script "Backup BDD recette"
|
||||
- `BACKUP_SCRIPT_COMMAND_CHECK_STATUT_RECETTE` : commande à exécuter pour le script "Check statut recette"
|
||||
- `BACKUP_SCRIPT_COMMAND_BACKUP_VAULTWARDEN` : commande à exécuter pour le script "Backup vault warden"
|
||||
- `DISK_REMOTE_HOST` : commande shell utilisée pour la verification disque distante
|
||||
- `DISK_REMOTE_SCRIPT_DIR` : dossier des scripts de vérification disque distante
|
||||
- `DISK_LOCAL_SCRIPT_DIR` : commande shell utilisée pour la verification disque locale
|
||||
- `BACKUPS_HOUR` : heure attendue des sauvegardes pour le contrôle de fraicheur
|
||||
|
||||
### 4. Installer les dépendances
|
||||
@@ -82,7 +79,7 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Par défaut, l'application Nuxt sera accessible sûr <http://localhost:3000>.
|
||||
Par défaut, l'application Nuxt sera accessible sur <http://localhost:3000>.
|
||||
|
||||
## Configuration necessaire
|
||||
|
||||
@@ -136,7 +133,7 @@ Usage :
|
||||
|
||||
- `npm run dev` : lance l'application en développement
|
||||
- `npm run build` : construit l'application pour la production
|
||||
- `npm run generate` : généré une sortie statique si ce mode est compatible avec votre usage
|
||||
- `npm run generate` : generee une sortie statique si ce mode est compatible avec votre usage
|
||||
- `npm run preview` : prévisualisé le build Nuxt
|
||||
- `npm run lint` : execute ESLint
|
||||
- `npm run lint:fix` : applique les corrections ESLint automatiques : collecte périodique CPU, mémoire et réseau
|
||||
- `npm run lint:fix` : applique les corrections ESLint automatiques
|
||||
|
||||
@@ -123,7 +123,10 @@
|
||||
background-clip: text;
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgb(var(--m-border)) rgb(var(--m-bg));
|
||||
}
|
||||
@keyframes fade-in-up {
|
||||
from {
|
||||
opacity: 0;
|
||||
|
||||
@@ -31,7 +31,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue"
|
||||
import { Icon as IconifyIcon } from "@iconify/vue"
|
||||
import backupOptions from "~/server/config/backup-options.json"
|
||||
|
||||
|
||||
@@ -107,6 +107,12 @@ type ScriptResult = {
|
||||
downloadFolders: string[]
|
||||
}
|
||||
|
||||
type ApiErrorLike = {
|
||||
data?: {
|
||||
statusMessage?: string
|
||||
}
|
||||
}
|
||||
|
||||
const emit = defineEmits<{
|
||||
result: [payload: ScriptResult]
|
||||
}>()
|
||||
@@ -171,7 +177,15 @@ const runScript = async (key: string) => {
|
||||
downloadFolders: data.downloadFolders || []
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
message.value = (error as any)?.data?.statusMessage || "Erreur execution script"
|
||||
const errorMessage =
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"data" in error &&
|
||||
typeof (error as ApiErrorLike).data?.statusMessage === "string"
|
||||
? (error as ApiErrorLike).data?.statusMessage
|
||||
: null
|
||||
|
||||
message.value = errorMessage || "Erreur execution script"
|
||||
emit("result", {
|
||||
key,
|
||||
label: scripts.value.find((item) => item.key === key)?.label || key,
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import {Icon as IconifyIcon} from "@iconify/vue"
|
||||
import { apiFetch } from "~/composables/useApiAuth"
|
||||
|
||||
const { data: messages, error } = await useFetch('/api/discord/messages', {
|
||||
interface DiscordMessage {
|
||||
id: string
|
||||
content: string
|
||||
author: { username: string }
|
||||
}
|
||||
|
||||
const { data: messages, error } = await useFetch<DiscordMessage[]>('/api/discord/messages', {
|
||||
$fetch: apiFetch,
|
||||
server: false
|
||||
})
|
||||
|
||||
@@ -44,7 +44,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {computed, ref} from "vue"
|
||||
import {Icon as IconifyIcon} from "@iconify/vue"
|
||||
import { apiRequest } from "~/composables/useApiAuth"
|
||||
|
||||
@@ -66,9 +65,14 @@ async function testDownload() {
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`)
|
||||
}
|
||||
const blob = await res.blob()
|
||||
const end = performance.now()
|
||||
const size = blob.size
|
||||
const reader = res.body!.getReader()
|
||||
let size = 0
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
size += value.length
|
||||
}
|
||||
const seconds = (end - start) / 1000
|
||||
download.value = Math.round((size * 8) / seconds / 1000000)
|
||||
}
|
||||
@@ -88,7 +92,7 @@ async function testUpload() {
|
||||
|
||||
async function testPing() {
|
||||
const start = performance.now()
|
||||
const response = await fetch('/api/ping')
|
||||
const response = await apiRequest('/api/ping')
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
@@ -47,7 +47,6 @@
|
||||
<script setup lang="ts">
|
||||
import CircleSkeleton from "~/components/skeleton/CircleSkeleton.vue"
|
||||
import TextSkeleton from "~/components/skeleton/TextSkeleton.vue"
|
||||
import {onBeforeUnmount, onMounted, ref} from "vue"
|
||||
import { apiFetch } from "~/composables/useApiAuth"
|
||||
|
||||
interface StatusRow {
|
||||
|
||||
@@ -24,25 +24,32 @@
|
||||
v-else
|
||||
:key="`${row.label}-${row.url}`"
|
||||
class="status-row"
|
||||
:class="row.status === 200 ? 'row-ok' : 'row-error'"
|
||||
:class="row.ok ? 'row-ok' : 'row-error'"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="status-dot" :class="row.status === 200 ? 'dot-ok' : 'dot-error'" />
|
||||
<span class="font-display text-sm font-semibold text-m-text">
|
||||
{{ row.label }}
|
||||
<div class="status-copy">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="status-dot" :class="row.ok ? 'dot-ok' : 'dot-error'" />
|
||||
<span class="font-display text-sm font-semibold text-m-text">
|
||||
{{ row.label }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="status-detail">
|
||||
{{ row.detail }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="status-meta">
|
||||
<span class="font-mono text-xs" :class="row.ok ? 'text-m-success' : 'text-m-error'">
|
||||
{{ statusLabel(row) }}
|
||||
</span>
|
||||
<span class="status-time">
|
||||
{{ formatCheckedAt(row.checkedAt) }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="font-mono text-xs" :class="row.status === 200 ? 'text-m-success' : 'text-m-error'">
|
||||
{{ statusLabel(row.status) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import CircleSkeleton from "~/components/skeleton/CircleSkeleton.vue"
|
||||
import TextSkeleton from "~/components/skeleton/TextSkeleton.vue"
|
||||
import {onBeforeUnmount, onMounted, ref} from "vue"
|
||||
import { apiFetch } from "~/composables/useApiAuth"
|
||||
|
||||
interface StatusRow {
|
||||
@@ -51,6 +58,7 @@ interface StatusRow {
|
||||
ok: boolean
|
||||
status: number
|
||||
checkedAt: string
|
||||
detail: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
@@ -58,6 +66,10 @@ interface StatusResponse {
|
||||
results: StatusRow[]
|
||||
}
|
||||
|
||||
interface BackupScriptRunResponse {
|
||||
ok: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
endpoint?: string
|
||||
@@ -72,12 +84,27 @@ const props = withDefaults(
|
||||
const rows = ref<StatusRow[]>([])
|
||||
const loading = ref(true)
|
||||
const initialized = ref(false)
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let statusTimer: ReturnType<typeof setInterval> | null = null
|
||||
let scriptTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const statusLabel = (status: number) => {
|
||||
if (status === 200) return "HTTP 200"
|
||||
if (status === 0) return "Injoignable"
|
||||
return `KO (${status})`
|
||||
const statusLabel = (row: StatusRow) => {
|
||||
if (row.ok) return "OK"
|
||||
if (row.status === 0) return "DOWN"
|
||||
return `KO (${row.status})`
|
||||
}
|
||||
|
||||
const formatCheckedAt = (checkedAt: string) => {
|
||||
const date = new Date(checkedAt)
|
||||
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return checkedAt
|
||||
}
|
||||
|
||||
return date.toLocaleTimeString("fr-FR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit"
|
||||
})
|
||||
}
|
||||
|
||||
const checkStatus = async () => {
|
||||
@@ -95,6 +122,7 @@ const checkStatus = async () => {
|
||||
ok: false,
|
||||
status: 0,
|
||||
checkedAt: new Date().toISOString(),
|
||||
detail: "Lecture du statut impossible",
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
]
|
||||
@@ -104,15 +132,34 @@ const checkStatus = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const runStatusScript = async () => {
|
||||
try {
|
||||
await apiFetch<BackupScriptRunResponse>("/api/backup-script", {
|
||||
method: "POST",
|
||||
body: { key: "check-statut-recette" }
|
||||
})
|
||||
await checkStatus()
|
||||
} catch (error) {
|
||||
console.error("Erreur execution check statut recette:", error)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
checkStatus()
|
||||
timer = setInterval(checkStatus, props.refreshMs)
|
||||
runStatusScript()
|
||||
statusTimer = setInterval(checkStatus, props.refreshMs)
|
||||
scriptTimer = setInterval(runStatusScript, 5 * 60 * 1000)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
if (statusTimer) {
|
||||
clearInterval(statusTimer)
|
||||
statusTimer = null
|
||||
}
|
||||
|
||||
if (scriptTimer) {
|
||||
clearInterval(scriptTimer)
|
||||
scriptTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -149,6 +196,7 @@ onBeforeUnmount(() => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
min-height: 3.2rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 14px;
|
||||
@@ -157,6 +205,30 @@ onBeforeUnmount(() => {
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.status-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.status-detail {
|
||||
margin: 0.35rem 0 0;
|
||||
color: rgb(var(--m-muted));
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.status-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.2rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-time {
|
||||
font-size: 0.72rem;
|
||||
color: rgb(var(--m-muted));
|
||||
}
|
||||
|
||||
.row-ok {
|
||||
border-color: rgb(var(--m-success) / 0.08);
|
||||
}
|
||||
|
||||
@@ -139,7 +139,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from "vue"
|
||||
import type { SystemMetrics } from "~/types/system"
|
||||
|
||||
type MetricKey = "cpu" | "ram"
|
||||
@@ -293,7 +292,7 @@ const visibleHistory = computed(() => {
|
||||
return history.value.filter((point) => point.sampledAt >= minTimestamp)
|
||||
})
|
||||
|
||||
const scaleMax = 100
|
||||
const scaleMax = computed(() => 100)
|
||||
|
||||
const formatValue = (value: number) => `${Math.round(value)}%`
|
||||
|
||||
|
||||
@@ -45,7 +45,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {computed} from "vue"
|
||||
import type { SystemMetrics } from "~/types/system";
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@@ -1,50 +1,3 @@
|
||||
function toHeadersObject(headers?: HeadersInit): Record<string, string> {
|
||||
if (!headers) {
|
||||
return {}
|
||||
}
|
||||
|
||||
if (headers instanceof Headers) {
|
||||
return Object.fromEntries(headers.entries())
|
||||
}
|
||||
|
||||
if (Array.isArray(headers)) {
|
||||
return Object.fromEntries(headers)
|
||||
}
|
||||
|
||||
return { ...headers }
|
||||
}
|
||||
|
||||
function getDownloadFileName(contentDisposition: string | null, fallback: string) {
|
||||
if (!contentDisposition) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i)
|
||||
if (utf8Match?.[1]) {
|
||||
return decodeURIComponent(utf8Match[1])
|
||||
}
|
||||
|
||||
const asciiMatch = contentDisposition.match(/filename="([^"]+)"/i)
|
||||
if (asciiMatch?.[1]) {
|
||||
return asciiMatch[1]
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
export function useApiAuthHeader() {
|
||||
const runtimeConfig = useRuntimeConfig()
|
||||
const token = runtimeConfig.public.apiSecretKey
|
||||
|
||||
if (!token) {
|
||||
return {}
|
||||
}
|
||||
|
||||
// Tous les appels frontend vers /api/* reutilisent ce header commun.
|
||||
return {
|
||||
}
|
||||
}
|
||||
|
||||
export const apiFetch = $fetch.create({})
|
||||
|
||||
export function apiRequest(input: RequestInfo | URL, init: RequestInit = {}) {
|
||||
@@ -52,38 +5,16 @@ export function apiRequest(input: RequestInfo | URL, init: RequestInit = {}) {
|
||||
}
|
||||
|
||||
export async function downloadApiFile(url: string, fileNameFallback: string) {
|
||||
// Les telechargements passent aussi par fetch pour pouvoir recuperer
|
||||
// le contenu et le nom de fichier renvoye par l'API.
|
||||
const response = await apiRequest(url)
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
const blob = await response.blob()
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const fileName = getDownloadFileName(
|
||||
response.headers.get("content-disposition"),
|
||||
fileNameFallback
|
||||
)
|
||||
const link = document.createElement("a")
|
||||
|
||||
link.href = objectUrl
|
||||
link.download = fileName
|
||||
link.href = url
|
||||
link.download = fileNameFallback
|
||||
link.style.display = "none"
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
|
||||
export function withApiAuth(init: RequestInit = {}) {
|
||||
// Fusionne le header d'auth avec d'eventuels headers deja fournis.
|
||||
return {
|
||||
...init,
|
||||
headers: {
|
||||
...useApiAuthHeader(),
|
||||
...toHeadersObject(init.headers)
|
||||
}
|
||||
}
|
||||
return { ...init }
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
<div class="sidebar-divider"/>
|
||||
<div class="status-card">
|
||||
<p class="status-label">Environnement</p>
|
||||
<p class="status-value">Production</p>
|
||||
<p class="status-value">{{ environmentLabel }}</p>
|
||||
<p class="status-description">
|
||||
Acces rapide au monitoring, aux sauvegardes et aux cartes systeme.
|
||||
</p>
|
||||
@@ -123,7 +123,7 @@
|
||||
<div class="sidebar-divider"/>
|
||||
<div class="status-card">
|
||||
<p class="status-label">Environnement</p>
|
||||
<p class="status-value">Production</p>
|
||||
<p class="status-value">{{ environmentLabel }}</p>
|
||||
<p class="status-description">
|
||||
Navigation rapide vers les vues principales de supervision.
|
||||
</p>
|
||||
@@ -153,6 +153,7 @@ const {
|
||||
public: {appVersion}
|
||||
} = useRuntimeConfig()
|
||||
const isMenuOpen = ref(false)
|
||||
const environmentLabel = import.meta.dev ? "Developpement" : "Production"
|
||||
const navItems = [
|
||||
{
|
||||
to: "/",
|
||||
@@ -169,6 +170,13 @@ const navItems = [
|
||||
icon: "mdi:database-arrow-up-outline"
|
||||
}
|
||||
]
|
||||
onMounted(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") isMenuOpen.value = false
|
||||
}
|
||||
document.addEventListener("keydown", handler)
|
||||
onBeforeUnmount(() => document.removeEventListener("keydown", handler))
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -20,7 +20,7 @@ const getRepoVersion = () => {
|
||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: "2025-07-15",
|
||||
devtools: { enabled: true },
|
||||
devtools: { enabled: process.env.NODE_ENV !== "production" },
|
||||
css: ["~/assets/css/main.css"],
|
||||
app: {
|
||||
head: {
|
||||
@@ -35,12 +35,12 @@ export default defineNuxtConfig({
|
||||
}
|
||||
},
|
||||
runtimeConfig: {
|
||||
authCookieSecure: process.env.AUTH_COOKIE_SECURE === "true",
|
||||
apiSecretKey: process.env.API_SECRET_KEY,
|
||||
discordBotToken: process.env.DISCORD_BOT_TOKEN,
|
||||
discordChannelId: process.env.DISCORD_CHANNEL_ID,
|
||||
public: {
|
||||
appVersion: getRepoVersion(),
|
||||
apiKey: process.env.API_SECRET_KEY
|
||||
appVersion: getRepoVersion()
|
||||
}
|
||||
},
|
||||
vite: {
|
||||
|
||||
200
package-lock.json
generated
200
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -16,10 +16,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@iconify/vue": "^5.0.0",
|
||||
"@nuxt/eslint": "^1.15.2",
|
||||
"nuxt": "^4.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nuxt/eslint": "^1.15.2",
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
"@semantic-release/commit-analyzer": "^13.0.1",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<template>
|
||||
<NuxtLayout name="default">
|
||||
<div class="dashboard-container">
|
||||
<header class="dashboard-header">
|
||||
<div class="header-copy">
|
||||
@@ -105,16 +104,11 @@
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue"
|
||||
import BackupRun from "~/components/BackupRun.vue"
|
||||
import { apiFetch, downloadApiFile } from "~/composables/useApiAuth"
|
||||
|
||||
definePageMeta({ layout: false })
|
||||
|
||||
type ScriptResult = {
|
||||
key: string | null
|
||||
label: string
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<template>
|
||||
<NuxtLayout name="default">
|
||||
<div class="dashboard-container">
|
||||
<header class="dashboard-header">
|
||||
<div>
|
||||
@@ -62,15 +61,12 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { apiFetch } from "~/composables/useApiAuth"
|
||||
import type { SystemMetrics } from "~/types/system";
|
||||
|
||||
definePageMeta({layout: false})
|
||||
|
||||
type DiskSourceResult = {
|
||||
key: string
|
||||
label: string
|
||||
@@ -192,7 +188,7 @@ const runScript = async () => {
|
||||
|
||||
const loadSystemMetrics = async () => {
|
||||
try {
|
||||
systemMetrics.value = await $fetch<SystemMetrics>("/api/system")
|
||||
systemMetrics.value = await apiFetch<SystemMetrics>("/api/system")
|
||||
} catch {
|
||||
systemMetrics.value = null
|
||||
} finally {
|
||||
|
||||
@@ -30,27 +30,23 @@ function parseLines(output: string): string[] {
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function quoteDir(pathValue: string) {
|
||||
return shellQuote(pathValue)
|
||||
}
|
||||
|
||||
async function listRemoteFiles(remoteDir: string): Promise<string[]> {
|
||||
const output = await runSsh(
|
||||
`cd ${quoteDir(remoteDir)} && ls -1A | sort -r | head -n ${MAX_FILES_PER_FOLDER}`
|
||||
`cd ${shellQuote(remoteDir)} && ls -1A | sort -r | head -n ${MAX_FILES_PER_FOLDER}`
|
||||
)
|
||||
return parseLines(output)
|
||||
}
|
||||
|
||||
async function listRemoteDirs(remoteRoot: string): Promise<string[]> {
|
||||
const output = await runSsh(
|
||||
`cd ${quoteDir(remoteRoot)} && for d in */; do [ -d "$d" ] && printf '%s\n' "\${d%/}"; done`
|
||||
`cd ${shellQuote(remoteRoot)} && for d in */; do [ -d "$d" ] && printf '%s\n' "\${d%/}"; done`
|
||||
)
|
||||
return parseLines(output)
|
||||
}
|
||||
|
||||
async function getLatestRemoteFile(remoteDir: string): Promise<string | null> {
|
||||
const output = await runSsh(
|
||||
`cd ${quoteDir(remoteDir)} && ls -1A | sort -r | head -n 1`
|
||||
`cd ${shellQuote(remoteDir)} && ls -1A | sort -r | head -n 1`
|
||||
)
|
||||
const files = parseLines(output)
|
||||
return files[0] || null
|
||||
|
||||
@@ -4,10 +4,9 @@ import {
|
||||
resolveFolderRemoteDir
|
||||
} from "../utils/ssh.ts"
|
||||
|
||||
import {process} from "std-env";
|
||||
import backupOptions from "../config/backup-options.json"
|
||||
|
||||
export const BACKUP_HOUR = process.env.BACKUPS_HOUR
|
||||
export const BACKUP_HOUR = Number(process.env.BACKUPS_HOUR) || 19
|
||||
|
||||
type BackupTarget = {
|
||||
name: string
|
||||
@@ -141,7 +140,7 @@ export default defineEventHandler(async () => {
|
||||
latestBackupAt: null,
|
||||
backupDate: null,
|
||||
expectedBackupDate: expectedDateKey,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
error: "Erreur lors de la verification"
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
29
server/api/discord/README.md
Normal file
29
server/api/discord/README.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Créer un bot discord
|
||||
|
||||
Allez sur le portail des développeurs Discord : https://discord.com/developers/applications
|
||||
|
||||
1. Cliquez sur "New Application" et donnez un nom à votre application.
|
||||
|
||||
|
||||
2. Dans le menu de gauche, cliquez sur "Bot" puis sur "Add Bot".
|
||||
|
||||
|
||||
3. Vous pouvez personnaliser votre bot en lui donnant un nom, une image de profil, etc.
|
||||
|
||||
|
||||
4. Sous la section "Token", cliquez sur "Copy" pour copier le token de votre bot. Gardez ce token secret, car il permet à quiconque de contrôler votre bot.
|
||||
|
||||
|
||||
5. Dans L'onglet "Installation", on peut décocher "Installation pour un utlisateur" si vous voulez installer le bot que sur des serveurs.
|
||||
|
||||
|
||||
6. Tout en bas dans "Paramètres d'installation par défaut", cliquez sur "applications.commands" et sélectionnez "bot" pour donner les permissions nécessaires à votre bot.
|
||||
|
||||
|
||||
7. Ensuite donner les permissions que vous souhaitez à votre bot en cochant les cases correspondantes. Pour l'utilisation pour Supervisor cocher "Voir les anciens messages"
|
||||
|
||||
|
||||
8. Enregistrez les modifications.
|
||||
|
||||
|
||||
9. Puis vous pouvez copier le d'installation et le copier pour inviter le bot au discord
|
||||
@@ -20,7 +20,11 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
)
|
||||
|
||||
return messages
|
||||
return (messages as any[]).map((m) => ({
|
||||
id: m.id,
|
||||
content: m.content,
|
||||
author: { username: m.author?.username ?? "Inconnu" }
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error("Erreur Discord messages:", error)
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ import {
|
||||
shellQuote,
|
||||
resolveFolderRemoteDir,
|
||||
REMOTE_HOST,
|
||||
isSafeFolder
|
||||
isSafeFolder,
|
||||
isSafeFile
|
||||
} from "../utils/ssh.ts"
|
||||
import { spawn } from "node:child_process"
|
||||
|
||||
@@ -29,6 +30,9 @@ export default defineEventHandler(async (event) => {
|
||||
if (folderNames.length === 0) {
|
||||
throw createError({ statusCode: 400, statusMessage: "Paramètre folders invalide" })
|
||||
}
|
||||
if (!REMOTE_HOST) {
|
||||
throw createError({ statusCode: 503, statusMessage: "Service non configure" })
|
||||
}
|
||||
|
||||
if (folderNames.some((folder) => !isSafeFolder(folder))) {
|
||||
throw createError({ statusCode: 400, statusMessage: "Paramètre folders invalide" })
|
||||
@@ -44,10 +48,7 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
|
||||
const fileName = await getLatestRemoteFile(remoteDir)
|
||||
if (!fileName || !isSafeFolder(fileName)) {
|
||||
continue
|
||||
}
|
||||
if (!fileName) {
|
||||
if (!fileName || !isSafeFile(fileName)) {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,10 @@ export default defineEventHandler(async (event) => {
|
||||
const folderName = typeof folder === "string" ? folder : null
|
||||
const fileName = typeof file === "string" ? file : null
|
||||
|
||||
if (!REMOTE_HOST) {
|
||||
throw createError({ statusCode: 503, statusMessage: "Service non configure" })
|
||||
}
|
||||
|
||||
if (!folderName || !fileName) {
|
||||
throw createError({ statusCode: 400, statusMessage: "Paramètres manquants" })
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ export default defineEventHandler(async (event) => {
|
||||
let received = 0
|
||||
|
||||
for await (const chunk of req) {
|
||||
if (received > MAX_UPLOAD_BYTES) throw createError({ statusCode: 413, statusMessage: "Fichier trop volumineux" })
|
||||
received += chunk.length
|
||||
if (received > MAX_UPLOAD_BYTES) {
|
||||
event.node.res.destroy()
|
||||
throw createError({statusCode: 413, statusMessage: "Fichier trop volumineux"})
|
||||
}
|
||||
}
|
||||
|
||||
return { received }
|
||||
})
|
||||
return {received}
|
||||
})
|
||||
|
||||
@@ -1,41 +1,160 @@
|
||||
import targets from "../config/version-status-targets.json"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { join } from "node:path"
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 5000
|
||||
type StatusEntry = {
|
||||
checkedAt: string
|
||||
status: "OK" | "DOWN"
|
||||
host: string
|
||||
detail: string
|
||||
}
|
||||
|
||||
type StatusResult = {
|
||||
label: string
|
||||
url: string
|
||||
ok: boolean
|
||||
status: number
|
||||
checkedAt: string
|
||||
detail: string
|
||||
}
|
||||
|
||||
const DEFAULT_RECETTE_SCRIPTS_DIR = "/home/malio/Malio-ops/RecetteScripts"
|
||||
|
||||
function parseEnvFile(content: string) {
|
||||
const values: Record<string, string> = {}
|
||||
|
||||
for (const rawLine of content.split("\n")) {
|
||||
const line = rawLine.trim()
|
||||
|
||||
if (!line || line.startsWith("#")) {
|
||||
continue
|
||||
}
|
||||
|
||||
const separatorIndex = line.indexOf("=")
|
||||
if (separatorIndex === -1) {
|
||||
continue
|
||||
}
|
||||
|
||||
const key = line.slice(0, separatorIndex).trim()
|
||||
const value = line.slice(separatorIndex + 1).trim()
|
||||
|
||||
if (!key) {
|
||||
continue
|
||||
}
|
||||
|
||||
values[key] = value.replace(/^['"]|['"]$/g, "")
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
function getLogFileName(date: Date) {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0")
|
||||
const day = String(date.getDate()).padStart(2, "0")
|
||||
|
||||
return `app_health_${year}-${month}-${day}.log`
|
||||
}
|
||||
|
||||
function parseStatusLine(line: string): StatusEntry | null {
|
||||
const parts = line.split(" | ")
|
||||
if (parts.length < 4) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [checkedAt, status, host, ...detailParts] = parts
|
||||
if ((status !== "OK" && status !== "DOWN") || !host) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
checkedAt,
|
||||
status,
|
||||
host,
|
||||
detail: detailParts.join(" | ")
|
||||
}
|
||||
}
|
||||
|
||||
function buildStatusResult(entry: StatusEntry): StatusResult {
|
||||
return {
|
||||
label: entry.host,
|
||||
url: `http://${entry.host}/`,
|
||||
ok: entry.status === "OK",
|
||||
status: entry.status === "OK" ? 200 : 0,
|
||||
checkedAt: entry.checkedAt,
|
||||
detail: entry.detail
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
const results = await Promise.all(
|
||||
targets.map(async (target) => {
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
||||
const recetteScriptsDir = process.env.RECETTE_SCRIPTS_DIR || DEFAULT_RECETTE_SCRIPTS_DIR
|
||||
const envFilePath = join(recetteScriptsDir, ".env")
|
||||
|
||||
try {
|
||||
const response = await fetch(target.url, {
|
||||
method: "GET",
|
||||
headers: { Accept: "application/json" },
|
||||
signal: controller.signal
|
||||
})
|
||||
try {
|
||||
const envFileContent = await readFile(envFilePath, "utf8")
|
||||
const envValues = parseEnvFile(envFileContent)
|
||||
const logDir = envValues.APP_LOG_DIR
|
||||
|
||||
return {
|
||||
label: target.label,
|
||||
url: target.url,
|
||||
ok: response.status === 200,
|
||||
status: response.status,
|
||||
checkedAt: new Date().toISOString()
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
label: target.label,
|
||||
url: target.url,
|
||||
ok: false,
|
||||
status: 0,
|
||||
checkedAt: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
if (!logDir) {
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Variable APP_LOG_DIR manquante"
|
||||
})
|
||||
}
|
||||
|
||||
const logFilePath = join(logDir, getLogFileName(new Date()))
|
||||
const logFileContent = await readFile(logFilePath, "utf8")
|
||||
const latestEntriesByHost = new Map<string, StatusEntry>()
|
||||
|
||||
for (const line of logFileContent.split("\n")) {
|
||||
const entry = parseStatusLine(line)
|
||||
if (!entry) {
|
||||
continue
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
return { results }
|
||||
latestEntriesByHost.set(entry.host, entry)
|
||||
}
|
||||
|
||||
const configuredHosts = (envValues.APP_URLS || "")
|
||||
.split(/\s+/)
|
||||
.map((host) => host.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const orderedResults = configuredHosts
|
||||
.map((host) => latestEntriesByHost.get(host))
|
||||
.filter((entry): entry is StatusEntry => Boolean(entry))
|
||||
.map(buildStatusResult)
|
||||
|
||||
const remainingResults = Array.from(latestEntriesByHost.entries())
|
||||
.filter(([host]) => !configuredHosts.includes(host))
|
||||
.map(([, entry]) => buildStatusResult(entry))
|
||||
|
||||
const results = [...orderedResults, ...remainingResults]
|
||||
|
||||
if (results.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 503,
|
||||
statusMessage: "Aucun statut disponible"
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
results
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erreur lecture status recette:", error)
|
||||
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"statusCode" in error &&
|
||||
"statusMessage" in error
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Erreur lors de l'opération"
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
[
|
||||
{ "label": "Ferme", "url": "http://ferme.malio-dev.fr/api/version" },
|
||||
{ "label": "SIRH", "url": "http://sirh.malio-dev.fr/api/version" },
|
||||
{ "label": "Inventory", "url": "http://inventory.malio-dev.fr/api/health" }
|
||||
]
|
||||
@@ -22,7 +22,7 @@ export default defineEventHandler((event) => {
|
||||
return
|
||||
}
|
||||
|
||||
const secureCookie = process.env.AUTH_COOKIE_SECURE === "true"
|
||||
const secureCookie = runtimeConfig.authCookieSecure
|
||||
|
||||
setCookie(event, "api_auth_token", expectedToken, {
|
||||
httpOnly: true,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { shellQuote } from "./ssh"
|
||||
|
||||
export type BackupScript = {
|
||||
key: string
|
||||
label: string
|
||||
@@ -32,10 +34,10 @@ const getDefaultBackupScriptCommands = (): Record<string, string> => {
|
||||
process.env.VAULTWARDEN_SCRIPTS_DIR || "/home/matt/vaultwarden/Malio-ops/BackupVaultWarden"
|
||||
|
||||
return {
|
||||
"backup-bdd-recette": `cd ${recetteScriptsDir} && bash backup-bdd-recette.sh`,
|
||||
"check-statut-recette": `cd ${recetteScriptsDir} && bash check-statut-recette.sh`,
|
||||
"backup-bdd-recette": `cd ${shellQuote(recetteScriptsDir)} && bash backup-bdd-recette.sh`,
|
||||
"check-statut-recette": `cd ${shellQuote(recetteScriptsDir)} && bash check-statut-recette.sh`,
|
||||
"backup-vaultwarden":
|
||||
`ssh ${vaultwardenHost} "cd ${vaultwardenScriptsDir} && bash backup-vaultwarden.sh"`
|
||||
`ssh ${shellQuote(vaultwardenHost)} "cd ${shellQuote(vaultwardenScriptsDir)} && bash backup-vaultwarden.sh"`
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user