-
Notifications
You must be signed in to change notification settings - Fork 160
/
supply.go
1019 lines (857 loc) · 29.1 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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package supply
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/cloudfoundry/libbuildpack"
"github.com/cloudfoundry/ruby-buildpack/src/ruby/cache"
"github.com/kr/text"
)
type Command interface {
Execute(string, io.Writer, io.Writer, string, ...string) error
Output(string, string, ...string) (string, error)
Run(*exec.Cmd) error
}
type Manifest interface {
AllDependencyVersions(string) []string
DefaultVersion(string) (libbuildpack.Dependency, error)
}
type Installer interface {
InstallDependency(libbuildpack.Dependency, string) error
InstallOnlyVersion(string, string) error
}
type Versions interface {
GetBundlerVersion() (string, error)
Engine() (string, error)
Version() (string, error)
JrubyVersion() (string, error)
RubyEngineVersion() (string, error)
HasGemVersion(gem string, constraints ...string) (bool, error)
VersionConstraint(version string, constraints ...string) (bool, error)
HasWindowsGemfileLock() (bool, error)
Gemfile() string
BundledWithVersion() (string, error)
}
type Stager interface {
BuildDir() string
DepDir() string
DepsIdx() string
LinkDirectoryInDepDir(string, string) error
WriteEnvFile(string, string) error
WriteProfileD(string, string) error
SetStagingEnvironment() error
}
type TempDir interface {
CopyDirToTemp(string) (string, error)
}
type Cache interface {
Metadata() *cache.Metadata
Restore() error
Save() error
}
type Supplier struct {
Stager Stager
Manifest Manifest
Installer Installer
Log *libbuildpack.Logger
Versions Versions
Cache Cache
Command Command
TempDir TempDir
cachedNeedsNode bool
needsNode bool
appHasGemfile bool
appHasGemfileLock bool
}
func Run(s *Supplier) error {
s.Log.BeginStep("Supplying Ruby")
_ = s.Command.Execute(s.Stager.BuildDir(), ioutil.Discard, ioutil.Discard, "touch", "/tmp/checkpoint")
if checksum, err := s.CalcChecksum(); err == nil {
s.Log.Debug("BuildDir Checksum Before Supply: %s", checksum)
}
if err := s.Setup(); err != nil {
s.Log.Error("Error during setup: %v", err)
return err
}
if err := s.Cache.Restore(); err != nil {
s.Log.Error("Unable to restore cache: %s", err.Error())
return err
}
if err := s.InstallBundler(); err != nil {
s.Log.Error("Unable to install bundler: %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 err := s.EnableLDLibraryPathEnv(); err != nil {
s.Log.Error("Unable to enable ld_library_path env: %s", err.Error())
return err
}
engine, rubyVersion, err := s.DetermineRuby()
if err != nil {
s.Log.Error("Unable to determine ruby: %s", err.Error())
return err
}
if engine == "jruby" {
if err = s.InstallJVM(); err != nil {
s.Log.Error("Unable to install JVM: %s", err.Error())
return err
}
}
// Search cache dir for sub-directories which don't match current ruby version.
if err := s.RemoveUnusedRubyVersions(engine, rubyVersion); err != nil {
s.Log.Error("Unable to remove unused ruby: %s", err.Error())
return err
}
if err := s.InstallRuby(engine, rubyVersion); err != nil {
s.Log.Error("Unable to install ruby: %s", err.Error())
return err
}
if err := s.AddPostRubyInstallDefaultEnv(engine); err != nil {
s.Log.Error("Unable to add gem path to default environment: %s", err.Error())
return err
}
if err := s.UpdateRubygems(); err != nil {
s.Log.Error("Unable to update rubygems: %s", err.Error())
return err
}
if err := s.AddPostRubyGemsInstallDefaultEnv(engine); err != nil {
s.Log.Error("Unable to add bundler path to default environment: %s", err.Error())
return err
}
if s.NeedsNode() {
if err := s.InstallNode(); err != nil {
s.Log.Error("Unable to install node: %s", err.Error())
return err
}
if err := s.InstallYarn(); err != nil {
s.Log.Error("Unable to install yarn: %s", err.Error())
return err
}
}
if err := s.InstallGems(); err != nil {
s.Log.Error("Unable to install gems: %s", err.Error())
return err
}
if err := s.RewriteShebangs(); err != nil {
s.Log.Error("Unable to rewrite shebangs: %s", err.Error())
return err
}
if err := s.SymlinkBundlerIntoRubygems(); err != nil {
s.Log.Error("Unable to symlink bundler into rubygems: %s", err.Error())
return err
}
if err := s.WriteProfileD(engine); err != nil {
s.Log.Error("Unable to write profile.d: %s", err.Error())
return err
}
if err := s.Cache.Save(); err != nil {
s.Log.Error("Unable to save cache: %s", err.Error())
return err
}
if err := s.Stager.SetStagingEnvironment(); err != nil {
s.Log.Error("Unable to setup environment variables: %s", err.Error())
return err
}
if checksum, err := s.CalcChecksum(); err == nil {
s.Log.Debug("BuildDir Checksum After Supply: %s", checksum)
}
if filesChanged, err := s.Command.Output(s.Stager.BuildDir(), "find", ".", "-newer", "/tmp/checkpoint", "-not", "-path", "./.cloudfoundry/*", "-not", "-path", "./.cloudfoundry"); err == nil && filesChanged != "" {
s.Log.Debug("Below files changed:")
s.Log.Debug(filesChanged)
}
return nil
}
func (s *Supplier) Setup() error {
if exists, err := libbuildpack.FileExists(s.Versions.Gemfile()); err != nil {
return fmt.Errorf("unable to determine if Gemfile exists: %v", err)
} else {
s.appHasGemfile = exists
}
if exists, err := libbuildpack.FileExists(fmt.Sprintf("%s.lock", s.Versions.Gemfile())); err != nil {
return fmt.Errorf("Unable to determine if Gemfile.lock exists: %v", err)
} else {
s.appHasGemfileLock = exists
}
return nil
}
func (s *Supplier) DetermineRuby() (string, string, error) {
if !s.appHasGemfile {
dep, err := s.Manifest.DefaultVersion("ruby")
if err != nil {
return "", "", fmt.Errorf("unable to determine default ruby version: %v", err)
}
return "ruby", dep.Version, nil
}
engine, err := s.Versions.Engine()
if err != nil {
return "", "", fmt.Errorf("unable to determine ruby engine: %v", err)
}
var rubyVersion string
if engine == "ruby" {
rubyVersion, err = s.Versions.Version()
if err != nil {
return "", "", fmt.Errorf("Unable to determine ruby version: %v", err)
}
if rubyVersion == "" {
if dep, err := s.Manifest.DefaultVersion("ruby"); err != nil {
return "", "", fmt.Errorf("Unable to determine ruby version: %v", err)
} else {
rubyVersion = dep.Version
s.Log.Warning("You have not declared a Ruby version in your Gemfile.\nDefaulting to %s\nSee http://docs.cloudfoundry.org/buildpacks/ruby/index.html#runtime for more information.", rubyVersion)
}
}
} else if engine == "jruby" {
rubyVersion, err = s.Versions.JrubyVersion()
if err != nil {
return "", "", fmt.Errorf("Unable to determine jruby version: %v", err)
}
} else {
return "", "", fmt.Errorf("Sorry, we do not support engine: %s", engine)
}
return engine, rubyVersion, nil
}
func (s *Supplier) RemoveUnusedRubyVersions(engine, version string) error {
splitVersion := strings.Split(version, ".")
majorMinorVersion := strings.Join([]string{splitVersion[0], splitVersion[1], "0"}, ".")
matches, err := filepath.Glob(filepath.Join(s.Stager.DepDir(), "vendor_bundle", engine, "*"))
if err != nil {
return err
}
for _, match := range matches {
if !strings.HasSuffix(match, majorMinorVersion) {
err := os.RemoveAll(match)
if err != nil {
return err
}
}
}
return nil
}
func (s *Supplier) InstallYarn() error {
exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "yarn.lock"))
if err != nil {
return err
}
if !exists {
return nil
}
yarnInstallDir := filepath.Join(s.Stager.DepDir(), "yarn")
if err != nil {
return err
}
if err := s.Installer.InstallOnlyVersion("yarn", yarnInstallDir); err != nil {
return err
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(yarnInstallDir, "bin"), "bin")
}
func (s *Supplier) InstallBundler() error {
contents, err := ioutil.ReadFile(fmt.Sprintf("%s.lock", s.Versions.Gemfile()))
if err != nil {
if !os.IsNotExist(err) {
return err
}
}
re := regexp.MustCompile(`BUNDLED WITH\s*(\d+\.\d+\.\d+)`)
matches := re.FindStringSubmatch(string(contents))
if len(matches) != 2 {
matches = []string{"", "2"}
}
if strings.HasPrefix(matches[1], "2") {
return s.installBundler("2.x.x")
}
return s.installBundler("1.x.x")
}
func (s *Supplier) InstallNode() error {
var dep libbuildpack.Dependency
version, err := libbuildpack.FindMatchingVersion("x", s.Manifest.AllDependencyVersions("node"))
if err != nil {
return err
}
dep.Name = "node"
dep.Version = version
nodeInstallDir := filepath.Join(s.Stager.DepDir(), "node")
if err := s.Installer.InstallDependency(dep, nodeInstallDir); err != nil {
return err
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(nodeInstallDir, "bin"), "bin")
}
func (s *Supplier) NeedsNode() bool {
if s.cachedNeedsNode {
return s.needsNode
}
s.cachedNeedsNode = true
s.needsNode = false
if s.isNodeInstalled() {
s.Log.BeginStep("Skipping install of nodejs since it has been supplied")
} else {
for _, name := range []string{"webpacker", "execjs", "cssbundling-rails", "jsbundling-rails"} {
s.Log.Debug("Test %s in gemfile", name)
hasgem, err := s.Versions.HasGemVersion(name, ">=0.0.0")
if err == nil && hasgem {
s.Log.Debug("Found %s in gemfile", name)
s.needsNode = true
break
}
}
}
return s.needsNode
}
func (s *Supplier) isNodeInstalled() bool {
_, err := s.Command.Output(s.Stager.BuildDir(), "node", "--version")
return err == nil
}
func (s *Supplier) InstallJVM() error {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), ".jdk")); err != nil {
return err
} else if exists {
s.Log.Info("Using pre-installed JDK")
return nil
}
jvmInstallDir := filepath.Join(s.Stager.DepDir(), "jvm")
if err := s.Installer.InstallOnlyVersion("openjdk1.8-latest", jvmInstallDir); err != nil {
return err
}
if err := s.Stager.LinkDirectoryInDepDir(filepath.Join(jvmInstallDir, "bin"), "bin"); err != nil {
return err
}
scriptContents := `
if ! [[ "${JAVA_OPTS}" == *-Xmx* ]]; then
export JAVA_MEM=${JAVA_MEM:--Xmx${JVM_MAX_HEAP:-384}m}
fi
export JAVA_OPTS=${JAVA_OPTS:--Xss512k -XX:+UseCompressedOops -Dfile.encoding=UTF-8}
export JRUBY_OPTS=${JRUBY_OPTS:--Xcompile.invokedynamic=false}
`
return s.Stager.WriteProfileD("jruby.sh", scriptContents)
}
func (s *Supplier) InstallRuby(name, version string) error {
installDir := filepath.Join(s.Stager.DepDir(), name)
if err := s.Installer.InstallDependency(libbuildpack.Dependency{Name: name, Version: version}, installDir); err != nil {
return err
}
if err := s.RewriteShebangs(); err != nil {
return err
}
if err := os.Symlink("ruby", filepath.Join(installDir, "bin", "ruby.exe")); err != nil {
return err
}
return s.Stager.LinkDirectoryInDepDir(filepath.Join(installDir, "bin"), "bin")
}
func (s *Supplier) VendorBundlePath() (string, error) {
bundlerVersion, err := s.Versions.GetBundlerVersion()
if err != nil {
return "", err
}
if strings.HasPrefix(bundlerVersion, "2.") {
return "vendor_bundle", nil
}
engine, err := s.Versions.Engine()
if err != nil {
return "", fmt.Errorf("Unable to determine ruby engine: %s", err)
}
rubyEngineVersion, err := s.Versions.RubyEngineVersion()
if err != nil {
return "", fmt.Errorf("Unable to determine ruby engine version: %s", err)
}
return filepath.Join("vendor_bundle", engine, rubyEngineVersion), nil
}
func (s *Supplier) RewriteShebangs() error {
engine, err := s.Versions.Engine()
if err != nil {
return err
}
files1, err := filepath.Glob(filepath.Join(s.Stager.DepDir(), "bin", "*"))
if err != nil {
return err
}
files2, err := filepath.Glob(filepath.Join(s.Stager.DepDir(), "vendor_bundle", engine, "*", "bin", "*"))
if err != nil {
return err
}
for _, file := range append(files1, files2...) {
if fileInfo, err := os.Stat(file); err != nil {
return err
} else if fileInfo.IsDir() {
continue
}
fileContents, err := ioutil.ReadFile(file)
if err != nil {
return err
}
shebangRegex := regexp.MustCompile(`^#!/.*ruby.*`)
fileContents = shebangRegex.ReplaceAll(fileContents, []byte("#!/usr/bin/env ruby"))
if err := ioutil.WriteFile(file, fileContents, 0755); err != nil {
return err
}
}
return nil
}
func (s *Supplier) SymlinkBundlerIntoRubygems() error {
s.Log.Debug("SymlinkBundlerIntoRubygems")
engine, err := s.Versions.Engine()
if err != nil {
return err
}
rubyEngineVersion, err := s.Versions.RubyEngineVersion()
if err != nil {
return fmt.Errorf("Unable to determine ruby engine: %s", err)
}
bundlerVersion, err := s.Versions.GetBundlerVersion()
if err != nil {
return err
}
destDir := filepath.Join(s.Stager.DepDir(), engine, "lib", "ruby", "gems", rubyEngineVersion, "gems")
if err := os.MkdirAll(destDir, 0755); err != nil {
return err
}
srcDir := filepath.Join(s.Stager.DepDir(), "bundler", "gems", "bundler-"+bundlerVersion)
relPath, err := filepath.Rel(destDir, srcDir)
if err != nil {
return err
}
destFile := filepath.Join(destDir, "bundler-"+bundlerVersion)
if found, err := libbuildpack.FileExists(destFile); err != nil {
return err
} else if found {
s.Log.Debug("Skipping linking bundler since destination exists")
return nil
}
return os.Symlink(relPath, destFile)
}
func (s *Supplier) UpdateRubygems() error {
dep := libbuildpack.Dependency{Name: "rubygems"}
versions := s.Manifest.AllDependencyVersions(dep.Name)
if len(versions) == 0 {
return nil
} else if len(versions) > 1 {
return fmt.Errorf("Too many versions of rubygems in manifest")
}
dep.Version = versions[0]
currVersion, err := s.Command.Output("/", "gem", "--version")
if err != nil {
return fmt.Errorf("Could not determine current version of rubygems: %v", err)
}
currVersion = strings.TrimSpace(currVersion)
if newer, err := s.Versions.VersionConstraint(currVersion, fmt.Sprintf(">= %s", dep.Version)); err != nil {
return fmt.Errorf("Could not parse rubygems version constraint: %s >= %s: %v", currVersion, dep.Version, err)
} else if newer {
return nil
}
if engine, err := s.Versions.Engine(); err != nil {
return err
} else if engine == "jruby" {
s.Log.Debug("Skipping update of rubygems since jruby")
return nil
}
s.Log.BeginStep("Update rubygems from %s to %s", currVersion, dep.Version)
tempDir, err := ioutil.TempDir("", "rubygems")
if err != nil {
return err
}
if err := s.Installer.InstallDependency(dep, tempDir); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(s.Stager.DepDir(), "gem_home"), 0755); err != nil {
return err
}
if output, err := s.Command.Output(tempDir, "ruby", "setup.rb"); err != nil {
s.Log.Error(output)
return fmt.Errorf("Could not install rubygems: %v", err)
}
return nil
}
type IndentedWriter struct {
w io.Writer
pad string
}
func (w *IndentedWriter) Write(p []byte) (n int, err error) {
lines := strings.Split(string(p), "\n")
for i, line := range lines {
lines[i] = w.pad + line
}
p = []byte(strings.Join(lines, "\n"))
return w.Write(p)
}
type LinuxTempDir struct {
Log *libbuildpack.Logger
}
func (t *LinuxTempDir) CopyDirToTemp(dir string) (string, error) {
tempDir, err := ioutil.TempDir("", "app")
if err != nil {
return "", err
}
cmd := exec.Command("cp", "-al", dir, tempDir)
if output, err := cmd.CombinedOutput(); err != nil {
t.Log.Error(string(output))
return "", fmt.Errorf("Could not copy build dir to temp: %v", err)
}
tempDir = filepath.Join(tempDir, filepath.Base(dir))
return tempDir, nil
}
func (s *Supplier) InstallGems() error {
if !s.appHasGemfile {
return nil
}
s.warnBundleConfig()
s.warnWindowsGemfile()
tempDir, err := s.TempDir.CopyDirToTemp(s.Stager.BuildDir())
if err != nil {
return nil
}
gemfileLock, err := filepath.Rel(s.Stager.BuildDir(), s.Versions.Gemfile())
if err != nil {
return nil
}
gemfileLock = fmt.Sprintf("%s.lock", filepath.Join(tempDir, gemfileLock))
if hasFile, err := s.Versions.HasWindowsGemfileLock(); err != nil {
return err
} else if hasFile {
s.Log.Debug("Remove %s", gemfileLock)
s.Log.Warning("Removing `Gemfile.lock` because it was generated on Windows.\nBundler will do a full resolve so native gems are handled properly.\nThis may result in unexpected gem versions being used in your app.\nIf you are using multi buildpacks, subsequent buildpacks may fail.\nIn rare occasions Bundler may not be able to resolve your dependencies at all.\nhttps://docs.cloudfoundry.org/buildpacks/ruby/windows.html")
if err := os.Remove(gemfileLock); err != nil {
return fmt.Errorf("Remove Gemfile.lock: %v", err)
}
}
// Remove .bundle/config && copy if exists
if exists, err := libbuildpack.FileExists(filepath.Join(tempDir, ".bundle", "config")); err != nil {
return err
} else if exists {
os.Remove(filepath.Join(tempDir, ".bundle", "config"))
libbuildpack.CopyFile(filepath.Join(s.Stager.BuildDir(), ".bundle", "config"), filepath.Join(tempDir, ".bundle", "config"))
}
vendorBundlePath, err := s.VendorBundlePath()
if err != nil {
return err
}
cmd := exec.Command("bundle", "config", "set", "path", filepath.Join(s.Stager.DepDir(), vendorBundlePath))
cmd.Dir = tempDir
if err := s.Command.Run(cmd); err != nil {
return err
}
cmd = exec.Command("bundle", "config", "set", "without", os.Getenv("BUNDLE_WITHOUT"))
cmd.Dir = tempDir
if err := s.Command.Run(cmd); err != nil {
return err
}
cmd = exec.Command("bundle", "config", "set", "bin", filepath.Join(s.Stager.DepDir(), "binstubs"))
cmd.Dir = tempDir
if err := s.Command.Run(cmd); err != nil {
return err
}
args := []string{
"install",
"--jobs=4",
"--retry=4",
}
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "vendor", "cache")); err != nil {
return err
} else if exists {
args = append(args, "--local")
}
if exists, err := libbuildpack.FileExists(gemfileLock); err != nil {
return err
} else if exists {
cmd = exec.Command("bundle", "config", "set", "deployment", "true")
cmd.Dir = tempDir
if err := s.Command.Run(cmd); err != nil {
return err
}
}
bundlerVersion, err := s.Versions.GetBundlerVersion()
if err != nil {
return err
}
// Read Gemfile.lock to see if Bundler With version is >2, and not equal to the current bundler version
// See: https://stackoverflow.com/questions/56680065/heroku-installs-bundler-then-throws-error-bundler-2-0-1
if s.appHasGemfileLock {
bundledWithVersion, err := s.Versions.BundledWithVersion()
if err != nil {
return fmt.Errorf("could not read Bundled With version from gemfile.lock: %s", err)
}
if bundledWithVersion != bundlerVersion && strings.HasPrefix(bundledWithVersion, "2") {
if err := s.removeIncompatibleBundledWithVersion(bundledWithVersion); err != nil {
return fmt.Errorf("could not remove Bundled With from end of "+
"gemfile.lock: %s", err)
}
}
}
s.Log.BeginStep("Installing dependencies using bundler %s", bundlerVersion)
s.Log.Info("Running: bundle %s", strings.Join(args, " "))
env := os.Environ()
env = append(env, "NOKOGIRI_USE_SYSTEM_LIBRARIES=true")
cmd = exec.Command("bundle", args...)
cmd.Dir = tempDir
cmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(" "))
cmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(" "))
cmd.Env = env
if err := s.Command.Run(cmd); err != nil {
return err
}
cmd = exec.Command("bundle", "binstubs", "--all", "--force")
cmd.Dir = tempDir
if err := s.Command.Run(cmd); err != nil {
return err
}
if err := s.regenerateBundlerBinStub(tempDir); err != nil {
return err
}
s.Log.Info("Cleaning up the bundler cache.")
cmd = exec.Command("bundle", "clean")
cmd.Dir = tempDir
cmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(" "))
cmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(" "))
cmd.Env = env
if err := s.Command.Run(cmd); err != nil {
return err
}
// Copy binstubs to bin
files, err := ioutil.ReadDir(filepath.Join(s.Stager.DepDir(), "binstubs"))
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("Could not read dep/binstubs directory: %v", err)
}
} else {
for _, file := range files {
target := filepath.Join(s.Stager.DepDir(), "bin", file.Name())
if exists, err := libbuildpack.FileExists(target); err != nil {
return fmt.Errorf("Checking existence: %v", err)
} else if !exists {
source := filepath.Join(s.Stager.DepDir(), "binstubs", file.Name())
if err := libbuildpack.CopyFile(source, target); err != nil {
return fmt.Errorf("CopyFile: %v", err)
}
}
}
}
// Save .bundle/config to global config
if exists, err := libbuildpack.FileExists(filepath.Join(tempDir, ".bundle", "config")); err == nil && exists {
s.Log.Debug("SaveBundleConfig; %s -> %s", filepath.Join(tempDir, ".bundle", "config"), os.Getenv("BUNDLE_CONFIG"))
if err := os.Rename(filepath.Join(tempDir, ".bundle", "config"), os.Getenv("BUNDLE_CONFIG")); err != nil {
return err
}
}
// Save Gemfile.lock for finalize
gemfileLockTarget := filepath.Join(s.Stager.DepDir(), "Gemfile.lock")
if exists, err := libbuildpack.FileExists(gemfileLock); err == nil && exists {
s.Log.Debug("SaveGemfileLock; %s -> %s", gemfileLock, gemfileLockTarget)
if err := libbuildpack.CopyFile(gemfileLock, gemfileLockTarget); err != nil {
return err
}
} else if err != nil {
fmt.Printf("Error checking if Gemfile.lock exists: %v", err)
}
return os.RemoveAll(tempDir)
}
func (s *Supplier) removeIncompatibleBundledWithVersion(bundledWithVersion string) error {
bundlerVersion, err := s.Versions.GetBundlerVersion()
if err != nil {
return err
}
s.Log.Warning(fmt.Sprintf(`Your Gemfile.lock was bundled with bundler %s, which is incompatible with the current bundler version (%s).`, bundledWithVersion, bundlerVersion))
s.Log.Warning(`Deleting "Bundled With" from the Gemfile.lock`)
gemfileLockPath := s.Versions.Gemfile() + ".lock"
file, err := ioutil.ReadFile(gemfileLockPath)
if err != nil {
return fmt.Errorf("failed to read gemfile.lock: %s", err)
}
match := regexp.MustCompile(`BUNDLED WITH\s+(\w|\.|-)+\n`)
output := match.ReplaceAll(file, []byte(""))
return ioutil.WriteFile(gemfileLockPath, output, 0666)
}
func (s *Supplier) regenerateBundlerBinStub(appDir string) error {
s.Log.BeginStep("Regenerating bundler binstubs...")
cmd := exec.Command("bundle", "binstubs", "bundler", "--force", "--path", filepath.Join(s.Stager.DepDir(), "binstubs"))
cmd.Dir = appDir
cmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(" "))
cmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(" "))
if err := s.Command.Run(cmd); err != nil {
return err
}
return libbuildpack.CopyFile(filepath.Join(s.Stager.DepDir(), "binstubs", "bundle"), filepath.Join(s.Stager.DepDir(), "bin", "bundle"))
}
func (s *Supplier) EnableLDLibraryPathEnv() error {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), "ld_library_path")); err != nil {
return err
} else if !exists {
return nil
}
envVar := filepath.Join(s.Stager.BuildDir(), "ld_library_path")
if env := os.Getenv("LD_LIBRARY_PATH"); env != "" {
envVar += ":" + env
}
if err := os.Setenv("LD_LIBRARY_PATH", envVar); err != nil {
return err
}
if err := s.Stager.WriteEnvFile("LD_LIBRARY_PATH", envVar); err != nil {
return err
}
scriptContents := fmt.Sprintf(`export %[1]s="%[2]s$([[ ! -z "${%[1]s:-}" ]] && echo ":$%[1]s")"`, "LD_LIBRARY_PATH", filepath.Join("$HOME", "ld_library_path"))
return s.Stager.WriteProfileD("app_lib_path.sh", scriptContents)
}
func (s *Supplier) CreateDefaultEnv() error {
environmentDefaults := map[string]string{
"RAILS_ENV": "production",
"RACK_ENV": "production",
"RAILS_GROUPS": "assets",
"BUNDLE_WITHOUT": "development:test",
"BUNDLE_GEMFILE": "Gemfile",
"BUNDLE_BIN": filepath.Join(s.Stager.DepDir(), "binstubs"),
"BUNDLE_CONFIG": filepath.Join(s.Stager.DepDir(), "bundle_config"),
"GEM_HOME": filepath.Join(s.Stager.DepDir(), "gem_home"),
"GEM_PATH": strings.Join([]string{
filepath.Join(s.Stager.DepDir(), "bundler"),
filepath.Join(s.Stager.DepDir(), "gem_home"),
}, ":"),
}
return s.writeEnvFiles(environmentDefaults, false)
}
func (s *Supplier) AddPostRubyInstallDefaultEnv(engine string) error {
rubyEngineVersion, err := s.Versions.RubyEngineVersion()
if err != nil {
return err
}
environmentDefaults := map[string]string{
"GEM_PATH": strings.Join([]string{
filepath.Join(s.Stager.DepDir(), "bundler"),
filepath.Join(s.Stager.DepDir(), "vendor_bundle", engine, rubyEngineVersion),
filepath.Join(s.Stager.DepDir(), "gem_home"),
}, ":"),
}
s.Log.Debug("Setting post ruby install env: %v", environmentDefaults)
return s.writeEnvFiles(environmentDefaults, true)
}
func (s *Supplier) AddPostRubyGemsInstallDefaultEnv(engine string) error {
vendorBundlePath, err := s.VendorBundlePath()
if err != nil {
return err
}
environmentDefaults := map[string]string{
"BUNDLE_PATH": filepath.Join(s.Stager.DepDir(), vendorBundlePath),
}
s.Log.Debug("Setting post ruby install env: %v", environmentDefaults)
return s.writeEnvFiles(environmentDefaults, true)
}
func (s *Supplier) writeEnvFiles(environment map[string]string, clobber bool) error {
for envVar, envDefault := range environment {
if os.Getenv(envVar) == "" || clobber {
_ = os.Setenv(envVar, envDefault)
if err := s.Stager.WriteEnvFile(envVar, envDefault); err != nil {
return err
}
}
}
return nil
}
func (s *Supplier) WriteProfileD(engine string) error {
s.Log.BeginStep("Creating runtime environment")
rubyEngineVersion, err := s.Versions.RubyEngineVersion()
if err != nil {
return err
}
vendorBundlePath := "vendor_bundle"
depsIdx := s.Stager.DepsIdx()
scriptContents := fmt.Sprintf(`
export LANG=${LANG:-en_US.UTF-8}
export RAILS_ENV=${RAILS_ENV:-production}
export RACK_ENV=${RACK_ENV:-production}
export RAILS_SERVE_STATIC_FILES=${RAILS_SERVE_STATIC_FILES:-enabled}
export RAILS_LOG_TO_STDOUT=${RAILS_LOG_TO_STDOUT:-enabled}
export GEM_HOME=${GEM_HOME:-$DEPS_DIR/%s/gem_home}
export GEM_PATH=${GEM_PATH:-$DEPS_DIR/%s/vendor_bundle/%s/%s:$DEPS_DIR/%s/gem_home:$DEPS_DIR/%s/bundler}
export BUNDLE_GEMFILE=${BUNDLE_GEMFILE:-$HOME/Gemfile}
export BUNDLE_PATH=$DEPS_DIR/%s/%s
export BUNDLE_BIN=$DEPS_DIR/%s/binstubs
## Change to current DEPS_DIR
bundle config PATH "$DEPS_DIR/%s/%s" > /dev/null
bundle config WITHOUT "%s" > /dev/null
bundle config BIN "$DEPS_DIR/%s/binstubs" > /dev/null
`, depsIdx,
depsIdx, engine, rubyEngineVersion, depsIdx, depsIdx,
depsIdx, vendorBundlePath,
depsIdx,
depsIdx, vendorBundlePath,
os.Getenv("BUNDLE_WITHOUT"),
depsIdx)
if s.appHasGemfile && s.appHasGemfileLock {
hasRails41, err := s.Versions.HasGemVersion("rails", ">=4.1.0.beta1")
if err != nil {
return fmt.Errorf("Could not determine rails version: %v", err)
}
if hasRails41 {
metadata := s.Cache.Metadata()
if metadata.SecretKeyBase == "" {
metadata.SecretKeyBase, err = s.Command.Output(s.Stager.BuildDir(), "bundle", "exec", "rake", "secret")
if err != nil {
return fmt.Errorf("Failed to run 'rake secret': %v", err)
}
metadata.SecretKeyBase = strings.TrimSpace(metadata.SecretKeyBase)
}
scriptContents += fmt.Sprintf("\nexport SECRET_KEY_BASE=${SECRET_KEY_BASE:-%s}\n", metadata.SecretKeyBase)
}
}
return s.Stager.WriteProfileD("ruby.sh", scriptContents)
}
func (s *Supplier) CalcChecksum() (string, error) {
h := md5.New()
basepath := s.Stager.BuildDir()
err := filepath.Walk(basepath, func(path string, info os.FileInfo, err error) error {
if info.Mode().IsRegular() {
relpath, err := filepath.Rel(basepath, path)
if strings.HasPrefix(relpath, ".cloudfoundry/") {
return nil
}
if err != nil {
return err
}
if _, err := io.WriteString(h, relpath); err != nil {
return err
}
if f, err := os.Open(path); err != nil {
return err
} else {
if _, err := io.Copy(h, f); err != nil {
return err
}
}
}
return nil
})
if err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func (s *Supplier) warnWindowsGemfile() {
if body, err := ioutil.ReadFile(s.Versions.Gemfile()); err == nil {
if bytes.Contains(body, []byte("\r\n")) {
s.Log.Warning("Windows line endings detected in Gemfile. Your app may fail to stage. Please use UNIX line endings.")
}
}
}
func (s *Supplier) warnBundleConfig() {
if exists, err := libbuildpack.FileExists(filepath.Join(s.Stager.BuildDir(), ".bundle", "config")); err == nil && exists {
s.Log.Warning("You have the `.bundle/config` file checked into your repository\nIt contains local state like the location of the installed bundle\nas well as configured git local gems, and other settings that should\nnot be shared between multiple checkouts of a single repo. Please\nremove the `.bundle/` folder from your repo and add it to your `.gitignore` file.")