/
python.go
343 lines (294 loc) · 8.05 KB
/
python.go
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package config
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"golang.org/x/sync/errgroup"
"github.com/otiai10/copy"
"github.com/spatocode/jerm/internal/log"
"github.com/spatocode/jerm/internal/utils"
)
type Python struct {
*Runtime
}
// NewPythonConfig instantiates a new Python runtime
func NewPythonRuntime() RuntimeInterface {
runtime := &Runtime{}
p := &Python{runtime}
p.Name = RuntimePython
version, err := p.getVersion()
if err != nil {
log.Debug(fmt.Sprintf("encountered an error while getting python version. Default to %s", DefaultPythonVersion))
p.Version = DefaultPythonVersion
return p
}
p.Version = version
return p
}
// Entry is the directory where the cloud function handler resides.
// The directory can be a file.
func (p *Python) Entry() string {
switch {
case p.IsDjango():
workDir, _ := os.Getwd()
entry, err := p.getDjangoProject(workDir)
if err != nil {
log.Debug(err.Error())
}
return entry
default:
return ""
}
}
// Gets the python version
func (p *Python) getVersion() (string, error) {
log.Debug("getting python version...")
pythonVersion, err := utils.GetShellCommandOutput("python", "-V")
if err != nil || strings.Contains(pythonVersion, " 2.") {
pythonVersion, err = utils.GetShellCommandOutput("python3", "-V")
}
s := strings.Split(pythonVersion, " ")
version := s[len(s)-1]
return version, err
}
// Gets the python active virtual environment
func (p *Python) getVirtualEnvironment() (string, error) {
venv := os.Getenv("VIRTUAL_ENV")
if venv != "" {
return strings.TrimSpace(venv), nil
}
_, err := utils.GetShellCommandOutput("pyenv")
if err != nil {
pyenvRoot, err := utils.GetShellCommandOutput("pyenv", "root")
if err != nil {
return "", err
}
pyenvRoot = strings.TrimSpace(pyenvRoot)
pyenvVersionName, err := utils.GetShellCommandOutput("pyenv", "version-name")
if err != nil {
return "", err
}
pyenvVersionName = strings.TrimSpace(pyenvVersionName)
venv = path.Join(pyenvRoot, "versions", pyenvVersionName)
return venv, nil
}
return "", nil
}
// Builds the Python deployment package
func (p *Python) Build(config *Config) (string, error) {
tempDir, err := os.MkdirTemp(os.TempDir(), "jerm-python")
if err != nil {
return "", err
}
handlerPath := filepath.Join(tempDir, "handler.py")
venv, err := p.getVirtualEnvironment()
if err != nil {
//TODO: installs requirements listed in requirements.txt file
return "", fmt.Errorf("cannot find a virtual env. Please ensure you're running in a virtual env")
}
version := strings.Split(p.Version, ".")
sitePackages := path.Join(venv, "lib", fmt.Sprintf("%s%s.%s", p.Name, version[0], version[1]), "site-packages")
if runtime.GOOS == "windows" {
sitePackages = path.Join(venv, "Lib", "site-packages")
}
dependencies := map[string]string{
"lambda-wsgi-adapter": "0.1.1",
}
if !utils.FileExists(filepath.Join(sitePackages, "werkzeug")) {
dependencies["werkzeug"] = "0.16.1"
}
err = p.installNecessaryDependencies(tempDir, sitePackages, dependencies)
if err != nil {
return "", err
}
err = p.copyNecessaryFilesToTempDir(config.Dir, tempDir, jermIgnoreFile)
if err != nil {
return "", err
}
err = p.copyNecessaryFilesToTempDir(sitePackages, tempDir, jermIgnoreFile)
if err != nil {
return "", err
}
log.Debug(fmt.Sprintf("built Python deployment package at %s", tempDir))
return handlerPath, err
}
// Copies files from src to dest
func (p *Python) copyNecessaryFilesToTempDir(src, dest, ignoreFile string) error {
log.Debug("copying necessary Python files...")
ignoredFiles := defaultIgnoredGlobs
files, err := ReadIgnoredFiles(ignoreFile)
if err == nil {
ignoredFiles = append(ignoredFiles, files...)
}
opt := copy.Options{
Skip: func(srcinfo os.FileInfo, src, dest string) (bool, error) {
for _, ignoredFile := range ignoredFiles {
match, _ := filepath.Match(ignoredFile, srcinfo.Name())
matchedFile := srcinfo.Name() == ignoredFile || match ||
strings.HasSuffix(srcinfo.Name(), ignoredFile) ||
strings.HasPrefix(srcinfo.Name(), ignoredFile)
if matchedFile {
return matchedFile, nil
}
}
return false, nil
},
}
err = copy.Copy(src, dest, opt)
if err != nil {
return err
}
return nil
}
// installRequirements installs requirements listed in requirements.txt file
// func (p *Python) installRequirements(dir string) error {
// return nil
// }
// Installs dependencies needed to run serverless Python
func (p *Python) installNecessaryDependencies(dir, sitePackages string, dependencies map[string]string) error {
log.Debug("installing necessary Python dependencies...")
var eg errgroup.Group
for project, version := range dependencies {
func(dep, ver string) {
eg.Go(func() error {
url := fmt.Sprintf("https://pypi.org/pypi/%s/json", dep)
res, err := utils.Request(url)
if err != nil {
return err
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
data := make(map[string]interface{})
err = json.Unmarshal(b, &data)
if err != nil {
return err
}
r := data["releases"]
releases, _ := r.(map[string]interface{})
for _, v := range releases[ver].([]interface{}) {
url := v.(map[string]interface{})["url"].(string)
filename := v.(map[string]interface{})["filename"].(string)
if filepath.Ext(filename) == ".whl" {
err := p.downloadDependencies(url, filename, dir)
if err != nil {
return err
}
}
}
return nil
})
}(project, version)
}
err := eg.Wait()
return err
}
// Downloads dependencies from pypi
func (p *Python) downloadDependencies(url, filename, dir string) error {
log.Debug("downloading dependencies...")
res, err := utils.Request(url)
if err != nil {
return err
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
return err
}
temp, err := os.MkdirTemp(os.TempDir(), "jerm-dep")
if err != nil {
return err
}
defer os.RemoveAll(temp)
filenamePath := filepath.Join(temp, filename)
file, err := os.Create(filenamePath)
if err != nil {
return err
}
defer file.Close()
file.Write(b)
if err := p.extractWheel(filenamePath, dir); err != nil {
return err
}
return nil
}
// Extracts python wheel from wheelPath to outputDir
func (p *Python) extractWheel(wheelPath, outputDir string) error {
log.Debug("extracting python wheel...")
var eg errgroup.Group
reader, err := zip.OpenReader(wheelPath)
if err != nil {
return err
}
defer reader.Close()
for _, file := range reader.File {
func(file *zip.File) {
eg.Go(func() error {
os.MkdirAll(filepath.Join(outputDir, filepath.Dir(file.Name)), 0755)
if err != nil {
return err
}
extractedFile, err := os.Create(filepath.Join(outputDir, file.Name))
if err != nil {
return err
}
defer extractedFile.Close()
zippedFile, err := file.Open()
if err != nil {
return err
}
defer zippedFile.Close()
if _, err = io.Copy(extractedFile, zippedFile); err != nil {
return err
}
return nil
})
}(file)
}
err = eg.Wait()
return err
}
// Check if it's a Django project
func (p *Python) IsDjango() bool {
return utils.FileExists("manage.py")
}
// Gets the Django project path
func (p *Python) getDjangoProject(dir string) (string, error) {
// Not the best way for finding django project path
// Using this naive hack for now
djangoPath := ""
walker := func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && d.Name() == "settings.py" {
d := filepath.Dir(path)
splitPath := strings.Split(d, string(filepath.Separator))
djangoPath = splitPath[len(splitPath)-1]
return io.EOF
}
return nil
}
err := filepath.WalkDir(dir, walker)
if err != nil {
if err == io.EOF {
err = nil
}
return djangoPath, err
}
return djangoPath, nil
}
// lambdaRuntime is the name of the python runtime as specified by AWS Lambda
func (p *Python) lambdaRuntime() (string, error) {
v := strings.Split(p.Version, ".")
return fmt.Sprintf("%s%s.%s", p.Name, v[0], v[1]), nil
}