feat(webhook): integra listener com a API de Status do Gitea
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
const http = require('http');
|
const http = require('http');
|
||||||
|
const https = require('https'); // Adicionado caso precise de HTTPS, mas usaremos HTTP para a VPN
|
||||||
const { exec } = require('child_process');
|
const { exec } = require('child_process');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
@@ -7,6 +8,8 @@ const HOST = '10.99.0.4';
|
|||||||
const SECRET_TOKEN = 'gitea_webhook_secret_clube67_58e4a92c3d18';
|
const SECRET_TOKEN = 'gitea_webhook_secret_clube67_58e4a92c3d18';
|
||||||
const SCRIPT_PATH = '/home/deploy/stack/clube67/deploy-prod-builder.sh';
|
const SCRIPT_PATH = '/home/deploy/stack/clube67/deploy-prod-builder.sh';
|
||||||
const LOG_FILE = '/home/deploy/stack/webhook-listener/deploy.log';
|
const LOG_FILE = '/home/deploy/stack/webhook-listener/deploy.log';
|
||||||
|
const GITEA_API_URL = 'http://10.99.0.3:3000/api/v1';
|
||||||
|
const GITEA_TOKEN = process.env.GITEA_TOKEN || 'ada47ca2fb196319dd10245cc216a327dac857ec';
|
||||||
|
|
||||||
function log(message) {
|
function log(message) {
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
@@ -15,6 +18,45 @@ function log(message) {
|
|||||||
fs.appendFileSync(LOG_FILE, logMessage, 'utf8');
|
fs.appendFileSync(LOG_FILE, logMessage, 'utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Funcao para atualizar o status do commit no Gitea usando a API
|
||||||
|
function updateCommitStatus(owner, repo, sha, state, description) {
|
||||||
|
if (!owner || !repo || !sha) return;
|
||||||
|
const postData = JSON.stringify({
|
||||||
|
state: state,
|
||||||
|
target_url: 'http://' + HOST + ':' + PORT,
|
||||||
|
description: description,
|
||||||
|
context: 'continuous-integration/webhook'
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = new URL(`${GITEA_API_URL}/repos/${owner}/${repo}/statuses/${sha}`);
|
||||||
|
const options = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: url.port,
|
||||||
|
path: url.pathname,
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': 'token ' + GITEA_TOKEN,
|
||||||
|
'Content-Length': Buffer.byteLength(postData)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const req = http.request(options, (res) => {
|
||||||
|
let responseBody = '';
|
||||||
|
res.on('data', chunk => responseBody += chunk);
|
||||||
|
res.on('end', () => {
|
||||||
|
log(`Gitea Status API (${state}): HTTP ${res.statusCode}`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', (e) => {
|
||||||
|
log(`Erro ao chamar API do Gitea: ${e.message}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
req.write(postData);
|
||||||
|
req.end();
|
||||||
|
}
|
||||||
|
|
||||||
// Garante que o arquivo de log exista
|
// Garante que o arquivo de log exista
|
||||||
try {
|
try {
|
||||||
if (!fs.existsSync(LOG_FILE)) {
|
if (!fs.existsSync(LOG_FILE)) {
|
||||||
@@ -70,7 +112,6 @@ const server = http.createServer((req, res) => {
|
|||||||
let body = '';
|
let body = '';
|
||||||
req.on('data', function(chunk) { body += chunk.toString(); });
|
req.on('data', function(chunk) { body += chunk.toString(); });
|
||||||
req.on('end', function() {
|
req.on('end', function() {
|
||||||
// Verificar se todos os commits sao bumps de versao automaticos (evita loop infinito)
|
|
||||||
var payload = {};
|
var payload = {};
|
||||||
try { payload = JSON.parse(body); } catch (e) {}
|
try { payload = JSON.parse(body); } catch (e) {}
|
||||||
|
|
||||||
@@ -78,8 +119,15 @@ const server = http.createServer((req, res) => {
|
|||||||
var headMsg = (payload.head_commit || {}).message || '';
|
var headMsg = (payload.head_commit || {}).message || '';
|
||||||
var allMessages = commits.map(function(c) { return c.message || ''; }).concat(headMsg).filter(function(m) { return m.trim() !== ''; });
|
var allMessages = commits.map(function(c) { return c.message || ''; }).concat(headMsg).filter(function(m) { return m.trim() !== ''; });
|
||||||
var VERSION_BUMP_RE = /^chore\(deploy\):\s*bump version/i;
|
var VERSION_BUMP_RE = /^chore\(deploy\):\s*bump version/i;
|
||||||
|
|
||||||
|
// Extrai dados do repositorio para a API do Gitea
|
||||||
|
const repoOwner = payload.repository && payload.repository.owner ? payload.repository.owner.login : null;
|
||||||
|
const repoName = payload.repository ? payload.repository.name : null;
|
||||||
|
const commitSha = payload.after || (payload.head_commit ? payload.head_commit.id : null);
|
||||||
|
|
||||||
if (allMessages.length > 0 && allMessages.every(function(msg) { return VERSION_BUMP_RE.test(msg); })) {
|
if (allMessages.length > 0 && allMessages.every(function(msg) { return VERSION_BUMP_RE.test(msg); })) {
|
||||||
log('Commit de bump de versao detectado -- deploy ignorado para evitar loop de CI.');
|
log('Commit de bump de versao detectado -- deploy ignorado para evitar loop de CI.');
|
||||||
|
updateCommitStatus(repoOwner, repoName, commitSha, 'success', 'Ignorado: bump version');
|
||||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
return res.end(JSON.stringify({ status: 'skipped', reason: 'version-bump commit' }));
|
return res.end(JSON.stringify({ status: 'skipped', reason: 'version-bump commit' }));
|
||||||
}
|
}
|
||||||
@@ -92,17 +140,24 @@ const server = http.createServer((req, res) => {
|
|||||||
isBuilding = true;
|
isBuilding = true;
|
||||||
log('Iniciando deploy-prod-builder.sh...');
|
log('Iniciando deploy-prod-builder.sh...');
|
||||||
|
|
||||||
|
// Atualiza Gitea dizendo que o build comecou
|
||||||
|
updateCommitStatus(repoOwner, repoName, commitSha, 'pending', 'Deploy em andamento na VPS 4');
|
||||||
|
|
||||||
exec(SCRIPT_PATH, function(error, stdout, stderr) {
|
exec(SCRIPT_PATH, function(error, stdout, stderr) {
|
||||||
isBuilding = false;
|
isBuilding = false;
|
||||||
if (error) {
|
if (error) {
|
||||||
log('Erro no processo de deploy: ' + error.message);
|
log('Erro no processo de deploy: ' + error.message);
|
||||||
|
// Atualiza Gitea dizendo que o build falhou
|
||||||
|
updateCommitStatus(repoOwner, repoName, commitSha, 'failure', 'Falha no deploy (VPS 4)');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
log('Processo de deploy finalizado.');
|
log('Processo de deploy finalizado.');
|
||||||
|
// Atualiza Gitea dizendo que o build foi concluido com sucesso
|
||||||
|
updateCommitStatus(repoOwner, repoName, commitSha, 'success', 'Deploy concluido com sucesso (VPS 4)');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(PORT, HOST, function() {
|
server.listen(PORT, HOST, function() {
|
||||||
log('Webhook listener ativo em http://' + HOST + ':' + PORT + '/webhook');
|
log('Webhook listener ativo em http://' + HOST + ':' + PORT + '/webhook com integracao a API do Gitea');
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user