-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
108 lines (91 loc) · 2.32 KB
/
index.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
'use strict';
const axios = require('axios');
const fsPromises = require('fs').promises;
const crypto = require('crypto');
const { spawn } = require('child_process');
const tar = require('tar');
const os = require('os');
const path = require('path');
if(process.argv.length < 5) {
console.log('Usage: node index.js <image> <handler> <lang>');
process.exit(-1)
}
const args = process.argv.slice(2);
const image = args[0];
const handler = args[1];
const lang = args[2];
async function build() {
const tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'builder-'));
try {
const tarFile = path.join(tempDir, 'req.tar');
await shrinkwrap(image, handler, lang);
let buildConfig = { image, buildArgs: {} };
await fsPromises.writeFile(
'./build/com.openfaas.docker.config',
JSON.stringify(buildConfig),
'utf8'
);
await tar.c(
{
cwd: './build',
file: tarFile,
},
['./context', './com.openfaas.docker.config']
);
let secret = await fsPromises.readFile('./payload.txt', 'utf8');
let data = await fsPromises.readFile(tarFile);
let hash = crypto
.createHmac('sha256', secret.trim())
.update(data)
.digest('hex');
try {
let res = await axios({
data: data,
method: 'post',
url: 'http://127.0.0.1:8081/build',
headers: {
'Content-Type': 'application/octet-stream',
'X-Build-Signature': 'sha256=' + hash,
}
})
console.log(`Success building image ${res.data.image}`)
} catch (err) {
console.log(`Building image ${image} failed: ${err.response.data.status}`)
}
} catch (err) {
throw err
} finally {
await fsPromises.rm(tempDir, { recursive: true });
}
}
async function shrinkwrap(image, handler, lang) {
const cmd = spawn('faas-cli', [
'build',
'--lang',
lang,
'--handler',
handler,
'--name',
'context',
'--image',
image,
'--shrinkwrap',
]);
for await (const chunk of cmd.stdout) {
console.log(chunk.toString());
}
let exitCode = await new Promise((resolve) => {
cmd.on('close', resolve);
});
if (exitCode) {
throw new Error('Failed to shrinkwrap handler');
}
return;
}
(async () => {
try {
await build();
} catch (err) {
console.error(err.message)
}
})();