-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdockerSetupService.js
More file actions
551 lines (478 loc) · 19.5 KB
/
dockerSetupService.js
File metadata and controls
551 lines (478 loc) · 19.5 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// src/dockerSetupService.js
const { app, ipcMain, BrowserWindow } = require('electron');
const { exec, spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const https = require('https');
// --- Configuration Constants ---
const DOCKER_SETUP_DONE_KEY = 'dockerSetupDone';
// Complete image name and tag
const REQUIRED_DOCKER_IMAGE = 'hexdolemonai/lemon-runtime-sandbox:latest';
// Complete image package download address (you need to provide the actual download URL)
// Please replace with the actual network address where your lemon_runtime_sandbox.tar file is stored
const DOCKER_IMAGE_TAR_URL = '';
// Complete locally saved image package file name
const DOWNLOADED_IMAGE_FILE_NAME = 'lemon_runtime_sandbox.tar';
// --- Internal State (Set during initialization) ---
let store;
let userDataPath;
//获取dockerimagefilename 不同的系统架构不一样
function getDockerImageFileName() {
let arch = process.arch;
if (arch === 'x64' ) {
return 'lemon_runtime_sandbox-x64.tar';
} else if (arch === 'arm64') {
return 'lemon_runtime_sandbox-arm64.tar';
} else {
return 'lemon_runtime_sandbox-x64.tar';
}
}
// --- Initialization Function ---
function initDockerSetupService(options) {
({ store, userDataPath } = options);
// --- IPC Handlers ---
ipcMain.handle('check-docker-setup', async () => {
const setupDone = store.get(DOCKER_SETUP_DONE_KEY, false);
return setupDone;
});
ipcMain.handle('start-docker-setup', async (event) => {
console.log('Triggering start-docker-setup');
const mainWindow = BrowserWindow.fromWebContents(event.sender);
checkAndRunDockerSetup(mainWindow)
});
}
// --- Helper Functions (Async) ---
/**
* Checks if Docker is installed and running
*/
const process = require('process');
/**
* Checks Docker availability
*/
async function checkDockerAvailability(webContents) {
try {
await executeDockerInfo();
return true;
} catch (error) {
// Installation failed, install docker
webContents.send('setup-status', {
step: 'installing-docker',
message: 'Docker is not installed or not installing.'
});
// let res = await installDocker(webContents);
// console.log('Docker installation result:', res);
return false;
}
}
// Install Docker
//http://lemon-ai.oss-cn-beijing.aliyuncs.com/docker/Docker-windows.exe
async function installDocker(webContents) {
try {
// Step 1: Detect system
const os = await checkSystem();
console.log("System type", os);
let download_file_name = "";
switch (os) {
case 'win64':
download_file_name = 'Docker-windows.exe';
break;
case 'macos-apple':
download_file_name = 'Docker-apple.dmg';
break;
case 'macos-intel':
download_file_name = 'Docker-intel.dmg';
break;
default:
return false; // If OS is not supported, return false directly
}
if (download_file_name !== "") {
// const download_url = `https://lemon-ai.oss-cn-beijing.aliyuncs.com/docker/${download_file_name}`;
// const downloadedFilePath = path.join(userDataPath, download_file_name);
// // Download file
// await downloadFile(download_url, downloadedFilePath, (progress) => {
// webContents.send('setup-status', { step: 'downloading', message: `Downloading installer package ${download_file_name}...`, progress: progress });
// });
// webContents.send('setup-status', { step: 'downloaded', message: `${download_file_name} download complete` });
// // Execute installation
// await executeInstaller(downloadedFilePath);
// webContents.send('setup-status', { step: 'installed', message: `Waiting for installation to complete` });
// // Check if Docker is installed successfully after a 3-second delay
// await new Promise(resolve => setTimeout(resolve, 3000));
// await checkDockerInstallation();
// console.log('Docker installation completed.');
// return true; // Return true if installation is successful
} else {
return false; // If the correct installer package is not selected, also return false
}
} catch (error) {
console.error('Error during Docker installation:', error);
webContents.send('setup-status', { step: 'error', message: `Installation error: ${error.message || error}` });
return false; // Return false on error
}
}
// Timer to check if Docker installation is complete
function checkDockerInstallation(interval = 3000) {
return new Promise((resolve, reject) => {
const timer = setInterval(() => {
exec('docker --version', (error, stdout, stderr) => {
if (!error && !stderr && stdout.toString().includes('Docker version')) {
console.log('✅ Docker installed successfully');
clearInterval(timer);
resolve(); // Installation complete, Promise resolves successfully
}else{
console.log('❌ Docker not installed successfully');
}
// If Docker is not found, continue to next check
});
}, interval);
});
}
// Execute Docker installer
async function executeInstaller(filePath) {
return new Promise((resolve, reject) => {
let command;
switch (process.platform) {
case 'win32':
command = `"${filePath}"`;
break;
case 'darwin':
command = `open "${filePath}"`; // macOS will open DMG files in Finder by default
break;
default:
reject(new Error(`Unsupported platform for installation: ${process.platform}`));
return;
}
console.log(`Executing installation command: ${command}`);
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error during installation: ${error.message}`);
reject(error);
return;
}
if (stderr) {
console.warn(`Installation warning/info output:\n${stderr}`);
}
console.log(`Successful installation output:\n${stdout}`);
resolve(stdout);
});
});
}
function checkSystem() {
return new Promise((resolve, reject) => {
if (process.platform === 'win32') {
// Check if it's a 64-bit system
resolve("win64")
} else if (process.platform === 'darwin') {
// Check if it's Apple Silicon
if (isAppleSilicon()) {
resolve("macos-apple")
}else{
resolve("macos-intel")
}
}
})
}
function isAppleSilicon() {
if (process.platform !== 'darwin') return false;
try {
// Run command to check hardware model in system report
const model = exec('sysctl -n machdep.cpu.brand_string').toString();
// Apple Silicon will have a specific identifier, e.g., "Apple M1"
return model.includes('Apple');
} catch (e) {
console.error('Unable to determine processor type:', e);
return false;
}
}
/**
* Executes docker info command
*/
function executeDockerInfo() {
return new Promise((resolve, reject) => {
console.log('Current PATH:', process.env.PATH);
exec('docker --version', (error, stdout, stderr) => {
if (error) {
console.error(`Docker check failed: ${error}`);
console.error(`Stderr: ${stderr}`);
return reject({ error, stderr });
}
resolve(stdout);
});
});
}
//判断docker 有没有运行 使用 docker ps 判断
function checkDockerRunning() {
return new Promise((resolve, reject) => {
exec('docker ps', (error, stdout, stderr) => {
if (error) {
console.log('Docker is not running');
console.error(`Docker check failed: ${error}`);
console.error(`Stderr: ${stderr}`);
return reject({ error, stderr });
}
if (stdout.includes('CONTAINER ID')) {
console.log('Docker is running');
} else {
console.log('Docker is not running');
}
resolve(stdout);
});
});
}
/**
* Handles Docker error messages
*/
function handleDockerError({ error, stderr }) {
console.error(`Handling Docker error: ${stderr}`);
if (isDockerNotInstalled(stderr)) {
return handleError(new Error('Docker command not found. Please ensure Docker is installed and added to your system PATH.'));
}
if (isDockerNotRunning(stderr)) {
console.error('Docker service is not running. Attempting to start Docker Desktop/Daemon...');
attemptStartDocker()
.then(() => console.log('Docker started successfully'))
.catch(startError => handleError(startError));
return;
}
if (isConnectionError(stderr)) {
console.warn('Detected inability to connect to Docker engine. Attempting automatic repair...');
attemptStartDocker()
.then(() => console.log('Docker reconnected'))
.catch(startError => handleError(startError));
return;
}
handleError(new Error(`Unable to check Docker status: ${stderr}`));
}
/**
* Checks if Docker is not installed
*/
function isDockerNotInstalled(stderr) {
return stderr.includes('command not found') || stderr.includes("'docker' is not recognized");
}
/**
* Checks if Docker is not running
*/
function isDockerNotRunning(stderr) {
return stderr.includes('Is the docker daemon running?');
}
/**
* Checks for connection error (e.g., Docker is running but cannot connect)
*/
function isConnectionError(stderr) {
return stderr.includes('error during connect: Get');
}
/**
* Attempts to start Docker based on the operating system
*/
function attemptStartDocker() {
return new Promise((resolve, reject) => {
const platform = process.platform;
let command;
if (platform === 'win32') {
// Windows
command = 'start "" "C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe"';
} else if (platform === 'darwin') {
// macOS
command = 'open -a Docker';
} else {
return reject('Unsupported operating system. Please start Docker manually.');
}
exec(command, (startError, startStdout, startStderr) => {
if (startError) {
console.error(`Failed to start Docker: ${startStderr}`);
return reject(`Unable to start Docker Desktop: ${startStderr}`);
}
return resolve("Docker Desktop started. Waiting a few seconds for Docker to run normally...");
});
});
}
/**
* Unified error handling
*/
function handleError(err) {
console.error(`Final error: ${err.message}`);
throw err;
}
/**
* Checks if the required Docker image exists
*/
async function checkDockerEnvironmentReady() {
return new Promise((resolve, reject) => {
// Use the refined image name for checking
exec(`docker images -q ${REQUIRED_DOCKER_IMAGE}`, (error, stdout, stderr) => {
if (error) {
console.warn(`Docker images check failed: ${stderr}`);
resolve(false);
} else {
resolve(stdout.trim().length > 0);
}
});
});
}
/**
* Downloads a file
*/
async function downloadFile(url, destinationPath, progressCallback) {
console.log(`Downloading file from ${url} to ${destinationPath}`);
// ... (download function remains unchanged)
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(destinationPath);
const request = https.get(url, (response) => {
if (response.statusCode !== 200) {
fs.unlink(destinationPath, () => {});
return reject(new Error(`Download failed, HTTP status code: ${response.statusCode}`));
}
const totalLength = parseInt(response.headers['content-length'], 10);
let downloadedLength = 0;
response.on('data', (chunk) => {
downloadedLength += chunk.length;
if (totalLength) {
const progress = downloadedLength / totalLength;
if (progressCallback) progressCallback(progress);
}
});
response.pipe(file);
file.on('finish', () => {
file.close(resolve);
});
file.on('error', (err) => {
fs.unlink(destinationPath, () => {});
reject(err);
});
});
request.on('error', (err) => {
fs.unlink(destinationPath, () => {});
reject(err);
});
});
}
/**
* Imports a Docker image (.tar)
*/
async function importDockerImage(imagePath) {
return new Promise((resolve, reject) => {
const dockerProcess = spawn('docker', ['load', '-i', imagePath]);
dockerProcess.stdout.on('data', (data) => {
console.log(`docker load stdout: ${data}`);
});
dockerProcess.stderr.on('data', (data) => {
console.error(`docker load stderr: ${data}`);
});
dockerProcess.on('error', (error) => {
console.error(`Failed to start docker load process: ${error}`);
reject(new Error(`Unable to execute 'docker load' command: ${error.message}`));
});
dockerProcess.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`'docker load' command failed, exit code: ${code}`));
}
});
});
}
// --- Function to check and run setup flow ---
async function checkAndRunDockerSetup(mainWindow) {
mainWindow.loadFile('setup.html');
console.log("Triggering checkAndRunDockerSetup")
const initialSetupDone = store.get(DOCKER_SETUP_DONE_KEY, false);
let dockerEnvironmentIsActuallyReady = false;
let errorMessage = null;
try {
console.log('Verifying current Docker environment state...');
// --- Execute actual Docker environment check here ---
// 1. Check if Docker is installed
let res = await checkDockerAvailability(mainWindow);
console.log('Docker availability check result:', res);
if (!res) {
throw new Error('Docker is not available.');
}
mainWindow.send('setup-status', {
step: 'startDocker',
message: 'Checking if Docker is running...'
});
//判断daoker是否运行
try {
console.log('Checking if Docker is running...');
await checkDockerRunning();
console.log('Checking if Docker is running...2');
mainWindow.send('setup-status', {
step: 'startDocker',
message: 'Docker is running.'
});
} catch (error) {
// Installation failed, install docker
mainWindow.send('setup-status', {
step: 'startDocker',
message: 'Docker is not running.'
});
// let res = await installDocker(webContents);
// console.log('Docker installation result:', res);
throw new Error('Docker is not started.');
}
//2. Run docker
// mainWindow.webContents.send('setup-status', { step: 'startDocker', message: `Starting Docker` });
// res = await attemptStartDocker()
// Delay for 3 seconds
// await new Promise(resolve => setTimeout(resolve, 10000));
mainWindow.webContents.send('setup-status', { step: 'checkDockerImages', message: `Checking required Docker images` });
dockerEnvironmentIsActuallyReady = await checkDockerEnvironmentReady();
console.log('Required Docker image ready:', dockerEnvironmentIsActuallyReady);
// If both checks pass, the environment is ready
if (dockerEnvironmentIsActuallyReady) {
console.log('Docker environment is ready.');
mainWindow.webContents.send('setup-status', { step: 'complete', message: `Docker image ${REQUIRED_DOCKER_IMAGE} is ready.` });
} else {
console.log('Docker environment is not ready');
// Image not detected, start image download and installation
// Full path to the locally saved image package
// const downloadedFilePath = path.join(userDataPath, getDockerImageFileName());
// 3. Download Docker image file
// mainWindow.webContents.send('setup-status', { step: 'downloading', message: `Downloading image package ${getDockerImageFileName()}...`, progress: 0 });
// Use the refined URL
// await downloadFile(DOCKER_IMAGE_TAR_URL, downloadedFilePath, (progress) => {
// console.log(`Download progress: ${progress}%`);
// mainWindow.webContents.send('setup-status', { step: 'downloading', message: `Downloading image package ${getDockerImageFileName()}...`, progress: progress });
// });
// 4. Import Docker image
// mainWindow.webContents.send('setup-status', { step: 'checkDockerImages', message: `Importing Docker image ${REQUIRED_DOCKER_IMAGE}...` });
// await importDockerImage(downloadedFilePath);
// 5. Mark setup as complete
mainWindow.webContents.send('setup-status', { step: 'complete', message: `Docker image ${REQUIRED_DOCKER_IMAGE} is not ready.` });
store.set(DOCKER_SETUP_DONE_KEY, false);
dockerEnvironmentIsActuallyReady = false;
}
} catch (error) {
// Catch any errors that occur during the check (e.g., Docker not running, Docker command not found, etc.)
console.error('Docker environment verification failed:', error);
errorMessage = `Docker environment check failed: ${error.message || error}`;
dockerEnvironmentIsActuallyReady = false; // Check failed, environment not ready
}
// --- Decide which page to load based on the actual check result ---
if (dockerEnvironmentIsActuallyReady) {
console.log('Loading main window as Docker environment is ready.');
// If the actual environment is ready, ensure the state in the store is also true
if (!initialSetupDone) { // Only write if store is false to avoid unnecessary writes
store.set(DOCKER_SETUP_DONE_KEY, true);
console.log('Updated store: DOCKER_SETUP_DONE_KEY set to true.');
}
if (process.env.NODE_ENV === 'development') {
mainWindow.loadURL('http://localhost:5005');
} else {
mainWindow.loadFile(path.join(__dirname, 'renderer/main_window/index.html'));
}
} else {
console.log('Loading setup page as Docker environment is NOT ready.');
// If the actual environment is not ready, ensure the state in the store is false
if (initialSetupDone) { // Only write if store is true
store.set(DOCKER_SETUP_DONE_KEY, false);
console.log('Updated store: DOCKER_SETUP_DONE_KEY set to false.');
}
}
}
// --- Export the functions needed by main.js ---
export {
initDockerSetupService,
checkAndRunDockerSetup,
DOCKER_SETUP_DONE_KEY
};