-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
183 lines (152 loc) · 5.8 KB
/
Copy pathindex.js
File metadata and controls
183 lines (152 loc) · 5.8 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
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
'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');
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'
}
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 = this.serverless.service.functions
const info = _.map(functions, (target) => {
return {
name: target.name,
includes: target.package.include
}
})
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', buildPath, '-r', requirementsPath]
if ( this.useDocker === true ){
cmd = 'docker'
args = ['exec',this.containerName, 'pip', ...args]
}
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}`)
}
if (ret.stderr.length != 0){
throw new this.serverless.classes.Error(`[serverless-package-python-functions] ${ret.stderr.toString()}`)
}
const out = ret.stdout.toString()
return out
}
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.')
} else {
this.runProcess(
'docker',
['run', '--rm', '-dt', '-v', `${process.cwd()}:/var/task`,
'--name',this.containerName, this.dockerImage, 'bash']
)
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( () => { 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;