-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswarm-app-config.ts
More file actions
265 lines (243 loc) · 9.56 KB
/
Copy pathswarm-app-config.ts
File metadata and controls
265 lines (243 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import yaml from "js-yaml";
import fs from "fs";
import {AssertionError} from "assert";
import nunjucks from "nunjucks";
import {JTDSchemaType} from "ajv/dist/types/jtd-schema.js";
import {Ajv} from "ajv/dist/jtd.js";
import {assertObjectOrNull} from "./asserts.js";
export interface SwarmAppNetworkConfig {
attachable?: boolean;
external: boolean;
name: string;
}
export interface SwarmAppEndpointSpecPort {
protocol?: "tcp" | "udp" | "sctp";
publish_mode?: "ingress" | "host";
published_port: number;
target_port: number;
}
export interface SwarmAppServiceConfig {
extends?: {file: string; name: string}[];
image?: string;
service_labels?: Record<string, string>;
command?: string[];
entrypoint?: string[];
container_labels?: Record<string, string>;
configs?: Record<string, {
source_file?: string;
content?: string;
}>;
environment?: Record<string, string>;
env_file?: string;
networks?: string[];
replicas?: number;
stop_signal?: "SIGTERM" | "SIGQUIT";
stop_grace_period?: number;
user?: string;
placement?: {
max_replicas_per_node?: number;
constraints?: string[];
preferences?: {spread: string}[];
};
endpoint_spec?: {
ports: SwarmAppEndpointSpecPort[];
};
health_check?: {
test?: string[];
interval?: number;
timeout?: number;
retries?: number;
start_period?: number;
start_interval?: number;
};
dir?: string;
mounts?: Record<string, {
source: string;
type: "bind" | "volume";
read_only: boolean;
}>;
update_config?: {
parallelism: number;
order: "stop-first" | "start-first";
};
}
export interface SwarmAppConfig {
networks?: Record<string, SwarmAppNetworkConfig>;
service_specs: Record<string, SwarmAppServiceConfig>;
}
export const swarmAppConfigSchema: JTDSchemaType<SwarmAppConfig> = {
properties: {
service_specs: {
values: {
optionalProperties: {
extends: {
elements: {
properties: {
file: {type: "string"},
name: {type: "string"},
},
},
},
image: {type: "string"},
service_labels: {values: {type: "string"}},
command: {elements: {type: "string"}},
entrypoint: {elements: {type: "string"}},
container_labels: {values: {type: "string"}},
configs: {
values: {
optionalProperties: {
source_file: {type: "string"},
content: {type: "string"},
},
},
},
environment: {values: {type: "string"}},
env_file: {type: "string"},
networks: {
elements: {type: "string"},
},
replicas: {type: "int32"},
stop_signal: {enum: ["SIGTERM", "SIGQUIT"]},
stop_grace_period: {type: "float64"},
user: {type: "string"},
placement: {
optionalProperties: {
max_replicas_per_node: {type: "int32"},
constraints: {elements: {type: "string"}},
preferences: {
elements: {
properties: {
spread: {type: "string"},
},
},
},
},
},
endpoint_spec: {
properties: {
ports: {
elements: {
properties: {
published_port: {type: "uint16"},
target_port: {type: "uint16"},
},
optionalProperties: {
publish_mode: {enum: ["ingress", "host"]},
protocol: {enum: ["tcp", "udp", "sctp"]},
},
},
},
},
},
health_check: {
optionalProperties: {
test: {elements: {type: "string"}},
interval: {type: "float64"},
timeout: {type: "float64"},
retries: {type: "int32"},
start_period: {type: "float64"},
start_interval: {type: "float64"},
},
},
dir: {type: "string"},
mounts: {
values: {
properties: {
source: {type: "string"},
type: {enum: ["volume", "bind"]},
read_only: {type: "boolean"},
},
},
},
update_config: {
properties: {
parallelism: {type: "int32"},
order: {enum: ["stop-first", "start-first"]},
},
},
},
},
},
},
optionalProperties: {
networks: {
values: {
properties: {
name: {type: "string"},
external: {type: "boolean"},
},
optionalProperties: {
attachable: {type: "boolean"},
},
},
},
},
};
export async function loadSwarmAppConfig (configFile: string, throwOnUndefined: boolean, injectHostEnv: boolean | null = true, templatingInputFile: string | null): Promise<SwarmAppConfig> {
const nunjucksEnv = new nunjucks.Environment(null, {throwOnUndefined});
const nunjucksEnvInput = injectHostEnv ? {env: process.env} : {};
const templatingInput = yaml.load(templatingInputFile ? await fs.promises.readFile(templatingInputFile, "utf8") : "---");
assertObjectOrNull(templatingInput, "templatingInput is not an object or null");
let configFileContent = await fs.promises.readFile(configFile, "utf8");
configFileContent = nunjucksEnv.renderString(configFileContent, templatingInput ? {...nunjucksEnvInput, ...templatingInput} : nunjucksEnvInput);
const swarmAppConfig = yaml.load(configFileContent);
// Validate json schema
const validate = new Ajv().compile(swarmAppConfigSchema);
if (!validate(swarmAppConfig)) {
throw new AssertionError({message: JSON.stringify(validate.errors)});
}
return swarmAppConfig;
}
export function parseEnvFile (src: string): Record<string, string> {
const regExp = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/mg;
const obj: Record<string, string> = {};
const lines = src.replace(/\r\n?/mg, "\n");
let match;
while ((match = regExp.exec(lines)) != null) {
const key = match[1];
if (!key) continue;
let value = match[2] ?? "";
value = value.trim();
const maybeQuote = value[0];
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === "\"") {
value = value.replace(/\\n/g, "\n");
value = value.replace(/\\r/g, "\r");
}
obj[key] = value;
}
return obj;
}
export async function expandSwarmAppConfig (swarmAppConfig: SwarmAppConfig, appName: string) {
// Create default network block if it's missing.
if (swarmAppConfig.networks?.default == null) {
swarmAppConfig.networks = swarmAppConfig.networks ?? {};
swarmAppConfig.networks.default = {
name: `${appName}_default`,
attachable: false,
external: false,
};
}
// Expand envFile to environment
for (const s of Object.values(swarmAppConfig.service_specs)) {
if (!s.env_file) continue;
const envFileCnt = await fs.promises.readFile(s.env_file, "utf8");
s.environment = {...s.environment, ...parseEnvFile(envFileCnt)};
delete s.env_file;
}
// Validate health_check test prefix
const validTestPrefixes = ["CMD", "CMD-SHELL", "NONE"];
for (const [name, s] of Object.entries(swarmAppConfig.service_specs)) {
const test = s.health_check?.test;
if (test?.[0] && !validTestPrefixes.includes(test[0])) {
throw new AssertionError({message: `service_specs.${name}.health_check.test[0] must be one of ${validTestPrefixes.join(", ")}, got "${test[0]}"`});
}
}
// Ensure com.docker.stack.namespace labels
for (const s of Object.values(swarmAppConfig.service_specs)) {
s.service_labels = s.service_labels ?? {};
s.service_labels["com.docker.stack.namespace"] = appName;
s.container_labels = s.container_labels ?? {};
s.container_labels["com.docker.stack.namespace"] = appName;
}
}