poad 2.60.0 → 2.61.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/create.js +40 -27
- package/global/start.js +6 -0
- package/global/stop.js +52 -19
- package/package.json +1 -1
- package/poad.js +25 -0
- package/project/cli.js +1 -1
- package/project/db/diff.js +99 -1
- package/project/flows.js +133 -39
- package/project/logs.js +92 -43
- package/project/migrate.js +2 -1
- package/project/upgrade.js +6 -0
- package/test/flows.test.js +256 -0
- package/test/help.test.js +18 -0
- package/test/project-lock.test.js +51 -0
- package/utils/banner.js +6 -4
- package/utils/help-details.js +35 -5
- package/utils/help.js +60 -8
- package/utils/project-lock.js +67 -0
- package/utils/reference.js +6 -3
package/project/flows.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// poad flows new <nom> crée poad/flows/<nom>.json (flow minimal)
|
|
2
2
|
// poad flows list flows du projet, vus par l'engine lancé
|
|
3
|
-
// poad flows run <nom> [clé=valeur …] [input=<fichier.json>] [--wait|--no-wait]
|
|
3
|
+
// poad flows run <nom> [clé=valeur …] [input=<fichier.json>] [--input '<json>'] [--wait|--no-wait|--detach]
|
|
4
4
|
// lance un flow et suit ses étapes
|
|
5
5
|
// poad flows runs [nom] [limit=20] dernières exécutions
|
|
6
6
|
// poad flows show <run_id> détail d'une exécution
|
|
@@ -10,14 +10,21 @@
|
|
|
10
10
|
// poad/flows/<nom>.json. L'engine (0.18.0+) le sert sous /flows/v1 ; sa file
|
|
11
11
|
// est sur le Valkey du projet (poad run valkey). Les étapes « conteneur » sont
|
|
12
12
|
// lancées par l'exécuteur (poad run runner).
|
|
13
|
+
//
|
|
14
|
+
// --env <environnement> (production : main) et --project <id> : le projet
|
|
15
|
+
// hébergé sur poad.io (session de poad login) au lieu de l'engine local, pour
|
|
16
|
+
// list, run, runs, show et cancel. poad.io remet au propriétaire un jeton
|
|
17
|
+
// service_role de 15 minutes (route storage-token du plan de contrôle,
|
|
18
|
+
// renouvelé pendant un long suivi) et la clé anon : jamais affichés.
|
|
13
19
|
const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
14
20
|
const POLL_MS = 700;
|
|
15
21
|
const TIMEOUT_MS = 10000;
|
|
16
22
|
const MAX_OUTPUT = 4000;
|
|
17
23
|
const MAX_STEP_OUTPUT = 300;
|
|
18
24
|
const FINAL = ['completed', 'failed', 'cancelled'];
|
|
25
|
+
const RUN_USAGE = "Usage: poad flows run <name> [key=value …] [input=<file.json>] [--input '<json>'] [--wait|--no-wait|--detach] [--env <name>] [--project <id>]";
|
|
19
26
|
const USAGE =
|
|
20
|
-
'Usage: poad flows new <name> | list | run <name> [key=value …] [input=<file.json>] [--
|
|
27
|
+
'Usage: poad flows new <name> | list | run <name> [key=value …] [input=<file.json>] [--input <json>] [--detach] | runs [name] [limit=20] | show <run_id> | cancel <run_id>, and --env <name> | --project <id> for poad.io';
|
|
21
28
|
const NEEDS_VALKEY = 'Flows need Valkey: "poad run valkey", then restart the project ("poad stop", "poad start").';
|
|
22
29
|
|
|
23
30
|
/** Flow minimal valide : déclencheur manuel → étape set qui rend un message. Pure. */
|
|
@@ -51,12 +58,25 @@ const parseValue = (text) => {
|
|
|
51
58
|
* fichier JSON (lu par l'appelant) ; les autres clé=valeur forment l'entrée.
|
|
52
59
|
*/
|
|
53
60
|
const parseRunArgs = (tokens) => {
|
|
54
|
-
const out = { name: null, input: {}, file: null, wait: true };
|
|
55
|
-
|
|
56
|
-
|
|
61
|
+
const out = { name: null, input: {}, file: null, inline: null, wait: true };
|
|
62
|
+
const list = tokens.map(String);
|
|
63
|
+
for (let i = 0; i < list.length; i++) {
|
|
64
|
+
const text = list[i];
|
|
57
65
|
if (text === '--wait') out.wait = true;
|
|
58
|
-
else if (text === '--no-wait') out.wait = false;
|
|
59
|
-
else if (text.startsWith('--'))
|
|
66
|
+
else if (text === '--no-wait' || text === '--detach' || text === '-d') out.wait = false;
|
|
67
|
+
else if (text === '--input' || text.startsWith('--input=')) {
|
|
68
|
+
// --input '<json>' : l'entrée en JSON (un objet), en ligne
|
|
69
|
+
let value = text === '--input' ? list[++i] : text.slice('--input='.length);
|
|
70
|
+
if (value === undefined) return { error: "--input needs a value: --input '{\"key\": \"value\"}'" };
|
|
71
|
+
let parsed;
|
|
72
|
+
try {
|
|
73
|
+
parsed = JSON.parse(value);
|
|
74
|
+
} catch (err) {
|
|
75
|
+
return { error: `--input: not valid JSON (${err.message})` };
|
|
76
|
+
}
|
|
77
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { error: '--input: a JSON object is expected, such as \'{"key": "value"}\'' };
|
|
78
|
+
out.inline = { ...(out.inline || {}), ...parsed };
|
|
79
|
+
} else if (text.startsWith('-')) return { error: `unknown option ${text}` };
|
|
60
80
|
else if (text.includes('=')) {
|
|
61
81
|
// Seul le premier « = » sépare : la valeur peut en contenir
|
|
62
82
|
const at = text.indexOf('=');
|
|
@@ -173,6 +193,43 @@ const explain = (status, body) => {
|
|
|
173
193
|
return `HTTP ${status}`;
|
|
174
194
|
};
|
|
175
195
|
|
|
196
|
+
/**
|
|
197
|
+
* --env et --project (poad.io), où qu'ils soient : rend { words, env, project } ou { error }. Pure.
|
|
198
|
+
* « --env x » et « --env=x » ; le reste des mots, dans l'ordre.
|
|
199
|
+
*/
|
|
200
|
+
const cloudOptions = (words) => {
|
|
201
|
+
const out = { words: [], env: null, project: null };
|
|
202
|
+
for (let i = 0; i < words.length; i++) {
|
|
203
|
+
const m = /^--(env|project)(?:=(.*))?$/s.exec(words[i]);
|
|
204
|
+
if (!m) {
|
|
205
|
+
out.words.push(words[i]);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
let v = m[2];
|
|
209
|
+
if (v === undefined) {
|
|
210
|
+
v = words[i + 1];
|
|
211
|
+
if (v === undefined || v.startsWith('-')) return { error: `--${m[1]} needs a value` };
|
|
212
|
+
i++;
|
|
213
|
+
}
|
|
214
|
+
if (!v) return { error: `--${m[1]} needs a value` };
|
|
215
|
+
out[m[1]] = v;
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Comme explain, pour poad.io : la passerelle sans service flows derrière elle
|
|
222
|
+
* n'est pas une affaire de Valkey local. Pure.
|
|
223
|
+
*/
|
|
224
|
+
const explainCloud = (status, body, label) => {
|
|
225
|
+
if (status >= 200 && status < 300) return null;
|
|
226
|
+
const error = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error : null;
|
|
227
|
+
if (status === 502 || status === 503 || status === 504 || (status === 404 && !(error && error.code))) return `The flows service of ${label} does not answer (HTTP ${status}): is the environment active? ("poad env ls", "poad cloud info")`;
|
|
228
|
+
if (error && error.message) return `${error.message}${error.hint ? ` (${error.hint})` : ''}`;
|
|
229
|
+
if (status === 401 || status === 403) return `${label} refused the access (HTTP ${status}): "poad login" again, or check that you own the project.`;
|
|
230
|
+
return `HTTP ${status}`;
|
|
231
|
+
};
|
|
232
|
+
|
|
176
233
|
class FlowsError extends Error {}
|
|
177
234
|
|
|
178
235
|
/**
|
|
@@ -190,51 +247,82 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
190
247
|
const doFetch = deps.fetch || fetch;
|
|
191
248
|
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
192
249
|
const started = deps.started || ((config) => require('../utils/docker').isDockerExist(config.project_uuid));
|
|
250
|
+
const cloudTarget = deps.cloudTarget || ((opts) => require('../utils/storage').cloudTarget(opts));
|
|
251
|
+
const fail = (message, code = 1) => {
|
|
252
|
+
process.exitCode = code;
|
|
253
|
+
console.log(chalk.redBright(message));
|
|
254
|
+
};
|
|
193
255
|
|
|
194
|
-
const root = findPoadDir(cwd);
|
|
195
|
-
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
196
|
-
const dir = path.join(path.dirname(root), 'flows');
|
|
197
|
-
const rel = (p) => path.relative(cwd, p) || p;
|
|
198
256
|
// Les mots tels que tapés : parseArgs convertit les valeurs et coupe au second « = »
|
|
199
|
-
const
|
|
257
|
+
const typed = cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
|
|
258
|
+
if (typed.error) return fail(`poad flows: ${typed.error}.`, 2);
|
|
259
|
+
const words = typed.words;
|
|
200
260
|
const command = words[0] || 'list';
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
console.log(chalk.redBright(message));
|
|
204
|
-
};
|
|
261
|
+
const cloud = Boolean(typed.env || typed.project);
|
|
262
|
+
const where = cloud ? ` ${[typed.env ? `--env ${typed.env}` : '', typed.project ? `--project ${typed.project}` : ''].filter(Boolean).join(' ')}` : '';
|
|
205
263
|
|
|
206
|
-
|
|
264
|
+
const root = findPoadDir(cwd);
|
|
265
|
+
// Avec --project, le dossier courant n'a pas besoin d'être un projet
|
|
266
|
+
if (!root && !(cloud && typed.project)) return fail(cloud ? 'Not in a poad project folder: cd into one, or pass --project <id>.' : 'You are not in a poad project directory.');
|
|
267
|
+
const dir = root ? path.join(path.dirname(root), 'flows') : null;
|
|
268
|
+
const rel = (p) => path.relative(cwd, p) || p;
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Engine visé, prêt à répondre, ou null (message affiché) :
|
|
272
|
+
* { base, key, apikey, label, cloud, renew? }
|
|
273
|
+
*/
|
|
207
274
|
const ready = async () => {
|
|
275
|
+
if (cloud) {
|
|
276
|
+
try {
|
|
277
|
+
const t = await cloudTarget({ env: typed.env, project: typed.project });
|
|
278
|
+
return { base: t.base, key: t.key, apikey: t.apikey || t.key, label: t.label, cloud: true, renew: t.renew, expires: t.renew && t.renew.first ? Date.parse(t.renew.first) : null };
|
|
279
|
+
} catch (err) {
|
|
280
|
+
return fail((err && err.message) || String(err), (err && err.exit) || 1) || null;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
208
283
|
const config = readConfig(root);
|
|
209
284
|
if (!supportsFlows(config)) return fail(`Flows need engine 0.18.0 or later (this project uses ${config.engine}): "poad upgrade".`) || null;
|
|
210
285
|
if (!(await started(config))) return fail('The project is not started: run "poad start".') || null;
|
|
211
|
-
|
|
286
|
+
const key = config.auth.service;
|
|
287
|
+
return { base: `http://localhost:${config.web.port}`, key, apikey: key, label: 'local engine', cloud: false };
|
|
212
288
|
};
|
|
213
289
|
|
|
214
|
-
/**
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
290
|
+
/** Jeton poad.io renouvelé une minute avant son expiration (suivi de plus de 15 minutes) */
|
|
291
|
+
const fresh = async (t) => {
|
|
292
|
+
if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
|
|
293
|
+
try {
|
|
294
|
+
const n = await t.renew.next();
|
|
295
|
+
Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
|
|
296
|
+
} catch (err) {
|
|
297
|
+
throw new FlowsError(`poad.io gave no new access: ${(err && err.message) || err}`);
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
/** Appel de /flows/v1 avec un jeton service_role ; lève FlowsError avec un message à afficher */
|
|
302
|
+
const call = async (t, method, route, body) => {
|
|
303
|
+
await fresh(t);
|
|
218
304
|
let res;
|
|
219
305
|
try {
|
|
220
|
-
res = await doFetch(`${base}/flows/v1${route}`, {
|
|
306
|
+
res = await doFetch(`${t.base}/flows/v1${route}`, {
|
|
221
307
|
method,
|
|
222
|
-
headers: { apikey:
|
|
308
|
+
headers: { apikey: t.apikey, authorization: `Bearer ${t.key}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
223
309
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
224
310
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
225
311
|
});
|
|
226
312
|
} catch (err) {
|
|
227
313
|
const timedOut = err && (err.name === 'TimeoutError' || err.name === 'AbortError');
|
|
228
|
-
|
|
314
|
+
const who = t.cloud ? t.label : 'The engine';
|
|
315
|
+
throw new FlowsError(timedOut ? `${who} did not answer within ${TIMEOUT_MS / 1000} s (${t.base}).` : `${who} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
229
316
|
}
|
|
230
317
|
const json = await res.json().catch(() => null);
|
|
231
|
-
const problem = explain(res.status, json);
|
|
318
|
+
const problem = t.cloud ? explainCloud(res.status, json, t.label) : explain(res.status, json);
|
|
232
319
|
if (problem) throw new FlowsError(problem);
|
|
233
320
|
return json || {};
|
|
234
321
|
};
|
|
235
322
|
|
|
236
323
|
// ------------------------------------------------------------------ new
|
|
237
324
|
if (command === 'new' || command === 'create') {
|
|
325
|
+
if (cloud) return fail('poad flows new writes poad/flows/<name>.json here: no --env nor --project (then "poad deploy").', 2);
|
|
238
326
|
const name = String(words[1] || '');
|
|
239
327
|
if (!NAME_RE.test(name)) return fail('Flow name: a letter first, then a-z, 0-9 and "-" (poad flows new send-report).');
|
|
240
328
|
const file = path.join(dir, `${name}.json`);
|
|
@@ -260,9 +348,9 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
260
348
|
if (!(err instanceof FlowsError)) throw err;
|
|
261
349
|
return fail(err.message);
|
|
262
350
|
}
|
|
263
|
-
console.log(`${chalk.bold('Flows')} ${chalk.grey(rel(dir))}`);
|
|
351
|
+
console.log(`${chalk.bold('Flows')} ${chalk.grey(cloud ? config.label : rel(dir))}`);
|
|
264
352
|
console.log(' ');
|
|
265
|
-
if (!flows.length) return console.log(chalk.grey(' None yet: "poad flows new <name>".'));
|
|
353
|
+
if (!flows.length) return console.log(chalk.grey(cloud ? ' None yet: "poad flows new <name>", then "poad deploy".' : ' None yet: "poad flows new <name>".'));
|
|
266
354
|
const width = Math.max(...flows.map((f) => String(f.name).length));
|
|
267
355
|
for (const flow of flows) for (const line of flowLines(flow, width)) console.log(line);
|
|
268
356
|
return;
|
|
@@ -272,11 +360,11 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
272
360
|
if (command === 'run') {
|
|
273
361
|
const parsed = parseRunArgs(words.slice(1));
|
|
274
362
|
if (parsed.error) {
|
|
275
|
-
fail(`poad flows run: ${parsed.error}
|
|
276
|
-
return console.log(chalk.grey(
|
|
363
|
+
fail(`poad flows run: ${parsed.error}.`, 2);
|
|
364
|
+
return console.log(chalk.grey(` ${RUN_USAGE}`));
|
|
277
365
|
}
|
|
278
|
-
// Le fichier d'abord, les clé=valeur par-dessus
|
|
279
|
-
let input = parsed.input;
|
|
366
|
+
// Le fichier d'abord, puis --input, les clé=valeur par-dessus
|
|
367
|
+
let input = { ...(parsed.inline || {}), ...parsed.input };
|
|
280
368
|
if (parsed.file !== null) {
|
|
281
369
|
let fromFile;
|
|
282
370
|
try {
|
|
@@ -285,7 +373,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
285
373
|
return fail(`input=${parsed.file}: ${err.code === 'ENOENT' ? 'no such file' : `not readable as JSON (${err.message})`}.`);
|
|
286
374
|
}
|
|
287
375
|
if (typeof fromFile !== 'object' || fromFile === null || Array.isArray(fromFile)) return fail(`input=${parsed.file}: the file must contain a JSON object.`);
|
|
288
|
-
input = { ...fromFile, ...parsed.input };
|
|
376
|
+
input = { ...fromFile, ...(parsed.inline || {}), ...parsed.input };
|
|
289
377
|
}
|
|
290
378
|
const config = await ready();
|
|
291
379
|
if (!config) return;
|
|
@@ -296,9 +384,15 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
296
384
|
if (!(err instanceof FlowsError)) throw err;
|
|
297
385
|
return fail(`Flow not started: ${err.message}`);
|
|
298
386
|
}
|
|
299
|
-
if (!
|
|
387
|
+
if (!runId) return fail('Flow not started: the engine gave no run id.');
|
|
388
|
+
if (!parsed.wait) {
|
|
389
|
+
// La sortie standard ne porte que l'id (scripts) ; la suite, sur la sortie d'erreur
|
|
390
|
+
console.log(runId);
|
|
391
|
+
if (cloud && process.stderr.isTTY) console.error(chalk.grey(` Follow it: poad flows show ${runId}${where}`));
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
300
394
|
|
|
301
|
-
console.log(`${chalk.bold(parsed.name)} ${chalk.grey(`run ${runId}`)}`);
|
|
395
|
+
console.log(`${chalk.bold(parsed.name)} ${chalk.grey(`run ${runId}${cloud ? ` ${config.label}` : ''}`)}`);
|
|
302
396
|
const seen = new Map();
|
|
303
397
|
let misses = 0;
|
|
304
398
|
let view = null;
|
|
@@ -311,7 +405,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
311
405
|
// Une lecture ratée n'arrête pas le suivi ; cinq de suite, si
|
|
312
406
|
if (++misses >= 5) {
|
|
313
407
|
fail(`Lost track of the run: ${err.message}`);
|
|
314
|
-
return console.log(chalk.grey(` It may still be running: poad flows show ${runId}`));
|
|
408
|
+
return console.log(chalk.grey(` It may still be running: poad flows show ${runId}${where}`));
|
|
315
409
|
}
|
|
316
410
|
await sleep(POLL_MS);
|
|
317
411
|
continue;
|
|
@@ -356,7 +450,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
356
450
|
}
|
|
357
451
|
console.log(`${chalk.bold('Runs')}${flow ? ` ${chalk.grey(flow)}` : ''}`);
|
|
358
452
|
console.log(' ');
|
|
359
|
-
if (!runs.length) return console.log(chalk.grey(flow ? ` No run of "${flow}" yet: poad flows run ${flow}` :
|
|
453
|
+
if (!runs.length) return console.log(chalk.grey(flow ? ` No run of "${flow}" yet: poad flows run ${flow}${where}` : ` No run yet: poad flows run <name>${where}`));
|
|
360
454
|
const width = Math.max(...runs.map((r) => String(r.flow).length));
|
|
361
455
|
for (const run of runs) console.log(runLine(run, width));
|
|
362
456
|
return;
|
|
@@ -365,7 +459,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
365
459
|
// ------------------------------------------------------------------ show, cancel
|
|
366
460
|
if (command === 'show' || command === 'cancel') {
|
|
367
461
|
const id = String(words[1] || '');
|
|
368
|
-
if (!id) return fail(`Usage: poad flows ${command} <run_id> ("poad flows runs" lists them)
|
|
462
|
+
if (!id) return fail(`Usage: poad flows ${command} <run_id> ("poad flows runs${where}" lists them).`, 2);
|
|
369
463
|
const config = await ready();
|
|
370
464
|
if (!config) return;
|
|
371
465
|
try {
|
|
@@ -408,4 +502,4 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
408
502
|
};
|
|
409
503
|
|
|
410
504
|
module.exports = (args, raw) => main(args, raw);
|
|
411
|
-
Object.assign(module.exports, { main, template, parseValue, parseRunArgs, duration, clip, pretty, stepKey, stepLine, flowLines, runLine, explain, NAME_RE, NEEDS_VALKEY });
|
|
505
|
+
Object.assign(module.exports, { main, template, parseValue, parseRunArgs, cloudOptions, duration, clip, pretty, stepKey, stepLine, flowLines, runLine, explain, explainCloud, NAME_RE, NEEDS_VALKEY });
|
package/project/logs.js
CHANGED
|
@@ -38,68 +38,69 @@
|
|
|
38
38
|
// dit pas. Le CLI lit _logs.entries dans la base du projet : ces filtres
|
|
39
39
|
// portent sur la colonne attrs et valent pour tout engine qui a le collecteur
|
|
40
40
|
// (les index qui les accélèrent arrivent avec l'engine 0.18.1).
|
|
41
|
-
|
|
41
|
+
// deps (tests) : started(config), connect(config), cwd.
|
|
42
|
+
module.exports = async (args = {}, raw = [], deps = {}) => {
|
|
42
43
|
const chalk = require('chalk-v2');
|
|
43
44
|
const { findPoadDir } = require('../utils/findpoad');
|
|
44
|
-
const { isDockerExist } = require('../utils/docker');
|
|
45
45
|
const { readConfig } = require('../utils/config');
|
|
46
46
|
const { supportsLogs } = require('../utils/logs');
|
|
47
|
-
const { connect } = require('../utils/migrations');
|
|
48
47
|
const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition } = require('../utils/logline');
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
48
|
+
const connect = deps.connect || require('../utils/migrations').connect;
|
|
49
|
+
const started = deps.started || (async (config) => {
|
|
50
|
+
// Docker muet n'est pas un projet arrêté
|
|
51
|
+
const Docker = require('dockerode');
|
|
52
|
+
try {
|
|
53
|
+
await new Docker().ping();
|
|
54
|
+
} catch (err) {
|
|
55
|
+
throw new LogsError(`Docker does not answer (${(err && err.code) || (err && err.message) || err}): start Docker, then "poad start".`);
|
|
56
|
+
}
|
|
57
|
+
return require('../utils/docker').isDockerExist(config.project_uuid);
|
|
58
|
+
});
|
|
59
|
+
const fail = (message) => {
|
|
58
60
|
process.exitCode = 1;
|
|
59
|
-
|
|
61
|
+
console.log(chalk.redBright(message));
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const root = findPoadDir(deps.cwd || process.cwd());
|
|
65
|
+
if (!root) return fail('You are not in a poad project directory.');
|
|
66
|
+
let config;
|
|
67
|
+
try {
|
|
68
|
+
config = readConfig(root);
|
|
69
|
+
} catch (err) {
|
|
70
|
+
return fail(`poad/config.toml is not readable: ${err.message}`);
|
|
60
71
|
}
|
|
72
|
+
if (!supportsLogs(config)) return fail(`Engine ${config.engine} has no log collector: "poad upgrade" to 0.8.1 or later (meanwhile: docker logs ${config.project_uuid}).`);
|
|
61
73
|
|
|
62
|
-
|
|
74
|
+
// Les filtres d'abord : une faute de frappe se dit même projet arrêté
|
|
75
|
+
const problem = checkOptions(args, raw, { LEVELS, ATTR_OPTIONS });
|
|
76
|
+
if (problem) return fail(problem);
|
|
77
|
+
const OPTIONS = optionNames(ATTR_OPTIONS);
|
|
63
78
|
const flag = (...names) => names.some((n) => args[n] === true);
|
|
64
79
|
const follow = flag('-f', '--follow', 'follow');
|
|
65
80
|
const asJson = flag('--json', 'json');
|
|
66
|
-
// « --since 5m » était accepté en silence : --since ignoré, « 5m » pris pour un nom de service, et aucune ligne.
|
|
67
|
-
// Une option s'écrit nom=valeur : mieux vaut le dire que de répondre « No log line matches ».
|
|
68
|
-
const unknown = Object.keys(args).filter((k) => k.startsWith('-') && !OPTIONS.includes(k));
|
|
69
|
-
if (unknown.length) {
|
|
70
|
-
const hint = unknown.map((k) => k.replace(/^-+/, '')).find((k) => OPTIONS.includes(k));
|
|
71
|
-
return console.log(chalk.redBright(`${unknown.join(', ')}: unknown option. Options are written name=value${hint ? `, for example ${hint}=${hint === 'since' ? '15m' : '…'}` : ' (level=warn since=15m flow=<name>), plus -f and --json'}.`));
|
|
72
|
-
}
|
|
73
81
|
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
74
82
|
const level = args.level ? String(args.level).toLowerCase() : null;
|
|
75
|
-
if (level && !LEVELS.includes(level)) {
|
|
76
|
-
process.exitCode = 1;
|
|
77
|
-
return console.log(chalk.redBright(`level=${level}: debug, info, warn, error or fatal`));
|
|
78
|
-
}
|
|
79
83
|
let since = null;
|
|
80
84
|
if (args.since) {
|
|
81
85
|
const m = /^(\d+)\s*(s|m|h|d)$/.exec(String(args.since));
|
|
82
|
-
if (!m) {
|
|
83
|
-
process.exitCode = 1;
|
|
84
|
-
return console.log(chalk.redBright(`since=${args.since}: a duration such as 30s, 15m, 2h, 1d`));
|
|
85
|
-
}
|
|
86
86
|
since = `${m[1]} ${{ s: 'seconds', m: 'minutes', h: 'hours', d: 'days' }[m[2]]}`;
|
|
87
87
|
}
|
|
88
88
|
// Attributs d'une ligne : flow=, run=, step=, function=
|
|
89
89
|
const attrs = attrConditions(args);
|
|
90
|
-
if (attrs.error)
|
|
91
|
-
process.exitCode = 1;
|
|
92
|
-
return console.log(chalk.redBright(attrs.error));
|
|
93
|
-
}
|
|
90
|
+
if (attrs.error) return fail(attrs.error);
|
|
94
91
|
// token= : la valeur telle que tapée (parseArgs ferait d'un préfixe tout en chiffres un nombre)
|
|
95
|
-
const typed = raw.find((w) => typeof w === 'string' && w.startsWith('token='));
|
|
92
|
+
const typed = (raw || []).find((w) => typeof w === 'string' && w.startsWith('token='));
|
|
96
93
|
const token = parseToken(typed !== undefined ? typed.slice('token='.length) : args.token);
|
|
97
|
-
if (token && token.error)
|
|
98
|
-
process.exitCode = 1;
|
|
99
|
-
return console.log(chalk.redBright(token.error));
|
|
100
|
-
}
|
|
94
|
+
if (token && token.error) return fail(token.error);
|
|
101
95
|
const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
|
|
102
96
|
|
|
97
|
+
try {
|
|
98
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".');
|
|
99
|
+
} catch (err) {
|
|
100
|
+
if (err instanceof LogsError) return fail(err.message);
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
|
|
103
104
|
// Conditions communes à la première lecture et au suivi
|
|
104
105
|
const where = [];
|
|
105
106
|
const values = [];
|
|
@@ -120,12 +121,17 @@ module.exports = async (args = {}, raw = []) => {
|
|
|
120
121
|
|
|
121
122
|
const print = (r) => console.log(asJson ? JSON.stringify(r) : formatLine(r, chalk));
|
|
122
123
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
let client;
|
|
125
|
+
try {
|
|
126
|
+
client = await connect(config);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
return fail(unreachable(config, err));
|
|
129
|
+
}
|
|
126
130
|
const from = (extra) => fromClause([...where, ...(extra ? [extra] : [])].join(' and ') || 'true', attrs.prefix);
|
|
127
131
|
let lastId = 0;
|
|
128
132
|
try {
|
|
133
|
+
// Le jeton par son nom actuel, son préfixe ou le début de son id : ses lignes, même sous un ancien nom
|
|
134
|
+
if (token) add(...tokenCondition(token, await resolveTokenIds(client, token)));
|
|
129
135
|
const first = await client.query(
|
|
130
136
|
`select id, ts, level, service, msg, request_id, attrs from ${from()} order by ts desc, id desc limit ${limit}`,
|
|
131
137
|
values,
|
|
@@ -154,9 +160,52 @@ module.exports = async (args = {}, raw = []) => {
|
|
|
154
160
|
}
|
|
155
161
|
}
|
|
156
162
|
} catch (err) {
|
|
157
|
-
|
|
158
|
-
|
|
163
|
+
// Connexion perdue (engine arrêté pendant le suivi), ou erreur de la base : une phrase, pas une trace
|
|
164
|
+
const lost = err && ['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT'].includes(err.code);
|
|
165
|
+
fail(lost || /Connection terminated/i.test(String(err && err.message)) ? unreachable(config, err, true) : `Logs not readable: ${(err && err.message) || err}`);
|
|
159
166
|
} finally {
|
|
160
167
|
await client.end().catch(() => {});
|
|
161
168
|
}
|
|
162
169
|
};
|
|
170
|
+
|
|
171
|
+
class LogsError extends Error {}
|
|
172
|
+
|
|
173
|
+
/** Noms d'options reconnus (le reste, sans « - » devant, sont des services). Pure. */
|
|
174
|
+
const optionNames = (ATTR_OPTIONS) => ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Ce qui ne va pas dans les options, en une phrase (null : tout va bien). Pure.
|
|
178
|
+
* raw : les mots tels que tapés (parseArgs fait d'un « clé= » vide le nombre 0).
|
|
179
|
+
*/
|
|
180
|
+
function checkOptions(args = {}, raw = [], { LEVELS, ATTR_OPTIONS }) {
|
|
181
|
+
const OPTIONS = optionNames(ATTR_OPTIONS);
|
|
182
|
+
// « --since 5m » était accepté en silence : --since ignoré, « 5m » pris pour un nom de service, et aucune ligne.
|
|
183
|
+
// Une option s'écrit nom=valeur : mieux vaut le dire que de répondre « No log line matches ».
|
|
184
|
+
const unknown = Object.keys(args).filter((k) => k.startsWith('-') && !OPTIONS.includes(k));
|
|
185
|
+
if (unknown.length) {
|
|
186
|
+
const hint = unknown.map((k) => k.replace(/^-+/, '').split('=')[0]).find((k) => OPTIONS.includes(k));
|
|
187
|
+
return `${unknown.join(', ')}: unknown option. Options are written name=value${hint ? `, for example ${hint}=${hint === 'since' ? '15m' : '…'}` : ' (level=warn since=15m flow=<name>), plus -f and --json'}.`;
|
|
188
|
+
}
|
|
189
|
+
const valued = OPTIONS.filter((o) => !o.startsWith('-') && !['follow', 'json'].includes(o));
|
|
190
|
+
for (const word of (raw || []).map(String)) {
|
|
191
|
+
const m = /^([a-z]+)=$/.exec(word);
|
|
192
|
+
if (m && valued.includes(m[1])) return `${m[1]}=: a value is expected${m[1] === 'since' ? ', such as since=15m' : m[1] === 'level' ? ' (debug, info, warn, error or fatal)' : ''}.`;
|
|
193
|
+
}
|
|
194
|
+
for (const o of ['level', 'since', 'request', 'grep', 'limit']) if (args[o] === true) return `${o}: a value is expected, written ${o}=<value>${o === 'since' ? ' (since=15m)' : o === 'level' ? ' (level=warn)' : o === 'limit' ? ' (limit=500)' : ''}.`;
|
|
195
|
+
if (args.level !== undefined && args.level !== '') {
|
|
196
|
+
const level = String(args.level).toLowerCase();
|
|
197
|
+
if (!LEVELS.includes(level)) return `level=${args.level}: debug, info, warn, error or fatal.`;
|
|
198
|
+
}
|
|
199
|
+
if (args.since !== undefined && args.since !== '' && !/^(\d+)\s*(s|m|h|d)$/.test(String(args.since))) return `since=${args.since}: a duration such as 30s, 15m, 2h, 1d.`;
|
|
200
|
+
if (args.limit !== undefined && args.limit !== '' && !(/^\d+$/.test(String(args.limit)) && Number(args.limit) >= 1 && Number(args.limit) <= 10000)) return `limit=${args.limit}: a number of lines from 1 to 10000.`;
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Base du projet injoignable : ce qu'il faut savoir et faire. Pure. */
|
|
205
|
+
function unreachable(config, err, during = false) {
|
|
206
|
+
const port = config && config.db && config.db.port;
|
|
207
|
+
const why = (err && err.code) || (err && err.message) || String(err);
|
|
208
|
+
return `${during ? 'Lost the connection to' : 'The log store (database of the project) does not answer on'} 127.0.0.1:${port} (${why}). The engine may be starting or stopping: wait a few seconds, or check it with "poad info" ("poad start" if it is stopped).`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
Object.assign(module.exports, { checkOptions, unreachable, optionNames });
|
package/project/migrate.js
CHANGED
|
@@ -14,5 +14,6 @@ module.exports = async () => {
|
|
|
14
14
|
const ok = await require('../utils/migrate-run')(root, config);
|
|
15
15
|
if (!ok) process.exitCode = 1;
|
|
16
16
|
// Tables de référence : après les migrations, quand leur structure est à jour
|
|
17
|
-
|
|
17
|
+
// --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
|
|
18
|
+
else if (!(await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') }))) process.exitCode = 1;
|
|
18
19
|
};
|
package/project/upgrade.js
CHANGED
|
@@ -21,6 +21,12 @@ module.exports = async (args = {}) => {
|
|
|
21
21
|
|
|
22
22
|
const root = findPoadDir(process.cwd());
|
|
23
23
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
24
|
+
// Une seule commande à la fois sur les conteneurs du projet (utils/project-lock.js)
|
|
25
|
+
const lock = require('../utils/project-lock').acquire(root, 'upgrade');
|
|
26
|
+
if (!lock.ok) {
|
|
27
|
+
process.exitCode = 1;
|
|
28
|
+
return console.log(chalk.redBright(require('../utils/project-lock').busyMessage(lock.held)));
|
|
29
|
+
}
|
|
24
30
|
const config = readConfig(root);
|
|
25
31
|
const flag = (name) => Boolean(args[name] || args[`--${name}`]);
|
|
26
32
|
const yes = flag('yes') || Boolean(args['-y']);
|