-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (80 loc) · 2.47 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
const sshExec = require('ssh-exec')
const YAML = require('yaml')
module.exports.warning = function (message, fileName, lineNumber) {
const warning = Error(message, fileName, lineNumber)
warning.logLevel = 'info'
return warning
}
module.exports.info = function (message, fileName, lineNumber) {
const info = Error(message, fileName, lineNumber)
info.logLevel = 'info'
return info
}
module.exports.datasetName = function (aString) {
/*
* trim the name, we remove ddf-[-], remove gapminder-[-],
* remove big-waffle-, replace open_numbers-[-] with on_,
* remove .git
*/
let name = aString.toLowerCase()
name = name.replace(/ddf-+/, '')
name = name.replace(/gapminder-+/, '')
name = name.replace(/big-*waffle-+/, '')
name = name.replace(/open_numbers-+/, 'on_')
name = name.replace(/\.git$/, '')
return name
}
let config
module.exports.getConfig = function () {
return new Promise((resolve, reject) => {
if (config) {
resolve(config)
} else {
const GCS = require('@google-cloud/storage').Storage
const { WritableStream } = require('memory-streams')
const Bucket = (new GCS()).bucket(process.env['CONFIG_BUCKET'] || 'org-gapminder-big-waffle-functions')
const keyFile = Bucket.file(process.env['CONFIG_FILE'] || `${process.env.FUNCTION_NAME.split('-', 2).shift().toLowerCase()}.yaml`)
const buffer = new WritableStream()
try {
keyFile.createReadStream()
.on('error', err => {
console.error(err)
reject(err)
})
.on('end', () => {
config = YAML.parse(buffer.toString())
resolve(config)
})
.pipe(buffer)
} catch (err) {
console.error(err)
reject(err)
}
}
})
}
module.exports.exec = function (cmd, config, res, content = 'OK') {
/*
* Return a Promise that will ssh into the big-waffle master
* and execute the command and resolve to an object with the
* stdout and stderror of the server.
*
* If a (http) res(ponse) is provided the provided content will
* be send to the response.
*/
const sshConfig = {
user: config.user || process.env.FUNCTION_NAME.toLowerCase(),
host: config.bwMaster,
key: config.privateKey
}
return new Promise((resolve, reject) => {
sshExec(cmd, sshConfig, function (err, stdout, stderr) {
if (res) res.send(content)
if (err) {
reject(err)
} else {
resolve({ stdout, stderr })
}
})
})
}