Repository navigation
Expand file tree
/
Copy pathinstall-service.js
More file actions
executable file
·242 lines (212 loc) · 10.5 KB
/
Copy pathinstall-service.js
File metadata and controls
executable file
·242 lines (212 loc) · 10.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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const { runCommand, checkRoot } = require('./src/systemUtils');
const SERVICE_NAME = 'cgateweb.service';
const SOURCE_SERVICE_FILE_TEMPLATE = path.join(__dirname, 'cgateweb.service.template');
const TARGET_SYSTEMD_DIR = '/etc/systemd/system';
// systemd paths are always POSIX; use path.posix so the constant is correct
// even when this file is required on a non-POSIX dev host (e.g. Windows tests).
const TARGET_SERVICE_FILE = path.posix.join(TARGET_SYSTEMD_DIR, SERVICE_NAME);
const BASE_INSTALL_PATH = __dirname;
function checkDependencies() {
console.log('Checking dependencies...');
// Check Node.js version. Keep the minimum aligned with package.json engines
// (^20.19.0 || ^22.13.0 || >=24).
const nodeVersion = process.version;
const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);
if (majorVersion < 20) {
console.error(`Node.js version ${nodeVersion} is too old. Minimum required: v20.19.0`);
process.exit(1);
}
console.log(`Node.js version: ${nodeVersion} ✓`);
// Check if package.json exists
const packageJsonPath = path.join(__dirname, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
console.error('package.json not found. Please run from the cgateweb directory.');
process.exit(1);
}
// Check if settings.js exists
const settingsPath = path.join(__dirname, 'settings.js');
if (!fs.existsSync(settingsPath)) {
console.warn('WARNING: settings.js not found. Application will use default settings.');
console.warn('Please create and configure settings.js before starting the service.');
} else {
console.log('Configuration file: settings.js ✓');
}
// Check if node_modules exists
const nodeModulesPath = path.join(__dirname, 'node_modules');
if (!fs.existsSync(nodeModulesPath)) {
console.error('node_modules directory not found.');
console.error('Please run "npm install" first to install dependencies.');
process.exit(1);
}
console.log('Dependencies installed ✓');
}
function ensureServiceUser() {
const username = 'cgateweb';
if (runCommand(`id ${username}`)) {
console.log(`Service user '${username}' already exists ✓`);
} else {
console.log(`Creating service user '${username}'...`);
// --user-group creates the matching group the unit's Group= needs.
// Debian's useradd happens to do this by default; not every distro
// does, and there the unit fails on group resolution.
if (!runCommand(`useradd --system --user-group --no-create-home --shell /usr/sbin/nologin ${username}`)) {
console.error(`Failed to create service user '${username}'.`);
process.exit(1);
}
console.log(`Service user '${username}' created ✓`);
}
}
/**
* Whether an install path sits under /home, where systemd's ProtectHome=yes
* would hide the unit's own WorkingDirectory and it would fail 200/CHDIR.
*
* Exported and pure so both branches can be tested directly. Inline, its
* coverage depended on where the repository happened to be checked out - the
* CI runner works under /home/runner, so the branch ran there and not on a
* developer's machine, which is a coverage figure that moves for reasons
* having nothing to do with the code.
*
* @param {string} installPath
* @returns {boolean}
*/
function isUnderHome(installPath) {
return installPath === '/home' || installPath.startsWith('/home/');
}
/**
* The ProtectHome value for an install path, plus any warnings to print.
*
* The warnings live here rather than at the call site so this whole decision -
* value and explanation - is testable without an installer run. Left inline,
* their coverage tracked the checkout path rather than the code.
*
* @param {string} installPath
* @returns {{ value: 'yes'|'no', warnings: string[] }}
*/
function resolveProtectHome(installPath) {
if (!isUnderHome(installPath)) {
return { value: 'yes', warnings: [] };
}
return {
value: 'no',
warnings: [
`WARNING: installing from ${installPath}, which is under /home.`,
' ProtectHome must be disabled for the service to start from there.',
' Consider moving the checkout to /opt/cgateweb and re-running this installer.'
]
};
}
function installService() {
console.log('--- cgateweb Systemd Service Installer ---');
checkRoot('install-service.js');
checkDependencies();
ensureServiceUser();
// 1. Check if source service file template exists
if (!fs.existsSync(SOURCE_SERVICE_FILE_TEMPLATE)) {
console.error(`Source service file template not found: ${SOURCE_SERVICE_FILE_TEMPLATE}`);
console.error('Please ensure cgateweb.service.template exists in the same directory.');
process.exit(1);
}
console.log(`Found source service file template: ${SOURCE_SERVICE_FILE_TEMPLATE}`);
// 2. Check if target directory exists
if (!fs.existsSync(TARGET_SYSTEMD_DIR)) {
console.error(`Target systemd directory not found: ${TARGET_SYSTEMD_DIR}`);
console.error('Is systemd installed and running correctly?');
process.exit(1);
}
// 2.1. Check if service is already running and stop it first
try {
const status = execSync(`systemctl is-active ${SERVICE_NAME}`, { encoding: 'utf8' }).trim();
if (status === 'active') {
console.log(`Stopping existing ${SERVICE_NAME} service...`);
if (!runCommand(`systemctl stop ${SERVICE_NAME}`)) {
console.warn('Failed to stop existing service, continuing with installation...');
}
}
} catch {
// Service doesn't exist or is inactive, which is fine
console.log('No existing service to stop.');
}
// 3. Read template, replace placeholder, and write target service file
try {
console.log(`Reading service template: ${SOURCE_SERVICE_FILE_TEMPLATE}`);
let serviceContent = fs.readFileSync(SOURCE_SERVICE_FILE_TEMPLATE, 'utf8');
console.log(`Replacing %I placeholder with path: ${BASE_INSTALL_PATH}`);
// Use a regular expression with the 'g' flag to replace all occurrences
serviceContent = serviceContent.replace(/%I/g, BASE_INSTALL_PATH);
// The interpreter running this installer is the one we just version
// checked, so it is the one the unit should run. Hardcoding
// /usr/bin/node meant a supported Node installed via nvm/fnm/asdf
// passed the check and then failed 203/EXEC at start.
console.log(`Using node binary: ${process.execPath}`);
serviceContent = serviceContent.replace(/%NODE%/g, process.execPath);
// ProtectHome=yes hides /home from the unit, so an install under /home
// cannot even chdir into its own WorkingDirectory (200/CHDIR). Relax it
// rather than ship a unit that cannot start, and say so - /opt is the
// better home for a system service.
const protectHome = resolveProtectHome(BASE_INSTALL_PATH);
protectHome.warnings.forEach(line => console.warn(line));
serviceContent = serviceContent.replace(/%PROTECT_HOME%/g, protectHome.value);
// Backup existing service file if it exists
if (fs.existsSync(TARGET_SERVICE_FILE)) {
const backupFile = `${TARGET_SERVICE_FILE}.backup.${Date.now()}`;
console.log(`Backing up existing service file to: ${backupFile}`);
fs.copyFileSync(TARGET_SERVICE_FILE, backupFile);
}
console.log(`Writing configured service file to ${TARGET_SERVICE_FILE}...`);
fs.writeFileSync(TARGET_SERVICE_FILE, serviceContent, { encoding: 'utf8', mode: 0o644 });
console.log('Service file written successfully.');
// The unit runs as 'cgateweb', not as whoever cloned the repo. Nothing
// chowns the checkout - doing so would take a developer's own working
// copy away from them - so check the service user can actually read the
// entry point and say exactly how to fix it if not. ReadWritePaths only
// lifts systemd's own restrictions; POSIX permissions still apply.
const entryPoint = path.join(BASE_INSTALL_PATH, 'index.js');
if (!runCommand(`sudo -u cgateweb test -r ${entryPoint}`)) {
console.warn(`WARNING: service user 'cgateweb' cannot read ${entryPoint}.`);
console.warn(' The service will fail to start. Grant access with either:');
console.warn(` sudo chgrp -R cgateweb ${BASE_INSTALL_PATH} && sudo chmod -R g+rX ${BASE_INSTALL_PATH}`);
console.warn(` sudo chown -R cgateweb:cgateweb ${BASE_INSTALL_PATH} (gives up your own write access)`);
}
} catch (error) {
console.error(`Failed to process service file: ${error.message}`);
process.exit(1);
}
// 4. Reload systemd daemon
if (!runCommand('systemctl daemon-reload')) {
console.error('Failed to reload systemd daemon. Service might not be recognized yet.');
// Continue installation attempt but warn user
}
// 5. Enable the service (to start on boot)
if (!runCommand(`systemctl enable ${SERVICE_NAME}`)) {
console.error(`Failed to enable ${SERVICE_NAME}. It may not start automatically on boot.`);
// Continue installation attempt
}
// 6. Start the service
if (!runCommand(`systemctl start ${SERVICE_NAME}`)) {
console.error(`Failed to start ${SERVICE_NAME}. Check service status with: systemctl status ${SERVICE_NAME}`);
process.exit(1); // Exit with error if start fails
}
console.log('---');
console.log(`cgateweb service installation completed.`);
console.log(`Use 'systemctl status ${SERVICE_NAME}' to check its status.`);
console.log(`Use 'journalctl -u ${SERVICE_NAME} -f' to follow its logs.`);
console.log(`To stop the service: systemctl stop ${SERVICE_NAME}`);
console.log(`To restart the service: systemctl restart ${SERVICE_NAME}`);
console.log(`To uninstall the service: systemctl stop ${SERVICE_NAME} && systemctl disable ${SERVICE_NAME} && rm ${TARGET_SERVICE_FILE}`);
console.log('---');
}
// Run the installation
if (require.main === module || (require.main && require.main.filename === __filename)) {
installService();
}
module.exports = {
installService,
checkDependencies,
ensureServiceUser,
isUnderHome,
resolveProtectHome
};