poad 2.23.0 → 2.25.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/global/install.js +7 -39
- package/global/start.js +1 -1
- package/package.json +2 -2
- package/project/cli.js +2 -0
- package/project/function.js +2 -0
- package/project/functions.js +155 -0
- package/project/upgrade.js +16 -2
- package/utils/latest.js +28 -0
- package/utils/pull.js +168 -16
package/global/install.js
CHANGED
|
@@ -1,50 +1,18 @@
|
|
|
1
1
|
module.exports = async (args) => {
|
|
2
|
-
const chalk = require('chalk');
|
|
2
|
+
const chalk = require('chalk-v2');
|
|
3
3
|
const Docker = require('dockerode');
|
|
4
|
-
const
|
|
4
|
+
const { pullImage } = require('../utils/pull');
|
|
5
5
|
|
|
6
6
|
const docker = new Docker();
|
|
7
7
|
const imageName = 'poadio/engine:' + global.package.engine;
|
|
8
8
|
|
|
9
|
-
// Create a new progress bar
|
|
10
|
-
const progressBar = new cliProgress.SingleBar(
|
|
11
|
-
{},
|
|
12
|
-
cliProgress.Presets.shades_classic
|
|
13
|
-
);
|
|
14
|
-
|
|
15
9
|
console.log(chalk.bold('\nInstalling poad environment...'));
|
|
16
10
|
|
|
17
11
|
// Sans plateforme imposée, Docker tire la variante de la machine (amd64 ou
|
|
18
12
|
// arm64) : sur un Mac Apple Silicon, l'engine tourne sans émulation.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
let downloadedSize = 0;
|
|
26
|
-
let totalSize = 0;
|
|
27
|
-
|
|
28
|
-
docker.modem.followProgress(stream, onFinished, onProgress);
|
|
29
|
-
|
|
30
|
-
function onProgress(event) {
|
|
31
|
-
if (event.progressDetail && event.progressDetail.total) {
|
|
32
|
-
if (totalSize === 0) {
|
|
33
|
-
totalSize = event.progressDetail.total;
|
|
34
|
-
progressBar.start(totalSize, 0);
|
|
35
|
-
}
|
|
36
|
-
downloadedSize = event.progressDetail.current;
|
|
37
|
-
progressBar.update(downloadedSize);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function onFinished(err, output) {
|
|
42
|
-
progressBar.stop();
|
|
43
|
-
if (err) {
|
|
44
|
-
console.error('Error:', err);
|
|
45
|
-
} else {
|
|
46
|
-
console.log(chalk.bold('poad environment installed successfully.'));
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
});
|
|
13
|
+
if (await pullImage(docker, imageName)) {
|
|
14
|
+
console.log(chalk.bold('poad environment installed successfully.'));
|
|
15
|
+
} else {
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
}
|
|
50
18
|
};
|
package/global/start.js
CHANGED
|
@@ -108,7 +108,7 @@ module.exports = async (args = {}) => {
|
|
|
108
108
|
...gelf.bindings,
|
|
109
109
|
},
|
|
110
110
|
// poad/migrations monté : la console y écrit les migrations qu'elle crée
|
|
111
|
-
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`],
|
|
111
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`],
|
|
112
112
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
113
113
|
// compris sous Linux
|
|
114
114
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -29,6 +29,8 @@ module.exports = {
|
|
|
29
29
|
},
|
|
30
30
|
migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
|
|
31
31
|
migration: 'Database migrations: migration new <name>, migration list',
|
|
32
|
+
functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): functions new <name> (or create), functions list, functions types (editor autocompletion)',
|
|
33
|
+
function: 'Same as functions: function create <name>, function list',
|
|
32
34
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
33
35
|
gen: {
|
|
34
36
|
description: 'Génération automatique des éléments clés pour votre projet',
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// poad functions new <nom> crée poad/functions/<nom>/index.ts
|
|
2
|
+
// poad functions list fonctions du projet et leur état dans l'engine lancé
|
|
3
|
+
// poad functions types types pour l'éditeur (autocomplétion), lus sur l'engine lancé
|
|
4
|
+
//
|
|
5
|
+
// Une fonction est un module qui exporte { fetch(request, env, ctx) }, au
|
|
6
|
+
// format de Cloudflare Workers. L'engine la sert sur /functions/v1/<nom> et
|
|
7
|
+
// la recharge à chaque enregistrement (engine 0.16.0).
|
|
8
|
+
const NAME_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
9
|
+
|
|
10
|
+
const TEMPLATE = (name) => `import { poadFromRequest, caller, type PoadEnv } from '@poadio/functions';
|
|
11
|
+
|
|
12
|
+
// Servie sur /functions/v1/${name}. Depuis votre application :
|
|
13
|
+
// const res = await poad.fetch('/functions/v1/${name}', { method: 'POST', body: JSON.stringify({ name: 'poad' }) });
|
|
14
|
+
export default {
|
|
15
|
+
async fetch(request: Request, env: PoadEnv): Promise<Response> {
|
|
16
|
+
// L'appelant, lu dans son jeton (null sans jeton)
|
|
17
|
+
const me = caller(request);
|
|
18
|
+
// Client poad au nom de l'appelant : les politiques RLS s'appliquent
|
|
19
|
+
const poad = poadFromRequest(request, env);
|
|
20
|
+
|
|
21
|
+
const body: { name?: string } = request.method === 'POST' ? await request.json().catch(() => ({})) : {};
|
|
22
|
+
console.log('${name} called', { role: me?.role });
|
|
23
|
+
return Response.json({ message: \`Hello \${body.name ?? me?.email ?? 'world'}\` });
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
`;
|
|
27
|
+
|
|
28
|
+
// tsconfig.json de poad/functions : API web (celles de workerd) et @poadio/*
|
|
29
|
+
// relié aux types déposés par l'engine, pour l'autocomplétion sans node_modules
|
|
30
|
+
const TSCONFIG = `{
|
|
31
|
+
"compilerOptions": {
|
|
32
|
+
"target": "ES2022",
|
|
33
|
+
"module": "ESNext",
|
|
34
|
+
"moduleResolution": "bundler",
|
|
35
|
+
"lib": ["ES2022", "WebWorker"],
|
|
36
|
+
"types": [],
|
|
37
|
+
"strict": true,
|
|
38
|
+
"noEmit": true,
|
|
39
|
+
"skipLibCheck": true,
|
|
40
|
+
"allowImportingTsExtensions": true,
|
|
41
|
+
"paths": {
|
|
42
|
+
"@poadio/*": ["./.poad/types/@poadio/*/index.d.ts"]
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"include": ["**/*.ts", "**/*.tsx"],
|
|
46
|
+
"exclude": ["node_modules"]
|
|
47
|
+
}
|
|
48
|
+
`;
|
|
49
|
+
const TYPE_FILE_RE = /^@poadio\/[a-z][a-z0-9-]*(\/[A-Za-z0-9_-]+)*\/[A-Za-z0-9_.-]+\.d\.ts$/;
|
|
50
|
+
|
|
51
|
+
module.exports = async (args = {}) => {
|
|
52
|
+
const chalk = require('chalk-v2');
|
|
53
|
+
const fs = require('fs');
|
|
54
|
+
const path = require('path');
|
|
55
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
56
|
+
const { isDockerExist } = require('../utils/docker');
|
|
57
|
+
const { readConfig } = require('../utils/config');
|
|
58
|
+
|
|
59
|
+
const root = findPoadDir(process.cwd());
|
|
60
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
61
|
+
const dir = path.join(path.dirname(root), 'functions');
|
|
62
|
+
const rel = (p) => path.relative(process.cwd(), p) || p;
|
|
63
|
+
const words = Object.keys(args);
|
|
64
|
+
|
|
65
|
+
// Types pour l'éditeur : lus sur l'engine lancé (accordés à son client poad)
|
|
66
|
+
// et déposés dans poad/functions/.poad/types. Renvoie le nombre de fichiers, ou null.
|
|
67
|
+
const installTypes = async () => {
|
|
68
|
+
const config = readConfig(root);
|
|
69
|
+
if (!(await isDockerExist(config.project_uuid))) return null;
|
|
70
|
+
let bundle;
|
|
71
|
+
try {
|
|
72
|
+
const res = await fetch(`http://localhost:${config.web.port}/functions/v1/types.json`, { signal: AbortSignal.timeout(5000) });
|
|
73
|
+
if (!res.ok) return null;
|
|
74
|
+
bundle = await res.json();
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
const files = Object.entries((bundle && bundle.files) || {}).filter(([name, text]) => TYPE_FILE_RE.test(name) && !name.includes('..') && typeof text === 'string');
|
|
79
|
+
if (!files.length) return null;
|
|
80
|
+
const typesDir = path.join(dir, '.poad', 'types');
|
|
81
|
+
fs.rmSync(typesDir, { recursive: true, force: true });
|
|
82
|
+
for (const [name, text] of files) {
|
|
83
|
+
const target = path.join(typesDir, name);
|
|
84
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
85
|
+
fs.writeFileSync(target, text);
|
|
86
|
+
}
|
|
87
|
+
// L'ancien fichier de types (client en « any ») masquerait les nouveaux
|
|
88
|
+
const old = path.join(dir, 'poad-functions.d.ts');
|
|
89
|
+
if (fs.existsSync(old) && fs.readFileSync(old, 'utf8').startsWith('// Généré par poad')) fs.rmSync(old);
|
|
90
|
+
const tsconfig = path.join(dir, 'tsconfig.json');
|
|
91
|
+
if (!fs.existsSync(tsconfig)) fs.writeFileSync(tsconfig, TSCONFIG);
|
|
92
|
+
return files.length;
|
|
93
|
+
};
|
|
94
|
+
const reportTypes = (count) => {
|
|
95
|
+
if (count) console.log(chalk.grey(` Editor types: ${rel(path.join(dir, '.poad', 'types'))} (${count} files) and ${rel(path.join(dir, 'tsconfig.json'))}. No install needed.`));
|
|
96
|
+
else console.log(chalk.yellowBright(' Editor types not installed: start the project (engine 0.16.4+), then "poad functions types".'));
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
if (words[0] === 'types') {
|
|
100
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
101
|
+
const count = await installTypes();
|
|
102
|
+
if (!count) process.exitCode = 1;
|
|
103
|
+
else console.log(`${chalk.greenBright('✔')} ${chalk.bold('Types of @poadio/functions and the poad clients')}`);
|
|
104
|
+
return reportTypes(count);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (words[0] === 'new' || words[0] === 'create') {
|
|
108
|
+
const name = String(words[1] || '');
|
|
109
|
+
if (!NAME_RE.test(name)) {
|
|
110
|
+
process.exitCode = 1;
|
|
111
|
+
return console.log(chalk.redBright('Function name: a letter first, then a-z, 0-9 and "-" (poad functions new send-mail).'));
|
|
112
|
+
}
|
|
113
|
+
const fnDir = path.join(dir, name);
|
|
114
|
+
if (fs.existsSync(fnDir)) {
|
|
115
|
+
process.exitCode = 1;
|
|
116
|
+
return console.log(chalk.redBright(`${rel(fnDir)} already exists.`));
|
|
117
|
+
}
|
|
118
|
+
fs.mkdirSync(fnDir, { recursive: true });
|
|
119
|
+
fs.writeFileSync(path.join(fnDir, 'index.ts'), TEMPLATE(name));
|
|
120
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel(path.join(fnDir, 'index.ts')))}`);
|
|
121
|
+
console.log(chalk.grey(` Served on /functions/v1/${name}, reloaded on save. Options in ${rel(path.join(fnDir, 'function.json'))}: { "verify_jwt": false, "service_role": true }.`));
|
|
122
|
+
return reportTypes(await installTypes());
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (words[0] === 'list' || !words.length) {
|
|
126
|
+
const local = fs.existsSync(dir)
|
|
127
|
+
? fs.readdirSync(dir).filter((n) => !n.startsWith('_') && !n.startsWith('.') && n !== 'node_modules' && fs.statSync(path.join(dir, n)).isDirectory())
|
|
128
|
+
: [];
|
|
129
|
+
console.log(`${chalk.bold('Functions')} ${chalk.grey(rel(dir))}`);
|
|
130
|
+
console.log(' ');
|
|
131
|
+
if (!local.length) return console.log(chalk.grey(' None yet: "poad functions new <name>".'));
|
|
132
|
+
const config = readConfig(root);
|
|
133
|
+
let state = null;
|
|
134
|
+
if (await isDockerExist(config.project_uuid)) {
|
|
135
|
+
try {
|
|
136
|
+
const key = config.auth.service;
|
|
137
|
+
const res = await fetch(`http://localhost:${config.web.port}/functions/v1/`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(4000) });
|
|
138
|
+
if (res.ok) state = new Map((await res.json()).functions.map((f) => [f.name, f]));
|
|
139
|
+
} catch {
|
|
140
|
+
/* engine sans service functions, ou arrêté */
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const name of local.sort()) {
|
|
144
|
+
const f = state && state.get(name);
|
|
145
|
+
const mark = !state ? chalk.grey('?') : f && f.status === 'ready' ? chalk.greenBright('✔') : chalk.redBright('✖');
|
|
146
|
+
const note = !state ? '' : !f ? chalk.yellowBright(' not loaded yet') : f.status === 'ready' ? chalk.grey(` /functions/v1/${name}${f.verify_jwt ? '' : ' (no token required)'}`) : chalk.redBright(` ${String(f.error || 'build failed').split('\n')[0]}`);
|
|
147
|
+
console.log(` ${mark} ${name}${note}`);
|
|
148
|
+
}
|
|
149
|
+
if (!state) console.log(chalk.grey('\n State unknown: the project is not started, or its engine has no functions (0.16.0+).'));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
process.exitCode = 1;
|
|
154
|
+
console.log(chalk.redBright('Usage: poad functions new <name> | poad functions list | poad functions types'));
|
|
155
|
+
};
|
package/project/upgrade.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// poad upgrade passe le projet sur
|
|
1
|
+
// poad upgrade passe le projet sur le dernier engine publié
|
|
2
|
+
// (Docker Hub, sinon celui du CLI) : sauvegarde
|
|
2
3
|
// (poad/backups), arrêt, mise à jour de config.toml,
|
|
3
4
|
// redémarrage (l'engine migre poad/data) et migrations
|
|
4
5
|
// poad upgrade to=<version> vers une version précise (plus récente)
|
|
@@ -102,8 +103,21 @@ module.exports = async (args = {}) => {
|
|
|
102
103
|
}
|
|
103
104
|
|
|
104
105
|
// Mise à jour
|
|
105
|
-
|
|
106
|
+
// Sans to= : le dernier engine publié (Docker Hub), sinon celui inscrit dans le CLI
|
|
106
107
|
const current = config.engine;
|
|
108
|
+
let target = String(args.to || '');
|
|
109
|
+
if (!target) {
|
|
110
|
+
const { latestEngine } = require('../utils/latest');
|
|
111
|
+
const latest = await latestEngine();
|
|
112
|
+
target = String(latest || global.package.engine || '');
|
|
113
|
+
if (!latest) {
|
|
114
|
+
console.log(chalk.grey(` Docker Hub unreachable: latest engine unknown, this CLI knows ${target || 'none'}.`));
|
|
115
|
+
// La version du CLI peut être en retard : jamais de retour en arrière sans to=
|
|
116
|
+
if (target && target !== current && !isNewerVersion(target, current)) {
|
|
117
|
+
return console.log(chalk.yellow(` This project uses engine ${current}. Retry online, or "poad upgrade to=<version>".`));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
107
121
|
if (!target) return console.log(chalk.redBright('No target engine version.'));
|
|
108
122
|
if (target === current) return console.log(chalk.green(` This project already uses engine ${current}.`));
|
|
109
123
|
if (!isNewerVersion(target, current)) {
|
package/utils/latest.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Dernière version publiée de l'engine, lue sur Docker Hub (poadio/engine) :
|
|
2
|
+
// le CLI n'a pas à être republié à chaque engine. Hors ligne ou réponse
|
|
3
|
+
// illisible : null, l'appelant garde la version inscrite dans le CLI.
|
|
4
|
+
const TAGS_URL = 'https://hub.docker.com/v2/repositories/poadio/engine/tags?page_size=100';
|
|
5
|
+
|
|
6
|
+
const compare = (a, b) => {
|
|
7
|
+
const x = a.split('.').map(Number);
|
|
8
|
+
const y = b.split('.').map(Number);
|
|
9
|
+
return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// Seules les versions x.y.z comptent : ni latest, ni préversion
|
|
13
|
+
const pickLatest = (tags) => {
|
|
14
|
+
const versions = (tags || []).filter((t) => typeof t === 'string' && /^\d+\.\d+\.\d+$/.test(t));
|
|
15
|
+
return versions.length ? versions.sort(compare).pop() : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const latestEngine = async (timeout = 4000) => {
|
|
19
|
+
try {
|
|
20
|
+
const res = await fetch(TAGS_URL, { signal: AbortSignal.timeout(timeout) });
|
|
21
|
+
if (!res.ok) return null;
|
|
22
|
+
return pickLatest(((await res.json()).results || []).map((t) => t.name));
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
module.exports = { latestEngine, pickLatest };
|
package/utils/pull.js
CHANGED
|
@@ -1,27 +1,179 @@
|
|
|
1
|
+
// Téléchargement des images Docker, avec une barre de progression.
|
|
2
|
+
|
|
3
|
+
const MB = 1024 * 1024;
|
|
4
|
+
// Part du téléchargement dans l'avancement d'une couche ; le reste est
|
|
5
|
+
// l'extraction.
|
|
6
|
+
const DOWNLOAD_SHARE = 0.8;
|
|
7
|
+
|
|
8
|
+
// Suit les événements de `docker pull` et en tire un avancement global.
|
|
9
|
+
// Docker n'annonce pas la taille totale de l'image, seulement celle de chaque
|
|
10
|
+
// couche quand son téléchargement commence : un total en octets reculerait à
|
|
11
|
+
// chaque nouvelle couche. L'avancement est donc la moyenne de celui des
|
|
12
|
+
// couches. Selon le moteur, des couches peuvent encore apparaître en cours de
|
|
13
|
+
// route : l'affichage garde le maximum atteint pour ne jamais reculer.
|
|
14
|
+
const createTracker = () => {
|
|
15
|
+
const layers = new Map();
|
|
16
|
+
let best = 0;
|
|
17
|
+
const layer = (id) => {
|
|
18
|
+
if (!layers.has(id)) layers.set(id, { fraction: 0, bytes: 0, done: false });
|
|
19
|
+
return layers.get(id);
|
|
20
|
+
};
|
|
21
|
+
const raise = (l, fraction) => {
|
|
22
|
+
if (fraction > l.fraction) l.fraction = Math.min(1, fraction);
|
|
23
|
+
};
|
|
24
|
+
const ratio = (detail) => (detail && detail.total > 0 ? Math.min(1, detail.current / detail.total) : 0);
|
|
25
|
+
|
|
26
|
+
const onEvent = (event) => {
|
|
27
|
+
if (!event || !event.id) return;
|
|
28
|
+
const detail = event.progressDetail;
|
|
29
|
+
switch (event.status) {
|
|
30
|
+
case 'Pulling fs layer':
|
|
31
|
+
case 'Waiting':
|
|
32
|
+
layer(event.id);
|
|
33
|
+
break;
|
|
34
|
+
case 'Downloading': {
|
|
35
|
+
const l = layer(event.id);
|
|
36
|
+
if (detail && detail.current > l.bytes) l.bytes = detail.current;
|
|
37
|
+
raise(l, DOWNLOAD_SHARE * ratio(detail));
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
case 'Verifying Checksum':
|
|
41
|
+
case 'Download complete':
|
|
42
|
+
raise(layer(event.id), DOWNLOAD_SHARE);
|
|
43
|
+
break;
|
|
44
|
+
case 'Extracting': {
|
|
45
|
+
const l = layer(event.id);
|
|
46
|
+
// Selon le moteur, l'extraction compte en octets ou en secondes ; on
|
|
47
|
+
// ne s'y fie que lorsqu'un total est donné.
|
|
48
|
+
raise(l, DOWNLOAD_SHARE + (1 - DOWNLOAD_SHARE) * ratio(detail));
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case 'Already exists':
|
|
52
|
+
case 'Pull complete': {
|
|
53
|
+
const l = layer(event.id);
|
|
54
|
+
l.fraction = 1;
|
|
55
|
+
l.done = true;
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
default:
|
|
59
|
+
// « Pulling from … », « Digest: … », « Status: … » : pas des couches.
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const snapshot = () => {
|
|
65
|
+
let fraction = 0;
|
|
66
|
+
let bytes = 0;
|
|
67
|
+
let done = 0;
|
|
68
|
+
for (const l of layers.values()) {
|
|
69
|
+
fraction += l.fraction;
|
|
70
|
+
bytes += l.bytes;
|
|
71
|
+
if (l.done) done += 1;
|
|
72
|
+
}
|
|
73
|
+
const count = layers.size;
|
|
74
|
+
best = Math.max(best, count ? fraction / count : 0);
|
|
75
|
+
return { fraction: best, bytes, done, count };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
return { onEvent, snapshot };
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// Tire une image. Lève une erreur en cas d'échec. `onEvent` reçoit chaque
|
|
82
|
+
// événement de Docker.
|
|
83
|
+
const pullStream = (docker, image, onEvent) =>
|
|
84
|
+
new Promise((resolve, reject) =>
|
|
85
|
+
docker.pull(image, (err, stream) =>
|
|
86
|
+
err ? reject(err) : docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()), onEvent)
|
|
87
|
+
)
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
// Tire une image en affichant une barre de progression (ou une simple ligne
|
|
91
|
+
// quand la sortie n'est pas un terminal). Renvoie false en cas d'échec
|
|
92
|
+
// (message déjà affiché).
|
|
93
|
+
const pullImage = async (docker, image) => {
|
|
94
|
+
const ora = require('ora');
|
|
95
|
+
const chalk = require('chalk-v2');
|
|
96
|
+
|
|
97
|
+
if (!process.stdout.isTTY) {
|
|
98
|
+
const pulling = ora(`Pulling ${image}`).start();
|
|
99
|
+
try {
|
|
100
|
+
await pullStream(docker, image);
|
|
101
|
+
pulling.succeed(`${image} pulled.`);
|
|
102
|
+
return true;
|
|
103
|
+
} catch (err) {
|
|
104
|
+
pulling.fail(chalk.redBright(`Cannot pull ${image}: ${err.message}`));
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const cliProgress = require('cli-progress');
|
|
110
|
+
const tracker = createTracker();
|
|
111
|
+
const bar = new cliProgress.SingleBar(
|
|
112
|
+
{
|
|
113
|
+
format: `${chalk.cyan('⬇')} ${image} ${chalk.cyan('{bar}')} {percentage}% │ {mb} MB │ {speed} │ {done}/{count} layers`,
|
|
114
|
+
barCompleteChar: '█',
|
|
115
|
+
barIncompleteChar: '░',
|
|
116
|
+
barsize: 24,
|
|
117
|
+
hideCursor: true,
|
|
118
|
+
clearOnComplete: true,
|
|
119
|
+
},
|
|
120
|
+
cliProgress.Presets.shades_classic
|
|
121
|
+
);
|
|
122
|
+
const payload = (s, speed) => ({
|
|
123
|
+
mb: (s.bytes / MB).toFixed(0),
|
|
124
|
+
speed: speed > 0 ? `${(speed / MB).toFixed(1)} MB/s` : '— MB/s',
|
|
125
|
+
done: s.done,
|
|
126
|
+
count: s.count,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
bar.start(1000, 0, payload(tracker.snapshot(), 0));
|
|
130
|
+
|
|
131
|
+
// Débit lissé, recalculé deux fois par seconde.
|
|
132
|
+
let speed = 0;
|
|
133
|
+
let lastBytes = 0;
|
|
134
|
+
let lastTime = Date.now();
|
|
135
|
+
const refresh = () => {
|
|
136
|
+
const s = tracker.snapshot();
|
|
137
|
+
const now = Date.now();
|
|
138
|
+
const elapsed = (now - lastTime) / 1000;
|
|
139
|
+
if (elapsed > 0) {
|
|
140
|
+
const instant = (s.bytes - lastBytes) / elapsed;
|
|
141
|
+
speed = speed ? speed * 0.6 + instant * 0.4 : instant;
|
|
142
|
+
lastBytes = s.bytes;
|
|
143
|
+
lastTime = now;
|
|
144
|
+
}
|
|
145
|
+
bar.update(Math.round(s.fraction * 1000), payload(s, speed));
|
|
146
|
+
};
|
|
147
|
+
const timer = setInterval(refresh, 500);
|
|
148
|
+
const started = Date.now();
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
await pullStream(docker, image, tracker.onEvent);
|
|
152
|
+
clearInterval(timer);
|
|
153
|
+
bar.stop();
|
|
154
|
+
const s = tracker.snapshot();
|
|
155
|
+
const seconds = ((Date.now() - started) / 1000).toFixed(0);
|
|
156
|
+
const size = s.bytes > 0 ? ` (${(s.bytes / MB).toFixed(0)} MB in ${seconds}s)` : '';
|
|
157
|
+
ora().succeed(`${image} pulled${size}.`);
|
|
158
|
+
return true;
|
|
159
|
+
} catch (err) {
|
|
160
|
+
clearInterval(timer);
|
|
161
|
+
bar.stop();
|
|
162
|
+
ora().fail(chalk.redBright(`Cannot pull ${image}: ${err.message}`));
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
1
167
|
// Tire une image Docker si elle n'est pas déjà là. Renvoie false en cas
|
|
2
168
|
// d'échec (message déjà affiché).
|
|
3
169
|
const pullIfMissing = async (docker, image) => {
|
|
4
|
-
const ora = require('ora');
|
|
5
|
-
const chalk = require('chalk-v2');
|
|
6
170
|
try {
|
|
7
171
|
await docker.getImage(image).inspect();
|
|
8
172
|
return true;
|
|
9
173
|
} catch {
|
|
10
174
|
/* absente : on la tire */
|
|
11
175
|
}
|
|
12
|
-
|
|
13
|
-
try {
|
|
14
|
-
await new Promise((resolve, reject) =>
|
|
15
|
-
docker.pull(image, (err, stream) =>
|
|
16
|
-
err ? reject(err) : docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()))
|
|
17
|
-
)
|
|
18
|
-
);
|
|
19
|
-
pulling.succeed(`${image} pulled.`);
|
|
20
|
-
return true;
|
|
21
|
-
} catch (err) {
|
|
22
|
-
pulling.fail(chalk.redBright(`Cannot pull ${image}: ${err.message}`));
|
|
23
|
-
return false;
|
|
24
|
-
}
|
|
176
|
+
return pullImage(docker, image);
|
|
25
177
|
};
|
|
26
178
|
|
|
27
|
-
module.exports = { pullIfMissing };
|
|
179
|
+
module.exports = { pullIfMissing, pullImage, createTracker };
|