poad 2.12.0 → 2.14.0
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/.github/workflows/release.yml +6 -1
- package/bun.lock +424 -0
- package/global/cli.js +1 -1
- package/global/init.js +9 -0
- package/global/run.js +14 -10
- package/global/start.js +43 -36
- package/package.json +6 -4
- package/project/cli.js +7 -0
- package/project/db/index.js +10 -0
- package/project/db/reset.js +92 -0
- package/project/db/seed.js +19 -0
- package/project/info.js +5 -73
- package/project/setup.js +241 -0
- package/project/upgrade.js +126 -0
- package/utils/backup.js +74 -0
- package/utils/config.js +36 -10
- package/utils/engine.js +59 -16
- package/utils/report.js +95 -0
- package/utils/seed.js +53 -0
- package/utils/services.js +13 -1
- package/utils/tomlfile.js +72 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// poad upgrade passe le projet sur l'engine du CLI : sauvegarde
|
|
2
|
+
// (poad/backups), arrêt, mise à jour de config.toml,
|
|
3
|
+
// redémarrage (l'engine migre poad/data) et migrations
|
|
4
|
+
// poad upgrade to=<version> vers une version précise (plus récente)
|
|
5
|
+
// poad upgrade --rollback revient à la dernière sauvegarde (file=<nom> : une autre)
|
|
6
|
+
// poad upgrade --list liste les sauvegardes
|
|
7
|
+
// --yes : sans question (obligatoire hors terminal)
|
|
8
|
+
module.exports = async (args = {}) => {
|
|
9
|
+
const chalk = require('chalk-v2');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const Docker = require('dockerode');
|
|
12
|
+
const docker = new Docker();
|
|
13
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
14
|
+
const { isDockerExist } = require('../utils/docker');
|
|
15
|
+
const { readConfig } = require('../utils/config');
|
|
16
|
+
const { SERVICES, containerState, autostartServices } = require('../utils/services');
|
|
17
|
+
const { pullIfMissing } = require('../utils/pull');
|
|
18
|
+
const { isNewerVersion } = require('../utils/engine');
|
|
19
|
+
const backup = require('../utils/backup');
|
|
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
|
+
const flag = (name) => Boolean(args[name] || args[`--${name}`]);
|
|
25
|
+
const yes = flag('yes') || Boolean(args['-y']);
|
|
26
|
+
const rel = (p) => path.relative(process.cwd(), p) || p;
|
|
27
|
+
|
|
28
|
+
const confirm = async (message) => {
|
|
29
|
+
if (yes) return true;
|
|
30
|
+
if (!process.stdin.isTTY) {
|
|
31
|
+
console.log(chalk.redBright('Not a terminal: confirm with --yes.'));
|
|
32
|
+
process.exitCode = 1;
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
const { confirm: ask } = require('@inquirer/prompts');
|
|
36
|
+
const ok = await ask({ message, default: false }).catch(() => false);
|
|
37
|
+
if (!ok) console.log(chalk.grey(' Nothing changed.'));
|
|
38
|
+
return ok;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// Arrête le projet en notant les services optionnels lancés à la main,
|
|
42
|
+
// pour les relancer après (ceux en autostart repartent avec poad start)
|
|
43
|
+
const stopProject = async () => {
|
|
44
|
+
const running = [];
|
|
45
|
+
for (const s of SERVICES.filter((x) => x.optional && x.configured(config))) {
|
|
46
|
+
if ((await containerState(docker, s.container(config))) === 'running') running.push(s.id);
|
|
47
|
+
}
|
|
48
|
+
if (await isDockerExist(config.project_uuid)) await require('../global/stop')({});
|
|
49
|
+
return running;
|
|
50
|
+
};
|
|
51
|
+
const startProject = async (running, startArgs) => {
|
|
52
|
+
await require('../global/start')(startArgs);
|
|
53
|
+
const fresh = readConfig(root);
|
|
54
|
+
const auto = new Set(autostartServices(fresh).map((s) => s.id));
|
|
55
|
+
const again = running.filter((id) => !auto.has(id));
|
|
56
|
+
if (again.length) {
|
|
57
|
+
await require('../global/run')({ services: again, quiet: true });
|
|
58
|
+
console.log(' ');
|
|
59
|
+
await require('../utils/report').printServices(root, readConfig(root));
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// --list
|
|
64
|
+
if (flag('list')) {
|
|
65
|
+
const all = backup.list(root);
|
|
66
|
+
if (!all.length) return console.log(chalk.grey(` No backup in ${rel(backup.backupsDir(root))} yet: "poad upgrade" creates one before upgrading.`));
|
|
67
|
+
console.log(chalk.bold(`Backups (${rel(backup.backupsDir(root))})`));
|
|
68
|
+
all.forEach((b, i) => console.log(` ${b.file} ${chalk.grey(`engine ${b.engine}, ${backup.humanSize(b.size)}`)}${i === 0 ? chalk.cyan(' ← --rollback') : ''}`));
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// --rollback
|
|
73
|
+
if (flag('rollback')) {
|
|
74
|
+
const all = backup.list(root);
|
|
75
|
+
const chosen = args.file ? all.find((b) => b.file === String(args.file) || b.file === `${args.file}.tgz`) : all[0];
|
|
76
|
+
if (!chosen) {
|
|
77
|
+
return console.log(chalk.redBright(args.file ? `No backup named ${args.file}: "poad upgrade --list".` : 'No backup to go back to.'));
|
|
78
|
+
}
|
|
79
|
+
console.log(chalk.bold('Roll back the project'));
|
|
80
|
+
console.log(chalk.grey(` From: ${chosen.file} (engine ${chosen.engine})`));
|
|
81
|
+
console.log(chalk.grey(` Replaces poad/config.toml and poad/data: changes made since the backup (data, users, files) are lost.`));
|
|
82
|
+
console.log(' ');
|
|
83
|
+
if (!(await confirm(`Go back to engine ${chosen.engine} and the data of ${chosen.file}?`))) return;
|
|
84
|
+
const running = await stopProject();
|
|
85
|
+
const ora = require('ora');
|
|
86
|
+
const image = `poadio/engine:${config.engine}`;
|
|
87
|
+
let progress = null;
|
|
88
|
+
try {
|
|
89
|
+
if (!(await pullIfMissing(docker, image))) throw new Error(`image ${image} unavailable`);
|
|
90
|
+
progress = ora('Restoring the backup').start();
|
|
91
|
+
await backup.restore(docker, root, image, chosen);
|
|
92
|
+
progress.succeed(chalk.bold(`Restored ${chosen.file} (engine ${chosen.engine}).`));
|
|
93
|
+
} catch (err) {
|
|
94
|
+
const msg = chalk.redBright(`Restore failed: ${err.message}. Nothing restarted.`);
|
|
95
|
+
if (progress) progress.fail(msg);
|
|
96
|
+
else console.log(msg);
|
|
97
|
+
process.exitCode = 1;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
console.log(' ');
|
|
101
|
+
return startProject(running, { noOffer: true });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Mise à jour
|
|
105
|
+
const target = String(args.to || global.package.engine || '');
|
|
106
|
+
const current = config.engine;
|
|
107
|
+
if (!target) return console.log(chalk.redBright('No target engine version.'));
|
|
108
|
+
if (target === current) return console.log(chalk.green(` This project already uses engine ${current}.`));
|
|
109
|
+
if (!isNewerVersion(target, current)) {
|
|
110
|
+
return console.log(chalk.yellow(` Engine ${target} is older than ${current}: "poad upgrade --rollback" restores a backup instead.`));
|
|
111
|
+
}
|
|
112
|
+
console.log(chalk.bold(`Upgrade the project: engine ${current} → ${target}`));
|
|
113
|
+
console.log(chalk.grey(` 1. Back up poad/config.toml and poad/data to ${rel(backup.backupsDir(root))}`));
|
|
114
|
+
console.log(chalk.grey(' 2. Restart on the new engine, which migrates the database, then apply poad/migrations'));
|
|
115
|
+
console.log(chalk.grey(' Something wrong after? "poad upgrade --rollback" puts everything back.'));
|
|
116
|
+
console.log(' ');
|
|
117
|
+
// L'image d'abord : rien n'est arrêté si elle n'existe pas
|
|
118
|
+
if (!(await pullIfMissing(docker, `poadio/engine:${target}`))) {
|
|
119
|
+
process.exitCode = 1;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!(await confirm(`Upgrade to engine ${target}?`))) return;
|
|
123
|
+
const running = await stopProject();
|
|
124
|
+
await startProject(running, { upgrade: true, allowMinor: true, target });
|
|
125
|
+
if (readConfig(root).engine !== target) process.exitCode = 1;
|
|
126
|
+
};
|
package/utils/backup.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Sauvegardes du projet local, prises avant une mise à jour de l'engine :
|
|
2
|
+
// poad/backups/<YYYYMMDDHHMMSS>-engine-<version>.tgz
|
|
3
|
+
// Elles contiennent poad/config.toml et poad/data (base, fichiers du storage,
|
|
4
|
+
// Keycloak, Valkey). Hors git (poad/.gitignore), et hors de poad/data pour
|
|
5
|
+
// survivre à poad db reset.
|
|
6
|
+
// tar tourne dans un conteneur : sous Linux, les fichiers de la base
|
|
7
|
+
// appartiennent à l'utilisateur postgres du conteneur.
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
const backupsDir = (root) => path.join(path.dirname(root), 'backups');
|
|
12
|
+
|
|
13
|
+
// Heure locale, comme les noms de migrations
|
|
14
|
+
const stamp = () => {
|
|
15
|
+
const d = new Date();
|
|
16
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
17
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Sauvegardes existantes, la plus récente en premier */
|
|
21
|
+
const list = (root) => {
|
|
22
|
+
const dir = backupsDir(root);
|
|
23
|
+
if (!fs.existsSync(dir)) return [];
|
|
24
|
+
return fs
|
|
25
|
+
.readdirSync(dir)
|
|
26
|
+
.filter((f) => /^\d{14}-engine-.+\.tgz$/.test(f))
|
|
27
|
+
.sort()
|
|
28
|
+
.reverse()
|
|
29
|
+
.map((file) => {
|
|
30
|
+
const full = path.join(dir, file);
|
|
31
|
+
return { file, path: full, engine: /-engine-(.+)\.tgz$/.exec(file)[1], size: fs.statSync(full).size };
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Lance une commande shell dans un conteneur jetable, poad/ monté sur /poad */
|
|
36
|
+
const runInContainer = async (docker, image, root, script) => {
|
|
37
|
+
const container = await docker.createContainer({
|
|
38
|
+
Image: image,
|
|
39
|
+
Entrypoint: ['sh', '-c'],
|
|
40
|
+
Cmd: [script],
|
|
41
|
+
HostConfig: { Binds: [`${path.dirname(root)}:/poad`] },
|
|
42
|
+
});
|
|
43
|
+
try {
|
|
44
|
+
await container.start();
|
|
45
|
+
const { StatusCode } = await container.wait();
|
|
46
|
+
if (StatusCode !== 0) throw new Error(`exit ${StatusCode}`);
|
|
47
|
+
} finally {
|
|
48
|
+
await container.remove().catch(() => {});
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Sauvegarde config.toml + data ; renvoie le chemin du fichier créé */
|
|
53
|
+
const create = async (docker, root, image, engine) => {
|
|
54
|
+
require('./config').ensureGitignore(root);
|
|
55
|
+
const file = `${stamp()}-engine-${engine}.tgz`;
|
|
56
|
+
const owner = '$(stat -c %u:%g /poad/config.toml)';
|
|
57
|
+
const parts = fs.existsSync(path.join(path.dirname(root), 'data')) ? 'config.toml data' : 'config.toml';
|
|
58
|
+
await runInContainer(
|
|
59
|
+
docker,
|
|
60
|
+
image,
|
|
61
|
+
root,
|
|
62
|
+
`mkdir -p /poad/backups && tar czf /poad/backups/${file} -C /poad ${parts} && chown ${owner} /poad/backups /poad/backups/${file}`
|
|
63
|
+
);
|
|
64
|
+
return path.join(backupsDir(root), file);
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** Remet config.toml et data tels qu'ils étaient dans la sauvegarde */
|
|
68
|
+
const restore = async (docker, root, image, backup) => {
|
|
69
|
+
await runInContainer(docker, image, root, `rm -rf /poad/data && tar xzf "/poad/backups/${path.basename(backup.path)}" -C /poad`);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const humanSize = (n) => (n > 1e9 ? `${(n / 1e9).toFixed(1)} GB` : n > 1e6 ? `${(n / 1e6).toFixed(1)} MB` : `${Math.ceil(n / 1e3)} KB`);
|
|
73
|
+
|
|
74
|
+
module.exports = { backupsDir, list, create, restore, humanSize };
|
package/utils/config.js
CHANGED
|
@@ -16,6 +16,7 @@ const SECRET_KEYS = ['secret', 'anon', 'service', 'admin'];
|
|
|
16
16
|
const GITIGNORE = `# Généré par poad : propre à chaque machine, jamais versionné
|
|
17
17
|
data/
|
|
18
18
|
secrets.toml
|
|
19
|
+
backups/
|
|
19
20
|
`;
|
|
20
21
|
|
|
21
22
|
const poadDir = (root) => path.dirname(root);
|
|
@@ -34,19 +35,29 @@ function generateSecrets() {
|
|
|
34
35
|
};
|
|
35
36
|
}
|
|
36
37
|
|
|
38
|
+
/** Écrit (ou complète) la section [auth] de secrets.toml, en mode 600 */
|
|
37
39
|
function writeSecrets(root, auth) {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
fs.
|
|
41
|
-
|
|
40
|
+
const { setKeys } = require('./tomlfile');
|
|
41
|
+
const file = secretsFile(root);
|
|
42
|
+
if (!fs.existsSync(file)) fs.writeFileSync(file, '# Secrets du projet poad local : hors git (poad/.gitignore)\n', { mode: 0o600 });
|
|
43
|
+
setKeys(file, 'auth', Object.fromEntries(SECRET_KEYS.map((k) => [k, auth[k]])), { mode: 0o600 });
|
|
42
44
|
}
|
|
43
45
|
|
|
44
|
-
/**
|
|
46
|
+
/** Mot de passe SMTP : dans secrets.toml ([smtp] pass), null le retire */
|
|
47
|
+
function writeSmtpPass(root, pass) {
|
|
48
|
+
const { setKeys, removeSection } = require('./tomlfile');
|
|
49
|
+
const file = secretsFile(root);
|
|
50
|
+
if (pass === null || pass === undefined) return removeSection(file, 'smtp');
|
|
51
|
+
if (!fs.existsSync(file)) fs.writeFileSync(file, '# Secrets du projet poad local : hors git (poad/.gitignore)\n', { mode: 0o600 });
|
|
52
|
+
setKeys(file, 'smtp', { pass }, { mode: 0o600 });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** poad/.gitignore : data/, secrets.toml et backups/ (complète un fichier existant) */
|
|
45
56
|
function ensureGitignore(root) {
|
|
46
57
|
const file = path.join(poadDir(root), '.gitignore');
|
|
47
58
|
if (!fs.existsSync(file)) return fs.writeFileSync(file, GITIGNORE);
|
|
48
59
|
const text = fs.readFileSync(file, 'utf-8');
|
|
49
|
-
const missing = ['data/', 'secrets.toml'].filter((l) => !text.split(/\r?\n/).includes(l));
|
|
60
|
+
const missing = ['data/', 'secrets.toml', 'backups/'].filter((l) => !text.split(/\r?\n/).includes(l));
|
|
50
61
|
if (missing.length) fs.writeFileSync(file, `${text.replace(/\s*$/, '')}\n${missing.join('\n')}\n`);
|
|
51
62
|
}
|
|
52
63
|
|
|
@@ -57,9 +68,10 @@ function stripSecrets(text) {
|
|
|
57
68
|
const kept = lines.filter((line) => {
|
|
58
69
|
const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
|
|
59
70
|
if (head) section = head[1].trim();
|
|
60
|
-
if (section !== 'auth') return true;
|
|
61
71
|
const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
|
|
62
|
-
return !(key && SECRET_KEYS.includes(key[1]));
|
|
72
|
+
if (section === 'auth') return !(key && SECRET_KEYS.includes(key[1]));
|
|
73
|
+
if (section === 'smtp') return !(key && key[1] === 'pass');
|
|
74
|
+
return true;
|
|
63
75
|
});
|
|
64
76
|
return kept.join('\n');
|
|
65
77
|
}
|
|
@@ -75,8 +87,21 @@ function loadConfig(root, notices = []) {
|
|
|
75
87
|
const inline = SECRET_KEYS.filter((k) => auth[k] !== undefined);
|
|
76
88
|
let secrets = null;
|
|
77
89
|
|
|
90
|
+
let stored = {};
|
|
78
91
|
if (fs.existsSync(secretsFile(root))) {
|
|
79
|
-
|
|
92
|
+
stored = toml.parse(fs.readFileSync(secretsFile(root), 'utf-8'));
|
|
93
|
+
secrets = stored.auth || {};
|
|
94
|
+
}
|
|
95
|
+
// Mot de passe SMTP écrit dans config.toml : il rejoint secrets.toml
|
|
96
|
+
const inlinePass = config.smtp && config.smtp.pass !== undefined ? String(config.smtp.pass) : null;
|
|
97
|
+
if (inlinePass !== null) {
|
|
98
|
+
writeSmtpPass(root, inlinePass);
|
|
99
|
+
stored.smtp = { ...(stored.smtp || {}), pass: inlinePass };
|
|
100
|
+
if (!inline.length) {
|
|
101
|
+
fs.writeFileSync(root, stripSecrets(text));
|
|
102
|
+
ensureGitignore(root);
|
|
103
|
+
notices.push(`SMTP password moved from config.toml to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
|
|
104
|
+
}
|
|
80
105
|
}
|
|
81
106
|
if (inline.length) {
|
|
82
107
|
// Ancien format : les secrets de config.toml priment (ce sont ceux que
|
|
@@ -94,6 +119,7 @@ function loadConfig(root, notices = []) {
|
|
|
94
119
|
}
|
|
95
120
|
|
|
96
121
|
config.auth = { ...auth, ...Object.fromEntries(SECRET_KEYS.map((k) => [k, secrets[k]])) };
|
|
122
|
+
if (config.smtp && stored.smtp && stored.smtp.pass !== undefined) config.smtp.pass = String(stored.smtp.pass);
|
|
97
123
|
return config;
|
|
98
124
|
}
|
|
99
125
|
|
|
@@ -108,4 +134,4 @@ function readConfig(root) {
|
|
|
108
134
|
return config;
|
|
109
135
|
}
|
|
110
136
|
|
|
111
|
-
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
|
137
|
+
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, writeSmtpPass, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
package/utils/engine.js
CHANGED
|
@@ -26,9 +26,10 @@ const storageInfo = (config) => {
|
|
|
26
26
|
module.exports = { usesMinio, storageInfo };
|
|
27
27
|
|
|
28
28
|
// Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
|
|
29
|
-
// à jour `engine` dans config.toml
|
|
30
|
-
//
|
|
31
|
-
//
|
|
29
|
+
// à jour `engine` dans config.toml. La mise à jour migre poad/data : le projet
|
|
30
|
+
// est d'abord sauvegardé dans poad/backups (poad upgrade --rollback y revient).
|
|
31
|
+
// poad start ne la propose qu'au sein de la même version mineure (seules des
|
|
32
|
+
// migrations s'appliquent) ; poad upgrade accepte aussi un saut de mineure.
|
|
32
33
|
const parseVersion = (v) => String(v || '').split('.').map(Number);
|
|
33
34
|
const isNewer = (a, b) => {
|
|
34
35
|
const pa = parseVersion(a);
|
|
@@ -46,45 +47,87 @@ const ask = (question) =>
|
|
|
46
47
|
});
|
|
47
48
|
});
|
|
48
49
|
|
|
49
|
-
/**
|
|
50
|
+
/** Écrit la version d'engine dans config.toml ; false si la ligne est introuvable */
|
|
51
|
+
const writeEngine = (root, version) => {
|
|
52
|
+
const fs = require('fs');
|
|
53
|
+
const text = fs.readFileSync(root, 'utf-8');
|
|
54
|
+
const updated = text.replace(/^(\s*engine\s*=\s*)["'][^"']*["']/m, `$1"${version}"`);
|
|
55
|
+
if (updated === text) return false;
|
|
56
|
+
fs.writeFileSync(root, updated);
|
|
57
|
+
return true;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Sauvegarde le projet avant migration ; renvoie le fichier, ou null (message affiché) */
|
|
61
|
+
const backupBefore = async (root, config, target) => {
|
|
62
|
+
const chalk = require('chalk-v2');
|
|
63
|
+
const ora = require('ora');
|
|
64
|
+
const Docker = require('dockerode');
|
|
65
|
+
const docker = new Docker();
|
|
66
|
+
const { pullIfMissing } = require('./pull');
|
|
67
|
+
const backup = require('./backup');
|
|
68
|
+
const progress = ora('Backing up the project').start();
|
|
69
|
+
try {
|
|
70
|
+
// Image qui sert à tar : celle du projet si elle est là, sinon la nouvelle
|
|
71
|
+
let image = `poadio/engine:${config.engine}`;
|
|
72
|
+
try {
|
|
73
|
+
await docker.getImage(image).inspect();
|
|
74
|
+
} catch {
|
|
75
|
+
image = `poadio/engine:${target}`;
|
|
76
|
+
progress.stop();
|
|
77
|
+
if (!(await pullIfMissing(docker, image))) throw new Error(`image ${image} unavailable`);
|
|
78
|
+
progress.start('Backing up the project');
|
|
79
|
+
}
|
|
80
|
+
const file = await backup.create(docker, root, image, config.engine);
|
|
81
|
+
const size = backup.humanSize(require('fs').statSync(file).size);
|
|
82
|
+
progress.succeed(`${chalk.bold('Backup:')} ${require('path').relative(process.cwd(), file)} (${size})`);
|
|
83
|
+
return file;
|
|
84
|
+
} catch (err) {
|
|
85
|
+
progress.fail(chalk.redBright(`Backup failed (${err.message}): engine not upgraded.`));
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Version d'engine à démarrer (celle du projet, ou la nouvelle si acceptée).
|
|
92
|
+
* args : upgrade (sans question), target (version voulue, défaut : celle du
|
|
93
|
+
* CLI), allowMinor (saut de version mineure permis), noOffer (ne rien proposer).
|
|
94
|
+
*/
|
|
50
95
|
const offerEngineUpgrade = async (root, config, args = {}) => {
|
|
51
96
|
const chalk = require('chalk-v2');
|
|
52
|
-
const
|
|
53
|
-
const target = global.package && global.package.engine;
|
|
97
|
+
const target = String(args.target || (global.package && global.package.engine) || '');
|
|
54
98
|
const current = config.engine;
|
|
55
|
-
if (!target || !isNewer(target, current)) return current;
|
|
99
|
+
if (args.noOffer || !target || !isNewer(target, current)) return current;
|
|
56
100
|
const [cMaj, cMin] = parseVersion(current);
|
|
57
101
|
const [tMaj, tMin] = parseVersion(target);
|
|
58
|
-
if (cMaj !== tMaj || cMin !== tMin) {
|
|
102
|
+
if ((cMaj !== tMaj || cMin !== tMin) && !args.allowMinor) {
|
|
59
103
|
console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}).`));
|
|
60
|
-
console.log(chalk.yellow(
|
|
104
|
+
console.log(chalk.yellow(' It is a new minor version: read the release notes, then "poad upgrade" (backs up first).'));
|
|
61
105
|
console.log(' ');
|
|
62
106
|
return current;
|
|
63
107
|
}
|
|
64
108
|
let accepted = Boolean(args.upgrade || args['--upgrade']);
|
|
65
109
|
if (!accepted) {
|
|
66
110
|
if (!process.stdin.isTTY) {
|
|
67
|
-
console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}). Run "poad
|
|
111
|
+
console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}). Run "poad upgrade" to switch.`));
|
|
68
112
|
console.log(' ');
|
|
69
113
|
return current;
|
|
70
114
|
}
|
|
71
115
|
console.log(chalk.yellow(` Engine ${target} is available (this project uses ${current}).`));
|
|
72
|
-
console.log(chalk.grey(' Upgrading
|
|
116
|
+
console.log(chalk.grey(' Upgrading migrates poad/data. The project is backed up first ("poad upgrade --rollback" goes back).'));
|
|
73
117
|
accepted = await ask(chalk.bold(` Upgrade this project to ${target}? (y/N) `));
|
|
74
118
|
console.log(' ');
|
|
75
119
|
}
|
|
76
120
|
if (!accepted) return current;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if (updated === text) {
|
|
121
|
+
if (!(await backupBefore(root, config, target))) return current;
|
|
122
|
+
if (!writeEngine(root, target)) {
|
|
80
123
|
console.log(chalk.redBright(` Cannot find engine in ${root}; edit it by hand.`));
|
|
81
124
|
return current;
|
|
82
125
|
}
|
|
83
|
-
|
|
84
|
-
console.log(chalk.green(` ${root}: engine ${current} → ${target}`));
|
|
126
|
+
console.log(chalk.green(` ${require('path').relative(process.cwd(), root)}: engine ${current} → ${target}`));
|
|
85
127
|
console.log(' ');
|
|
86
128
|
return target;
|
|
87
129
|
};
|
|
88
130
|
|
|
89
131
|
module.exports.offerEngineUpgrade = offerEngineUpgrade;
|
|
90
132
|
module.exports.isNewerVersion = isNewer;
|
|
133
|
+
module.exports.writeEngine = writeEngine;
|
package/utils/report.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Affichage de l'état du projet, commun à poad info et poad start : le projet
|
|
2
|
+
// (URL, base, clés, migrations), puis le panneau des services (Mailpit,
|
|
3
|
+
// Keycloak, Valkey) avec leur état et leurs accès.
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
async function migrationsLine(root, config) {
|
|
7
|
+
const migrations = require('./migrations');
|
|
8
|
+
const count = migrations.files(root).list.length;
|
|
9
|
+
if (!count) return null;
|
|
10
|
+
let client;
|
|
11
|
+
try {
|
|
12
|
+
client = await migrations.connect(config);
|
|
13
|
+
const st = await migrations.status(root, client);
|
|
14
|
+
const done = st.list.length - st.pending.length;
|
|
15
|
+
return `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
|
|
16
|
+
} catch {
|
|
17
|
+
return `${count} file(s), state unknown`;
|
|
18
|
+
} finally {
|
|
19
|
+
if (client) await client.end().catch(() => {});
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function printProject(root, config) {
|
|
24
|
+
const chalk = require('chalk-v2');
|
|
25
|
+
const prettyoutput = require('prettyoutput');
|
|
26
|
+
const { storageInfo } = require('./engine');
|
|
27
|
+
const mail = require('./mail');
|
|
28
|
+
console.log(chalk.bold('POAD project'));
|
|
29
|
+
console.log(' ');
|
|
30
|
+
const info = {
|
|
31
|
+
Engine: config.engine,
|
|
32
|
+
'API URL': `http://localhost:${config.web.port}`,
|
|
33
|
+
'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
|
|
34
|
+
...storageInfo(config),
|
|
35
|
+
...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
|
|
36
|
+
'JWT secret': `${config.auth.secret}`,
|
|
37
|
+
'anon key': config.auth.anon,
|
|
38
|
+
'service_role key': config.auth.service,
|
|
39
|
+
Config: `${path.relative(process.cwd(), root)} (secrets: ${path.relative(process.cwd(), require('./config').secretsFile(root))})`,
|
|
40
|
+
};
|
|
41
|
+
const line = await migrationsLine(root, config);
|
|
42
|
+
if (line) info.Migrations = line;
|
|
43
|
+
console.log(prettyoutput(info));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function printServices(root, config) {
|
|
47
|
+
const chalk = require('chalk-v2');
|
|
48
|
+
const Docker = require('dockerode');
|
|
49
|
+
const docker = new Docker();
|
|
50
|
+
const { SERVICES, containerState } = require('./services');
|
|
51
|
+
|
|
52
|
+
// En cours, arrêtés (configurés), ou disponibles
|
|
53
|
+
const rows = [];
|
|
54
|
+
for (const s of SERVICES) {
|
|
55
|
+
const configured = s.configured(config);
|
|
56
|
+
if (!configured && !s.optional) continue; // Mailpit remplacé par un vrai SMTP
|
|
57
|
+
const state = configured ? await containerState(docker, s.container(config)) : null;
|
|
58
|
+
rows.push({ s, configured, running: state === 'running', auto: configured && s.optional && s.autostart(config) });
|
|
59
|
+
}
|
|
60
|
+
if (!rows.length) return;
|
|
61
|
+
|
|
62
|
+
const width = Math.max(...rows.map((r) => r.s.label.length));
|
|
63
|
+
const rule = chalk.grey('─'.repeat(48));
|
|
64
|
+
console.log(chalk.bold('Services'));
|
|
65
|
+
console.log(rule);
|
|
66
|
+
for (const { s, configured, running, auto } of rows) {
|
|
67
|
+
const label = chalk.bold(s.label.padEnd(width));
|
|
68
|
+
const tag = auto ? chalk.cyan(' auto') : '';
|
|
69
|
+
if (running) {
|
|
70
|
+
console.log(`${chalk.greenBright('●')} ${label} ${chalk.greenBright('running')}${tag}`);
|
|
71
|
+
for (const [k, v] of Object.entries(s.info(config, root))) {
|
|
72
|
+
// Une liste (comptes de test) : une ligne par entrée, alignées
|
|
73
|
+
const lines = Array.isArray(v) ? v : [v];
|
|
74
|
+
lines.forEach((l, i) => console.log(` ${chalk.grey((i ? '' : k).padEnd(16))} ${l}`));
|
|
75
|
+
}
|
|
76
|
+
} else if (configured) {
|
|
77
|
+
const how = s.optional ? `poad run ${s.cmd}` : 'poad stop && poad start';
|
|
78
|
+
console.log(`${chalk.yellowBright('○')} ${label} ${chalk.yellowBright('stopped')}${tag} ${chalk.grey(`(${how})`)}`);
|
|
79
|
+
} else {
|
|
80
|
+
console.log(`${chalk.grey('·')} ${chalk.grey(s.label.padEnd(width))} ${chalk.grey(`available: poad run ${s.cmd}, or poad setup`)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
console.log(rule);
|
|
84
|
+
const stopped = rows.filter((r) => r.s.optional && r.configured && !r.running).length;
|
|
85
|
+
if (stopped) console.log(chalk.grey(' "poad run --all" starts every configured service; "poad setup" chooses those started with the project.'));
|
|
86
|
+
console.log(' ');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Projet puis services */
|
|
90
|
+
async function printReport(root, config) {
|
|
91
|
+
await printProject(root, config);
|
|
92
|
+
await printServices(root, config);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = { printReport, printProject, printServices, migrationsLine };
|
package/utils/seed.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// poad/seed.sql : données de développement (utilisateurs de test, lignes
|
|
2
|
+
// d'exemple…), jamais en production. Appliqué après les migrations quand la
|
|
3
|
+
// base est neuve (premier poad start, poad db reset), ou à la main avec
|
|
4
|
+
// poad db seed. Il s'exécute dans une transaction : tout ou rien.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
|
|
8
|
+
const seedFile = (root) => path.join(path.dirname(root), 'seed.sql');
|
|
9
|
+
|
|
10
|
+
/** Applique seed.sql ; renvoie { applied, error } (applied false s'il n'existe pas) */
|
|
11
|
+
async function applySeed(root, config) {
|
|
12
|
+
const file = seedFile(root);
|
|
13
|
+
if (!fs.existsSync(file)) return { applied: false, error: null };
|
|
14
|
+
const sql = fs.readFileSync(file, 'utf-8');
|
|
15
|
+
if (!sql.trim()) return { applied: false, error: null };
|
|
16
|
+
const { connect } = require('./migrations');
|
|
17
|
+
const client = await connect(config);
|
|
18
|
+
try {
|
|
19
|
+
await client.query('begin');
|
|
20
|
+
await client.query(sql);
|
|
21
|
+
await client.query('commit');
|
|
22
|
+
return { applied: true, error: null };
|
|
23
|
+
} catch (err) {
|
|
24
|
+
await client.query('rollback').catch(() => {});
|
|
25
|
+
const line = err.position ? ` (line ${sql.slice(0, Number(err.position) - 1).split('\n').length})` : '';
|
|
26
|
+
return { applied: false, error: `${err.message}${line}` };
|
|
27
|
+
} finally {
|
|
28
|
+
await client.end().catch(() => {});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Application avec affichage ; renvoie true si rien n'a échoué */
|
|
33
|
+
async function runSeed(root, config) {
|
|
34
|
+
const chalk = require('chalk-v2');
|
|
35
|
+
const rel = path.relative(process.cwd(), seedFile(root));
|
|
36
|
+
let r;
|
|
37
|
+
try {
|
|
38
|
+
r = await applySeed(root, config);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
console.log(chalk.redBright(`Seed not applied: ${err.message}`));
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (r.error) {
|
|
44
|
+
console.log(`${chalk.redBright('✖')} ${chalk.bold(rel)}`);
|
|
45
|
+
console.log(chalk.redBright(` ${r.error}`));
|
|
46
|
+
console.log(chalk.grey(' Rolled back: fix the file, then "poad db seed".'));
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (r.applied) console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel)}`);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { seedFile, applySeed, runSeed };
|
package/utils/services.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// - Valkey : optionnel, `poad run valkey`.
|
|
5
5
|
// Un service optionnel est « configuré » quand config.toml a sa section (port
|
|
6
6
|
// choisi au premier lancement) : `poad run --all` relance ceux-là.
|
|
7
|
+
// Avec autostart = true dans sa section, `poad start` le lance aussi
|
|
8
|
+
// (`poad setup` règle ces options).
|
|
7
9
|
|
|
8
10
|
const kc = require('./keycloak');
|
|
9
11
|
const valkey = require('./valkey');
|
|
@@ -18,6 +20,7 @@ const SERVICES = [
|
|
|
18
20
|
optional: false,
|
|
19
21
|
container: (config) => mail.mailContainerName(config),
|
|
20
22
|
configured: (config) => mail.usesMailpit(config),
|
|
23
|
+
autostart: (config) => mail.usesMailpit(config),
|
|
21
24
|
info: (config) => ({ URL: `http://localhost:${mail.mailPort(config)}`, SMTP: 'mail:1025 (depuis l’engine)' }),
|
|
22
25
|
},
|
|
23
26
|
{
|
|
@@ -26,8 +29,11 @@ const SERVICES = [
|
|
|
26
29
|
optional: true,
|
|
27
30
|
names: kc.NAMES,
|
|
28
31
|
cmd: 'kc',
|
|
32
|
+
section: 'keycloak',
|
|
29
33
|
container: (config) => kc.containerName(config),
|
|
30
34
|
configured: (config) => Boolean(config.keycloak && config.keycloak.port),
|
|
35
|
+
autostart: (config) => Boolean(config.keycloak && config.keycloak.autostart === true),
|
|
36
|
+
savePort: (root, port) => kc.savePort(root, port),
|
|
31
37
|
info: (config, root) => {
|
|
32
38
|
const base = `http://localhost:${config.keycloak.port}`;
|
|
33
39
|
// Lecture seule : rien n'est créé tant que `poad run kc` n'a pas tourné
|
|
@@ -55,8 +61,11 @@ const SERVICES = [
|
|
|
55
61
|
optional: true,
|
|
56
62
|
names: valkey.NAMES,
|
|
57
63
|
cmd: 'valkey',
|
|
64
|
+
section: 'valkey',
|
|
58
65
|
container: (config) => valkey.containerName(config),
|
|
59
66
|
configured: (config) => valkey.enabled(config),
|
|
67
|
+
autostart: (config) => Boolean(config.valkey && config.valkey.autostart === true),
|
|
68
|
+
savePort: (root, port) => valkey.savePort(root, port),
|
|
60
69
|
info: (config) => ({ URL: `redis://127.0.0.1:${config.valkey.port}`, 'From the engine': valkey.URL }),
|
|
61
70
|
},
|
|
62
71
|
];
|
|
@@ -77,4 +86,7 @@ const wantedServices = (args = {}) => SERVICES.filter((s) => s.optional && s.nam
|
|
|
77
86
|
/** --all, all : tous les services optionnels configurés */
|
|
78
87
|
const wantsAll = (args = {}) => Boolean(args.all || args['--all'] || args['-a']);
|
|
79
88
|
|
|
80
|
-
|
|
89
|
+
/** Services optionnels que poad start lance (autostart = true) */
|
|
90
|
+
const autostartServices = (config) => SERVICES.filter((s) => s.optional && s.configured(config) && s.autostart(config));
|
|
91
|
+
|
|
92
|
+
module.exports = { SERVICES, containerState, wantedServices, wantsAll, autostartServices };
|