-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcompose.ts
More file actions
259 lines (235 loc) · 6.79 KB
/
Copy pathcompose.ts
File metadata and controls
259 lines (235 loc) · 6.79 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
import fs from "fs";
import path from "path";
import yaml from "js-yaml";
import {
Manifest,
Compose,
ComposeService,
ComposeVolumes,
PackageImage
} from "../types";
import { upstreamImageLabel, UPSTREAM_VERSION_VARNAME } from "../params";
import { toTitleCase } from "./format";
import { mapValues } from "lodash";
const composeFileName = "docker-compose.yml";
/**
* Get compose path. Without arguments defaults to './docker-compose.yml'
*
* @param dir: './folder', [optional] directory to load the manifest from
* @return path = './dappnode_package.json'
*/
export function getComposePath(dir = "./"): string {
return path.join(dir, composeFileName);
}
/**
* Read the docker-compose.
* Without arguments defaults to write the manifest at './docker-compose.yml'
*
* @param dir: './folder', [optional] directory to load the manifest from
*/
export function generateAndWriteCompose(dir: string, manifest: Manifest): void {
const composeYaml = generateCompose(manifest);
writeCompose(dir, composeYaml);
}
/**
* Read a compose data (string, without parsing)
* Without arguments defaults to write the manifest at './docker-compose.yml'
*
* @param dir: './folder', [optional] directory to load the manifest from
* @return compose object
*/
export function readComposeString(dir: string): string {
const path = getComposePath(dir);
// Recommended way of checking a file existance https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
let data;
try {
data = fs.readFileSync(path, "utf8");
} catch (e) {
if (e.code === "ENOENT") {
throw Error(
`No docker-compose found at ${path}. Make sure you are in a directory with an initialized DNP.`
);
} else {
throw e;
}
}
return data;
}
/**
* Read a compose parsed data
* Without arguments defaults to write the manifest at './docker-compose.yml'
*
* @param dir: './folder', [optional] directory to load the manifest from
* @return compose object
*/
export function readCompose(dir: string): Compose {
const data = readComposeString(dir);
// Parse compose in try catch block to show a comprehensive error message
try {
const compose = yaml.safeLoad(data);
if (!compose) throw Error("result is undefined");
if (typeof compose === "string") throw Error("result is a string");
return compose as Compose;
} catch (e) {
throw Error(`Error parsing docker-compose: ${e.message}`);
}
}
/**
* Writes the docker-compose.
* Without arguments defaults to write the manifest at './docker-compose.yml'
*/
export function writeCompose(dir: string, compose: Compose): void {
const path = getComposePath(dir);
const composeString = yaml.dump(compose, { indent: 2 });
fs.writeFileSync(path, composeString);
}
export function generateCompose(manifest: Manifest): Compose {
const ensName = manifest.name.replace("/", "_").replace("@", "");
const service: ComposeService = {
build: "./build",
image: manifest.name + ":" + manifest.version
};
// Image name
service.image = manifest.name + ":" + manifest.version;
service.restart = manifest.image?.restart || "always";
// Volumes
if (manifest.image?.volumes) {
service.volumes = [
...(manifest.image.volumes || []),
...(manifest.image.external_vol || [])
];
}
// Ports
if (manifest.image?.ports) {
service.ports = manifest.image.ports;
}
// Volumes
const volumes: ComposeVolumes = {};
// Regular volumes
if (manifest.image?.volumes) {
manifest.image.volumes.map(vol => {
// Make sure it's a named volume
if (!vol.startsWith("/") && !vol.startsWith("~")) {
const volName = vol.split(":")[0];
volumes[volName] = {};
}
});
}
// External volumes
if (manifest.image?.external_vol) {
manifest.image.external_vol.map(vol => {
const volName = vol.split(":")[0];
volumes[volName] = {
external: {
name: volName
}
};
});
}
const dockerCompose: Compose = {
version: "3.4",
services: {
[ensName]: service
}
};
if (Object.getOwnPropertyNames(volumes).length)
dockerCompose.volumes = volumes;
return dockerCompose;
}
function getImageTag({
serviceName,
name,
version,
serviceCount
}: {
serviceName: string;
name: string;
version: string;
serviceCount: number;
}) {
return serviceCount > 1
? `${serviceName}.${name}:${version}`
: `${name}:${version}`;
}
type ExternalImage = { imageTag: string; newImageTag: string };
/**
* Update service image tag to current version
* @returns updated imageTags
*/
export function updateComposeImageTags(
compose: Compose,
{ name, version }: { name: string; version: string },
options?: { editExternalImages?: boolean }
): Compose {
return {
...compose,
services: mapValues(compose.services, (service, serviceName) => {
const newImageTag = getImageTag({
serviceName,
name,
version,
serviceCount: Object.keys(compose.services).length
});
return service.build
? {
...service,
image: newImageTag
}
: options?.editExternalImages
? {
...service,
image: newImageTag,
labels: {
...(service.labels || {}),
[upstreamImageLabel]: service.image
}
}
: service;
})
};
}
export function getComposePackageImages(
compose: Compose,
{ name, version }: { name: string; version: string }
): PackageImage[] {
return Object.entries(compose.services).map(
([serviceName, service]): PackageImage => {
const imageTag = getImageTag({
serviceName,
name,
version,
serviceCount: Object.keys(compose.services).length
});
return service.build
? { type: "local", imageTag }
: { type: "external", imageTag, originalImageTag: service.image };
}
);
}
export function parseComposeUpstreamVersion(
compose: Compose
): string | undefined {
const upstreamVersions: { name: string; version: string }[] = [];
for (const service of Object.values(compose.services))
if (
typeof service.build === "object" &&
typeof service.build.args === "object"
) {
for (const [varName, version] of Object.entries(service.build.args)) {
if (varName.startsWith(UPSTREAM_VERSION_VARNAME)) {
const name = varName
.replace(UPSTREAM_VERSION_VARNAME, "")
.replace(/^[^a-zA-Z\d]+/, "")
.replace(/[^a-zA-Z\d]+$/, "");
upstreamVersions.push({ name: toTitleCase(name), version });
}
}
}
return upstreamVersions.length === 0
? undefined
: upstreamVersions.length === 1
? upstreamVersions[0].version
: upstreamVersions
.map(({ name, version }) => (name ? `${name}: ${version}` : version))
.join(", ");
}