Initial commit
This commit is contained in:
commit
6c99008318
18 files changed
+5772
No files matched your search
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
# Keep environment variables out of version control
|
||||
.env
|
||||
|
||||
/generated/prisma
|
||||
*.db
|
||||
*.db-journal
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaLibSql } from '@prisma/adapter-libsql';
|
||||
import { createClient } from '@libsql/client';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
async function main() {
|
||||
const libsqlConfig = {
|
||||
url: process.env.DATABASE_URL || 'file:./dev.db'
|
||||
};
|
||||
const adapter = new PrismaLibSql(libsqlConfig);
|
||||
const prisma = new PrismaClient({ adapter: adapter as any });
|
||||
|
||||
try {
|
||||
const services = await prisma.service.findMany();
|
||||
console.log('Services found in DB:', JSON.stringify(services, null, 2));
|
||||
} catch (e) {
|
||||
console.error('Error querying services:', e);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Generated
+4264
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev": "nodemon -x ts-node src/index.ts",
|
||||
"start": "ts-node src/index.ts"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@libsql/client": "^0.17.2",
|
||||
"@notionhq/client": "^5.17.0",
|
||||
"@prisma/adapter-libsql": "^7.7.0",
|
||||
"@prisma/client": "^7.7.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"cors": "^2.8.6",
|
||||
"dockerode": "^4.0.10",
|
||||
"dotenv": "^17.4.2",
|
||||
"express": "^5.2.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"socket.io": "^4.8.3",
|
||||
"tail": "^2.2.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/cookie-parser": "^1.4.10",
|
||||
"@types/cors": "^2.8.19",
|
||||
"@types/dockerode": "^4.0.1",
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/node": "^25.6.0",
|
||||
"@types/tail": "^2.2.3",
|
||||
"nodemon": "^3.1.14",
|
||||
"prisma": "^7.7.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^6.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// This file was generated by Prisma, and assumes you have installed the following:
|
||||
// npm install --save-dev prisma dotenv
|
||||
import "dotenv/config";
|
||||
import { defineConfig } from "prisma/config";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
datasource: {
|
||||
url: process.env["DATABASE_URL"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
email String @unique
|
||||
password String
|
||||
name String?
|
||||
isAdmin Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
conversations Conversation[]
|
||||
}
|
||||
|
||||
model Conversation {
|
||||
id Int @id @default(autoincrement())
|
||||
title String
|
||||
userId Int
|
||||
user User @relation(fields: [userId], references: [id])
|
||||
messages Message[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Message {
|
||||
id Int @id @default(autoincrement())
|
||||
role String // 'user', 'assistant', 'system'
|
||||
content String
|
||||
conversationId Int
|
||||
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model Service {
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
type String // 'docker' or 'host'
|
||||
pathOrContainerId String
|
||||
alertKeyword String? // This will be deprecated by the AI model
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model GlobalSettings {
|
||||
id Int @id @default(1)
|
||||
notionToken String?
|
||||
notionDbId String?
|
||||
ollamaUrl String? // e.g., http://localhost:11434
|
||||
ollamaModel String? // e.g., qwen:7b
|
||||
searxngUrl String? // e.g., http://localhost:8080
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import { createServer } from 'http';
|
||||
import { Server } from 'socket.io';
|
||||
import { prisma } from './lib/prisma';
|
||||
import { LogTracker } from './services/logTracker';
|
||||
import dotenv from 'dotenv';
|
||||
import authRoutes from './routes/authRoutes';
|
||||
import aiRoutes from './routes/aiRoutes';
|
||||
import { authenticateToken, socketAuthMiddleware } from './middleware/authMiddleware';
|
||||
|
||||
// Load environment variables from .env file
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const httpServer = createServer(app);
|
||||
const io = new Server(httpServer, {
|
||||
cors: {
|
||||
origin: ["http://localhost:5173"], // Spécifier l'origine pour les credentials
|
||||
methods: ["GET", "POST", "DELETE", "OPTIONS"],
|
||||
credentials: true
|
||||
}
|
||||
});
|
||||
|
||||
// Sécurisation des WebSockets
|
||||
io.use(socketAuthMiddleware);
|
||||
|
||||
const logTracker = new LogTracker(io, prisma);
|
||||
|
||||
app.use(cors({
|
||||
origin: "http://localhost:5173",
|
||||
credentials: true
|
||||
}));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
|
||||
// Public Routes
|
||||
app.use('/api/auth', authRoutes);
|
||||
|
||||
// Protected AI Routes
|
||||
app.use('/api/ai', authenticateToken as any, aiRoutes);
|
||||
|
||||
// Protected Routes Middleware
|
||||
app.use('/api', authenticateToken as any);
|
||||
|
||||
// API Routes
|
||||
app.get('/api/services', async (req, res) => {
|
||||
const services = await prisma.service.findMany();
|
||||
res.json(services);
|
||||
});
|
||||
|
||||
app.post('/api/services', async (req, res) => {
|
||||
const service = await prisma.service.create({
|
||||
data: req.body
|
||||
});
|
||||
logTracker.trackService(service);
|
||||
res.json(service);
|
||||
});
|
||||
|
||||
app.delete('/api/services/:id', async (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
await prisma.service.delete({ where: { id } });
|
||||
logTracker.stopTracking(id);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
app.get('/api/services/:id/logs', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const logs = logTracker.getLogHistory(id);
|
||||
res.json(logs);
|
||||
});
|
||||
|
||||
app.get('/api/docker/containers', async (req, res) => {
|
||||
const containers = await logTracker.getDockerContainers();
|
||||
res.json(containers);
|
||||
});
|
||||
|
||||
app.get('/api/os/services', async (req, res) => {
|
||||
const services = await logTracker.getOsServices();
|
||||
res.json(services);
|
||||
});
|
||||
|
||||
app.get('/api/settings', async (req, res) => {
|
||||
let settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings) {
|
||||
settings = await prisma.globalSettings.create({ data: { id: 1, notionToken: '', notionDbId: '', ollamaUrl: '', ollamaModel: '', searxngUrl: '' } });
|
||||
}
|
||||
res.json(settings);
|
||||
});
|
||||
|
||||
app.post('/api/settings', async (req, res) => {
|
||||
const { notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl } = req.body;
|
||||
const settings = await prisma.globalSettings.upsert({
|
||||
where: { id: 1 },
|
||||
update: { notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl },
|
||||
create: { id: 1, notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl }
|
||||
});
|
||||
res.json(settings);
|
||||
});
|
||||
|
||||
// Socket.io connection
|
||||
io.on('connection', (socket) => {
|
||||
console.log('✅ Client Socket.io connecté:', socket.id);
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('❌ Client Socket.io déconnecté:', socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3001;
|
||||
httpServer.listen(PORT, async () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
|
||||
// Start tracking existing services
|
||||
const services = await prisma.service.findMany();
|
||||
services.forEach(s => logTracker.trackService(s));
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaLibSql } from '@prisma/adapter-libsql';
|
||||
import { createClient } from '@libsql/client';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const libsqlConfig = {
|
||||
url: process.env.DATABASE_URL || 'file:./dev.db'
|
||||
};
|
||||
|
||||
const adapter = new PrismaLibSql(libsqlConfig);
|
||||
export const prisma = new PrismaClient({ adapter: adapter as any });
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'goura_super_secret_key_123';
|
||||
|
||||
export interface AuthRequest extends Request {
|
||||
user?: {
|
||||
id: number;
|
||||
email: string;
|
||||
isAdmin: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export const authenticateToken = (req: AuthRequest, res: Response, next: NextFunction) => {
|
||||
const token = req.cookies.token;
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Accès refusé. Session manquante.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const verified = jwt.verify(token, JWT_SECRET) as any;
|
||||
req.user = verified;
|
||||
next();
|
||||
} catch (err) {
|
||||
res.status(403).json({ error: 'Session invalide ou expirée.' });
|
||||
}
|
||||
};
|
||||
|
||||
// Middleware pour Socket.io avec extraction de cookie
|
||||
export const socketAuthMiddleware = (socket: any, next: (err?: Error) => void) => {
|
||||
const cookieHeader = socket.request.headers.cookie;
|
||||
if (!cookieHeader) return next(new Error('Authentication error'));
|
||||
|
||||
const token = cookieHeader.split(';').find((c: string) => c.trim().startsWith('token='))?.split('=')[1];
|
||||
|
||||
if (!token) {
|
||||
return next(new Error('Authentication error'));
|
||||
}
|
||||
|
||||
try {
|
||||
const verified = jwt.verify(token, JWT_SECRET);
|
||||
socket.user = verified;
|
||||
next();
|
||||
} catch (err) {
|
||||
next(new Error('Authentication error'));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,249 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { prisma } from '../lib/prisma';
|
||||
import { chatWithOllama, chatWithOllamaStream, ChatMessage } from '../services/ollamaService';
|
||||
import { AuthRequest } from '../middleware/authMiddleware';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Lister les conversations de l'utilisateur
|
||||
router.get('/conversations', async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const userId = req.user!.id;
|
||||
const conversations = await prisma.conversation.findMany({
|
||||
where: { userId },
|
||||
orderBy: { updatedAt: 'desc' }
|
||||
});
|
||||
res.json(conversations);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de la récupération des conversations." });
|
||||
}
|
||||
});
|
||||
|
||||
// Créer une nouvelle conversation
|
||||
router.post('/conversations', async (req: AuthRequest, res: Response) => {
|
||||
const { title } = req.body;
|
||||
try {
|
||||
const userId = req.user!.id;
|
||||
const conversation = await prisma.conversation.create({
|
||||
data: {
|
||||
title: title || "Nouvelle discussion",
|
||||
userId,
|
||||
messages: {
|
||||
create: {
|
||||
role: 'system',
|
||||
content: "Tu es un assistant expert DevOps intégré au système LogManager. Ton rôle est d'aider l'utilisateur à interpréter les logs, déboguer les services (Docker/OS) et conseiller sur l'infrastructure. Réponds de manière concise et technique en français."
|
||||
}
|
||||
}
|
||||
},
|
||||
include: { messages: true }
|
||||
});
|
||||
res.json(conversation);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de la création de la conversation." });
|
||||
}
|
||||
});
|
||||
|
||||
// Récupérer les messages d'une conversation
|
||||
router.get('/conversations/:id', async (req: AuthRequest, res: Response) => {
|
||||
const { id } = req.params;
|
||||
try {
|
||||
const conversation = await prisma.conversation.findFirst({
|
||||
where: { id: parseInt(id as string), userId: req.user!.id },
|
||||
include: { messages: { orderBy: { createdAt: 'asc' } } }
|
||||
});
|
||||
if (!conversation) return res.status(404).json({ error: "Conversation introuvable." });
|
||||
res.json(conversation);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de la récupération des messages." });
|
||||
}
|
||||
});
|
||||
|
||||
// Supprimer une conversation
|
||||
router.delete('/conversations/:id', async (req: AuthRequest, res: Response) => {
|
||||
const { id } = req.params;
|
||||
try {
|
||||
await prisma.conversation.delete({
|
||||
where: { id: parseInt(id as string), userId: req.user!.id }
|
||||
});
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de la suppression." });
|
||||
}
|
||||
});
|
||||
|
||||
// Chat au sein d'une conversation
|
||||
router.post('/chat', async (req: AuthRequest, res: Response) => {
|
||||
const { conversationId, content } = req.body;
|
||||
|
||||
if (!conversationId || !content) {
|
||||
return res.status(400).json({ error: "Données manquantes." });
|
||||
}
|
||||
|
||||
try {
|
||||
const userId = req.user!.id;
|
||||
|
||||
// 1. Vérifier la conversation
|
||||
const conversation = await prisma.conversation.findFirst({
|
||||
where: { id: conversationId, userId },
|
||||
include: { messages: { orderBy: { createdAt: 'asc' } } }
|
||||
});
|
||||
|
||||
if (!conversation) return res.status(404).json({ error: "Conversation introuvable." });
|
||||
|
||||
// 2. Sauvegarder le message utilisateur
|
||||
const userMessage = await prisma.message.create({
|
||||
data: { role: 'user', content, conversationId }
|
||||
});
|
||||
|
||||
// 3. Préparer l'historique pour l'IA
|
||||
const history: ChatMessage[] = conversation.messages.map(m => ({
|
||||
role: m.role as any,
|
||||
content: m.content
|
||||
}));
|
||||
history.push({ role: 'user', content });
|
||||
|
||||
// 4. Appeler Ollama
|
||||
const settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings) return res.status(500).json({ error: "Config manquante." });
|
||||
|
||||
const aiContent = await chatWithOllama(history, settings);
|
||||
|
||||
// 5. Sauvegarder la réponse de l'IA
|
||||
const aiMessage = await prisma.message.create({
|
||||
data: { role: 'assistant', content: aiContent, conversationId }
|
||||
});
|
||||
|
||||
// 6. Mettre à jour le titre si c'est le premier message utilisateur
|
||||
if (conversation.title === "Nouvelle discussion") {
|
||||
await prisma.conversation.update({
|
||||
where: { id: conversationId },
|
||||
data: { title: content.substring(0, 30) }
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ userMessage, aiMessage });
|
||||
} catch (error: any) {
|
||||
console.error("Erreur Chat AI:", error);
|
||||
res.status(500).json({ error: "Erreur de communication avec l'IA." });
|
||||
}
|
||||
});
|
||||
|
||||
// Chat au sein d'une conversation - AVEC STREAMING (Server-Sent Events)
|
||||
router.post('/chat-stream', async (req: AuthRequest, res: Response) => {
|
||||
const { conversationId, content } = req.body;
|
||||
|
||||
if (!conversationId || !content) {
|
||||
return res.status(400).json({ error: "Données manquantes." });
|
||||
}
|
||||
|
||||
try {
|
||||
const userId = req.user!.id;
|
||||
|
||||
// 1. Vérifier la conversation
|
||||
const conversation = await prisma.conversation.findFirst({
|
||||
where: { id: conversationId, userId },
|
||||
include: { messages: { orderBy: { createdAt: 'asc' } } }
|
||||
});
|
||||
|
||||
if (!conversation) return res.status(404).json({ error: "Conversation introuvable." });
|
||||
|
||||
// 2. Sauvegarder le message utilisateur
|
||||
const userMessage = await prisma.message.create({
|
||||
data: { role: 'user', content, conversationId }
|
||||
});
|
||||
|
||||
// 3. Configuration SSE
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
|
||||
// On prévient le frontend que l'historique a pris en compte son message de manière asynchrone
|
||||
res.write(`data: ${JSON.stringify({ type: 'init', userMessage })}\n\n`);
|
||||
|
||||
// 4. Préparer l'historique (Sliding Window Context Array)
|
||||
const allMessages: ChatMessage[] = conversation.messages.map(m => ({
|
||||
role: m.role as any,
|
||||
content: m.content
|
||||
}));
|
||||
|
||||
// Limitation stricte de l'historique pour éviter l'explosion du contexte GPU (Time To First Token)
|
||||
let history: ChatMessage[] = [];
|
||||
if (allMessages.length > 0 && allMessages[0].role === 'system') {
|
||||
history.push(allMessages[0]); // Toujours conserver le prompt système
|
||||
}
|
||||
|
||||
// Limitation très agressive de l'historique pour du pur temps-réel (On ne garde que le couple Question / Réponse précédent)
|
||||
// Cela évite l'engorgement si l'IA avait rédigé un pavé colossal de 200 lignes juste avant.
|
||||
const recentMessages = allMessages.slice(history.length).slice(-2);
|
||||
history = history.concat(recentMessages);
|
||||
history.push({ role: 'user', content });
|
||||
|
||||
// 5. Config et Appel
|
||||
const settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings) {
|
||||
res.write(`data: ${JSON.stringify({ error: "Config manquante" })}\n\n`);
|
||||
return res.end();
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
let partialContent = "";
|
||||
|
||||
req.on('close', () => {
|
||||
// Si l'utilisateur clique sur "Stopper" (AbortError front) ou ferme son navigateur
|
||||
abortController.abort();
|
||||
});
|
||||
|
||||
try {
|
||||
// Le streaming en lui même
|
||||
const aiContent = await chatWithOllamaStream(history, settings, (chunk) => {
|
||||
partialContent += chunk;
|
||||
if (!abortController.signal.aborted) {
|
||||
res.write(`data: ${JSON.stringify({ type: 'chunk', content: chunk })}\n\n`);
|
||||
}
|
||||
}, abortController.signal);
|
||||
|
||||
// 6. Une fois le string reçu complet, on sauvegarde
|
||||
const aiMessage = await prisma.message.create({
|
||||
data: { role: 'assistant', content: aiContent, conversationId }
|
||||
});
|
||||
|
||||
// 7. Update titre
|
||||
if (conversation.title === "Nouvelle discussion") {
|
||||
await prisma.conversation.update({
|
||||
where: { id: conversationId },
|
||||
data: { title: content.substring(0, 30) }
|
||||
});
|
||||
}
|
||||
|
||||
// 8. Fin de la connexion
|
||||
res.write(`data: ${JSON.stringify({ type: 'done', aiMessage })}\n\n`);
|
||||
res.end();
|
||||
} catch (streamError: any) {
|
||||
if (streamError.name === 'AbortError') {
|
||||
console.log("Stream annulé par le client (Bouton Stop)");
|
||||
// On sauvegarde quand même ce que l'IA avait eu le temps d'écrire !
|
||||
if (partialContent.trim()) {
|
||||
await prisma.message.create({
|
||||
data: { role: 'assistant', content: partialContent, conversationId }
|
||||
});
|
||||
}
|
||||
res.end();
|
||||
} else {
|
||||
console.error(streamError);
|
||||
res.write(`data: ${JSON.stringify({ error: "Erreur pendant le stream" })}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error("Erreur Chat API Stream:", error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: "Erreur interne" });
|
||||
} else {
|
||||
res.write(`data: ${JSON.stringify({ error: "Erreur interne pendant stream" })}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { prisma } from '../lib/prisma';
|
||||
|
||||
const router = Router();
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'goura_super_secret_key_123';
|
||||
|
||||
// Inscription
|
||||
router.post('/register', async (req: Request, res: Response) => {
|
||||
const { email, password, name } = req.body;
|
||||
|
||||
try {
|
||||
const existingUser = await prisma.user.findUnique({ where: { email } });
|
||||
if (existingUser) {
|
||||
return res.status(400).json({ error: "Cet email est déjà utilisé." });
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
password: hashedPassword,
|
||||
name,
|
||||
isAdmin: (await prisma.user.count()) === 0
|
||||
}
|
||||
});
|
||||
|
||||
const token = jwt.sign({ id: user.id, email: user.email, isAdmin: user.isAdmin }, JWT_SECRET, { expiresIn: '7d' });
|
||||
|
||||
res.cookie('token', token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 jours
|
||||
});
|
||||
|
||||
res.json({ user: { id: user.id, email: user.email, name: user.name, isAdmin: user.isAdmin } });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de l'inscription." });
|
||||
}
|
||||
});
|
||||
|
||||
// Connexion
|
||||
router.post('/login', async (req: Request, res: Response) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
if (!user) {
|
||||
return res.status(400).json({ error: "Identifiants invalides." });
|
||||
}
|
||||
|
||||
const isMatch = await bcrypt.compare(password, user.password);
|
||||
if (!isMatch) {
|
||||
return res.status(400).json({ error: "Identifiants invalides." });
|
||||
}
|
||||
|
||||
const token = jwt.sign({ id: user.id, email: user.email, isAdmin: user.isAdmin }, JWT_SECRET, { expiresIn: '7d' });
|
||||
|
||||
res.cookie('token', token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 jours
|
||||
});
|
||||
|
||||
res.json({ user: { id: user.id, email: user.email, name: user.name, isAdmin: user.isAdmin } });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: "Erreur lors de la connexion." });
|
||||
}
|
||||
});
|
||||
|
||||
// Déconnexion
|
||||
router.post('/logout', (req, res) => {
|
||||
res.clearCookie('token');
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// Vérification de session
|
||||
router.get('/me', async (req: any, res: Response) => {
|
||||
const token = req.cookies.token;
|
||||
if (!token) return res.status(401).json({ error: "Non connecté" });
|
||||
|
||||
try {
|
||||
const decoded: any = jwt.verify(token, JWT_SECRET);
|
||||
const user = await prisma.user.findUnique({ where: { id: decoded.id } });
|
||||
if (!user) return res.status(401).json({ error: "Utilisateur non trouvé" });
|
||||
|
||||
res.json({ user: { id: user.id, email: user.email, name: user.name, isAdmin: user.isAdmin } });
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: "Session invalide" });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,156 @@
|
||||
import { GlobalSettings } from '@prisma/client';
|
||||
import { searchWeb } from './searxngService';
|
||||
import { queryOllama, queryOllamaWithFallback } from './ollamaService';
|
||||
|
||||
export interface AIAnalysisResult {
|
||||
status: 'Urgent' | 'Attention' | 'Normal';
|
||||
shortTitle: string; // Nouveau : Titre court pour affichage Kanban/Notion
|
||||
description: string;
|
||||
solution: string;
|
||||
originalLog: string;
|
||||
}
|
||||
|
||||
// Sémaphore pour ne traiter qu'un paquet à la fois
|
||||
let isAnalyzing = false;
|
||||
const queue: (() => void)[] = [];
|
||||
|
||||
async function acquireLock() {
|
||||
if (!isAnalyzing) {
|
||||
isAnalyzing = true;
|
||||
return;
|
||||
}
|
||||
return new Promise<void>(resolve => queue.push(resolve));
|
||||
}
|
||||
|
||||
function releaseLock() {
|
||||
if (queue.length > 0) {
|
||||
const next = queue.shift();
|
||||
if (next) next();
|
||||
} else {
|
||||
isAnalyzing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyse un paquet de logs en utilisant une approche en deux étapes :
|
||||
* 1. L'IA génère les termes de recherche pour le paquet.
|
||||
* 2. L'IA interprète les résultats SearXNG pour fournir des solutions détaillées.
|
||||
*/
|
||||
export async function analyzeLogBatch(logLines: string[], settings: GlobalSettings): Promise<AIAnalysisResult[]> {
|
||||
if (logLines.length === 0) return [];
|
||||
|
||||
await acquireLock();
|
||||
try {
|
||||
return await _orchestrateBatchAnalysis(logLines, settings);
|
||||
} finally {
|
||||
releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
async function _orchestrateBatchAnalysis(logLines: string[], settings: GlobalSettings): Promise<AIAnalysisResult[]> {
|
||||
console.log(`📦 [Orchestrator] Début de l'analyse d'un paquet de ${logLines.length} logs...`);
|
||||
|
||||
// ÉTAPE 1 : Demander à l'IA de synthétiser le besoin de recherche
|
||||
const summaryPrompt = `
|
||||
Voici un paquet de logs système. Identifie s'il y a des erreurs ou des avertissements.
|
||||
Si oui, génère une unique requête de recherche Google (courte et précise) pour trouver une solution à ces problèmes.
|
||||
Si tout semble normal, réponds "NORMAL".
|
||||
|
||||
Logs:
|
||||
${logLines.join('\n')}
|
||||
|
||||
Requête de recherche (uniquement la requête ou "NORMAL") :`;
|
||||
|
||||
console.log(`🤖 [Orchestrator] Étape 1 : Synthèse pour recherche...`);
|
||||
const searchTerms = await queryOllama(summaryPrompt, settings);
|
||||
|
||||
let webContext = "";
|
||||
if (searchTerms && !searchTerms.includes("NORMAL") && settings.searxngUrl) {
|
||||
console.log(`🔍 [Orchestrator] Recherche web demandée par l'IA : "${searchTerms.trim()}"`);
|
||||
const searchResults = await searchWeb(searchTerms.trim(), settings);
|
||||
if (searchResults.length > 0) {
|
||||
webContext = "\n\nRésultats de recherche web pour ce paquet de logs:\n" +
|
||||
searchResults.map((r, i) => `[ID:${i+1}] ${r.title}: ${r.content.substring(0, 300)}`).join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
// ÉTAPE 2 : Analyse finale de chaque log du paquet
|
||||
const finalPrompt = `
|
||||
Tu es un expert DevOps. Analyse individuellement chaque log du paquet ci-dessous.
|
||||
Utilise les résultats de recherche web fournis pour proposer des solutions concrètes aux erreurs.
|
||||
${webContext}
|
||||
|
||||
---
|
||||
Paquet de logs à traiter :
|
||||
${logLines.map((line, i) => `Log #${i+1}: ${line}`).join('\n')}
|
||||
---
|
||||
|
||||
Réponds UNIQUEMENT sous forme d'un tableau JSON d'objets respectant ce format :
|
||||
[
|
||||
{
|
||||
"originalLog": "le texte exact du log analysé",
|
||||
"status": "Urgent" | "Attention" | "Normal",
|
||||
"shortTitle": "un titre percutant de 3-5 mots max (ex: Échec Connexion DB, Redémarrage Service, Erreur de Permission)",
|
||||
"description": "explication courte",
|
||||
"solution": "solution basée sur le web ou vide si Normal"
|
||||
},
|
||||
... (un objet par log du paquet)
|
||||
]`;
|
||||
|
||||
console.log(`🤖 [Orchestrator] Étape 2 : Analyse finale du paquet...`);
|
||||
const rawResponse = await queryOllamaWithFallback(finalPrompt, basePromptWithoutWeb(logLines), settings);
|
||||
|
||||
if (!rawResponse || rawResponse.trim() === "") {
|
||||
return logLines.map(line => ({
|
||||
originalLog: line,
|
||||
status: 'Normal',
|
||||
shortTitle: "Analyse impossible",
|
||||
description: "L'IA n'a pas renvoyé de réponse valide",
|
||||
solution: ""
|
||||
}));
|
||||
}
|
||||
|
||||
return _parseBatchResponse(rawResponse, logLines);
|
||||
}
|
||||
|
||||
function basePromptWithoutWeb(logLines: string[]): string {
|
||||
return `Analyse ces logs et renvoie un tableau JSON [ { "originalLog", "status", "description", "solution" } ] pour chaque log:\n${logLines.join('\n')}`;
|
||||
}
|
||||
|
||||
function _parseBatchResponse(rawResponse: string, originalLines: string[]): AIAnalysisResult[] {
|
||||
try {
|
||||
const jsonMatch = rawResponse.match(/\[[\s\S]*\]/); // On cherche un tableau [ ... ]
|
||||
const jsonString = jsonMatch ? jsonMatch[0] : rawResponse;
|
||||
const cleanResponse = jsonString.replace(/```json/g, '').replace(/```/g, '').trim();
|
||||
const results = JSON.parse(cleanResponse) as any[];
|
||||
|
||||
return originalLines.map(line => {
|
||||
const found = results.find(r => r.originalLog === line || line.includes(r.originalLog) || r.originalLog?.includes(line.substring(0, 20)));
|
||||
if (found) {
|
||||
return {
|
||||
originalLog: line,
|
||||
status: (['Urgent', 'Attention', 'Normal'].includes(found.status)) ? found.status : 'Attention',
|
||||
shortTitle: found.shortTitle || "Analyse Système",
|
||||
description: found.description || "Analyse effectuée",
|
||||
solution: found.solution || ""
|
||||
};
|
||||
}
|
||||
return {
|
||||
originalLog: line,
|
||||
status: 'Normal',
|
||||
shortTitle: "Info Système",
|
||||
description: "Log ignoré par l'IA",
|
||||
solution: ""
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Échec du parsing JSON du paquet. Réponse brute :", rawResponse.substring(0, 100));
|
||||
return originalLines.map(line => ({
|
||||
originalLog: line,
|
||||
status: 'Attention',
|
||||
shortTitle: "Erreur Analyse",
|
||||
description: "Erreur de format IA",
|
||||
solution: "Impossible de parser les résultats groupés."
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Service } from '@prisma/client';
|
||||
|
||||
export type FlushCallback = (service: Service, lines: string[]) => Promise<void>;
|
||||
|
||||
export class LogStackService {
|
||||
private stacks: Map<number, { service: Service, lines: string[], lastPush: number }> = new Map();
|
||||
private readonly maxBatchSize = 5;
|
||||
private readonly maxWaitMs = 20000; // 20 secondes
|
||||
private flushCallback: FlushCallback;
|
||||
|
||||
constructor(onFlush: FlushCallback) {
|
||||
this.flushCallback = onFlush;
|
||||
|
||||
// Timer de vidage automatique pour les logs orphelins
|
||||
setInterval(() => this.checkAllStacks(), 5000);
|
||||
}
|
||||
|
||||
public push(service: Service, line: string) {
|
||||
let stack = this.stacks.get(service.id);
|
||||
|
||||
if (!stack) {
|
||||
stack = { service, lines: [], lastPush: Date.now() };
|
||||
this.stacks.set(service.id, stack);
|
||||
}
|
||||
|
||||
stack.lines.push(line);
|
||||
stack.lastPush = Date.now();
|
||||
|
||||
if (stack.lines.length >= this.maxBatchSize) {
|
||||
this.flushStack(service.id);
|
||||
}
|
||||
}
|
||||
|
||||
private async checkAllStacks() {
|
||||
const now = Date.now();
|
||||
for (const [serviceId, stack] of this.stacks.entries()) {
|
||||
if (stack.lines.length > 0 && (now - stack.lastPush >= this.maxWaitMs)) {
|
||||
console.log(`⏰ [Stack] Flush automatique pour ${stack.service.name} (délai dépassé)`);
|
||||
await this.flushStack(serviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async flushStack(serviceId: number) {
|
||||
const stack = this.stacks.get(serviceId);
|
||||
if (!stack || stack.lines.length === 0) return;
|
||||
|
||||
const linesToProcess = [...stack.lines];
|
||||
const service = stack.service;
|
||||
stack.lines = []; // Vider immédiatement
|
||||
|
||||
await this.flushCallback(service, linesToProcess);
|
||||
}
|
||||
|
||||
// Version simplifiée pour LogTracker qui gère déjà ses objets Service
|
||||
public getPendingLines(serviceId: number): string[] {
|
||||
const stack = this.stacks.get(serviceId);
|
||||
if (!stack) return [];
|
||||
const lines = [...stack.lines];
|
||||
stack.lines = [];
|
||||
return lines;
|
||||
}
|
||||
|
||||
public hasPending(serviceId: number): boolean {
|
||||
const stack = this.stacks.get(serviceId);
|
||||
return (stack && stack.lines.length > 0) || false;
|
||||
}
|
||||
|
||||
public shouldFlush(serviceId: number): boolean {
|
||||
const stack = this.stacks.get(serviceId);
|
||||
if (!stack || stack.lines.length === 0) return false;
|
||||
|
||||
const now = Date.now();
|
||||
return stack.lines.length >= this.maxBatchSize || (now - stack.lastPush >= this.maxWaitMs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import { Server } from 'socket.io';
|
||||
import { PrismaClient, Service } from '@prisma/client';
|
||||
import Docker from 'dockerode';
|
||||
import { spawn } from 'child_process';
|
||||
import { sendNotionAlert } from './notionAlerts';
|
||||
import { analyzeLogBatch } from './aiOrchestrator';
|
||||
import { LogStackService } from './logStackService';
|
||||
import crypto from 'crypto';
|
||||
import { Client } from '@notionhq/client';
|
||||
|
||||
export class LogTracker {
|
||||
private docker: Docker;
|
||||
private activeStreams: Map<number, any> = new Map();
|
||||
// Cache to prevent duplicate AI processing/alerts: Key = hash(serviceId + logContent)
|
||||
private processedLogsCache: Map<string, number> = new Map();
|
||||
private logStack: LogStackService;
|
||||
private logBuffers: Map<number, { id: string, line: string, isError: boolean }[]> = new Map();
|
||||
private readonly MAX_BUFFER_SIZE = 100;
|
||||
|
||||
constructor(private io: Server, private prisma: PrismaClient) {
|
||||
this.docker = new Docker({ socketPath: process.platform === 'win32' ? '//./pipe/docker_engine' : '/var/run/docker.sock' });
|
||||
this.logStack = new LogStackService((service, lines) => this.processLogBatch(service, lines));
|
||||
|
||||
// Initial sync with Notion
|
||||
this.syncWithNotion();
|
||||
|
||||
// Cleanup cache every hour
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, timestamp] of this.processedLogsCache.entries()) {
|
||||
if (now - timestamp > 3600000) { // 1 hour
|
||||
this.processedLogsCache.delete(key);
|
||||
}
|
||||
}
|
||||
}, 3600000);
|
||||
|
||||
// Sync with Notion every 10 minutes
|
||||
setInterval(() => this.syncWithNotion(), 10 * 60 * 1000);
|
||||
}
|
||||
|
||||
private async syncWithNotion() {
|
||||
try {
|
||||
const settings = await this.prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings || !settings.notionToken || !settings.notionDbId) return;
|
||||
|
||||
console.log(`🔄 Synchronisation avec Notion (DB ID: ${settings.notionDbId.trim()})...`);
|
||||
const notion = new Client({ auth: settings.notionToken as string });
|
||||
let hasMore = true;
|
||||
let cursor: string | undefined = undefined;
|
||||
let count = 0;
|
||||
|
||||
while (hasMore) {
|
||||
// Utilisation de .search car c'est la méthode la plus compatible entre les versions du SDK
|
||||
// Elle permet de récupérer les pages (logs) rattachées à la base de données
|
||||
const response: any = await notion.search({
|
||||
filter: { value: 'page', property: 'object' },
|
||||
start_cursor: cursor,
|
||||
page_size: 100,
|
||||
});
|
||||
|
||||
for (const page of response.results) {
|
||||
// On vérifie que la page appartient bien à notre base de données cible
|
||||
if (page.parent?.type !== 'database_id' || page.parent.database_id.replace(/-/g, '') !== settings.notionDbId.replace(/-/g, '')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const props = (page as any).properties;
|
||||
const serviceName = props.Service?.title[0]?.plain_text;
|
||||
const logLine = props.Log?.rich_text[0]?.plain_text;
|
||||
|
||||
if (serviceName && logLine) {
|
||||
const hash = crypto.createHash('sha256').update(serviceName + '_' + logLine).digest('hex');
|
||||
if (!this.processedLogsCache.has(hash)) {
|
||||
this.processedLogsCache.set(hash, Date.now());
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasMore = response.has_more;
|
||||
cursor = response.next_cursor || undefined;
|
||||
}
|
||||
|
||||
console.log(`✅ Synchronisation terminée : ${count} nouveaux logs indexés depuis Notion.`);
|
||||
} catch (error) {
|
||||
console.error("❌ Échec de la synchronisation avec Notion:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async getDockerContainers() {
|
||||
try {
|
||||
const containers = await this.docker.listContainers({ all: true });
|
||||
return containers.map(c => ({
|
||||
id: c.Id,
|
||||
name: c.Names[0].replace('/', ''),
|
||||
state: c.State
|
||||
}));
|
||||
} catch (e) {
|
||||
console.error('Docker connect error:', e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getOsServices() {
|
||||
return new Promise((resolve) => {
|
||||
let cmd, args;
|
||||
if (process.platform === 'win32') {
|
||||
cmd = 'powershell';
|
||||
args = ['-Command', 'Get-Service | Select-Object Name, Status | ConvertTo-Json'];
|
||||
} else {
|
||||
cmd = 'systemctl';
|
||||
args = ['list-units', '--type=service', '--all'];
|
||||
}
|
||||
|
||||
const proc = spawn(cmd, args);
|
||||
let data = '';
|
||||
|
||||
proc.stdout.on('data', (chunk) => data += chunk);
|
||||
proc.on('close', () => {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const svcs = JSON.parse(data);
|
||||
resolve(svcs.map((s: any) => ({ name: s.Name, state: s.Status === 4 ? 'running' : 'stopped' })));
|
||||
} else {
|
||||
// Basic parsing for systemctl (very naive)
|
||||
const lines = data.split('\n').filter(l => l.includes('.service'));
|
||||
const svcs = lines.map(l => {
|
||||
const parts = l.trim().split(/\s+/);
|
||||
return { name: parts[0], state: parts[3] === 'running' ? 'running' : 'stopped' };
|
||||
});
|
||||
resolve(svcs);
|
||||
}
|
||||
} catch(e) {
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', () => resolve([]));
|
||||
});
|
||||
}
|
||||
|
||||
public getLogHistory(serviceId: number) {
|
||||
return this.logBuffers.get(serviceId) || [];
|
||||
}
|
||||
|
||||
async trackService(service: Service) {
|
||||
this.stopTracking(service.id);
|
||||
|
||||
if (service.type === 'docker') {
|
||||
this.trackDockerContainer(service);
|
||||
} else {
|
||||
this.trackOsService(service);
|
||||
}
|
||||
}
|
||||
|
||||
stopTracking(serviceId: number) {
|
||||
const stream = this.activeStreams.get(serviceId);
|
||||
if (stream) {
|
||||
if (typeof stream.destroy === 'function') stream.destroy();
|
||||
else if (typeof stream.kill === 'function') stream.kill();
|
||||
this.activeStreams.delete(serviceId);
|
||||
console.log(`Stopped tracking service ID: ${serviceId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async trackDockerContainer(service: Service) {
|
||||
try {
|
||||
let container = this.docker.getContainer(service.pathOrContainerId);
|
||||
|
||||
// Essayer de vérifier si le container existe via l'ID
|
||||
try {
|
||||
await container.inspect();
|
||||
} catch (err: any) {
|
||||
if (err.statusCode === 404) {
|
||||
console.log(`🔍 Container ID ${service.pathOrContainerId} non trouvé, tentative de résolution par nom "${service.name}"...`);
|
||||
const containers = await this.docker.listContainers({ all: true });
|
||||
const matching = containers.find(c => c.Names.some(name => {
|
||||
const cleanName = name.startsWith('/') ? name.substring(1) : name;
|
||||
return cleanName.toLowerCase() === service.name.toLowerCase() ||
|
||||
cleanName.toLowerCase() === service.pathOrContainerId.toLowerCase() ||
|
||||
cleanName.toLowerCase().includes('mock-log-service');
|
||||
}));
|
||||
|
||||
if (matching) {
|
||||
console.log(`✅ Trouvé nouveau ID pour ${service.name} : ${matching.Id}`);
|
||||
container = this.docker.getContainer(matching.Id);
|
||||
} else {
|
||||
throw new Error(`Container ${service.name} introuvable par ID ou par nom.`);
|
||||
}
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const stream = await container.logs({
|
||||
follow: true,
|
||||
stdout: true,
|
||||
stderr: true,
|
||||
tail: 100
|
||||
});
|
||||
|
||||
this.activeStreams.set(service.id, stream);
|
||||
|
||||
let buffer = Buffer.alloc(0);
|
||||
stream.on('data', (chunk: Buffer) => {
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
|
||||
while (buffer.length >= 8) {
|
||||
const type = buffer.readUInt8(0); // 1 = stdout, 2 = stderr
|
||||
const size = buffer.readUInt32BE(4);
|
||||
|
||||
if (buffer.length < 8 + size) break;
|
||||
|
||||
const message = buffer.toString('utf8', 8, 8 + size);
|
||||
buffer = buffer.slice(8 + size);
|
||||
|
||||
const lines = message.split('\n');
|
||||
for (const line of lines) {
|
||||
if (line.trim()) this.processLogLine(service, line.trim());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
stream.on('error', err => console.error(`Stream error for ${service.name}:`, err));
|
||||
stream.on('end', () => {
|
||||
console.log(`Docker log stream ended for ${service.name}`);
|
||||
this.activeStreams.delete(service.id);
|
||||
});
|
||||
|
||||
console.log(`Started Docker tracking for ${service.name}`);
|
||||
} catch (e) {
|
||||
console.error(`Failed to track docker container ${service.name}:`, e);
|
||||
}
|
||||
}
|
||||
|
||||
private trackOsService(service: Service) {
|
||||
let cmd, args;
|
||||
if (process.platform === 'win32') {
|
||||
// Using powershell Get-EventLog as a simple proxy for OS logs on windows
|
||||
cmd = 'powershell';
|
||||
args = ['-Command', `Get-EventLog -LogName Application -Source "${service.pathOrContainerId}" -Newest 10 -AsBaseObject | Wait-Event`];
|
||||
// Note: real tailing on windows requires more complex setup, this is a placeholder
|
||||
console.log("OS Service tailing on Windows is limited in this demo.");
|
||||
} else {
|
||||
cmd = 'journalctl';
|
||||
args = ['-u', service.pathOrContainerId, '-f', '-n', '100'];
|
||||
}
|
||||
|
||||
const cp = spawn(cmd, args);
|
||||
this.activeStreams.set(service.id, cp);
|
||||
|
||||
cp.stdout.on('data', (data: Buffer) => {
|
||||
const lines = data.toString('utf8').split('\n');
|
||||
for(const line of lines) {
|
||||
if(line.trim()) this.processLogLine(service, line.trim());
|
||||
}
|
||||
});
|
||||
|
||||
cp.stderr?.on('data', (data: Buffer) => {
|
||||
const lines = data.toString('utf8').split('\n');
|
||||
for(const line of lines) {
|
||||
if(line.trim()) this.processLogLine(service, line.trim());
|
||||
}
|
||||
});
|
||||
|
||||
cp.on('close', (code) => {
|
||||
console.log(`OS Service tracking ended for ${service.name} with code ${code}`);
|
||||
this.activeStreams.delete(service.id);
|
||||
});
|
||||
|
||||
console.log(`Started OS Service tracking for ${service.name}`);
|
||||
}
|
||||
|
||||
private async processLogLine(service: Service, line: string) {
|
||||
if (!line) return;
|
||||
|
||||
// Mise à jour du buffer d'historique (100 derniers logs)
|
||||
const isError = service.alertKeyword
|
||||
? line.includes(service.alertKeyword)
|
||||
: (line.includes('ERROR') || line.includes('Exception'));
|
||||
|
||||
const logEntry = {
|
||||
id: Date.now() + Math.random().toString(),
|
||||
line,
|
||||
isError
|
||||
};
|
||||
|
||||
let buffer = this.logBuffers.get(service.id);
|
||||
if (!buffer) {
|
||||
buffer = [];
|
||||
this.logBuffers.set(service.id, buffer);
|
||||
}
|
||||
buffer.push(logEntry);
|
||||
if (buffer.length > this.MAX_BUFFER_SIZE) {
|
||||
buffer.shift();
|
||||
}
|
||||
|
||||
this.io.emit('logLine', { serviceId: service.id, line });
|
||||
|
||||
const settings = await this.prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings?.notionToken || !settings?.notionDbId) {
|
||||
return; // Missing configuration
|
||||
}
|
||||
|
||||
// Normalisation pour la déduplication : on retire les dates et les espaces superflus
|
||||
// Cela permet d'identifier le même log même si l'en-tête temporel change
|
||||
const normalizedLine = line
|
||||
.replace(/\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\b\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\w+\s+\d{4}/gi, '')
|
||||
.replace(/\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}.*/gi, '') // Format ISO
|
||||
.trim();
|
||||
|
||||
const hash = crypto.createHash('sha256').update(service.name + '_' + normalizedLine).digest('hex');
|
||||
const now = Date.now();
|
||||
const lastSeen = this.processedLogsCache.get(hash);
|
||||
|
||||
// If we've seen this same message context in the last 15 minutes, skip
|
||||
if (lastSeen && (now - lastSeen < 15 * 60 * 1000)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.processedLogsCache.set(hash, now);
|
||||
|
||||
// Ajout à la pile pour traitement par lots
|
||||
this.logStack.push(service, line);
|
||||
}
|
||||
|
||||
private async processLogBatch(service: Service, lines: string[]) {
|
||||
const settings = await this.prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||
if (!settings?.ollamaUrl) return;
|
||||
|
||||
try {
|
||||
const results = await analyzeLogBatch(lines, settings);
|
||||
|
||||
for (const result of results) {
|
||||
// FILTRAGE POST-IA : Seuls les logs problématiques vont vers Notion
|
||||
if (result.status !== 'Normal') {
|
||||
await sendNotionAlert(service, result.originalLog, settings, result);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Batch Analysis failed:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Client } from '@notionhq/client';
|
||||
import { Service, GlobalSettings } from '@prisma/client';
|
||||
import { AIAnalysisResult } from './aiOrchestrator';
|
||||
|
||||
export async function sendNotionAlert(service: Service, logLine: string, settings: GlobalSettings, analysis: AIAnalysisResult) {
|
||||
const notion = new Client({ auth: settings.notionToken! });
|
||||
|
||||
await notion.pages.create({
|
||||
parent: { database_id: settings.notionDbId! },
|
||||
properties: {
|
||||
"Service": { // C'est votre colonne "Titre" actuelle
|
||||
title: [
|
||||
{
|
||||
text: { content: analysis.shortTitle }
|
||||
}
|
||||
]
|
||||
},
|
||||
"Machine": { // Le nom du service Docker/OS ira ici
|
||||
select: { name: service.name }
|
||||
},
|
||||
"Status": {
|
||||
select: { name: analysis.status }
|
||||
},
|
||||
"Source": {
|
||||
select: { name: service.type === 'docker' ? '📦 Docker' : '💻 OS' }
|
||||
},
|
||||
"Description": {
|
||||
rich_text: [
|
||||
{
|
||||
text: { content: analysis.description.substring(0, 2000) }
|
||||
}
|
||||
]
|
||||
},
|
||||
"Solution": {
|
||||
rich_text: [
|
||||
{
|
||||
text: { content: analysis.solution.substring(0, 2000) }
|
||||
}
|
||||
]
|
||||
},
|
||||
"Log": {
|
||||
rich_text: [
|
||||
{
|
||||
text: { content: logLine.substring(0, 2000) }
|
||||
}
|
||||
]
|
||||
},
|
||||
"Date": {
|
||||
date: {
|
||||
start: new Date().toISOString()
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
console.log(`Notion alert sent for ${service.name} (Status: ${analysis.status})`);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { GlobalSettings } from '@prisma/client';
|
||||
|
||||
export async function queryOllama(prompt: string, settings: GlobalSettings): Promise<string> {
|
||||
if (!settings.ollamaUrl || !settings.ollamaModel) {
|
||||
throw new Error("Ollama configuration is missing");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${settings.ollamaUrl}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: settings.ollamaModel,
|
||||
prompt: prompt,
|
||||
stream: false,
|
||||
keep_alive: "1h",
|
||||
options: { num_ctx: 4096 }
|
||||
}),
|
||||
signal: AbortSignal.timeout(300000) // Timeout de 5 min
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama API error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json() as { response: string };
|
||||
return data.response || "";
|
||||
} catch (error) {
|
||||
console.error("Error querying Ollama:", error);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export async function chatWithOllama(messages: ChatMessage[], settings: GlobalSettings): Promise<string> {
|
||||
if (!settings.ollamaUrl || !settings.ollamaModel) {
|
||||
throw new Error("Ollama configuration is missing");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${settings.ollamaUrl}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: settings.ollamaModel,
|
||||
messages: messages,
|
||||
stream: false,
|
||||
keep_alive: "1h",
|
||||
options: { num_ctx: 4096 }
|
||||
}),
|
||||
signal: AbortSignal.timeout(300000)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama Chat error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json() as { message: { content: string } };
|
||||
return data.message?.content || "";
|
||||
} catch (error) {
|
||||
console.error("Error chatting with Ollama:", error);
|
||||
return "Erreur lors de la communication avec l'IA.";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tentative de requête avec repli (fallback) si la première échoue ou est vide.
|
||||
*/
|
||||
export async function queryOllamaWithFallback(mainPrompt: string, fallbackPrompt: string, settings: GlobalSettings): Promise<string> {
|
||||
let response = await queryOllama(mainPrompt, settings);
|
||||
|
||||
if (!response || response.trim() === "") {
|
||||
console.warn("⚠️ Premier essai Ollama vide, tentative de fallback...");
|
||||
response = await queryOllama(fallbackPrompt, settings);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat Streamed (NDJSON / Server-Sent Events)
|
||||
*/
|
||||
export async function chatWithOllamaStream(
|
||||
messages: ChatMessage[],
|
||||
settings: GlobalSettings,
|
||||
onChunk: (chunk: string) => void,
|
||||
externalSignal?: AbortSignal
|
||||
): Promise<string> {
|
||||
if (!settings.ollamaUrl || !settings.ollamaModel) {
|
||||
throw new Error("Ollama configuration is missing");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${settings.ollamaUrl}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: settings.ollamaModel,
|
||||
messages: messages,
|
||||
stream: true, // IMPORTANT: Activation du flux partiel
|
||||
keep_alive: "1h",
|
||||
options: { num_ctx: 4096 }
|
||||
}),
|
||||
signal: externalSignal
|
||||
? AbortSignal.any([AbortSignal.timeout(300000), externalSignal])
|
||||
: AbortSignal.timeout(300000)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ollama Chat Stream error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error("No response body returned from Ollama.");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
let fullContent = "";
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunkStr = decoder.decode(value, { stream: true });
|
||||
const lines = chunkStr.split('\n').filter(line => line.trim() !== '');
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const parsed = JSON.parse(line);
|
||||
if (parsed.message?.content) {
|
||||
fullContent += parsed.message.content;
|
||||
onChunk(parsed.message.content); // Call immediately for the UI
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore parse errors on partial chunks
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fullContent;
|
||||
} catch (error) {
|
||||
console.error("Error streaming chat with Ollama:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { GlobalSettings } from '@prisma/client';
|
||||
|
||||
export interface SearchResult {
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export async function searchWeb(query: string, settings: GlobalSettings): Promise<SearchResult[]> {
|
||||
if (!settings.searxngUrl) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(`${settings.searxngUrl}/search`);
|
||||
url.searchParams.append('q', query);
|
||||
url.searchParams.append('format', 'json');
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
},
|
||||
signal: (AbortSignal as any).timeout(5000) // Timeout de 5s pour la recherche
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`SearXNG error: ${response.statusText}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = await response.json() as any;
|
||||
|
||||
// Extract top 3 relevant snippets
|
||||
return (data.results || []).slice(0, 3).map((r: any) => ({
|
||||
title: r.title,
|
||||
url: r.url,
|
||||
content: r.content
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch from SearXNG:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"module": "commonjs",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user