diff --git a/infra/n8n/workflows/alert-queue-processor.json b/infra/n8n/workflows/alert-queue-processor.json new file mode 100644 index 0000000..62d50c2 --- /dev/null +++ b/infra/n8n/workflows/alert-queue-processor.json @@ -0,0 +1,177 @@ +[ + { + "updatedAt": "2026-08-05T20:15:46.000Z", + "createdAt": "2026-08-05T20:15:42.923Z", + "id": "alertQueueProc01", + "name": "Alert Queue Processor", + "description": null, + "active": true, + "isArchived": false, + "nodes": [ + { + "parameters": { + "rule": { + "interval": [ + { + "field": "minutes", + "minutesInterval": 15 + } + ] + } + }, + "name": "Every 15 Minutes", + "type": "n8n-nodes-base.scheduleTrigger", + "typeVersion": 1.2, + "position": [ + 260, + 300 + ], + "id": "cron" + }, + { + "parameters": { + "operation": "executeQuery", + "query": "SELECT * FROM alert_queue ORDER BY created_at", + "options": {} + }, + "name": "Get Queue", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 460, + 300 + ], + "id": "getqueue", + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + }, + { + "parameters": { + "jsCode": "\nconst items = $('Get Queue').all();\nif (items.length === 0) return [];\nconst alerts = items.map(i => i.json);\nconst hosts = [...new Set(alerts.map(a => a.host))];\nconst lines = alerts.map(a => `${a.host} (${a.ip}): ${a.alert_text}`).join('\\n');\nconst title = hosts.length === 1 ? `🚨 ${hosts[0]} (${alerts[0].ip})` : `🚨 Массовый сбой (${hosts.length} хостов)`;\nreturn [{ json: { text: `${title}\\n\\n${lines}` } }];\n" + }, + "name": "Aggregate Alerts", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 660, + 300 + ], + "id": "aggregate" + }, + { + "parameters": { + "chatId": "273442500", + "text": "={{ $json.text }}" + }, + "name": "Send Summary", + "type": "n8n-nodes-base.telegram", + "typeVersion": 1.2, + "position": [ + 860, + 300 + ], + "id": "sendsummary", + "credentials": { + "telegramApi": { + "id": "MI5ZSM5d514km2wE", + "name": "Telegram Bot" + } + } + }, + { + "parameters": { + "operation": "executeQuery", + "query": "DELETE FROM alert_queue", + "options": {} + }, + "name": "Clear Queue", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 1060, + 300 + ], + "id": "clearqueue", + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + } + ], + "connections": { + "Every 15 Minutes": { + "main": [ + [ + { + "node": "Get Queue", + "type": "main", + "index": 0 + } + ] + ] + }, + "Get Queue": { + "main": [ + [ + { + "node": "Aggregate Alerts", + "type": "main", + "index": 0 + } + ] + ] + }, + "Aggregate Alerts": { + "main": [ + [ + { + "node": "Send Summary", + "type": "main", + "index": 0 + } + ] + ] + }, + "Send Summary": { + "main": [ + [ + { + "node": "Clear Queue", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1" + }, + "staticData": { + "node:Every 15 Minutes": { + "recurrenceRules": [ + null + ], + "recurrenceRuleSignatures": [ + null + ] + } + }, + "meta": null, + "nodeGroups": [], + "pinData": {}, + "triggerCount": 1, + "sourceWorkflowId": null, + "tags": [], + "versionMetadata": { + "name": null, + "description": null + } + } +] diff --git a/infra/n8n/workflows/buryan-health-monitor.json b/infra/n8n/workflows/buryan-health-monitor.json new file mode 100644 index 0000000..81ec8fc --- /dev/null +++ b/infra/n8n/workflows/buryan-health-monitor.json @@ -0,0 +1,239 @@ +[ + { + "updatedAt": "2026-08-05T20:52:59.000Z", + "createdAt": "2026-08-03T21:21:20.902Z", + "id": "afdmDW35vpDd6oNs", + "name": "Buryan Health Monitor", + "description": null, + "active": true, + "isArchived": false, + "nodes": [ + { + "parameters": { + "httpMethod": "POST", + "path": "buryan-health", + "options": {} + }, + "type": "n8n-nodes-base.webhook", + "typeVersion": 2.1, + "position": [ + 0, + 0 + ], + "id": "4970a1ff-d80f-4b39-a443-07bd2954186b", + "name": "Webhook", + "webhookId": "9c0ce777-9b87-44f1-b800-38f5c8fba650" + }, + { + "parameters": { + "operation": "executeQuery", + "query": "SELECT CASE WHEN h.host IS NULL THEN 0 ELSE 1 END AS has_prev, COALESCE(h.failed,0) AS failed, COALESCE(h.mem,0) AS mem, COALESCE(h.disk,0) AS disk FROM (VALUES (1)) v LEFT JOIN host_states h ON h.host = '{{ $json.body.host }}'", + "options": {} + }, + "id": "getprevstate", + "name": "Get Prev State", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 260, + 300 + ], + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + }, + { + "parameters": { + "jsCode": "const body = $('Webhook').first().json.body || {};\nconst prevRows = $('Get Prev State').all();\nconst prev = (prevRows.length && prevRows[0].json.has_prev) ? prevRows[0].json : null;\nconst failed = body.failed || 0, mem = body.mem || 0, disk = body.disk || 0;\nconst alerts = [];\n\nif (!prev) {\n if (failed > 0) alerts.push('❌ Упало контейнеров: ' + failed);\n if (mem >= 90) alerts.push('❌ Память критична: ' + mem + '%');\n if (disk >= 90) alerts.push('❌ Диск критичен: ' + disk + '%');\n} else {\n const pf = prev.failed || 0, pm = prev.mem || 0, pd = prev.disk || 0;\n \n // failed изменения\n if (pf === 0 && failed > 0) alerts.push('❌ Упало контейнеров: ' + failed);\n if (pf > 0 && failed === 0) alerts.push('✅ Контейнеры восстановлены');\n \n // mem изменения (переход через 90)\n if (pm < 90 && mem >= 90) alerts.push('❌ Память критична: ' + mem + '%');\n if (pm >= 90 && mem < 90) alerts.push('✅ Память в норме: ' + mem + '%');\n \n // disk изменения (переход через 90)\n if (pd < 90 && disk >= 90) alerts.push('❌ Диск критичен: ' + disk + '%');\n if (pd >= 90 && disk < 90) alerts.push('✅ Диск в норме: ' + disk + '%');\n}\n\nreturn [{ json: {\n send_alert: alerts.length > 0,\n alert_text: alerts.join('\\n'),\n host: body.host || 'unknown',\n ip: body.ip || '',\n failed: failed,\n restarted: body.restarted || 0,\n mem: mem,\n disk: disk,\n containers: JSON.stringify(body.containers || []).replace(/'/g, \"''\")\n}}];\n" + }, + "name": "Compare States", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 460, + 300 + ], + "id": "comparestates" + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "typeValidation": "strict" + }, + "conditions": [ + { + "leftValue": "={{ $json.send_alert }}", + "rightValue": true, + "operator": { + "type": "boolean", + "operation": "equals", + "singleValue": true + } + } + ], + "combinator": "and" + }, + "options": {} + }, + "name": "State Changed?", + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + 660, + 300 + ], + "id": "statechanged" + }, + { + "parameters": { + "operation": "executeQuery", + "query": "INSERT INTO host_states (host, ip, failed, restarted, mem, disk, containers, last_report_at, last_alert_sent) VALUES ('{{ $('Compare States').first().json.host }}', '{{ $('Compare States').first().json.ip }}', {{ $('Compare States').first().json.failed }}, {{ $('Compare States').first().json.restarted }}, {{ $('Compare States').first().json.mem }}, {{ $('Compare States').first().json.disk }}, '{{ $('Compare States').first().json.containers }}'::jsonb, NOW(), NOW()) ON CONFLICT (host) DO UPDATE SET ip=EXCLUDED.ip, failed=EXCLUDED.failed, restarted=EXCLUDED.restarted, mem=EXCLUDED.mem, disk=EXCLUDED.disk, containers=EXCLUDED.containers, last_report_at=NOW(), last_alert_sent=NOW()", + "options": {} + }, + "id": "upsertwithalert", + "name": "Upsert With Alert", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 1060, + 100 + ], + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + }, + { + "parameters": { + "operation": "executeQuery", + "query": "INSERT INTO host_states (host, ip, failed, restarted, mem, disk, containers, last_report_at)\nVALUES ('{{ $json.host }}', '{{ $json.ip }}', {{ $json.failed }}, {{ $json.restarted }}, {{ $json.mem }}, {{ $json.disk }}, '{{ $json.containers }}'::jsonb, NOW())\nON CONFLICT (host) DO UPDATE SET ip=EXCLUDED.ip, failed=EXCLUDED.failed, restarted=EXCLUDED.restarted, mem=EXCLUDED.mem, disk=EXCLUDED.disk, containers=EXCLUDED.containers, last_report_at=NOW()", + "options": {} + }, + "id": "upsertnoalert", + "name": "Upsert No Alert", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 860, + 450 + ], + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + }, + { + "parameters": { + "operation": "executeQuery", + "query": "INSERT INTO alert_queue (host, ip, alert_type, alert_text, mem, disk)\nVALUES (\n '{{ $('Compare States').first().json.host }}',\n '{{ $('Compare States').first().json.ip }}',\n CASE\n WHEN {{ $('Compare States').first().json.failed }} > 0 THEN 'failed_up'\n WHEN {{ $('Compare States').first().json.failed }} = 0 THEN 'failed_down'\n WHEN {{ $('Compare States').first().json.mem }} >= 90 THEN 'mem_up'\n WHEN {{ $('Compare States').first().json.mem }} < 90 THEN 'mem_down'\n WHEN {{ $('Compare States').first().json.disk }} >= 90 THEN 'disk_up'\n WHEN {{ $('Compare States').first().json.disk }} < 90 THEN 'disk_down'\n END,\n '{{ $('Compare States').first().json.alert_text }}',\n {{ $('Compare States').first().json.mem }},\n {{ $('Compare States').first().json.disk }}\n)", + "options": {} + }, + "id": "insertqueue", + "name": "Insert Alert Queue", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.4, + "position": [ + 860, + 200 + ], + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + } + ], + "connections": { + "Webhook": { + "main": [ + [ + { + "node": "Get Prev State", + "type": "main", + "index": 0 + } + ] + ] + }, + "Get Prev State": { + "main": [ + [ + { + "node": "Compare States", + "type": "main", + "index": 0 + } + ] + ] + }, + "Compare States": { + "main": [ + [ + { + "node": "State Changed?", + "type": "main", + "index": 0 + } + ] + ] + }, + "State Changed?": { + "main": [ + [ + { + "node": "Insert Alert Queue", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Upsert No Alert", + "type": "main", + "index": 0 + } + ] + ] + }, + "Insert Alert Queue": { + "main": [ + [ + { + "node": "Upsert With Alert", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1", + "binaryMode": "separate", + "availableInMCP": false + }, + "staticData": null, + "meta": { + "templateCredsSetupCompleted": true + }, + "nodeGroups": [], + "pinData": {}, + "triggerCount": 1, + "sourceWorkflowId": null, + "tags": [], + "versionMetadata": { + "name": null, + "description": null + } + } +] diff --git a/infra/n8n/workflows/gitea-task-dispatcher.json b/infra/n8n/workflows/gitea-task-dispatcher.json new file mode 100644 index 0000000..14f7096 --- /dev/null +++ b/infra/n8n/workflows/gitea-task-dispatcher.json @@ -0,0 +1,147 @@ +[ + { + "id": "eqYDYibHxBt8NPq4", + "name": "Gitea Task Dispatcher", + "active": true, + "nodes": [ + { + "parameters": { + "httpMethod": "POST", + "path": "gitea-task", + "options": {} + }, + "name": "Webhook", + "type": "n8n-nodes-base.webhook", + "typeVersion": 2.1, + "position": [ + 0, + 0 + ], + "webhookId": "fe5c7ad8-99fa-45f5-8e75-a365d7f08ae22" + }, + { + "parameters": { + "jsCode": "const w = $input.first().json;\nconst d = w.body || {};\nconst action = d.action || '';\nif (action !== 'opened' && action !== 'closed') return [];\nconst i = d.issue || {};\nconst r = d.repository || {};\nconst prefix = action === 'closed' ? 'CLOSED' : 'NEW';\nconst text = prefix + ' ' + (i.title || '?') + ' #' + (i.number || '?') + ' in ' + (r.full_name || '?') + '\\n' + (i.html_url || '');\nreturn [{ json: { text: text, critical: action === 'closed', repo: r.full_name || '?', alert_type: 'gitea_issue_' + action, alert_text: text } }];" + }, + "name": "Parse", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 240, + 0 + ] + }, + { + "parameters": { + "jsCode": "return $input.all().filter(it => it.json.critical);" + }, + "name": "OnlyCritical", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 480, + -120 + ] + }, + { + "parameters": { + "chatId": "273442500", + "text": "={{ $json.text }}" + }, + "name": "Telegram Send", + "type": "n8n-nodes-base.telegram", + "typeVersion": 1.2, + "position": [ + 720, + -120 + ], + "credentials": { + "telegramApi": { + "id": "MI5ZSM5d514km2wE", + "name": "Telegram Bot" + } + } + }, + { + "parameters": { + "operation": "insert", + "schema": { + "__rl": true, + "mode": "name", + "value": "public" + }, + "table": { + "__rl": true, + "mode": "name", + "value": "alert_queue" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "host": "={{ $json.repo }}", + "alert_type": "={{ $json.alert_type }}", + "alert_text": "={{ $json.alert_text }}" + } + }, + "options": {} + }, + "name": "Queue Insert", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2.5, + "position": [ + 480, + 120 + ], + "credentials": { + "postgres": { + "id": "8czcy3lV8sUxWTd9", + "name": "Monitoring" + } + } + } + ], + "connections": { + "Webhook": { + "main": [ + [ + { + "node": "Parse", + "type": "main", + "index": 0 + } + ] + ] + }, + "Parse": { + "main": [ + [ + { + "node": "OnlyCritical", + "type": "main", + "index": 0 + }, + { + "node": "Queue Insert", + "type": "main", + "index": 0 + } + ] + ] + }, + "OnlyCritical": { + "main": [ + [ + { + "node": "Telegram Send", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1" + } + } +] diff --git a/infra/n8n/workflows/workflow-current.json b/infra/n8n/workflows/workflow-current.json new file mode 100644 index 0000000..74c3701 --- /dev/null +++ b/infra/n8n/workflows/workflow-current.json @@ -0,0 +1,229 @@ +[ + { + "id": "TSqu00NJx2JOrtoN", + "name": "Uptime Kuma → Gitea Self-Healing", + "description": null, + "active": true, + "createdAt": "2026-09-11T12:37:51.879Z", + "updatedAt": "2026-09-25T07:26:21.344Z", + "isArchived": false, + "sourceWorkflowId": null, + "triggerCount": 1, + "nodes": [ + { + "name": "Uptime Kuma Webhook", + "webhookId": "95de5809-c2a6-4ba1-a472-89debbc46fbb", + "type": "n8n-nodes-base.webhook", + "typeVersion": 2, + "position": [ + 256, + 304 + ], + "parameters": { + "path": "uptime-kuma", + "options": {}, + "httpMethod": "POST", + "responseMode": "responseNode" + }, + "id": "3d7a7e98-5b78-4709-9474-1e10bae2469b" + }, + { + "name": "Extract Info", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 480, + 304 + ], + "parameters": { + "jsCode": "const webhookData = $input.first().json;\nconst body = webhookData.body || webhookData;\n\nconst monitorName = body.monitor_name || 'Unknown';\nconst monitorUrl = body.monitor_url || '';\nconst status = parseInt(body.heartbeat_status) || 0;\nconst message = body.heartbeat_message || 'Service is down';\n\nconst ctMatch = monitorName.match(/\\((\\d+)\\)/);\nconst ctId = ctMatch ? ctMatch[1] : null;\n\nreturn [{\n json: {\n monitorName,\n monitorUrl,\n status,\n message,\n ctId,\n timestamp: new Date().toISOString(),\n shouldAlert: status === 0 && ctId !== null\n }\n}];" + }, + "id": "49a459f5-1b1e-4bd6-83d9-b231a7d018c6" + }, + { + "name": "Should Create Issue?", + "type": "n8n-nodes-base.if", + "typeVersion": 2, + "position": [ + 720, + 304 + ], + "parameters": { + "options": {}, + "conditions": { + "boolean": [ + { + "value1": "={{ $json.shouldAlert }}", + "value2": true + } + ], + "options": { + "version": 1, + "leftValue": "", + "caseSensitive": true, + "typeValidation": "strict" + }, + "combinator": "and" + } + }, + "id": "a5a56bde-cd3c-404c-959d-5eb4cf344f80" + }, + { + "name": "Create Gitea Issue", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 944, + 208 + ], + "parameters": { + "url": "http://192.168.1.140:3000/api/v1/repos/root/buryan-hub/issues", + "method": "POST", + "options": {}, + "jsonBody": "={{ JSON.stringify({ title: \"AUTO-FIX: \" + $json.monitorName + \" DOWN\", body: \"CT_DOWN:\" + $json.ctId + \"\\n\\nАвтоматическое восстановление \" + $json.monitorName + \".\\n\\nURL: \" + $json.monitorUrl + \"\\nMessage: \" + $json.message + \"\\nTime: \" + $json.timestamp, labels: [2] }) }}", + "sendBody": true, + "sendHeaders": true, + "specifyBody": "json", + "headerParameters": { + "parameters": [ + { + "name": "Authorization", + "value": "token 416f50c1a559be2def78bd6e3616a97906b0623d" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + } + }, + "id": "ffc579ec-a0cf-41d4-9444-66fc9af71bfb" + }, + { + "name": "Respond", + "type": "n8n-nodes-base.respondToWebhook", + "typeVersion": 1.1, + "position": [ + 1184, + 208 + ], + "parameters": { + "options": {}, + "respondWith": "json", + "responseBody": "={{ JSON.stringify({ ok: true, issue_created: $json.html_url || null }) }}" + }, + "id": "b7050fd1-a247-4b50-846d-4358e7073e89" + }, + { + "id": "06142831-0672-469e-898e-79463b84f3db", + "name": "Notify Telegram", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 1200, + 304 + ], + "parameters": { + "method": "POST", + "url": "https://193.233.210.184/tg-api/bot8668603602:AAHVmUmq44dcomw8QOfw_qj1aICXuT5c5XU/sendMessage", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "bodyParameters": { + "parameters": [ + { + "name": "chat_id", + "value": "=273442500" + }, + { + "name": "text", + "value": "=🚨 {{ $json.monitorName }} DOWN\n\nURL: {{ $json.monitorUrl }}\nВремя: {{ new Date().toLocaleString(\"ru-RU\") }}\n\nIssue создан в Gitea" + }, + { + "name": "parse_mode", + "value": "HTML" + } + ] + }, + "options": { + "allowUnauthorizedCerts": true + }, + "proxy": "http://193.233.210.184:1080" + } + } + ], + "connections": { + "Extract Info": { + "main": [ + [ + { + "node": "Should Create Issue?", + "type": "main", + "index": 0 + } + ] + ] + }, + "Create Gitea Issue": { + "main": [ + [ + { + "node": "Notify Telegram", + "type": "main", + "index": 0 + } + ] + ] + }, + "Uptime Kuma Webhook": { + "main": [ + [ + { + "node": "Extract Info", + "type": "main", + "index": 0 + } + ] + ] + }, + "Should Create Issue?": { + "main": [ + [ + { + "node": "Create Gitea Issue", + "type": "main", + "index": 0 + } + ] + ] + }, + "Notify Telegram": { + "main": [ + [ + { + "node": "Respond", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "nodeGroups": [], + "settings": { + "binaryMode": "separate", + "executionOrder": "v1" + }, + "staticData": null, + "pinData": {}, + "meta": null, + "tags": [] + } +]