-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver.js
279 lines (239 loc) · 6.66 KB
/
server.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
const fs = require('fs')
const url = require('url')
const path = require('path')
const Docker = require('dockerode')
const {
app,
BrowserWindow,
dialog
} = require('electron')
require('@electron/remote/main').initialize()
/*
* Electron Window Management.
*/
let mainWindow = null
const createWindow = () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
allowRunningInsecureContent: true,
enableRemoteModule: true,
devTools: true,
contextIsolation: false,
},
})
mainWindow.maximize()
mainWindow.loadURL(
require('url').format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true,
})
)
mainWindow.on('closed', () => {
mainWindow = null
})
}
const exit = () => {
console.log('Exiting...')
process.platform !== 'darwin' ? app.quit() : app.exit(0)
}
/*
* Docker management for launching Core backend.
*/
// Volumes management
const pathExists = path => {
try {
if (fs.existsSync(path)) {
return true
}
} catch (err) {
console.error(err)
return false
}
}
const home = app.getPath('home')
const media = process.platform === 'darwin' ? '/Volumes' : '/media'
const bindings = [
pathExists(home) ? `${home}:/home` : null,
pathExists(media) ? `${media}:/media` : null,
pathExists('/ec/vol/ecpoint') ? '/ec/vol/ecpoint:/ec/vol/ecpoint' : null,
pathExists('/mnt') ? '/mnt:/mnt' : null,
pathExists('/vol') ? '/vol:/vol' : null,
pathExists('/tmp') ? '/tmp:/tmp' : null,
pathExists('/var/tmp') ? '/var/tmp:/var/tmp' : null,
pathExists('/scratch') ? '/scratch:/scratch' : null,
].filter(e => e !== null)
console.log(`Detected volume bindings: ${bindings}`)
// Docker image names
const backendImage = `oldreliabletech/ecpoint-calibrate-core:${app.getVersion()}`
const loggerImage = `oldreliabletech/ecpoint-calibrate-logger:${app.getVersion()}`
// Initialize Docker to communicate with the Docker Engine.
const docker = new Docker({
socketPath: '/var/run/docker.sock',
})
// containers is an array that tracks the IDs of the containers launched. This
// is particularly useful for stopping the containers on shutdown.
const containers = []
// dockerRuntimePromises is an array of Promise objects that tracks the status
// of spawning various Docker containers required to run the software.
// The Promise object is created before pulling and running the image, and
// resolved only when the container has started running on the host.
//
// Electron app must wait for the promises in this array to be resolved
// successfully before launching the GUI window.
const dockerRuntimePromises = []
const stopContainers = async containers =>
await Promise.all(
containers.map(container => {
console.log('Stopping container: ' + container)
return docker.getContainer(container).stop({})
})
)
const findAndStopStaleContainers = async () =>
new Promise(
async (resolve, reject) =>
await docker.listContainers({
filters: {
ancestor: [backendImage, loggerImage],
},
},
async (err, data) => {
if (err) {
if (!!err.json) {
console.error(err.json.message)
} else {
console.error(err)
}
reject()
exit()
} else {
await stopContainers(data.map(c => c.Id.substring(0, 12)))
resolve()
}
}
)
)
const containerFactory = opts => image =>
new Promise(function(resolve, reject) {
docker.pull(image, (err, stream) => {
docker.modem.followProgress(stream, onFinished, onProgress)
function onFinished(err, output) {
docker
.run(image, [], process.stdout, opts, function(err, data, container) {
if (err) {
console.error(err.json.message)
reject()
exit()
return
}
return container.remove({
force: true,
})
})
.on('container', function(container) {
const cid = container.id.substring(0, 12)
console.log(`Running Docker container: image=${image} containerID=${cid}`)
containers.push(cid)
// Wait for 5 seconds before resolving the promise, to be sure that
// the container is ready to serve requests.
setTimeout(function() {
resolve()
}, 5000)
})
}
function onProgress(event) {
console.log(event.status)
}
})
})
const backendSvc = containerFactory({
ExposedPorts: {
'8888/tcp': {},
},
Env: [`HOST_BINDINGS=${bindings.join(',')}`],
Hostconfig: {
Binds: bindings,
PortBindings: {
'8888/tcp': [{
HostPort: '8888',
}, ],
},
},
})
const loggerSvc = containerFactory({
ExposedPorts: {
'9001/tcp': {},
},
Hostconfig: {
Binds: ['/var/tmp:/var/tmp'],
PortBindings: {
'9001/tcp': [{
HostPort: '9001',
}, ],
},
},
})
app.on('ready', async () => {
if (!process.env.DEV && !process.argv.includes('--fork')) {
// Stop all stale containers left running from a previous ungraceful shutdown.
await findAndStopStaleContainers()
// Start background Docker services.
dockerRuntimePromises.push(backendSvc(backendImage))
dockerRuntimePromises.push(loggerSvc(loggerImage))
// Wait for the background Docker services to be ready.
await Promise.all(dockerRuntimePromises)
}
// Launch the GUI window.
createWindow()
})
app.on('window-all-closed', async () => {
if (!process.env.DEV && !process.argv.includes('--fork')) {
await stopContainers(containers)
}
exit()
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
exports.selectDirectory = () => {
const path = dialog.showOpenDialogSync(mainWindow, {
properties: ['openDirectory'],
})
return path && path.length !== 0 ? path.pop() : null
}
exports.saveFile = defaultPath =>
dialog.showSaveDialogSync(mainWindow, {
title: 'Output file path',
defaultPath,
})
exports.openFile = () => {
const path = dialog.showOpenDialogSync(mainWindow, {
title: 'Input file path',
properties: ['openFile'],
})
return path && path.length !== 0 ? path.pop() : null
}
exports.openPDF = (filePath, title) => {
let pdfWindow = new BrowserWindow({
title: title,
width: 1200,
height: 800,
webPreferences: {
plugins: true,
},
})
pdfWindow.loadURL(
url.format({
pathname: filePath,
protocol: 'file:',
slashes: true,
})
)
pdfWindow.setMenu(null)
pdfWindow.on('closed', function() {
pdfWindow = null
})
}