-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
247 lines (202 loc) · 8.1 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
'use strict';
const BbPromise = require('bluebird');
const _ = require('lodash');
const Fse = require('fs-extra');
const Path = require('path');
const ChildProcess = require('child_process');
const zipper = require('zip-local');
const upath = require('upath');
const readlineSync = require('readline-sync');
BbPromise.promisifyAll(Fse);
class PkgPyFuncs {
fetchConfig(){
if (!this.serverless.service.custom){
this.error("No serverless custom configurations are defined")
}
const config = this.serverless.service.custom.pkgPyFuncs
if ( !config ) {
this.error("No serverless-package-python-functions configuration detected. Please see documentation")
}
this.requirementsFile = config.requirementsFile || 'requirements.txt'
config.buildDir ? this.buildDir = config.buildDir : this.error("No buildDir configuration specified")
this.globalRequirements = config.globalRequirements || []
this.globalIncludes = config.globalIncludes || []
config.cleanup === undefined ? this.cleanup = true : this.cleanup = config.cleanup
this.useDocker = config.useDocker || false
this.dockerImage = config.dockerImage || `lambci/lambda:build-${this.serverless.service.provider.runtime}`
this.containerName = config.containerName || 'serverless-package-python-functions'
this.mountSSH = config.mountSSH || false
this.abortOnPackagingErrors = config.abortOnPackagingErrors || false
this.dockerServicePath = '/var/task'
}
autoconfigArtifacts() {
_.map(this.serverless.service.functions, (func_config, func_name) => {
let autoArtifact = `${this.buildDir}/${func_config.name}.zip`
func_config.package.artifact = func_config.package.artifact || autoArtifact
this.serverless.service.functions[func_name] = func_config
})
}
clean(){
if (!this.cleanup) {
this.log('Cleanup is set to "false". Build directory and Docker container (if used) will be retained')
return false
}
this.log("Cleaning build directory...")
Fse.removeAsync(this.buildDir)
.catch( err => { this.log(err) } )
if (this.useDocker){
this.log("Removing Docker container...")
this.runProcess('docker', ['stop',this.containerName,'-t','0'])
}
return true
}
selectAll() {
const functions = _.reject(this.serverless.service.functions, (target) => {
return target.runtime && !(target.runtime + '').match(/python/i);
});
const info = _.map(functions, (target) => {
return {
name: target.name,
includes: target.package.include,
artifact: target.package.artifact
}
})
return info
}
installRequirements(buildPath,requirementsPath){
if ( !Fse.pathExistsSync(requirementsPath) ) {
return
}
const size = Fse.statSync(requirementsPath).size
if (size === 0){
this.log(`WARNING: requirements file at ${requirementsPath} is empty. Skiping.`)
return
}
let cmd = 'pip'
let args = ['install', '--upgrade', '-t', upath.normalize(buildPath), '-r']
if ( this.useDocker === true ){
cmd = 'docker'
args = ['exec', this.containerName, 'pip', ...args]
requirementsPath = `${this.dockerServicePath}/${requirementsPath}`
}
args = [...args, upath.normalize(requirementsPath)]
return this.runProcess(cmd, args)
}
checkDocker(){
const out = this.runProcess('docker', ['version', '-f', 'Server Version {{.Server.Version}} & Client Version {{.Client.Version}}'])
this.log(`Using Docker ${out}`)
}
runProcess(cmd,args){
const ret = ChildProcess.spawnSync(cmd,args)
if (ret.error){
throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.error.message}`)
}
const out = ret.stdout.toString()
if (ret.stderr.length != 0){
const errorText = ret.stderr.toString().trim()
this.log(errorText) // prints stderr
if (this.abortOnPackagingErrors){
const countErrorNewLines = errorText.split('\n').length
if(!errorText.includes("ERROR:") && countErrorNewLines < 2 && errorText.toLowerCase().includes('git clone')){
// Ignore false positive due to pip git clone printing to stderr
} else if(errorText.toLowerCase().includes('warning') && !errorText.toLowerCase().includes('error')){
// Ignore warnings
} else if(errorText.toLowerCase().includes('docker')){
console.log('stdout:', out)
this.error("Docker Error Detected")
} else {
// Error is not false positive,
console.log('___ERROR DETECTED, BEGIN STDOUT____\n', out)
this.requestUserConfirmation()
}
}
}
return out
}
requestUserConfirmation(prompt="\n\n??? Do you wish to continue deployment with the stated errors? \n",
yesText="Continuing Deployment!",
noText='ABORTING DEPLOYMENT'
){
const response = readlineSync.question(prompt);
if(response.toLowerCase().includes('y')) {
console.log(yesText);
return
} else {
console.log(noText)
this.error('Aborting')
return
}
}
setupContainer(){
let out = this.runProcess('docker',['ps', '-a', '--filter',`name=${this.containerName}`,'--format','{{.Names}}'])
out = out.replace(/^\s+|\s+$/g, '')
if ( out === this.containerName ){
this.log('Container already exists. Reusing.')
let out = this.runProcess('docker', ['kill', `${this.containerName}`])
this.log(out)
}
let args = ['run', '--rm', '-dt', '-v', `${process.cwd()}:${this.dockerServicePath}`]
if (this.mountSSH) {
args = args.concat(['-v', `${process.env.HOME}/.ssh:/root/.ssh`])
}
args = args.concat(['--name',this.containerName, this.dockerImage, 'bash'])
this.runProcess('docker', args)
this.log('Container created')
}
ensureImage(){
const out = this.runProcess('docker', ['images', '--format','{{.Repository}}:{{.Tag}}','--filter',`reference=${this.dockerImage}`]).replace(/^\s+|\s+$/g, '')
if ( out != this.dockerImage ){
this.log(`Docker Image ${this.dockerImage} is not already installed on your system. Downloading. This might take a while. Subsequent deploys will be faster...`)
this.runProcess('docker', ['pull', this.dockerImage])
}
}
setupDocker(){
if (!this.useDocker){
return
}
this.log('Packaging using Docker container...')
this.checkDocker()
this.ensureImage()
this.log(`Creating Docker container "${this.containerName}"...`)
this.setupContainer()
this.log('Docker setup completed')
}
makePackage(target){
this.log(`Packaging ${target.name}...`)
const buildPath = Path.join(this.buildDir, target.name)
const requirementsPath = Path.join(buildPath,this.requirementsFile)
// Create package directory and package files
Fse.ensureDirSync(buildPath)
// Copy includes
let includes = target.includes || []
if (this.globalIncludes){
includes = _.concat(includes, this.globalIncludes)
}
_.forEach(includes, (item) => { Fse.copySync(item, buildPath) } )
// Install requirements
let requirements = [requirementsPath]
if (this.globalRequirements){
requirements = _.concat(requirements, this.globalRequirements)
}
_.forEach(requirements, (req) => { this.installRequirements(buildPath,req) })
zipper.sync.zip(buildPath).compress().save(`${buildPath}.zip`)
}
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.log = (msg) => { this.serverless.cli.log(`[serverless-package-python-functions] ${msg}`) }
this.error = (msg) => { throw new Error(`[serverless-package-python-functions] ${msg}`) }
this.hooks = {
'before:package:createDeploymentArtifacts': () => BbPromise.bind(this)
.then(this.fetchConfig)
.then(this.autoconfigArtifacts)
.then( () => { Fse.ensureDirAsync(this.buildDir) })
.then(this.setupDocker)
.then(this.selectAll)
.map(this.makePackage),
'after:deploy:deploy': () => BbPromise.bind(this)
.then(this.clean)
};
}
}
module.exports = PkgPyFuncs;