-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
295 lines (239 loc) · 8.49 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
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
'use strict'
var archiver = require('archiver')
var assign = require('deep-assign')
var async = require('async')
var format = require('string-format-obj')
var multiline = require('multiline')
var outputStream = require('gce-output-stream')
var path = require('path')
var pumpify = require('pumpify')
var slug = require('slug')
var through = require('through2')
var Compute = require('@google-cloud/compute')
var Storage = require('@google-cloud/storage')
var resolveConfig = function (pkg, explicitConfig) {
var config = {
root: process.cwd(),
nodeVersion: 'stable',
gcloud: {
projectId: process.env.GCLOUD_PROJECT_ID,
keyFile: process.env.GCLOUD_KEY_FILE
},
vm: {
zone: process.env.GCLOUD_ZONE || 'us-central1-a',
os: 'centos',
http: true,
https: true
}
}
assign(config, pkg.gcloudDeploy, explicitConfig)
// gcloud wants `keyFilename`
config.gcloud.keyFilename = config.gcloud.keyFile
delete config.gcloud.keyFile
if (!config.gcloud.projectId) {
throw new Error('A projectId is required')
}
if (!config.gcloud.credentials && !config.gcloud.keyFilename) {
throw new Error('Authentication with a credentials object or keyFile path is required')
}
return config
}
module.exports = function (config) {
if (typeof config !== 'object') config = { root: config || process.cwd() }
var pkg = require(path.join(config.root, 'package.json'))
config = resolveConfig(pkg, config)
var gcloudConfig = config.gcloud
var pkgRoot = config.root
var uniqueId = slug(pkg.name, { lower: true }) + '-' + Date.now()
var gce = new Compute(gcloudConfig)
var gcs = new Storage(gcloudConfig)
var deployStream = pumpify()
async.waterfall([
createTarStream,
uploadTar,
createVM,
startVM
], function (err, vm) {
if (err) return deployStream.destroy(err)
var outputCfg = assign({}, gcloudConfig, { name: vm.name, zone: vm.zone.name })
outputCfg.authConfig = {}
if (gcloudConfig.credentials) outputCfg.authConfig.credentials = gcloudConfig.credentials
if (gcloudConfig.keyFilename) outputCfg.authConfig.keyFile = gcloudConfig.keyFilename
deployStream.setPipeline(outputStream(outputCfg), through())
// sniff the output stream for when it's safe to delete the tar file
deleteTarFile(outputStream(outputCfg))
})
function createTarStream (callback) {
var tarStream = archiver.create('tar', { gzip: true })
tarStream.bulk([{ expand: true, cwd: pkgRoot, src: ['**', '!node_modules/**'] }])
tarStream.finalize()
callback(null, tarStream)
}
function uploadTar (tarStream, callback) {
var bucketName = gcloudConfig.projectId + '-gcloud-deploy-tars'
var bucket = gcs.bucket(bucketName)
bucket.get({ autoCreate: true }, function (err) {
if (err) return callback(err)
deployStream.emit('bucket', bucket)
deployStream.bucket = bucket
var tarFile = bucket.file(uniqueId + '.tar')
var writeStream = tarFile.createWriteStream({
gzip: true,
public: true
})
tarStream.pipe(writeStream)
.on('error', callback)
.on('finish', function () {
deployStream.emit('file', tarFile)
deployStream.file = tarFile
callback(null, tarFile)
})
})
}
function createVM (file, callback) {
var vmCfg = config.vm
// most node apps will have dependencies that requires compiling. without
// these build tools, the libraries might not install
var installBuildEssentialsCommands = {
debian: multiline.stripIndent(function () {/*
apt-get update
apt-get install -yq build-essential git-core
*/}),
fedora: multiline.stripIndent(function () {/*
yum -y groupinstall "Development Tools" "Development Libraries"
*/}),
suse: multiline.stripIndent(function () {/*
sudo zypper --non-interactive addrepo http://download.opensuse.org/distribution/13.2/repo/oss/ repo
sudo zypper --non-interactive --no-gpg-checks rm product:SLES-12-0.x86_64 cpp48-4.8.3+r212056-11.2.x86_64 suse-build-key-12.0-4.1.noarch
sudo zypper --non-interactive --no-gpg-checks install --auto-agree-with-licenses --type pattern devel_basis
*/})
}
var installBuildEssentialsCommand
switch (vmCfg.os) {
case 'centos':
case 'centos-cloud':
case 'redhat':
case 'rhel':
case 'rhel-cloud':
installBuildEssentialsCommand = installBuildEssentialsCommands.fedora
break
case 'suse':
case 'suse-cloud':
case 'opensuse':
case 'opensuse-cloud':
installBuildEssentialsCommand = installBuildEssentialsCommands.suse
break
case 'debian':
case 'debian-cloud':
case 'ubuntu':
case 'ubuntu-cloud':
case 'ubuntu-os-cloud':
default:
installBuildEssentialsCommand = installBuildEssentialsCommands.debian
break
}
var startupScript = format(multiline.stripIndent(function () {/*
#! /bin/bash
set -v
{installBuildEssentialsCommand}
{customStartupScript}
export NVM_DIR=/usr/local/nvm
export HOME=/root
export GCLOUD_VM=true
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash
source /usr/local/nvm/nvm.sh
nvm install {version}
if [ ! -d /opt/app ]; then
mkdir /opt/app
fi
cd /opt/app
curl https://storage.googleapis.com/{bucketName}/{fileName} | tar -xz
npm install --only-production
npm start &
*/}), {
installBuildEssentialsCommand: installBuildEssentialsCommand,
customStartupScript: config.startupScript || '',
bucketName: file.bucket.name,
fileName: file.name,
version: config.nodeVersion
})
vmCfg.metadata = vmCfg.metadata || {}
vmCfg.metadata.items = vmCfg.metadata.items || []
vmCfg.metadata.items.push({ key: 'startup-script', value: startupScript })
var zone = gce.zone(vmCfg.zone)
var onVMReady = function (vm) {
deployStream.emit('vm', vm)
deployStream.vm = vm
callback(null, vm)
}
var vm = zone.vm(vmCfg.name || uniqueId)
if (vmCfg.name) {
// re-use an existing VM
// @tood implement `setMetadata` in gcloud-node#vm
vm.setMetadata({
'startup-script': startupScript
}, _onOperationComplete(function (err) {
if (err) return callback(err)
onVMReady(vm)
}))
} else {
// create a VM
vm.create(vmCfg, _onOperationComplete(function (err) {
if (err) return callback(err)
onVMReady(vm)
}))
}
}
function startVM (vm, callback) {
// if re-using a VM, we have to stop & start to apply the new startup script
vm.stop(_onOperationComplete(function (err) {
if (err) return callback(err)
vm.start(_onOperationComplete(function (err) {
if (err) return callback(err)
vm.getMetadata(function (err, metadata) {
if (err) return callback(err)
var url = 'http://' + metadata.networkInterfaces[0].accessConfigs[0].natIP
deployStream.emit('start', url)
deployStream.url = url
callback(null, vm)
})
}))
}))
}
function deleteTarFile (outputStream) {
var tarFile = deployStream.file
var startupScriptStarted = false
outputStream.pipe(through(function (outputLine, enc, next) {
outputLine = outputLine.toString('utf8')
startupScriptStarted = startupScriptStarted || outputLine.indexOf('Starting Google Compute Engine user scripts') > -1
// if npm install is running, the file has already been downloaded
if (startupScriptStarted && outputLine.indexOf('npm install') > -1) {
outputStream.end()
tarFile.delete(function (err, apiResponse) {
if (err) {
var error = new Error('The tar file (' + tarFile.name + ') could not be deleted')
error.response = apiResponse
deployStream.destroy(error)
}
})
} else {
next()
}
}))
}
return deployStream
}
// helper to wait for an operation to complete before executing the callback
// this also supports creation callbacks, specifically `createVM`, which has an
// extra arg with the instance object of the created VM
function _onOperationComplete (callback) {
return function (err, operation, apiResponse) {
if (err) return callback(err)
if (arguments.length === 4) {
operation = apiResponse
}
operation
.on('error', callback)
.on('complete', callback.bind(null, null))
}
}