This repository has been archived by the owner on Nov 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
compose.js
240 lines (213 loc) · 7.39 KB
/
compose.js
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
// npm packages
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const {v1: uuidv1} = require('uuid');
const {spawn} = require('child_process');
const {getHost, getEnv} = require('../../util');
// generates new base name for deployment
const generateBaseName = ({username, config}) =>
`exo-${_.kebabCase(username)}-${_.kebabCase(config.name.split(':').shift())}`;
// maps array labels to objects, if necessary
const asObjectLabels = labels =>
!Array.isArray(labels)
? labels
: labels.reduce((acc, label) => {
// Split at =, but only retain first value
const [name, ...values] = label.split('=');
const value = values.join('=');
return {...acc, [name]: value};
}, {});
// function to update compose file with required vars
const updateCompose = ({username, baseName, serverConfig, composePath}) => {
const uid = uuidv1();
// read compose file
const compose = yaml.safeLoad(fs.readFileSync(composePath, 'utf8'));
// modify networks
const network = serverConfig.exoframeNetwork;
compose.networks = Object.assign(
{},
{
[network]: {
external: true,
},
},
compose.networks
);
// modify services
Object.keys(compose.services).forEach(svcKey => {
const name = `${baseName}-${svcKey}-${uid.split('-').shift()}`;
const networks = Array.from(new Set([network, ...(compose.services[svcKey].networks || ['default'])]));
// update basic settings
const ext = {
container_name: name,
restart: 'on-failure:2',
};
compose.services[svcKey] = Object.assign({}, ext, compose.services[svcKey], {networks});
// update labels if needed
const extLabels = {
'exoframe.name': name,
'exoframe.deployment': name,
'exoframe.user': username,
'exoframe.project': baseName,
'traefik.docker.network': network,
'traefik.enable': 'true',
};
compose.services[svcKey].labels = Object.assign({}, extLabels, asObjectLabels(compose.services[svcKey].labels));
});
// write new compose back to file
fs.writeFileSync(composePath, yaml.safeDump(compose), 'utf8');
return compose;
};
// function to execute docker-compose file and return the output
const executeCompose = ({cmd, resultStream, tempDockerDir, folder, writeStatus, env = {}}) =>
new Promise(resolve => {
const dc = spawn('docker-compose', cmd, {cwd: path.join(tempDockerDir, folder), env: {...process.env, ...env}});
const log = [];
dc.stdout.on('data', data => {
const message = data.toString().replace(/\n$/, '');
const hasError = message.toLowerCase().includes('error');
log.push(message);
writeStatus(resultStream, {message, level: hasError ? 'error' : 'info'});
});
dc.stderr.on('data', data => {
const message = data.toString().replace(/\n$/, '');
const hasError = message.toLowerCase().includes('error');
log.push(message);
writeStatus(resultStream, {message, level: hasError ? 'error' : 'info'});
});
dc.on('exit', code => {
writeStatus(resultStream, {message: `Docker-compose exited with code ${code.toString()}`, level: 'info'});
resolve({code: code.toString(), log});
});
});
// extract pre-built image names from build log
const logToImages = log =>
log
.filter(line => line.startsWith('Successfully tagged'))
.map(line => line.replace(/^Successfully tagged /, '').trim());
// template name
exports.name = 'docker-compose';
// function to check if the template fits this recipe
exports.checkTemplate = async ({tempDockerDir, folder}) => {
// compose file path
const composePath = path.join(tempDockerDir, folder, 'docker-compose.yml');
// if project already has docker-compose - just exit
try {
fs.readFileSync(composePath);
return true;
} catch (e) {
return false;
}
};
// function to execute current template
exports.executeTemplate = async ({
username,
config,
serverConfig,
tempDockerDir,
folder,
resultStream,
docker,
util,
}) => {
// compose file path
const composePath = path.join(tempDockerDir, folder, 'docker-compose.yml');
// if it does - run compose workflow
util.logger.debug('Docker-compose file found, executing compose workflow..');
util.writeStatus(resultStream, {message: 'Deploying docker-compose project..', level: 'info'});
// generate basename
const baseName = generateBaseName({username, config});
// update compose file with project params
const composeConfig = updateCompose({username, baseName, config, serverConfig, composePath, util, resultStream});
// exit if update failed
if (!composeConfig) {
return;
}
util.logger.debug('Compose modified:', composeConfig);
util.writeStatus(resultStream, {message: 'Compose file modified', data: composeConfig, level: 'verbose'});
// generate host
const host = getHost({serverConfig, name: baseName, config});
const env = getEnv({username, config, name: baseName, host}).reduce(
(merged, [key, value]) => ({...merged, [key]: value}),
{}
);
// re-build images if needed
const {code: buildExitCode, log: buildLog} = await executeCompose({
cmd: ['--project-name', baseName, 'build', '--force-rm'],
env,
resultStream,
tempDockerDir,
folder,
writeStatus: util.writeStatus,
});
util.logger.debug('Compose build executed, exit code:', buildExitCode);
if (buildExitCode !== '0') {
util.writeStatus(resultStream, {
message: `Deployment failed! Docker-compose build exited with code: ${buildExitCode}.`,
log: buildLog,
level: 'error',
});
resultStream.end('');
return;
}
// run compose via plugins if available
const plugins = util.getPlugins();
for (const plugin of plugins) {
// only run plugins that have compose function
if (!plugin.compose) {
continue;
}
const images = logToImages(buildLog);
const result = await plugin.compose({
images,
composeConfig,
composePath,
baseName,
docker,
util,
serverConfig,
resultStream,
tempDockerDir,
folder,
yaml,
});
util.logger.debug('Running compose with plugin:', plugin.config.name, result);
if (result && plugin.config.exclusive) {
util.logger.debug('Compose finished via exclusive plugin:', plugin.config.name);
return;
}
}
// execute compose 'up -d'
const {code: exitCode, log: execLog} = await executeCompose({
cmd: ['--project-name', baseName, 'up', '-d'],
env,
resultStream,
tempDockerDir,
folder,
writeStatus: util.writeStatus,
});
util.logger.debug('Compose up executed, exit code:', exitCode);
if (exitCode !== '0') {
util.writeStatus(resultStream, {
message: `Deployment failed! Docker-compose up exited with code: ${exitCode}.`,
log: execLog,
level: 'error',
});
resultStream.end('');
return;
}
// get container infos
const allContainers = await docker.daemon.listContainers({all: true});
const deployments = await Promise.all(
Object.keys(composeConfig.services)
.map(svc => composeConfig.services[svc].container_name)
.map(name => allContainers.find(c => c.Names.find(n => n === `/${name}`)))
.map(info => docker.daemon.getContainer(info.Id))
.map(container => container.inspect())
);
// return them
util.writeStatus(resultStream, {message: 'Deployment success!', deployments, level: 'info'});
resultStream.end('');
};