-
Notifications
You must be signed in to change notification settings - Fork 279
/
Copy pathsupply.go
926 lines (772 loc) · 27.4 KB
/
supply.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
package supply
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/cloudfoundry/python-buildpack/src/python/conda"
"github.com/cloudfoundry/python-buildpack/src/python/pipfile"
"os/exec"
"github.com/cloudfoundry/libbuildpack"
"github.com/cloudfoundry/libbuildpack/snapshot"
"github.com/kr/text"
)
const EnvPipVersion = "BP_PIP_VERSION"
type Stager interface {
BuildDir() string
CacheDir() string
DepDir() string
DepsIdx() string
LinkDirectoryInDepDir(destDir, destSubDir string) error
WriteEnvFile(envVar, envVal string) error
WriteProfileD(scriptName, scriptContents string) error
}
type Manifest interface {
AllDependencyVersions(depName string) []string
DefaultVersion(depName string) (libbuildpack.Dependency, error)
IsCached() bool
}
type Installer interface {
InstallDependency(dep libbuildpack.Dependency, outputDir string) error
InstallOnlyVersion(depName, installDir string) error
}
type Command interface {
Execute(dir string, stdout io.Writer, stderr io.Writer, program string, args ...string) error
Output(dir string, program string, args ...string) (string, error)
RunWithOutput(cmd *exec.Cmd) ([]byte, error)
}
type Reqs interface {
FindAnyPackage(buildDir string, searchedPackages ...string) (bool, error)
FindStalePackages(oldRequirementsPath, newRequirementsPath string, excludedPackages ...string) ([]string, error)
}
type Supplier struct {
PythonVersion string
Manifest Manifest
Installer Installer
Stager Stager
Command Command
Log *libbuildpack.Logger
Logfile *os.File
HasNltkData bool
removeRequirementsText bool
Requirements Reqs
}
func Run(s *Supplier) error {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "environment.yml")); err != nil {
s.Log.Error("Error checking existence of environment.yml: %v", err)
return err
} else if exists {
return conda.Run(conda.New(s.Installer, s.Stager, s.Command, s.Log))
} else {
return RunPython(s)
}
}
func RunPython(s *Supplier) error {
s.Log.BeginStep("Supplying Python")
dirSnapshot := snapshot.Dir(s.Stager.BuildDir(), s.Log)
if err := s.SetupCacheDir(); err != nil {
s.Log.Error("Error setting up cache: %v", err)
return err
}
if err := s.CopyRuntimeTxt(); err != nil {
s.Log.Error("Error copying runtime.txt to deps dir: %v", err)
return err
}
if err := s.HandlePipfile(); err != nil {
s.Log.Error("Error checking for Pipfile.lock: %v", err)
return err
}
if err := s.InstallPython(); err != nil {
s.Log.Error("Could not install python: %v", err)
return err
}
if err := s.InstallPip(); err != nil {
s.Log.Error("Could not install pip: %v", err)
return err
}
if err := s.InstallPipEnv(); err != nil {
s.Log.Error("Could not install pipenv: %v", err)
return err
}
if err := s.HandleRequirementstxt(); err != nil {
s.Log.Error("Error checking requirements.txt: %v", err)
return err
}
if err := s.HandlePylibmc(); err != nil {
s.Log.Error("Error checking Pylibmc: %v", err)
return err
}
if err := s.HandleFfi(); err != nil {
s.Log.Error("Error checking ffi: %v", err)
return err
}
if err := s.UninstallUnusedDependencies(); err != nil {
s.Log.Error("Error uninstalling unused dependencies: %v", err)
return err
}
vendored, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "vendor"))
if err != nil {
return fmt.Errorf("could not check vendor existence: %v", err)
}
if vendored {
if err := s.RunPipVendored(); err != nil {
s.Log.Error("Could not install vendored pip packages: %v", err)
return err
}
} else {
if err := s.RunPipUnvendored(); err != nil {
s.Log.Error("Could not install pip packages: %v", err)
return err
}
}
if err := s.DownloadNLTKCorpora(); err != nil {
s.Log.Error("Could not download NLTK Corpora: %v", err)
return err
}
if err := s.RewriteShebangs(); err != nil {
s.Log.Error("Unable to rewrite she-bangs: %s", err.Error())
return err
}
if err := s.CreateDefaultEnv(); err != nil {
s.Log.Error("Unable to setup default environment: %s", err.Error())
return err
}
if cacheDirSize, err := s.Command.Output(os.Getenv("XDG_CACHE_HOME"), "du", "--summarize", os.Getenv("XDG_CACHE_HOME")); err == nil {
s.Log.Debug("Size of pip cache dir: %s", cacheDirSize)
}
if s.removeRequirementsText {
if err := os.Remove(filepath.Join(s.Stager.BuildDir(), "requirements.txt")); err != nil {
s.Log.Error("Unable to clean up app directory: %s", err.Error())
return err
}
}
dirSnapshot.Diff()
return nil
}
func (s *Supplier) CopyRuntimeTxt() error {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "runtime.txt")); err != nil {
return err
} else if exists {
if err = libbuildpack.CopyFile(filepath.Join(s.Stager.BuildDir(), "runtime.txt"), filepath.Join(s.Stager.DepDir(), "runtime.txt")); err != nil {
return err
}
}
return nil
}
func (s *Supplier) HandlePipfile() error {
var pipfileExists, runtimeExists bool
var pipfileJson pipfile.Lock
var err error
if pipfileExists, err = libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "Pipfile.lock")); err != nil {
return err
}
if runtimeExists, err = libbuildpack.FileExists(filepath.Join(s.Stager.DepDir(), "runtime.txt")); err != nil {
return err
}
if pipfileExists && !runtimeExists {
if err = libbuildpack.NewJSON().Load(filepath.Join(s.Stager.BuildDir(), "Pipfile.lock"), &pipfileJson); err != nil {
return err
}
formattedVersion := s.formatVersion(pipfileJson.Meta.Requires.Version)
if err := os.WriteFile(filepath.Join(s.Stager.DepDir(), "runtime.txt"), []byte(formattedVersion), 0644); err != nil {
return err
}
}
return nil
}
func (s *Supplier) InstallPython() error {
var dep libbuildpack.Dependency
runtimetxtExists, err := libbuildpack.FileExists(filepath.Join(s.Stager.DepDir(), "runtime.txt"))
if err != nil {
return err
}
if runtimetxtExists {
userDefinedVersion, err := os.ReadFile(filepath.Join(s.Stager.DepDir(), "runtime.txt"))
if err != nil {
return err
}
s.PythonVersion = strings.TrimSpace(strings.NewReplacer("\\r", "", "\\n", "").Replace(string(userDefinedVersion)))
s.Log.Debug("***Version info: (%s)", s.PythonVersion)
}
if s.PythonVersion != "" {
versions := s.Manifest.AllDependencyVersions("python")
shortPythonVersion := strings.TrimLeft(s.PythonVersion, "python-")
s.Log.Debug("***Version info: (%s) (%s)", s.PythonVersion, shortPythonVersion)
ver, err := libbuildpack.FindMatchingVersion(shortPythonVersion, versions)
if err != nil {
return err
}
dep.Name = "python"
dep.Version = ver
s.Log.Debug("***Version info: %s, %s, %s", dep.Name, s.PythonVersion, dep.Version)
} else {
var err error
dep, err = s.Manifest.DefaultVersion("python")
if err != nil {
return err
}
}
pythonInstallDir := filepath.Join(s.Stager.DepDir(), "python")
if err := s.Installer.InstallDependency(dep, pythonInstallDir); err != nil {
return err
}
if err := s.Stager.LinkDirectoryInDepDir(filepath.Join(pythonInstallDir, "bin"), "bin"); err != nil {
return err
}
if found, err := libbuildpack.FileExists(filepath.Join(pythonInstallDir, "usr", "lib", "x86_64-linux-gnu")); err != nil {
return err
} else if found {
if err := s.Stager.LinkDirectoryInDepDir(filepath.Join(pythonInstallDir, "usr", "lib", "x86_64-linux-gnu"), "lib"); err != nil {
return err
}
}
if err := s.Stager.LinkDirectoryInDepDir(filepath.Join(pythonInstallDir, "lib"), "lib"); err != nil {
return err
}
if err := os.Setenv("PATH", fmt.Sprintf("%s:%s", filepath.Join(s.Stager.DepDir(), "bin"), os.Getenv("PATH"))); err != nil {
return err
}
if err := os.Setenv("PYTHONPATH", s.Stager.DepDir()); err != nil {
return err
}
version := regexp.MustCompile(`\d+\.\d+`).FindString(dep.Version)
//Remove once Python 3.7 is out of support (June 2023)
if version == "3.7" {
if err := os.Setenv("CFLAGS", fmt.Sprintf("-I%s", filepath.Join(s.Stager.DepDir(), "python", "include", fmt.Sprintf("python%sm", version)))); err != nil {
return err
}
} else {
if err := os.Setenv("CFLAGS", fmt.Sprintf("-I%s", filepath.Join(s.Stager.DepDir(), "python", "include", fmt.Sprintf("python%s", version)))); err != nil {
return err
}
}
return nil
}
func (s *Supplier) RewriteShebangs() error {
files, err := filepath.Glob(filepath.Join(s.Stager.DepDir(), "bin", "*"))
if err != nil {
return err
}
for _, file := range files {
if fileInfo, err := os.Stat(file); err != nil {
return err
} else if fileInfo.IsDir() {
continue
}
fileContents, err := os.ReadFile(file)
if err != nil {
return err
}
shebangRegex := regexp.MustCompile(`^#!/.*/python.*`)
fileContents = shebangRegex.ReplaceAll(fileContents, []byte("#!/usr/bin/env python"))
if err := os.WriteFile(file, fileContents, 0755); err != nil {
return err
}
}
return nil
}
func (s *Supplier) InstallPip() error {
pipVersion := os.Getenv(EnvPipVersion)
if pipVersion == "" {
s.Log.Info("Using python's pip module")
versionCmd := append(pipCommand(), "--version")
return s.Command.Execute(s.Stager.BuildDir(), indentWriter(os.Stdout), indentWriter(os.Stderr), versionCmd[0], versionCmd[1:]...)
}
if pipVersion != "latest" {
return fmt.Errorf("invalid pip version: %s", pipVersion)
}
tempPath := filepath.Join("/tmp", "pip")
if err := s.Installer.InstallOnlyVersion("pip", tempPath); err != nil {
return err
}
if err := s.Command.Execute(s.Stager.BuildDir(), indentWriter(os.Stdout), indentWriter(os.Stderr),
"python",
"-m", "pip",
"install", "pip",
"--exists-action=w",
"--no-index",
"--ignore-installed",
fmt.Sprintf("--find-links=%s", tempPath),
); err != nil {
return err
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(s.Stager.DepDir(), "python", "bin"), "bin")
}
func (s *Supplier) InstallPipEnv() error {
requirementstxtExists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "requirements.txt"))
if err != nil {
return err
} else if requirementstxtExists {
return nil
}
pipfileExists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "Pipfile"))
if err != nil {
return err
} else if !pipfileExists {
return nil
}
hasLockFile, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "Pipfile.lock"))
if err != nil {
return fmt.Errorf("could not check Pipfile.lock existence: %v", err)
} else if hasLockFile {
s.Log.Info("Generating 'requirements.txt' from Pipfile.lock")
requirementsContents, err := pipfileToRequirements(filepath.Join(s.Stager.BuildDir(), "Pipfile.lock"))
if err != nil {
return fmt.Errorf("failed to write `requirement.txt` from Pipfile.lock: %s", err.Error())
}
return s.writeTempRequirementsTxt(requirementsContents)
}
s.Log.Info("Installing pipenv")
if err := s.Installer.InstallOnlyVersion("pipenv", filepath.Join("/tmp", "pipenv")); err != nil {
return err
}
if err := s.installFfi(); err != nil {
return err
}
for _, dep := range []string{"setuptools_scm", "pytest-runner", "parver", "invoke", "pipenv", "wheel"} {
s.Log.Info("Installing %s", dep)
out := &bytes.Buffer{}
stderr := &bytes.Buffer{}
if err := s.runPipInstall(
dep,
"--exists-action=w",
"--no-index",
fmt.Sprintf("--find-links=%s", filepath.Join("/tmp", "pipenv")),
); err != nil {
return fmt.Errorf("Failed to install %s: %v.\nStdout: %v\nStderr: %v", dep, err, out, stderr)
}
}
s.Stager.LinkDirectoryInDepDir(filepath.Join(s.Stager.DepDir(), "python", "bin"), "bin")
s.Log.Info("Generating 'requirements.txt' with pipenv")
cmd := exec.Command("pipenv", "lock", "--requirements")
cmd.Dir = s.Stager.BuildDir()
cmd.Env = append(os.Environ(), "VIRTUALENV_NEVER_DOWNLOAD=true")
output, err := s.Command.RunWithOutput(cmd)
if err != nil {
return err
}
outputString := string(output)
// Remove output due to virtualenv
if strings.HasPrefix(outputString, "Using ") {
reqs := strings.SplitN(outputString, "\n", 2)
if len(reqs) > 0 {
outputString = reqs[1]
}
}
return s.writeTempRequirementsTxt(outputString)
}
func pipfileToRequirements(lockFilePath string) (string, error) {
var lockFile struct {
Meta struct {
Sources []struct {
URL string
}
} `json:"_meta"`
Default map[string]struct {
Version string
}
}
lockContents, err := os.ReadFile(lockFilePath)
if err != nil {
return "", err
}
err = json.Unmarshal(lockContents, &lockFile)
if err != nil {
return "", err
}
buf := &bytes.Buffer{}
for i, source := range lockFile.Meta.Sources {
if i == 0 {
fmt.Fprintf(buf, "-i %s\n", source.URL)
} else {
fmt.Fprintf(buf, "--extra-index-url %s\n", source.URL)
}
}
for pkg, obj := range lockFile.Default {
fmt.Fprintf(buf, "%s%s\n", pkg, obj.Version)
}
return buf.String(), nil
}
func (s *Supplier) HandlePylibmc() error {
exists, err := s.Requirements.FindAnyPackage(s.Stager.BuildDir(), "pylibmc")
if err != nil {
return err
}
if !exists {
return nil
}
return s.installLibmemcache()
}
func (s *Supplier) installLibmemcache() error {
memcachedDir := filepath.Join(s.Stager.DepDir(), "libmemcache")
s.Log.BeginStep("Noticed pylibmc. Bootstrapping libmemcached.")
if err := s.Installer.InstallOnlyVersion("libmemcache", memcachedDir); err != nil {
return err
}
os.Setenv("LIBMEMCACHED", memcachedDir)
s.Stager.WriteEnvFile("LIBMEMCACHED", memcachedDir)
s.Stager.LinkDirectoryInDepDir(filepath.Join(memcachedDir, "lib"), "lib")
s.Stager.LinkDirectoryInDepDir(filepath.Join(memcachedDir, "lib", "sasl2"), "lib")
s.Stager.LinkDirectoryInDepDir(filepath.Join(memcachedDir, "lib", "pkgconfig"), "pkgconfig")
s.Stager.LinkDirectoryInDepDir(filepath.Join(memcachedDir, "include"), "include")
return nil
}
func (s *Supplier) HandleRequirementstxt() error {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "requirements.txt")); err != nil {
return err
} else if exists {
return nil
}
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "setup.py")); err != nil {
return err
} else if !exists {
return nil
}
return s.writeTempRequirementsTxt("-e .")
}
func (s *Supplier) installFfi() error {
ffiDir := filepath.Join(s.Stager.DepDir(), "libffi")
// Only install libffi if we haven't done so already
// This could be installed twice because pipenv installs it, but
// we later run HandleFfi, which installs it if a dependency
// from requirements.txt needs libffi.
if os.Getenv("LIBFFI") != ffiDir {
s.Log.BeginStep("Noticed dependency requiring libffi. Bootstrapping libffi.")
if err := s.Installer.InstallOnlyVersion("libffi", ffiDir); err != nil {
return err
}
versions := s.Manifest.AllDependencyVersions("libffi")
os.Setenv("LIBFFI", ffiDir)
s.Stager.WriteEnvFile("LIBFFI", ffiDir)
s.Stager.LinkDirectoryInDepDir(filepath.Join(ffiDir, "lib"), "lib")
s.Stager.LinkDirectoryInDepDir(filepath.Join(ffiDir, "lib", "pkgconfig"), "pkgconfig")
s.Stager.LinkDirectoryInDepDir(filepath.Join(ffiDir, "lib", "libffi-"+versions[0], "include"), "include")
}
return nil
}
func (s *Supplier) HandleFfi() error {
exists, err := s.Requirements.FindAnyPackage(s.Stager.BuildDir(),
"pymysql", "argon2-cffi", "bcrypt", "cffi", "cryptography", "django[argon2]", "Django[argon2]",
"django[bcrypt]", "Django[bcrypt]", "PyNaCl", "pyOpenSSL", "PyOpenSSL", "requests[security]", "misaka")
if err != nil {
return err
}
if !exists {
return nil
}
return s.installFfi()
}
func (s *Supplier) UninstallUnusedDependencies() error {
requirementsDeclaredExists, err := libbuildpack.FileExists(filepath.Join(s.Stager.DepDir(), "python", "requirements-declared.txt"))
if err != nil {
return err
}
if requirementsDeclaredExists {
fileContents, _ := os.ReadFile(filepath.Join(s.Stager.DepDir(), "python", "requirements-declared.txt"))
s.Log.Info("requirements-declared: %s", string(fileContents))
staleContents, err := s.Requirements.FindStalePackages(
filepath.Join(s.Stager.DepDir(), "python", "requirements-declared.txt"),
filepath.Join(s.Stager.BuildDir(), "requirements.txt"),
"setuptools", "pip", "wheel")
if err != nil {
return err
}
if len(staleContents) == 0 {
return nil
}
staleContentString := strings.Join(staleContents[:], "\n")
if err := os.WriteFile(filepath.Join(s.Stager.DepDir(), "python", "requirements-stale.txt"), []byte(staleContentString), 0644); err != nil {
return err
}
s.Log.BeginStep("Uninstalling stale dependencies")
if err := s.Command.Execute(
s.Stager.BuildDir(),
indentWriter(os.Stdout),
indentWriter(os.Stderr),
"python",
"-m",
"pip",
"uninstall",
"-r",
filepath.Join(s.Stager.DepDir(), "python", "requirements-stale.txt", "-y", "--exists-action=w"),
); err != nil {
return err
}
}
return nil
}
func (s *Supplier) RunPipUnvendored() error {
s.Log.BeginStep("Running Pip Install (Unvendored)")
shouldContinue, requirementsPath, err := s.shouldRunPip()
if err != nil {
return err
} else if !shouldContinue {
return nil
}
// Search lines from requirements.txt that begin with -i, --index-url, --extra-index-url or --trusted-host
// and add them to the pydistutils file. We do this so that easy_install will use
// the same indexes as pip. This may not actually be necessary because it's possible that
// easy_install has been fixed upstream, but it has no ill side-effects.
reqs, err := os.ReadFile(requirementsPath)
if err != nil {
return fmt.Errorf("could not read requirements.txt: %v", err)
}
distUtils := map[string][]string{}
re := regexp.MustCompile(`(?m)^\s*(-i|--index-url)\s+(.*)$`)
match := re.FindStringSubmatch(string(reqs))
if len(match) > 0 {
distUtils["index_url"] = []string{match[len(match)-1]}
}
re = regexp.MustCompile(`(?m)^\s*--extra-index-url\s+(.*)$`)
matches := re.FindAllStringSubmatch(string(reqs), -1)
for _, m := range matches {
distUtils["find_links"] = append(distUtils["find_links"], m[len(m)-1])
}
re = regexp.MustCompile(`(?m)^\s*--trusted-host\s+(.*)$`)
matches = re.FindAllStringSubmatch(string(reqs), -1)
if len(matches) > 0 {
var allowHosts []string
for _, m := range matches {
allowHosts = append(allowHosts, m[len(m)-1])
}
distUtils["allow_hosts"] = []string{strings.Join(allowHosts, ",")}
}
if err := writePyDistUtils(distUtils); err != nil {
return err
}
if err := s.runPipInstall(
"-r", requirementsPath,
"--ignore-installed",
"--exists-action=w",
"--src="+filepath.Join(s.Stager.DepDir(), "src"),
"--disable-pip-version-check",
"--no-warn-script-location",
); err != nil {
return fmt.Errorf("could not run pip: %v", err)
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(s.Stager.DepDir(), "python", "bin"), "bin")
}
func (s *Supplier) RunPipVendored() error {
s.Log.BeginStep("Running Pip Install (Vendored)")
shouldContinue, requirementsPath, err := s.shouldRunPip()
if err != nil {
return err
} else if !shouldContinue {
return nil
}
distUtils := map[string][]string{
"allows_hosts": {""},
"find_links": {filepath.Join(s.Stager.BuildDir(), "vendor")},
}
if err := writePyDistUtils(distUtils); err != nil {
return err
}
installArgs := []string{
"-r", requirementsPath,
"--ignore-installed",
"--exists-action=w",
"--src=" + filepath.Join(s.Stager.DepDir(), "src"),
"--no-index",
"--find-links=file://" + filepath.Join(s.Stager.BuildDir(), "vendor"),
"--disable-pip-version-check",
"--no-warn-script-location",
}
if s.hasBuildOptions() {
s.Log.Info("Using the pip --no-build-isolation flag since it is available")
installArgs = append(installArgs, "--no-build-isolation")
}
// Remove lines from requirements.txt that begin with -i, --index-url and --extra-index-url
// because specifying index links here makes pip always want internet access,
// and pipenv generates requirements.txt with -i.
originalReqs, err := os.ReadFile(requirementsPath)
if err != nil {
return fmt.Errorf("could not read requirements.txt: %v", err)
}
re := regexp.MustCompile(`(?m)^\s*(-i|--index-url|--extra-index-url)\s+(.*)$`)
modifiedReqs := re.ReplaceAll(originalReqs, []byte{})
err = os.WriteFile(requirementsPath, modifiedReqs, 0644)
if err != nil {
return fmt.Errorf("could not overwrite requirements file: %v", err)
}
vendorHasSdist, err := containsSdist(filepath.Join(s.Stager.BuildDir(), "vendor"))
if err != nil {
return fmt.Errorf("error checking for sdists in vendor dir: %v", err)
}
if vendorHasSdist {
s.Log.Info("source distribution found in vendor. Installing common build-time dependencies in staging")
err := s.InstallCommonBuildDependencies()
if err != nil {
return fmt.Errorf("error installing common build dependencies: %v", err)
}
}
if err := s.runPipInstall(installArgs...); err != nil {
s.Log.Info("Running pip install failed. You need to include all dependencies in the vendor directory.")
return fmt.Errorf("could not run pip: %v", err)
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(s.Stager.DepDir(), "python", "bin"), "bin")
}
// sdist packages have 2 kinds of dependencies: build-time deps and
// runtime-deps. Before PEP-517, there was no standard to specify a package's
// build-time deps, but with PEP-517, a package defines its build-time deps in
// its pyproject.toml. In an online install, pip reads it and downloads
// build-time deps and builds the sdist. In a vendored (offline) install, this
// is not possible because "pip download" is not smart enough to download
// build-time deps during vendoring (pypa/pip issue#8302). Before pip 23.1,
// when build-time deps were missing, pip fell back to using the legacy
// 'setup.py install' method. pip 23.1 started enforcing PEP 517. Therefore,
// for vendored apps with sdists, we install the 2 most common build-time
// dependencies - wheel and setuptools. These are packaged by the dependency
// pipeline within the "pip" dependency.
func (s *Supplier) InstallCommonBuildDependencies() error {
var commonDeps = []string{"wheel", "setuptools"}
tempPath := filepath.Join("/tmp", "common_build_deps")
if err := s.Installer.InstallOnlyVersion("pip", tempPath); err != nil {
return err
}
for _, dep := range commonDeps {
s.Log.Info("Installing build-time dependency %s", dep)
args := []string{dep, "--no-index", "--upgrade-strategy=only-if-needed", fmt.Sprintf("--find-links=%s", tempPath)}
if err := s.runPipInstall(args...); err != nil {
return fmt.Errorf("could not install build-time dependency %s: %v", dep, err)
}
}
return nil
}
func (s *Supplier) CreateDefaultEnv() error {
var environmentVars = map[string]string{
"PYTHONPATH": s.Stager.DepDir(),
"LIBRARY_PATH": filepath.Join(s.Stager.DepDir(), "lib"),
"PYTHONHOME": filepath.Join(s.Stager.DepDir(), "python"),
"PYTHONUNBUFFERED": "1",
"PYTHONHASHSEED": "random",
"LANG": "en_US.UTF-8",
}
scriptContents := fmt.Sprintf(`export LANG=${LANG:-en_US.UTF-8}
export PYTHONHASHSEED=${PYTHONHASHSEED:-random}
export PYTHONPATH=$DEPS_DIR/%s
export PYTHONHOME=$DEPS_DIR/%s/python
export PYTHONUNBUFFERED=1
export FORWARDED_ALLOW_IPS='*'
export GUNICORN_CMD_ARGS=${GUNICORN_CMD_ARGS:-'--access-logfile -'}
`, s.Stager.DepsIdx(), s.Stager.DepsIdx())
if s.HasNltkData {
scriptContents += fmt.Sprintf(`export NLTK_DATA=$DEPS_DIR/%s/python/nltk_data`, s.Stager.DepsIdx())
environmentVars["NLTK_DATA"] = filepath.Join(s.Stager.DepDir(), "python", "nltk_data")
}
for envVar, envValue := range environmentVars {
if err := s.Stager.WriteEnvFile(envVar, envValue); err != nil {
return err
}
}
return s.Stager.WriteProfileD("python.sh", scriptContents)
}
func (s *Supplier) DownloadNLTKCorpora() error {
if err := s.Command.Execute("/", io.Discard, io.Discard, "python", "-m", "nltk.downloader", "-h"); err != nil {
return nil
}
s.Log.BeginStep("Downloading NLTK corpora...")
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "nltk.txt")); err != nil {
return fmt.Errorf("Couldn't check nltk.txt existence: %v", err)
} else if !exists {
s.Log.Info("nltk.txt not found, not downloading any corpora")
return nil
}
bPackages, err := os.ReadFile(filepath.Join(s.Stager.BuildDir(), "nltk.txt"))
if err != nil {
return err
}
sPackages := strings.TrimSpace(strings.NewReplacer("\r", " ", "\n", " ").Replace(string(bPackages)))
args := []string{"-m", "nltk.downloader", "-d", filepath.Join(s.Stager.DepDir(), "python", "nltk_data")}
args = append(args, strings.Split(sPackages, " ")...)
s.Log.BeginStep("Downloading NLTK packages: %s", sPackages)
if err := s.Command.Execute("/", indentWriter(os.Stdout), indentWriter(os.Stderr), "python", args...); err != nil {
return err
}
s.HasNltkData = true
return nil
}
func (s *Supplier) SetupCacheDir() error {
if err := os.Setenv("XDG_CACHE_HOME", filepath.Join(s.Stager.CacheDir(), "pip_cache")); err != nil {
return err
}
if err := s.Stager.WriteEnvFile("XDG_CACHE_HOME", filepath.Join(s.Stager.CacheDir(), "pip_cache")); err != nil {
return err
}
return nil
}
func writePyDistUtils(distUtils map[string][]string) error {
pyDistUtilsPath := filepath.Join(os.Getenv("HOME"), ".pydistutils.cfg")
b := strings.Builder{}
b.WriteString("[easy_install]\n")
for k, v := range distUtils {
b.WriteString(fmt.Sprintf("%s = %s\n", k, strings.Join(v, "\n\t")))
}
if err := os.WriteFile(pyDistUtilsPath, []byte(b.String()), os.ModePerm); err != nil {
return err
}
return nil
}
func (s *Supplier) shouldRunPip() (bool, string, error) {
if os.Getenv("PIP_CERT") == "" {
os.Setenv("PIP_CERT", "/etc/ssl/certs/ca-certificates.crt")
}
requirementsPath := filepath.Join(s.Stager.BuildDir(), "requirements.txt")
if exists, err := libbuildpack.FileExists(requirementsPath); err != nil {
return false, "", fmt.Errorf("could not determine existence of requirements.txt: %v", err)
} else if !exists {
s.Log.Debug("Skipping 'pip install' since requirements.txt does not exist")
return false, "", nil
}
return true, requirementsPath, nil
}
func pipCommand() []string {
if os.Getenv(EnvPipVersion) != "" {
return []string{"pip"}
}
return []string{"python", "-m", "pip"}
}
func (s *Supplier) runPipInstall(args ...string) error {
installCmd := append(append(pipCommand(), "install"), args...)
s.Log.Info(strings.Join(installCmd, " "))
return s.Command.Execute(s.Stager.BuildDir(), indentWriter(os.Stdout), indentWriter(os.Stderr), installCmd[0], installCmd[1:]...)
}
func (s *Supplier) formatVersion(version string) string {
verSlice := strings.Split(version, ".")
if len(verSlice) < 3 {
return fmt.Sprintf("python-%s.x", version)
}
return fmt.Sprintf("python-%s", version)
}
func (s *Supplier) writeTempRequirementsTxt(content string) error {
s.removeRequirementsText = true
return os.WriteFile(filepath.Join(s.Stager.BuildDir(), "requirements.txt"), []byte(content), 0644)
}
func (s *Supplier) hasBuildOptions() bool {
helpCommand := append(pipCommand(), "install", "--no-build-isolation", "-h")
err := s.Command.Execute(s.Stager.BuildDir(), nil, nil, helpCommand[0], helpCommand[1:]...)
return nil == err
}
func indentWriter(writer io.Writer) io.Writer {
return text.NewIndentWriter(writer, []byte(" "))
}
// sdists are identified by .tar.gz, .tgz, or .zip extensions
// in the vendor dir. docs.python.org/3.10/distutils/sourcedist.html
func containsSdist(vendorDir string) (bool, error) {
files, err := os.ReadDir(vendorDir)
if err != nil {
return false, err
}
for _, file := range files {
if !file.IsDir() {
ext := strings.ToLower(filepath.Ext(file.Name()))
if strings.HasSuffix(strings.ToLower(file.Name()), ".tar.gz") || ext == ".tgz" || ext == ".zip" {
return true, nil
}
}
}
return false, nil
}