poad 2.15.0 → 2.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/run.js +1 -0
- package/global/start.js +16 -1
- package/package.json +2 -2
- package/project/cli.js +1 -0
- package/project/gen/types.js +2 -1
- package/project/logs.js +129 -0
- package/utils/logs.js +77 -0
- package/utils/mail.js +1 -0
- package/utils/valkey.js +1 -0
package/global/run.js
CHANGED
|
@@ -140,6 +140,7 @@ module.exports = async (args = {}) => {
|
|
|
140
140
|
PortBindings: { '8080/tcp': [{ HostPort: String(port) }] },
|
|
141
141
|
Binds: [`${importDir}:/opt/keycloak/data/import:ro`],
|
|
142
142
|
AutoRemove: true,
|
|
143
|
+
...require('../utils/logs').containerLogConfig(config),
|
|
143
144
|
},
|
|
144
145
|
});
|
|
145
146
|
await container.start();
|
package/global/start.js
CHANGED
|
@@ -58,9 +58,13 @@ module.exports = async (args = {}) => {
|
|
|
58
58
|
const progress = ora('Starting containers').start();
|
|
59
59
|
try {
|
|
60
60
|
// Réseau du projet : l'engine y joint Mailpit (« mail ») et Keycloak
|
|
61
|
+
// Collecteur des journaux : port GELF de l'engine, choisi avant de lancer
|
|
62
|
+
// Mailpit (qui y envoie ses journaux)
|
|
63
|
+
const logs = require('../utils/logs');
|
|
64
|
+
await logs.ensureGelfPort(root, config);
|
|
61
65
|
await mail.ensureNetwork(docker, config);
|
|
62
|
-
if (mailpit) await mail.startMailpit(docker, config);
|
|
63
66
|
const net = mail.onNetwork(config, 'engine');
|
|
67
|
+
const gelf = logs.engineBindings(config);
|
|
64
68
|
const container = await docker.createContainer({
|
|
65
69
|
name: containerName,
|
|
66
70
|
Image: image,
|
|
@@ -71,6 +75,9 @@ module.exports = async (args = {}) => {
|
|
|
71
75
|
// http://localhost:* (désactivé par défaut, hors du CLI)
|
|
72
76
|
'OMNEEDIA_AUTH_ALLOW_LOCALHOST_REDIRECTS=true',
|
|
73
77
|
'DATA_VOLUME_MOUNTPOINT=/data',
|
|
78
|
+
// Projet local : journaux détaillés (SQL, requêtes lentes dès 100 ms).
|
|
79
|
+
// Sans cette variable, l'engine démarre en production.
|
|
80
|
+
'POAD_MODE=development',
|
|
74
81
|
'POSTGRES_PASSWORD=postgres',
|
|
75
82
|
'ADMIN_API_KEY=' + config.auth.admin,
|
|
76
83
|
'JWT_SECRET=' + config.auth.secret,
|
|
@@ -79,11 +86,13 @@ module.exports = async (args = {}) => {
|
|
|
79
86
|
...mail.smtpEnv(config),
|
|
80
87
|
...valkey.engineEnv(config),
|
|
81
88
|
],
|
|
89
|
+
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
|
|
82
90
|
HostConfig: {
|
|
83
91
|
NetworkMode: net.NetworkMode,
|
|
84
92
|
PortBindings: {
|
|
85
93
|
'5432/tcp': [{ HostPort: config.db.port.toString() }],
|
|
86
94
|
'8000/tcp': [{ HostPort: config.web.port.toString() }],
|
|
95
|
+
...gelf.bindings,
|
|
87
96
|
},
|
|
88
97
|
Binds: [path.dirname(root) + '/data:/data'],
|
|
89
98
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
@@ -94,6 +103,12 @@ module.exports = async (args = {}) => {
|
|
|
94
103
|
NetworkingConfig: net.endpoint,
|
|
95
104
|
});
|
|
96
105
|
await container.start();
|
|
106
|
+
// Mailpit après le collecteur de l'engine, pour qu'il reçoive ses journaux
|
|
107
|
+
// (GELF) dès le départ. L'engine ne joint Mailpit qu'à l'envoi d'un e-mail.
|
|
108
|
+
if (mailpit) {
|
|
109
|
+
await logs.waitForCollector(container);
|
|
110
|
+
await mail.startMailpit(docker, config);
|
|
111
|
+
}
|
|
97
112
|
} catch (err) {
|
|
98
113
|
progress.fail(chalk.redBright(`Error: containers failed to start: ${err.message}`));
|
|
99
114
|
await mail.stopMailpit(docker, config);
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -16,6 +16,7 @@ module.exports = {
|
|
|
16
16
|
seed: 'Apply poad/seed.sql (development data)',
|
|
17
17
|
},
|
|
18
18
|
upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade --rollback, upgrade --list (--yes outside a terminal)',
|
|
19
|
+
logs: 'Unified logs of the project: logs [service…] level=warn since=15m request=<id> grep=<text> limit=100 -f --json',
|
|
19
20
|
gen: {
|
|
20
21
|
description: 'Generators: gen types (TypeScript types of the database)',
|
|
21
22
|
types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
|
package/project/gen/types.js
CHANGED
|
@@ -38,6 +38,7 @@ module.exports = async (args = {}) => {
|
|
|
38
38
|
const before = fs.existsSync(out) ? fs.readFileSync(out, 'utf-8') : null;
|
|
39
39
|
fs.writeFileSync(out, text);
|
|
40
40
|
const tables = (text.match(/^ {6}\w+: \{$/gm) || []).length;
|
|
41
|
-
|
|
41
|
+
const shown = path.relative(process.cwd(), out).startsWith('..') ? out : path.relative(process.cwd(), out);
|
|
42
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(shown)}${before === text ? chalk.grey(' (unchanged)') : ''}`);
|
|
42
43
|
console.log(chalk.grey(` ${tables} table(s). Use it with: createClient<Database>(url, anonKey)`));
|
|
43
44
|
};
|
package/project/logs.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// poad logs : les journaux unifiés du projet (schéma _logs, engine 0.8.1+).
|
|
2
|
+
// poad logs les 100 dernières lignes, tous services
|
|
3
|
+
// poad logs data auth seulement ces services (gateway, data, auth,
|
|
4
|
+
// storage, meta, postgres, logs, engine,
|
|
5
|
+
// mailpit, keycloak, valkey)
|
|
6
|
+
// poad logs level=warn warn, error et fatal
|
|
7
|
+
// poad logs since=15m depuis 15 minutes (s, m, h, d)
|
|
8
|
+
// poad logs request=6f1c… tout le chemin d'une requête (début de l'id suffit)
|
|
9
|
+
// poad logs grep=timeout messages qui contiennent ce texte
|
|
10
|
+
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
11
|
+
// poad logs -f | --follow suivi en direct
|
|
12
|
+
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
13
|
+
module.exports = async (args = {}) => {
|
|
14
|
+
const chalk = require('chalk-v2');
|
|
15
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
16
|
+
const { isDockerExist } = require('../utils/docker');
|
|
17
|
+
const { readConfig } = require('../utils/config');
|
|
18
|
+
const { supportsLogs } = require('../utils/logs');
|
|
19
|
+
const { connect } = require('../utils/migrations');
|
|
20
|
+
|
|
21
|
+
const root = findPoadDir(process.cwd());
|
|
22
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
23
|
+
const config = readConfig(root);
|
|
24
|
+
if (!supportsLogs(config)) {
|
|
25
|
+
process.exitCode = 1;
|
|
26
|
+
return console.log(chalk.redBright(`Engine ${config.engine} has no log collector: "poad upgrade" to 0.8.1 or later (meanwhile: docker logs ${config.project_uuid}).`));
|
|
27
|
+
}
|
|
28
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
29
|
+
process.exitCode = 1;
|
|
30
|
+
return console.log(chalk.redBright('The project is not started: run "poad start".'));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', '-f', '--follow', 'follow', '--json', 'json'];
|
|
34
|
+
const flag = (...names) => names.some((n) => args[n] === true);
|
|
35
|
+
const follow = flag('-f', '--follow', 'follow');
|
|
36
|
+
const asJson = flag('--json', 'json');
|
|
37
|
+
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
38
|
+
const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
39
|
+
const level = args.level ? String(args.level).toLowerCase() : null;
|
|
40
|
+
if (level && !LEVELS.includes(level)) {
|
|
41
|
+
process.exitCode = 1;
|
|
42
|
+
return console.log(chalk.redBright(`level=${level}: debug, info, warn, error or fatal`));
|
|
43
|
+
}
|
|
44
|
+
let since = null;
|
|
45
|
+
if (args.since) {
|
|
46
|
+
const m = /^(\d+)\s*(s|m|h|d)$/.exec(String(args.since));
|
|
47
|
+
if (!m) {
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
return console.log(chalk.redBright(`since=${args.since}: a duration such as 30s, 15m, 2h, 1d`));
|
|
50
|
+
}
|
|
51
|
+
since = `${m[1]} ${{ s: 'seconds', m: 'minutes', h: 'hours', d: 'days' }[m[2]]}`;
|
|
52
|
+
}
|
|
53
|
+
const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
|
|
54
|
+
|
|
55
|
+
// Conditions communes à la première lecture et au suivi
|
|
56
|
+
const where = [];
|
|
57
|
+
const values = [];
|
|
58
|
+
const add = (sql, v) => {
|
|
59
|
+
values.push(v);
|
|
60
|
+
where.push(sql.replace('?', `$${values.length}`));
|
|
61
|
+
};
|
|
62
|
+
if (services.length) add('service = any(?)', services);
|
|
63
|
+
if (level) add('level = any(?)', LEVELS.slice(LEVELS.indexOf(level)));
|
|
64
|
+
if (since) add("ts >= now() - ?::interval", since);
|
|
65
|
+
if (args.request) add('request_id like ?', `${String(args.request).replace(/[%_]/g, '')}%`);
|
|
66
|
+
if (args.grep) add('msg ilike ?', `%${String(args.grep).replace(/[%_\\]/g, (c) => `\\${c}`)}%`);
|
|
67
|
+
|
|
68
|
+
const COLORS = ['cyanBright', 'magentaBright', 'blueBright', 'greenBright', 'yellow', 'cyan', 'magenta', 'blue'];
|
|
69
|
+
const colorOf = (s) => COLORS[[...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % COLORS.length];
|
|
70
|
+
const LEVEL_STYLE = { debug: chalk.grey, info: chalk.green, warn: chalk.yellowBright, error: chalk.redBright, fatal: chalk.bgRed.white };
|
|
71
|
+
const width = 8;
|
|
72
|
+
|
|
73
|
+
const print = (r) => {
|
|
74
|
+
if (asJson) return console.log(JSON.stringify(r));
|
|
75
|
+
const a = r.attrs || {};
|
|
76
|
+
const time = new Date(r.ts).toISOString().slice(11, 23);
|
|
77
|
+
const svc = chalk[colorOf(r.service)](r.service.padEnd(width).slice(0, width));
|
|
78
|
+
const lvl = (LEVEL_STYLE[r.level] || chalk.white)(r.level.padEnd(5));
|
|
79
|
+
const extra = [];
|
|
80
|
+
// La durée d'une requête lente de Postgres est déjà dans son message
|
|
81
|
+
if (a.duration_ms !== undefined && r.service !== 'postgres') extra.push(`${a.duration_ms} ms`);
|
|
82
|
+
if (a.role) extra.push(a.role);
|
|
83
|
+
if (a.error_code || a.error) extra.push(chalk.yellow([a.error_code, a.error].filter(Boolean).join(': ')));
|
|
84
|
+
if (a.err && a.err.message) extra.push(chalk.redBright(a.err.message));
|
|
85
|
+
if (a.sql) extra.push(chalk.grey(String(a.sql).replace(/\s+/g, ' ').slice(0, 160)));
|
|
86
|
+
if (a.statement && r.service === 'postgres') extra.push(chalk.grey(String(a.statement).replace(/\s+/g, ' ').slice(0, 160)));
|
|
87
|
+
const req = r.request_id ? chalk.grey(` ·${r.request_id.slice(0, 8)}`) : '';
|
|
88
|
+
console.log(`${chalk.grey(time)} ${svc} ${lvl} ${r.msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`);
|
|
89
|
+
if (a.err && a.err.stack && r.level !== 'debug') console.log(chalk.grey(String(a.err.stack).split('\n').slice(1, 6).join('\n')));
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const client = await connect(config);
|
|
93
|
+
const cond = (extra) => [...where, ...(extra ? [extra] : [])].join(' and ') || 'true';
|
|
94
|
+
let lastId = 0;
|
|
95
|
+
try {
|
|
96
|
+
const first = await client.query(
|
|
97
|
+
`select id, ts, level, service, msg, request_id, attrs from _logs.entries where ${cond()} order by ts desc, id desc limit ${limit}`,
|
|
98
|
+
values,
|
|
99
|
+
);
|
|
100
|
+
for (const r of first.rows.reverse()) {
|
|
101
|
+
print(r);
|
|
102
|
+
lastId = Math.max(lastId, Number(r.id));
|
|
103
|
+
}
|
|
104
|
+
if (!follow) {
|
|
105
|
+
if (!first.rows.length && !asJson) console.log(chalk.grey(' No log line matches.'));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!lastId) lastId = Number((await client.query('select coalesce(max(id), 0) as id from _logs.entries')).rows[0].id);
|
|
109
|
+
// Suivi : les lignes arrivent par lots du collecteur (toutes les 500 ms)
|
|
110
|
+
let stopped = false;
|
|
111
|
+
process.on('SIGINT', () => (stopped = true));
|
|
112
|
+
while (!stopped) {
|
|
113
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
114
|
+
const next = await client.query(
|
|
115
|
+
`select id, ts, level, service, msg, request_id, attrs from _logs.entries where ${cond(`id > ${lastId}`)} order by id limit 2000`,
|
|
116
|
+
values,
|
|
117
|
+
);
|
|
118
|
+
for (const r of next.rows) {
|
|
119
|
+
print(r);
|
|
120
|
+
lastId = Math.max(lastId, Number(r.id));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} catch (err) {
|
|
124
|
+
process.exitCode = 1;
|
|
125
|
+
console.log(chalk.redBright(`Logs not readable: ${err.message}`));
|
|
126
|
+
} finally {
|
|
127
|
+
await client.end().catch(() => {});
|
|
128
|
+
}
|
|
129
|
+
};
|
package/utils/logs.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Journaux unifiés (engine 0.8.1 et plus, docs/logging.md de l'infra) :
|
|
2
|
+
// - l'engine publie le port GELF de son collecteur (12201/udp) sur
|
|
3
|
+
// 127.0.0.1:<[logs] gelf_port de config.toml> ;
|
|
4
|
+
// - Mailpit, Keycloak et Valkey y envoient leurs journaux (pilote gelf de
|
|
5
|
+
// Docker) ; docker logs continue de fonctionner (copie locale de Docker).
|
|
6
|
+
// Si l'engine est arrêté, leurs messages sont perdus pour _logs (UDP), mais
|
|
7
|
+
// restent dans docker logs.
|
|
8
|
+
const { setKeys } = require('./tomlfile');
|
|
9
|
+
|
|
10
|
+
const GELF_CONTAINER_PORT = '12201/udp';
|
|
11
|
+
|
|
12
|
+
const supportsLogs = (config) => {
|
|
13
|
+
const [major, minor, patch] = String(config.engine || '').split('.').map(Number);
|
|
14
|
+
return major > 0 || minor > 8 || (minor === 8 && patch >= 1);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const gelfPort = (config) => Number(config.logs && config.logs.gelf_port) || null;
|
|
18
|
+
|
|
19
|
+
/** Port GELF du projet, choisi et écrit dans config.toml au premier besoin */
|
|
20
|
+
async function ensureGelfPort(root, config) {
|
|
21
|
+
if (!supportsLogs(config)) return null;
|
|
22
|
+
const existing = gelfPort(config);
|
|
23
|
+
if (existing) return existing;
|
|
24
|
+
const { findFreePorts } = require('./ports');
|
|
25
|
+
const [port] = await findFreePorts(1);
|
|
26
|
+
setKeys(root, 'logs', { gelf_port: port });
|
|
27
|
+
config.logs = { ...(config.logs || {}), gelf_port: port };
|
|
28
|
+
return port;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Ports de l'engine pour le collecteur : ExposedPorts et PortBindings à fusionner */
|
|
32
|
+
const engineBindings = (config) => {
|
|
33
|
+
const port = supportsLogs(config) && gelfPort(config);
|
|
34
|
+
if (!port) return { exposed: {}, bindings: {} };
|
|
35
|
+
return {
|
|
36
|
+
exposed: { [GELF_CONTAINER_PORT]: {} },
|
|
37
|
+
bindings: { [GELF_CONTAINER_PORT]: [{ HostIp: '127.0.0.1', HostPort: String(port) }] },
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** HostConfig.LogConfig d'un conteneur du CLI (rien si l'engine n'a pas de collecteur) */
|
|
42
|
+
const containerLogConfig = (config) => {
|
|
43
|
+
const port = supportsLogs(config) && gelfPort(config);
|
|
44
|
+
if (!port) return {};
|
|
45
|
+
return {
|
|
46
|
+
LogConfig: {
|
|
47
|
+
Type: 'gelf',
|
|
48
|
+
Config: {
|
|
49
|
+
'gelf-address': `udp://127.0.0.1:${port}`,
|
|
50
|
+
'gelf-compression-type': 'none',
|
|
51
|
+
// Ne jamais bloquer le conteneur si le collecteur ne répond pas
|
|
52
|
+
mode: 'non-blocking',
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Attend (5 s au plus) que le collecteur de l'engine écoute : sa ligne de
|
|
60
|
+
* démarrage apparaît dans les journaux du conteneur. Sans collecteur (engine
|
|
61
|
+
* plus ancien), rend la main après le délai.
|
|
62
|
+
*/
|
|
63
|
+
async function waitForCollector(container, timeoutMs = 5000) {
|
|
64
|
+
const end = Date.now() + timeoutMs;
|
|
65
|
+
while (Date.now() < end) {
|
|
66
|
+
try {
|
|
67
|
+
const buf = await container.logs({ stdout: true, stderr: true, tail: 200 });
|
|
68
|
+
if (String(buf).includes('"service":"logs"')) return true;
|
|
69
|
+
} catch {
|
|
70
|
+
/* conteneur pas encore prêt */
|
|
71
|
+
}
|
|
72
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { supportsLogs, gelfPort, ensureGelfPort, engineBindings, containerLogConfig, waitForCollector };
|
package/utils/mail.js
CHANGED
|
@@ -73,6 +73,7 @@ const startMailpit = async (docker, config) => {
|
|
|
73
73
|
NetworkMode: net.NetworkMode,
|
|
74
74
|
PortBindings: { '8025/tcp': [{ HostPort: String(mailPort(config)) }] },
|
|
75
75
|
AutoRemove: true,
|
|
76
|
+
...require('./logs').containerLogConfig(config),
|
|
76
77
|
},
|
|
77
78
|
NetworkingConfig: net.endpoint,
|
|
78
79
|
});
|
package/utils/valkey.js
CHANGED
|
@@ -54,6 +54,7 @@ const containerOptions = (config, root, net) => ({
|
|
|
54
54
|
PortBindings: { '6379/tcp': [{ HostIp: '127.0.0.1', HostPort: String(config.valkey.port) }] },
|
|
55
55
|
Binds: [`${dataDir(root)}:/data`],
|
|
56
56
|
AutoRemove: true,
|
|
57
|
+
...require('./logs').containerLogConfig(config),
|
|
57
58
|
},
|
|
58
59
|
});
|
|
59
60
|
|