-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
127 lines (110 loc) · 3.73 KB
/
server.js
File metadata and controls
127 lines (110 loc) · 3.73 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
const { Command } = require('commander');
const fs = require('fs');
const path = require('path');
const util = require('util');
const { pipeline } = require('stream');
const {
formatDate,
ensurePath,
resolveHome,
createKey,
createHash,
decompress,
} = require('./utils');
const exec = require('child_process').exec;
const execSync = util.promisify(exec);
const shellExec = require('shell-exec');
const pump = util.promisify(pipeline);
const bearerAuthPlugin = require('fastify-bearer-auth');
const { setTimeout } = require('timers');
const fastify = require('fastify')({
logger: false,
});
const program = new Command();
program
.version('1.0.0')
.option('-i, --with-app-name', 'append with app-name', true)
.option('-p, --port <port>', 'listening port')
.option('-w, --working-path <path>', 'the working path')
.option('-a, --app-path <path>', 'the application path')
.option('-n, --app-name <name>', 'the application name');
program.parse(process.argv);
const APP_NAME = program.appName || 'gitops-runner';
const KEY_PATH = resolveHome(`/var/lib/${APP_NAME}/${APP_NAME}.key`);
const WORKING_PATH = resolveHome(program.workingPath || '~/.gitops-runner');
const APP_PATH = resolveHome(program.appPath || '/var/www/html');
function getEncrypedKey() {
return fs.readFileSync(KEY_PATH, 'utf-8').trim();
}
createKey(KEY_PATH);
fastify.register(bearerAuthPlugin, {
auth: (key, req) => new String(createHash(key)) == getEncrypedKey(),
});
fastify.register(require('fastify-multipart'));
fastify.get('/start', async (req, reply) => {
exec(`${APP_PATH}/run.sh`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.log(`stdout: ${err}`)
return;
}
// the *entire* stdout and stderr (buffered)
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
})
reply.send({
status: 'ok'
})
})
fastify.post('/deploy', async (req, reply) => {
ensurePath(WORKING_PATH)
if (program.withAppName) {
ensurePath(APP_PATH)
}
const options = { limits: { fileSize: 200 * 1000 * 1000 } };
const data = await req.file(options);
const target = path.join(WORKING_PATH, `${data.filename}`);
await pump(data.file, fs.createWriteStream(target));
let appName = `${path.basename(path.basename(data.filename, '.gz'), '.tar')}`;
appName = `${path.basename(appName, '.zip')}`;
const deployPath = path.join(WORKING_PATH, `${appName}_${formatDate(new Date())}`);
if (data.filename.endsWith('.gz'))
await decompress(target, deployPath);
else if (data.filename.endsWith('.zip')) {
await execSync(`unzip ${target} -d ${deployPath} > /dev/null`);
} else {
fs.copyFileSync(target, deployPath);
}
console.log(`${deployPath} uploaded.`);
let wwwPath = `${APP_PATH}`;
if (program.withAppName) {
wwwPath += `/${appName}`;
}
console.log(`${wwwPath} deploying.`);
if (fs.existsSync(wwwPath)) fs.unlinkSync(wwwPath);
fs.symlinkSync(deployPath, wwwPath);
console.log(`${wwwPath} deployed.`);
setTimeout(async () => {
const serviceName = `${wwwPath}/systemd/service-name`;
if (fs.existsSync(serviceName)) {
let name = new String(fs.readFileSync(serviceName)).trimEnd();
if (fs.existsSync('/usr/sbin/service')) {
shellExec(`service ${name} restart`);
console.log(`service ${name} restart`);
} else {
console.log(`The system does not support 'service ${name} restart'`);
}
}
}, 5000);
reply.send({
name: data.filename,
deploy: deployPath,
target: wwwPath,
nginx: `location / { root ${wwwPath}/; }`,
});
});
// Run the server!
fastify.listen({ port: program.port || 3000, host: '0.0.0.0' }, (err, address) => {
if (err) throw err;
console.log(`Server listening on ${address}`);
});