@foliwake/cli 0.10.2 → 0.11.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/CHANGELOG.md +48 -0
- package/README.md +196 -14
- package/config/docker/compose.varnish.yaml +44 -0
- package/config/docker/compose.yaml +165 -0
- package/dist/commands/dev.d.ts +3 -0
- package/dist/commands/dev.js +58 -21
- package/dist/commands/docker/backup.d.ts +12 -0
- package/dist/commands/docker/backup.js +29 -0
- package/dist/commands/docker/configure.d.ts +23 -0
- package/dist/commands/docker/configure.js +73 -0
- package/dist/commands/docker/exec.d.ts +8 -0
- package/dist/commands/docker/exec.js +26 -0
- package/dist/commands/docker/install.d.ts +33 -0
- package/dist/commands/docker/install.js +126 -0
- package/dist/commands/docker/link.d.ts +12 -0
- package/dist/commands/docker/link.js +24 -0
- package/dist/commands/docker/list.d.ts +7 -0
- package/dist/commands/docker/list.js +16 -0
- package/dist/commands/docker/logs.d.ts +15 -0
- package/dist/commands/docker/logs.js +33 -0
- package/dist/commands/docker/remove.d.ts +13 -0
- package/dist/commands/docker/remove.js +35 -0
- package/dist/commands/docker/restart.d.ts +9 -0
- package/dist/commands/docker/restart.js +18 -0
- package/dist/commands/docker/restore.d.ts +14 -0
- package/dist/commands/docker/restore.js +34 -0
- package/dist/commands/docker/start.d.ts +9 -0
- package/dist/commands/docker/start.js +18 -0
- package/dist/commands/docker/status.d.ts +10 -0
- package/dist/commands/docker/status.js +22 -0
- package/dist/commands/docker/stop.d.ts +9 -0
- package/dist/commands/docker/stop.js +18 -0
- package/dist/commands/docker/update.d.ts +14 -0
- package/dist/commands/docker/update.js +42 -0
- package/dist/commands/project/publish.d.ts +1 -0
- package/dist/commands/project/publish.js +9 -2
- package/dist/core-command.d.ts +4 -1
- package/dist/core-command.js +6 -2
- package/dist/core-types.d.ts +1 -0
- package/dist/dev/container.d.ts +45 -0
- package/dist/dev/container.js +128 -0
- package/dist/dev/remote-html.js +2 -2
- package/dist/docker/asker.d.ts +4 -0
- package/dist/docker/asker.js +34 -0
- package/dist/docker/backup.d.ts +21 -0
- package/dist/docker/backup.js +114 -0
- package/dist/docker/cache-plan.d.ts +17 -0
- package/dist/docker/cache-plan.js +58 -0
- package/dist/docker/compose-file.d.ts +18 -0
- package/dist/docker/compose-file.js +58 -0
- package/dist/docker/context.d.ts +55 -0
- package/dist/docker/context.js +12 -0
- package/dist/docker/engine.d.ts +8 -0
- package/dist/docker/engine.js +51 -0
- package/dist/docker/env-block.d.ts +19 -0
- package/dist/docker/env-block.js +117 -0
- package/dist/docker/env-keys.d.ts +4 -0
- package/dist/docker/env-keys.js +33 -0
- package/dist/docker/env-verify.d.ts +17 -0
- package/dist/docker/env-verify.js +62 -0
- package/dist/docker/install-plan.d.ts +81 -0
- package/dist/docker/install-plan.js +332 -0
- package/dist/docker/install.d.ts +22 -0
- package/dist/docker/install.js +118 -0
- package/dist/docker/instance.d.ts +105 -0
- package/dist/docker/instance.js +184 -0
- package/dist/docker/lifecycle.d.ts +19 -0
- package/dist/docker/lifecycle.js +70 -0
- package/dist/docker/ports.d.ts +14 -0
- package/dist/docker/ports.js +50 -0
- package/dist/docker/process-context.d.ts +8 -0
- package/dist/docker/process-context.js +26 -0
- package/dist/docker/remove.d.ts +7 -0
- package/dist/docker/remove.js +82 -0
- package/dist/docker/report.d.ts +32 -0
- package/dist/docker/report.js +109 -0
- package/dist/docker/runner.d.ts +28 -0
- package/dist/docker/runner.js +55 -0
- package/dist/docker/settings-files.d.ts +40 -0
- package/dist/docker/settings-files.js +125 -0
- package/dist/docker/trace-url.d.ts +5 -0
- package/dist/docker/trace-url.js +36 -0
- package/dist/docker/update.d.ts +29 -0
- package/dist/docker/update.js +317 -0
- package/dist/docker-command.d.ts +17 -0
- package/dist/docker-command.js +37 -0
- package/dist/project-preview.d.ts +8 -0
- package/dist/project-preview.js +27 -5
- package/dist/project-publish.d.ts +8 -7
- package/dist/project-publish.js +124 -57
- package/dist/publish-code.d.ts +75 -0
- package/dist/publish-code.js +223 -0
- package/dist/render/site-status.js +2 -2
- package/package.json +13 -8
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// `docker backup` and `docker restore`: the data volume of an instance as one .tar.gz on this computer
|
|
2
|
+
// (src/server/data-backup.ts does the work, inside a helper container of the instance's own image with the
|
|
3
|
+
// volume mounted). The helper has no network and no labels of the instance; it is removed afterwards.
|
|
4
|
+
// A backup may run while the server runs (its databases are copied consistently); a restore refuses
|
|
5
|
+
// while the server runs. Archives hold the server's secrets: they are written 0600.
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { askerOf } from './asker.js';
|
|
10
|
+
import { DockerFailure, DockerUsageError } from './context.js';
|
|
11
|
+
import { containerOf, dataVolume } from './instance.js';
|
|
12
|
+
import { failureText } from './runner.js';
|
|
13
|
+
import { instanceDir, readEnvFile } from './settings-files.js';
|
|
14
|
+
const IN_HELPER = '/tmp/foliwake-backup.tar.gz';
|
|
15
|
+
/** The image the helper runs: the server's, else the one of the instance's settings. */
|
|
16
|
+
async function helperImage(ctx, instance) {
|
|
17
|
+
const server = containerOf(instance, 'server');
|
|
18
|
+
if (server)
|
|
19
|
+
return server.imageId;
|
|
20
|
+
const image = (await readEnvFile(ctx.env, instance.name))?.values.FOLIWAKE_IMAGE;
|
|
21
|
+
if (!image)
|
|
22
|
+
throw new DockerUsageError(`${instance.name} has no server container and no image in its settings.`);
|
|
23
|
+
return image;
|
|
24
|
+
}
|
|
25
|
+
/** `docker create` of a helper on the data volume running `foliwake <args>`; its name. */
|
|
26
|
+
async function createHelper(ctx, instance, args, helper) {
|
|
27
|
+
const { user, image = await helperImage(ctx, instance) } = helper;
|
|
28
|
+
const name = `${instance.name}-data-${randomBytes(4).toString('hex')}`;
|
|
29
|
+
const volume = `${dataVolume(instance.name)}:/data`;
|
|
30
|
+
const options = ['--name', name, '--network', 'none', '-v', volume, ...(user ? ['--user', user] : [])];
|
|
31
|
+
const created = await ctx.docker.run(['create', ...options, image, ...args]);
|
|
32
|
+
if (created.code !== 0)
|
|
33
|
+
throw new DockerFailure(`The helper container could not be made: ${failureText(created)}`);
|
|
34
|
+
return name;
|
|
35
|
+
}
|
|
36
|
+
async function runHelper(ctx, name, what) {
|
|
37
|
+
const ran = await ctx.docker.run(['start', '-a', name]);
|
|
38
|
+
if (ran.code !== 0)
|
|
39
|
+
throw new DockerFailure(`The ${what} failed: ${failureText(ran)}`);
|
|
40
|
+
}
|
|
41
|
+
const removeHelper = async (ctx, name) => void (await ctx.docker.run(['rm', '-f', name]));
|
|
42
|
+
/** `<instance folder>/backups/<UTC time>.tar.gz` on this computer. */
|
|
43
|
+
export function defaultBackupFile(env, name, now = new Date()) {
|
|
44
|
+
const stamp = now.toISOString().replace(/[:.]/g, '-');
|
|
45
|
+
return path.join(instanceDir(env, name), 'backups', `${name}-${stamp}.tar.gz`);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Writes the backup of the instance's data volume to `out` (default: defaultBackupFile); the file. `image`
|
|
49
|
+
* runs the backup (default: the server's): `docker update` passes the image it switches to, so a fix of
|
|
50
|
+
* the backup itself takes effect before the switch.
|
|
51
|
+
*/
|
|
52
|
+
export async function backupInstance(ctx, instance, out, image) {
|
|
53
|
+
const file = path.resolve(out ?? defaultBackupFile(ctx.env, instance.name));
|
|
54
|
+
if (existsSync(file))
|
|
55
|
+
throw new DockerUsageError(`${file} exists already; choose another --out.`);
|
|
56
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
57
|
+
const args = ['data', 'backup', '--data', '/data', '--out', IN_HELPER];
|
|
58
|
+
const helper = await createHelper(ctx, instance, args, { image });
|
|
59
|
+
try {
|
|
60
|
+
await runHelper(ctx, helper, 'backup');
|
|
61
|
+
const copied = await ctx.docker.run(['cp', `${helper}:${IN_HELPER}`, file]);
|
|
62
|
+
if (copied.code !== 0)
|
|
63
|
+
throw new DockerFailure(`The backup could not be copied out: ${failureText(copied)}`);
|
|
64
|
+
chmodSync(file, 0o600);
|
|
65
|
+
return file;
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
await removeHelper(ctx, helper);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** `docker backup [name] [--out FILE]`. */
|
|
72
|
+
export async function runBackup(ctx, instance, out) {
|
|
73
|
+
const file = await backupInstance(ctx, instance, out);
|
|
74
|
+
ctx.out(`Backed up the data of ${instance.name} to ${file} (private: it holds the server's secrets).`);
|
|
75
|
+
ctx.out(`Restore it with \`foliwake docker restore ${instance.name} --from ${file}\` (the instance stopped).`);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
/** `docker restore [name] --from FILE [--replace]`: the server must be stopped. */
|
|
79
|
+
export async function runRestore(ctx, instance, request) {
|
|
80
|
+
const file = path.resolve(request.from);
|
|
81
|
+
if (!existsSync(file))
|
|
82
|
+
throw new DockerUsageError(`${file} does not exist.`);
|
|
83
|
+
const running = instance.containers.filter((container) => container.state === 'running');
|
|
84
|
+
if (running.length > 0) {
|
|
85
|
+
throw new DockerUsageError(`${instance.name} is running: stop it first (\`foliwake docker stop ${instance.name}\`).`);
|
|
86
|
+
}
|
|
87
|
+
const args = ['data', 'restore', '--data', '/data', '--from', IN_HELPER, ...(request.replace ? ['--replace'] : [])];
|
|
88
|
+
// As root: the archive's files get back their owner (the image's user); the helper has no network.
|
|
89
|
+
const helper = await createHelper(ctx, instance, args, { user: '0' });
|
|
90
|
+
try {
|
|
91
|
+
const copied = await ctx.docker.run(['cp', file, `${helper}:${IN_HELPER}`]);
|
|
92
|
+
if (copied.code !== 0)
|
|
93
|
+
throw new DockerFailure(`The backup could not be copied in: ${failureText(copied)}`);
|
|
94
|
+
await runHelper(ctx, helper, 'restore');
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await removeHelper(ctx, helper);
|
|
98
|
+
}
|
|
99
|
+
ctx.out(`Restored ${file} into the data of ${instance.name}. Start it with \`foliwake docker start ${instance.name}\`.`);
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
/** --replace deletes the volume's data: the name typed in a terminal, --yes without one; false: cancelled. */
|
|
103
|
+
export async function confirmReplace(ctx, name, yes) {
|
|
104
|
+
if (!ctx.interactive) {
|
|
105
|
+
if (!yes)
|
|
106
|
+
throw new DockerUsageError('Without a terminal, `restore --replace` needs --yes.');
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
const typed = await askerOf(ctx).text(`Type ${name} to delete its current data and restore the backup`);
|
|
110
|
+
if (typed === name)
|
|
111
|
+
return true;
|
|
112
|
+
ctx.err('The name did not match; nothing was changed.');
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type CacheMode } from './compose-file.js';
|
|
2
|
+
import { type DockerContext } from './context.js';
|
|
3
|
+
import type { EnvValues } from './env-keys.js';
|
|
4
|
+
export declare const DEFAULT_CACHE_PORT = 8090;
|
|
5
|
+
export interface CachePlan {
|
|
6
|
+
cache: CacheMode;
|
|
7
|
+
/** The Varnish port on the instance's address; null without Varnish. */
|
|
8
|
+
cachePort: number | null;
|
|
9
|
+
}
|
|
10
|
+
export declare function chooseCache(ctx: DockerContext, request: {
|
|
11
|
+
cache?: string | undefined;
|
|
12
|
+
cachePort?: string | undefined;
|
|
13
|
+
}, used: Map<number, string>, bind: string): Promise<CachePlan>;
|
|
14
|
+
/** Writes the plan into the .env values (and removes what a cache no longer there left). */
|
|
15
|
+
export declare function applyCache(values: EnvValues, plan: CachePlan): void;
|
|
16
|
+
/** The cache of an instance's settings. */
|
|
17
|
+
export declare const cacheOf: (values: EnvValues) => CacheMode;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// `--cache varnish` of `docker install` and `docker configure`: a Varnish of the instance in front of its
|
|
2
|
+
// live sites (config/docker/compose.varnish.yaml), on a port of its own (default: the first free one from
|
|
3
|
+
// 8090). Off by default. The .env values tell the server to write the VCL into the shared volume
|
|
4
|
+
// (src/server/one-port/varnish-vcl.ts) and where to send its BANs; without the cache they are removed.
|
|
5
|
+
import { CACHE_MODES } from './compose-file.js';
|
|
6
|
+
import { DockerUsageError } from './context.js';
|
|
7
|
+
import { firstFreePort, parsePort, portProblem } from './ports.js';
|
|
8
|
+
export const DEFAULT_CACHE_PORT = 8090;
|
|
9
|
+
/** What the server reads (the VCL file, the cache's address, how the cache reaches the server). */
|
|
10
|
+
const SERVER_VALUES = {
|
|
11
|
+
FOLIWAKE_CACHE_VCL_OUTPUT: '/varnish/default.vcl',
|
|
12
|
+
FOLIWAKE_CACHE_URL: 'http://varnish:80',
|
|
13
|
+
FOLIWAKE_CACHE_BACKEND: 'foliwake:8080',
|
|
14
|
+
};
|
|
15
|
+
function cacheMode(value) {
|
|
16
|
+
const mode = value ?? 'none';
|
|
17
|
+
if (!CACHE_MODES.includes(mode)) {
|
|
18
|
+
throw new DockerUsageError(`--cache must be none or varnish; got ${JSON.stringify(value)}.`);
|
|
19
|
+
}
|
|
20
|
+
return mode;
|
|
21
|
+
}
|
|
22
|
+
/** The port asked for (refused when taken), else the first free one from 8090. */
|
|
23
|
+
async function cachePortOf(ctx, typed, used, bind) {
|
|
24
|
+
if (typed === undefined) {
|
|
25
|
+
const free = await firstFreePort(ctx, used, bind, DEFAULT_CACHE_PORT);
|
|
26
|
+
if (free === null)
|
|
27
|
+
throw new DockerUsageError('No free port for the cache: choose one with --cache-port.');
|
|
28
|
+
return free;
|
|
29
|
+
}
|
|
30
|
+
const port = parsePort(typed);
|
|
31
|
+
if (port === null)
|
|
32
|
+
throw new DockerUsageError(`--cache-port must be a port number; got ${JSON.stringify(typed)}.`);
|
|
33
|
+
const problem = await portProblem(ctx, used, bind, port);
|
|
34
|
+
if (problem)
|
|
35
|
+
throw new DockerUsageError(`Cache port ${problem}.`);
|
|
36
|
+
return port;
|
|
37
|
+
}
|
|
38
|
+
export async function chooseCache(ctx, request, used, bind) {
|
|
39
|
+
const cache = cacheMode(request.cache);
|
|
40
|
+
if (cache === 'none') {
|
|
41
|
+
if (request.cachePort !== undefined)
|
|
42
|
+
throw new DockerUsageError('--cache-port goes with --cache varnish.');
|
|
43
|
+
return { cache, cachePort: null };
|
|
44
|
+
}
|
|
45
|
+
return { cache, cachePort: await cachePortOf(ctx, request.cachePort, used, bind) };
|
|
46
|
+
}
|
|
47
|
+
/** Writes the plan into the .env values (and removes what a cache no longer there left). */
|
|
48
|
+
export function applyCache(values, plan) {
|
|
49
|
+
values.FOLIWAKE_CACHE = plan.cache;
|
|
50
|
+
for (const key of [...Object.keys(SERVER_VALUES), 'VARNISH_PORT'])
|
|
51
|
+
delete values[key];
|
|
52
|
+
if (plan.cache === 'none' || plan.cachePort === null)
|
|
53
|
+
return;
|
|
54
|
+
Object.assign(values, SERVER_VALUES);
|
|
55
|
+
values.VARNISH_PORT = String(plan.cachePort);
|
|
56
|
+
}
|
|
57
|
+
/** The cache of an instance's settings. */
|
|
58
|
+
export const cacheOf = (values) => (values.FOLIWAKE_CACHE === 'varnish' ? 'varnish' : 'none');
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type TracesMode } from './instance.js';
|
|
2
|
+
/** The template in the package (dist/docker/ → ../../config/docker). */
|
|
3
|
+
export declare const TEMPLATE_FILE: string;
|
|
4
|
+
/** The image of `install` without --image; the same default as the engine's deploy/docker/compose.yaml. */
|
|
5
|
+
export declare const DEFAULT_IMAGE = "ghcr.io/foliwake/foliwake:main";
|
|
6
|
+
/** The fragment merged in with `--cache varnish` (a Varnish of the instance in front of the live sites). */
|
|
7
|
+
export declare const VARNISH_FILE: string;
|
|
8
|
+
export type CacheMode = 'none' | 'varnish';
|
|
9
|
+
export declare const CACHE_MODES: readonly CacheMode[];
|
|
10
|
+
export interface ComposeChoice {
|
|
11
|
+
name: string;
|
|
12
|
+
traces: TracesMode;
|
|
13
|
+
cliVersion: string;
|
|
14
|
+
/** Default `none`. */
|
|
15
|
+
cache?: CacheMode;
|
|
16
|
+
}
|
|
17
|
+
/** The compose.yaml text of an instance. */
|
|
18
|
+
export declare function composeFile(choice: ComposeChoice, template?: string): Promise<string>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The compose.yaml of an instance, from the template shipped in the CLI package
|
|
2
|
+
// (config/docker/compose.yaml): the project name, the dev.foliwake.* labels on every container,
|
|
3
|
+
// volume and the network, and the Jaeger service and its configurations only with Jaeger traces. The
|
|
4
|
+
// file names variables only (their values are in .env); no secret value is ever written here.
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import YAML from 'yaml';
|
|
9
|
+
import { LABEL } from './instance.js';
|
|
10
|
+
/** The template in the package (dist/docker/ → ../../config/docker). */
|
|
11
|
+
export const TEMPLATE_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../config/docker/compose.yaml');
|
|
12
|
+
/** The image of `install` without --image; the same default as the engine's deploy/docker/compose.yaml. */
|
|
13
|
+
export const DEFAULT_IMAGE = 'ghcr.io/foliwake/foliwake:main';
|
|
14
|
+
/** The fragment merged in with `--cache varnish` (a Varnish of the instance in front of the live sites). */
|
|
15
|
+
export const VARNISH_FILE = path.join(path.dirname(TEMPLATE_FILE), 'compose.varnish.yaml');
|
|
16
|
+
export const CACHE_MODES = ['none', 'varnish'];
|
|
17
|
+
/** The Varnish service, the `vcl` volume it shares with the server, and the server's mount of it. */
|
|
18
|
+
async function addVarnish(doc, name, labels) {
|
|
19
|
+
const fragment = YAML.parse(await readFile(VARNISH_FILE, 'utf8'));
|
|
20
|
+
doc.setIn(['services', 'varnish'], doc.createNode({ ...fragment.services.varnish, labels: labels('cache') }));
|
|
21
|
+
const volumes = doc.getIn(['services', 'foliwake', 'volumes']);
|
|
22
|
+
volumes.add('vcl:/varnish');
|
|
23
|
+
doc.setIn(['volumes', 'vcl'], doc.createNode({ labels: { [LABEL.instance]: name, [LABEL.role]: 'vcl' } }));
|
|
24
|
+
}
|
|
25
|
+
/** The compose.yaml text of an instance. */
|
|
26
|
+
export async function composeFile(choice, template) {
|
|
27
|
+
// The template's own header (lines of `#` before the first key) describes the template, not this file.
|
|
28
|
+
const text = (template ?? (await readFile(TEMPLATE_FILE, 'utf8'))).replace(/^(?:#.*\n)+\n?/, '');
|
|
29
|
+
const doc = YAML.parseDocument(text);
|
|
30
|
+
const labels = (role) => ({
|
|
31
|
+
[LABEL.instance]: choice.name,
|
|
32
|
+
[LABEL.role]: role,
|
|
33
|
+
[LABEL.traces]: choice.traces,
|
|
34
|
+
[LABEL.cli]: choice.cliVersion,
|
|
35
|
+
});
|
|
36
|
+
doc.commentBefore =
|
|
37
|
+
` Generated by \`foliwake docker\` ${choice.cliVersion} for instance ${choice.name}; \`foliwake docker ` +
|
|
38
|
+
`configure\` and \`update\` rewrite it.\n Values are in .env next to this file (private, 0600). By ` +
|
|
39
|
+
`hand: docker compose -p ${choice.name} ps`;
|
|
40
|
+
doc.set('name', choice.name);
|
|
41
|
+
doc.setIn(['services', 'foliwake', 'labels'], doc.createNode(labels('server')));
|
|
42
|
+
doc.setIn(['volumes', 'data'], doc.createNode({ labels: { [LABEL.instance]: choice.name, [LABEL.role]: 'data' } }));
|
|
43
|
+
doc.setIn(['networks'], doc.createNode({ default: { labels: { [LABEL.instance]: choice.name } } }));
|
|
44
|
+
if (choice.cache === 'varnish')
|
|
45
|
+
await addVarnish(doc, choice.name, labels);
|
|
46
|
+
if (choice.traces === 'jaeger') {
|
|
47
|
+
doc.setIn(['services', 'jaeger', 'labels'], doc.createNode(labels('jaeger')));
|
|
48
|
+
doc.setIn(['services', 'foliwake', 'depends_on'], doc.createNode({ jaeger: { condition: 'service_started' } }));
|
|
49
|
+
doc.setIn(['volumes', 'jaeger-data'], doc.createNode({ labels: { [LABEL.instance]: choice.name, [LABEL.role]: 'jaeger-data' } }));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
doc.deleteIn(['services', 'jaeger']);
|
|
53
|
+
doc.delete('x-jaeger-memory');
|
|
54
|
+
doc.delete('x-jaeger-badger');
|
|
55
|
+
doc.deleteIn(['volumes', 'jaeger-data']);
|
|
56
|
+
}
|
|
57
|
+
return doc.toString({ lineWidth: 0 });
|
|
58
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Readable, Writable } from 'node:stream';
|
|
2
|
+
import type { DockerRunner } from './runner.js';
|
|
3
|
+
export interface PromptStreams {
|
|
4
|
+
input: Readable;
|
|
5
|
+
output: Writable;
|
|
6
|
+
}
|
|
7
|
+
export interface Choice<T> {
|
|
8
|
+
value: T;
|
|
9
|
+
label: string;
|
|
10
|
+
hint?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The questions of the commands; @clack/prompts in a terminal (asker.ts), a script in tests.
|
|
14
|
+
* Cancelling throws DockerCancelled.
|
|
15
|
+
*/
|
|
16
|
+
export interface Asker {
|
|
17
|
+
intro(title: string): void;
|
|
18
|
+
text(message: string, options?: {
|
|
19
|
+
initial?: string;
|
|
20
|
+
validate?: (value: string) => string | undefined;
|
|
21
|
+
}): Promise<string>;
|
|
22
|
+
/** Hidden input; empty allowed only with `optional`. */
|
|
23
|
+
secret(message: string, options?: {
|
|
24
|
+
optional?: boolean;
|
|
25
|
+
}): Promise<string>;
|
|
26
|
+
select<T extends string>(message: string, choices: ReadonlyArray<Choice<T>>, initial: T): Promise<T>;
|
|
27
|
+
confirm(message: string, initial: boolean): Promise<boolean>;
|
|
28
|
+
}
|
|
29
|
+
export interface DockerContext {
|
|
30
|
+
docker: DockerRunner;
|
|
31
|
+
env: NodeJS.ProcessEnv;
|
|
32
|
+
out(line?: string): void;
|
|
33
|
+
err(line?: string): void;
|
|
34
|
+
/** Questions may be asked (a terminal, and not --no-interactive). */
|
|
35
|
+
interactive: boolean;
|
|
36
|
+
prompts: PromptStreams;
|
|
37
|
+
/** The questions (default: @clack/prompts on `prompts`); asked only when `interactive`. */
|
|
38
|
+
asker?: Asker;
|
|
39
|
+
/** The version of this CLI (label dev.foliwake.cli). */
|
|
40
|
+
cliVersion: string;
|
|
41
|
+
/** True when `port` can be bound on `host` now (default: a test listen). */
|
|
42
|
+
portFree?(host: string, port: number): Promise<boolean>;
|
|
43
|
+
/** Opens a URL in the browser (default: open / xdg-open). */
|
|
44
|
+
openBrowser?(url: string): void;
|
|
45
|
+
}
|
|
46
|
+
/** A command line or a situation the command refuses before changing anything: exit 2. */
|
|
47
|
+
export declare class DockerUsageError extends Error {
|
|
48
|
+
}
|
|
49
|
+
/** Docker or Compose failed while the command ran: exit 1. */
|
|
50
|
+
export declare class DockerFailure extends Error {
|
|
51
|
+
}
|
|
52
|
+
/** Ctrl+C or Escape in a question: nothing (more) was changed; exit 130. */
|
|
53
|
+
export declare class DockerCancelled extends Error {
|
|
54
|
+
constructor();
|
|
55
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** A command line or a situation the command refuses before changing anything: exit 2. */
|
|
2
|
+
export class DockerUsageError extends Error {
|
|
3
|
+
}
|
|
4
|
+
/** Docker or Compose failed while the command ran: exit 1. */
|
|
5
|
+
export class DockerFailure extends Error {
|
|
6
|
+
}
|
|
7
|
+
/** Ctrl+C or Escape in a question: nothing (more) was changed; exit 130. */
|
|
8
|
+
export class DockerCancelled extends Error {
|
|
9
|
+
constructor() {
|
|
10
|
+
super('Cancelled.');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { DockerContext } from './context.js';
|
|
2
|
+
export declare const MIN_COMPOSE: readonly [2, 24];
|
|
3
|
+
/** Major and minor of a `docker compose version --format json` answer ("v2.29.1", "2.24.0-desktop.1"), or null. */
|
|
4
|
+
export declare function composeVersion(stdout: string): [number, number] | null;
|
|
5
|
+
/** Refuses (exit 2, nothing changed) when the Docker engine does not answer. */
|
|
6
|
+
export declare function checkDaemon(ctx: DockerContext): Promise<void>;
|
|
7
|
+
/** Refuses (exit 2, nothing changed) when the engine does not answer or Compose is too old. */
|
|
8
|
+
export declare function checkEngine(ctx: DockerContext): Promise<void>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { DockerUsageError } from './context.js';
|
|
2
|
+
export const MIN_COMPOSE = [2, 24];
|
|
3
|
+
/** Major and minor of a `docker compose version --format json` answer ("v2.29.1", "2.24.0-desktop.1"), or null. */
|
|
4
|
+
export function composeVersion(stdout) {
|
|
5
|
+
let version;
|
|
6
|
+
try {
|
|
7
|
+
version = JSON.parse(stdout).version;
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const match = typeof version === 'string' ? /^v?(\d+)\.(\d+)/.exec(version) : null;
|
|
13
|
+
return match ? [Number(match[1]), Number(match[2])] : null;
|
|
14
|
+
}
|
|
15
|
+
const atLeast = ([major, minor]) => major > MIN_COMPOSE[0] || (major === MIN_COMPOSE[0] && minor >= MIN_COMPOSE[1]);
|
|
16
|
+
/** The `Server` part of `docker version --format json`, or null when the engine did not answer. */
|
|
17
|
+
function serverOf(stdout) {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(stdout).Server ?? null;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Refuses (exit 2, nothing changed) when the Docker engine does not answer. */
|
|
26
|
+
export async function checkDaemon(ctx) {
|
|
27
|
+
const info = await ctx.docker.run(['version', '--format', 'json']);
|
|
28
|
+
if (serverOf(info.stdout))
|
|
29
|
+
return;
|
|
30
|
+
throw new DockerUsageError('The Docker engine does not answer. Start Docker (Docker Desktop, OrbStack, colima or the docker ' +
|
|
31
|
+
'service) and check `docker info`; a remote engine is used through `docker context use` or DOCKER_HOST.');
|
|
32
|
+
}
|
|
33
|
+
/** Refuses (exit 2, nothing changed) when Compose is missing or older than MIN_COMPOSE. */
|
|
34
|
+
async function checkCompose(ctx) {
|
|
35
|
+
const compose = await ctx.docker.run(['compose', 'version', '--format', 'json']);
|
|
36
|
+
const version = compose.code === 0 ? composeVersion(compose.stdout) : null;
|
|
37
|
+
const need = `${MIN_COMPOSE[0]}.${MIN_COMPOSE[1]}`;
|
|
38
|
+
if (!version) {
|
|
39
|
+
throw new DockerUsageError(`Docker Compose v2 (\`docker compose\`, at least ${need}) is needed and was not found. Install it: ` +
|
|
40
|
+
`https://docs.docker.com/compose/install/`);
|
|
41
|
+
}
|
|
42
|
+
if (!atLeast(version)) {
|
|
43
|
+
throw new DockerUsageError(`Docker Compose ${version.join('.')} is too old: at least ${need} is needed (\`up --wait\`, ` +
|
|
44
|
+
`\`config --format json\`). Update Docker or the Compose plugin: https://docs.docker.com/compose/install/`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Refuses (exit 2, nothing changed) when the engine does not answer or Compose is too old. */
|
|
48
|
+
export async function checkEngine(ctx) {
|
|
49
|
+
await checkDaemon(ctx);
|
|
50
|
+
await checkCompose(ctx);
|
|
51
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type EnvKey, type EnvValues } from './env-keys.js';
|
|
2
|
+
export declare const BLOCK_BEGIN = "# >>> managed by foliwake docker (do not edit inside; `foliwake docker configure` rewrites it) >>>";
|
|
3
|
+
export declare const BLOCK_END = "# <<< managed by foliwake docker <<<";
|
|
4
|
+
export interface EnvFile {
|
|
5
|
+
values: EnvValues;
|
|
6
|
+
/** The operator's text (all lines outside the block, in their order), exactly as in the file. */
|
|
7
|
+
operator?: string;
|
|
8
|
+
}
|
|
9
|
+
/** A key of ours inside the block, in the one form the CLI writes. */
|
|
10
|
+
export declare function envLine(key: EnvKey, value: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* The CLI's values and the operator's text. Refuses (DockerUsageError), before anything is written:
|
|
13
|
+
* markers that are not one standalone BEGIN line followed by one standalone END line (inline,
|
|
14
|
+
* duplicated, unclosed, out of order), a block edited by hand, and a line of the operator's that
|
|
15
|
+
* starts by assigning one of our keys.
|
|
16
|
+
*/
|
|
17
|
+
export declare function parseEnv(text: string, where?: string): EnvFile;
|
|
18
|
+
/** The file: the operator's text unchanged, then the block (last, so that its values win). */
|
|
19
|
+
export declare function renderEnv({ values, operator }: EnvFile): string;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// The .env of an instance: the operator's own text, kept byte for byte and never parsed to rewrite
|
|
2
|
+
// it, then LAST the block the CLI owns, between two marker lines. Compose takes the last definition
|
|
3
|
+
// of a variable in the file, so the block's values win over anything above them; after every write
|
|
4
|
+
// env-verify.ts asks Compose itself what it read and puts the old files back on any difference.
|
|
5
|
+
// Inside the block the CLI writes its keys in one form it controls (KEY=value, or KEY='value'
|
|
6
|
+
// without an apostrophe, backslash or line break), so it reads them back without emulating
|
|
7
|
+
// Compose's .env syntax.
|
|
8
|
+
import { DockerUsageError } from './context.js';
|
|
9
|
+
import { ENV_KEYS } from './env-keys.js';
|
|
10
|
+
export const BLOCK_BEGIN = '# >>> managed by foliwake docker (do not edit inside; `foliwake docker configure` rewrites it) >>>';
|
|
11
|
+
export const BLOCK_END = '# <<< managed by foliwake docker <<<';
|
|
12
|
+
/** The first line `foliwake docker` wrote before the block existed (earlier builds of this command). */
|
|
13
|
+
const OLD_HEADER = '# Written by `foliwake docker`';
|
|
14
|
+
const PLAIN = /^[\w@%+=:,./-]*$/;
|
|
15
|
+
/** A key of ours inside the block, in the one form the CLI writes. */
|
|
16
|
+
export function envLine(key, value) {
|
|
17
|
+
if (PLAIN.test(value))
|
|
18
|
+
return `${key}=${value}`;
|
|
19
|
+
if (/['\\\n\r]/.test(value)) {
|
|
20
|
+
throw new DockerUsageError(`The value of ${key} contains an apostrophe, a backslash or a line break; ` +
|
|
21
|
+
'foliwake docker does not write such values.');
|
|
22
|
+
}
|
|
23
|
+
// Single quotes: Compose takes the value literally (no ${…} substitution).
|
|
24
|
+
return `${key}='${value}'`;
|
|
25
|
+
}
|
|
26
|
+
/** The value of a line the CLI wrote, or null when the line is not in that form. */
|
|
27
|
+
function ownLine(line) {
|
|
28
|
+
const match = /^([A-Z0-9_]+)=(.*)$/.exec(line);
|
|
29
|
+
if (!match || !ENV_KEYS.includes(match[1]))
|
|
30
|
+
return null;
|
|
31
|
+
const raw = match[2];
|
|
32
|
+
if (PLAIN.test(raw))
|
|
33
|
+
return { key: match[1], value: raw };
|
|
34
|
+
const quoted = /^'([^'\\\n\r]*)'$/.exec(raw);
|
|
35
|
+
return quoted ? { key: match[1], value: quoted[1] } : null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A fast first error with a line number: a line of the operator's that starts by assigning one of
|
|
39
|
+
* our keys (`KEY=`, `KEY:`, `export KEY=`). Not a full check: Compose's own reading after the write
|
|
40
|
+
* (env-verify.ts) is that.
|
|
41
|
+
*/
|
|
42
|
+
function firstAssignedKey(lines, lineNumbers) {
|
|
43
|
+
for (let i = 0; i < lines.length; i++) {
|
|
44
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*[=:]/.exec(lines[i]);
|
|
45
|
+
if (match && ENV_KEYS.includes(match[1]))
|
|
46
|
+
return { key: match[1], line: lineNumbers[i] };
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const isMarker = (line, marker) => line.trimEnd() === marker;
|
|
51
|
+
const mentions = (line) => line.includes('managed by foliwake docker');
|
|
52
|
+
/**
|
|
53
|
+
* The CLI's values and the operator's text. Refuses (DockerUsageError), before anything is written:
|
|
54
|
+
* markers that are not one standalone BEGIN line followed by one standalone END line (inline,
|
|
55
|
+
* duplicated, unclosed, out of order), a block edited by hand, and a line of the operator's that
|
|
56
|
+
* starts by assigning one of our keys.
|
|
57
|
+
*/
|
|
58
|
+
export function parseEnv(text, where = '.env') {
|
|
59
|
+
const lines = text.split('\n');
|
|
60
|
+
const begins = lines.flatMap((line, index) => (isMarker(line, BLOCK_BEGIN) ? [index] : []));
|
|
61
|
+
const ends = lines.flatMap((line, index) => (isMarker(line, BLOCK_END) ? [index] : []));
|
|
62
|
+
const stray = lines.findIndex((line) => mentions(line) && !isMarker(line, BLOCK_BEGIN) && !isMarker(line, BLOCK_END));
|
|
63
|
+
const malformed = (what) => new DockerUsageError(`${where}: the block managed by foliwake docker is damaged (${what}). Nothing was changed; restore ` +
|
|
64
|
+
`the file, or remove the block's lines and run \`foliwake docker configure\` again.`);
|
|
65
|
+
if (stray !== -1)
|
|
66
|
+
throw malformed(`line ${stray + 1} names a marker but is not one`);
|
|
67
|
+
let blockStart;
|
|
68
|
+
let blockEnd;
|
|
69
|
+
if (begins.length === 0 && ends.length === 0) {
|
|
70
|
+
// No block: a file of an earlier build (its header and leading keys become the block), or none.
|
|
71
|
+
blockStart = lines[0]?.startsWith(OLD_HEADER) ? 0 : -1;
|
|
72
|
+
blockEnd = blockStart;
|
|
73
|
+
if (blockStart === 0)
|
|
74
|
+
while (blockEnd + 1 < lines.length && ownLine(lines[blockEnd + 1]))
|
|
75
|
+
blockEnd++;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
if (begins.length !== 1 || ends.length !== 1)
|
|
79
|
+
throw malformed('a marker is missing or repeated');
|
|
80
|
+
[blockStart] = begins;
|
|
81
|
+
[blockEnd] = ends;
|
|
82
|
+
if (blockEnd < blockStart)
|
|
83
|
+
throw malformed('the end marker comes before the start marker');
|
|
84
|
+
}
|
|
85
|
+
const values = {};
|
|
86
|
+
// A marked block's values are between its markers; an old file's run up to and including blockEnd.
|
|
87
|
+
const valuesEnd = begins.length ? blockEnd : blockEnd + 1;
|
|
88
|
+
for (let i = blockStart + 1; blockStart !== -1 && i < valuesEnd; i++) {
|
|
89
|
+
const own = ownLine(lines[i]);
|
|
90
|
+
if (!own) {
|
|
91
|
+
throw new DockerUsageError(`${where}, line ${i + 1}: the block managed by foliwake docker was edited by hand. Restore it, or ` +
|
|
92
|
+
`change the setting with \`foliwake docker configure\`.`);
|
|
93
|
+
}
|
|
94
|
+
values[own.key] = own.value;
|
|
95
|
+
}
|
|
96
|
+
// The block's lines: from the start marker (or an old file's header) to the end marker (or its last own line).
|
|
97
|
+
const inBlock = (index) => blockStart !== -1 && index >= blockStart && index <= blockEnd;
|
|
98
|
+
const outside = lines.map((line, index) => ({ line, number: index + 1 })).filter((_, index) => !inBlock(index));
|
|
99
|
+
const conflict = firstAssignedKey(outside.map((entry) => entry.line), outside.map((entry) => entry.number));
|
|
100
|
+
if (conflict) {
|
|
101
|
+
throw new DockerUsageError(`${where}, line ${conflict.line}: ${conflict.key} is set outside the block managed by foliwake docker ` +
|
|
102
|
+
`as well. Remove that line, and set ${conflict.key} with \`foliwake docker configure\` (or install).`);
|
|
103
|
+
}
|
|
104
|
+
return { values, operator: outside.map((entry) => entry.line).join('\n') };
|
|
105
|
+
}
|
|
106
|
+
/** The file: the operator's text unchanged, then the block (last, so that its values win). */
|
|
107
|
+
export function renderEnv({ values, operator = '' }) {
|
|
108
|
+
const lines = [BLOCK_BEGIN];
|
|
109
|
+
for (const key of ENV_KEYS) {
|
|
110
|
+
const value = values[key];
|
|
111
|
+
if (value !== undefined)
|
|
112
|
+
lines.push(envLine(key, value));
|
|
113
|
+
}
|
|
114
|
+
lines.push(BLOCK_END);
|
|
115
|
+
const separator = operator === '' || operator.endsWith('\n') ? '' : '\n';
|
|
116
|
+
return `${operator}${separator}${lines.join('\n')}\n`;
|
|
117
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The keys of the block; the operator's own lines go outside it and are kept. */
|
|
2
|
+
export declare const ENV_KEYS: readonly ["FOLIWAKE_INSTANCE", "FOLIWAKE_TRACES", "FOLIWAKE_IMAGE", "FOLIWAKE_BIND", "FOLIWAKE_HOST_PORT", "FOLIWAKE_PUBLIC_ORIGIN", "FOLIWAKE_DOMAIN", "FOLIWAKE_TRUST_PROXY", "FOLIWAKE_OWNER_EMAIL", "FOLIWAKE_STORAGE_ENDPOINT", "FOLIWAKE_STORAGE_REGION", "FOLIWAKE_STORAGE_BUCKET", "FOLIWAKE_STORAGE_CREATE_BUCKETS", "FOLIWAKE_STORAGE_ACCESS_KEY_ID", "FOLIWAKE_STORAGE_SECRET_ACCESS_KEY", "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_HEADERS", "FOLIWAKE_ENVIRONMENT", "FOLIWAKE_TRACE_URL_TEMPLATE", "JAEGER_CONFIG", "JAEGER_UI_PORT", "FOLIWAKE_CACHE", "FOLIWAKE_CACHE_VCL_OUTPUT", "FOLIWAKE_CACHE_URL", "FOLIWAKE_CACHE_BACKEND", "VARNISH_PORT", "FOLIWAKE_PREVIOUS_IMAGE"];
|
|
3
|
+
export type EnvKey = (typeof ENV_KEYS)[number];
|
|
4
|
+
export type EnvValues = Partial<Record<EnvKey, string>>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The .env keys `foliwake docker` owns: written in its block of an instance's .env (env-block.ts).
|
|
2
|
+
/** The keys of the block; the operator's own lines go outside it and are kept. */
|
|
3
|
+
export const ENV_KEYS = [
|
|
4
|
+
'FOLIWAKE_INSTANCE',
|
|
5
|
+
'FOLIWAKE_TRACES',
|
|
6
|
+
'FOLIWAKE_IMAGE',
|
|
7
|
+
'FOLIWAKE_BIND',
|
|
8
|
+
'FOLIWAKE_HOST_PORT',
|
|
9
|
+
'FOLIWAKE_PUBLIC_ORIGIN',
|
|
10
|
+
'FOLIWAKE_DOMAIN',
|
|
11
|
+
'FOLIWAKE_TRUST_PROXY',
|
|
12
|
+
'FOLIWAKE_OWNER_EMAIL',
|
|
13
|
+
'FOLIWAKE_STORAGE_ENDPOINT',
|
|
14
|
+
'FOLIWAKE_STORAGE_REGION',
|
|
15
|
+
'FOLIWAKE_STORAGE_BUCKET',
|
|
16
|
+
'FOLIWAKE_STORAGE_CREATE_BUCKETS',
|
|
17
|
+
'FOLIWAKE_STORAGE_ACCESS_KEY_ID',
|
|
18
|
+
'FOLIWAKE_STORAGE_SECRET_ACCESS_KEY',
|
|
19
|
+
'OTEL_EXPORTER_OTLP_ENDPOINT',
|
|
20
|
+
'OTEL_EXPORTER_OTLP_HEADERS',
|
|
21
|
+
'FOLIWAKE_ENVIRONMENT',
|
|
22
|
+
'FOLIWAKE_TRACE_URL_TEMPLATE',
|
|
23
|
+
'JAEGER_CONFIG',
|
|
24
|
+
'JAEGER_UI_PORT',
|
|
25
|
+
// `--cache varnish` (cache-plan.ts): the mode, the server's cache settings, the Varnish port.
|
|
26
|
+
'FOLIWAKE_CACHE',
|
|
27
|
+
'FOLIWAKE_CACHE_VCL_OUTPUT',
|
|
28
|
+
'FOLIWAKE_CACHE_URL',
|
|
29
|
+
'FOLIWAKE_CACHE_BACKEND',
|
|
30
|
+
'VARNISH_PORT',
|
|
31
|
+
// Not read by Compose: the image before the last `update`, for the rollback hint of `status`.
|
|
32
|
+
'FOLIWAKE_PREVIOUS_IMAGE',
|
|
33
|
+
];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type DockerContext } from './context.js';
|
|
2
|
+
import type { EnvFile } from './env-block.js';
|
|
3
|
+
import { type EnvKey } from './env-keys.js';
|
|
4
|
+
import { type PreviousFiles } from './settings-files.js';
|
|
5
|
+
/** The keys whose effective value differs from what the CLI wrote (empty: all as written). */
|
|
6
|
+
export declare function differingKeys(ctx: DockerContext, name: string, values: EnvFile['values']): Promise<EnvKey[]>;
|
|
7
|
+
/**
|
|
8
|
+
* Writes the files, checks them with Compose, and on any difference puts back what was there and
|
|
9
|
+
* refuses. Returns the folder and how to undo this write (for a step that fails later, e.g. a pull).
|
|
10
|
+
*/
|
|
11
|
+
export declare function writeVerified(ctx: DockerContext, name: string, files: {
|
|
12
|
+
compose: string;
|
|
13
|
+
env: EnvFile;
|
|
14
|
+
}): Promise<{
|
|
15
|
+
dir: string;
|
|
16
|
+
previous: PreviousFiles;
|
|
17
|
+
}>;
|