-
Notifications
You must be signed in to change notification settings - Fork 160
/
finalize.go
419 lines (358 loc) · 11.7 KB
/
finalize.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
package finalize
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/cloudfoundry/libbuildpack"
"github.com/kr/text"
)
type Stager interface {
BuildDir() string
DepsIdx() string
DepDir() string
}
type Command interface {
Run(*exec.Cmd) error
}
type Finalizer struct {
Stager Stager
Versions Versions
Log *libbuildpack.Logger
Command Command
Gem12Factor bool
GemStaticAssets bool
GemStdoutLogging bool
RailsVersion int
}
func Run(f *Finalizer) error {
f.Log.BeginStep("Finalizing Ruby")
gemfileName := "Gemfile"
if os.Getenv("BUNDLE_GEMFILE") != "" {
gemfileName = os.Getenv("BUNDLE_GEMFILE")
}
if err := f.AssertGemfileLockExists(gemfileName); err != nil {
f.Log.Error(err.Error())
return err
}
if err := f.Setup(); err != nil {
f.Log.Error("Error determining versions: %v", err)
return err
}
if err := f.RestoreGemfileLock(gemfileName); err != nil {
f.Log.Error("Error copying Gemfile.lock to app: %v", err)
return err
}
if err := f.RestoreBundleConfig(); err != nil {
f.Log.Error("Error copying .bundle/config to app: %v", err)
return err
}
if err := f.InstallPlugins(); err != nil {
f.Log.Error("Error installing plugins: %v", err)
return err
}
if err := f.WriteDatabaseYml(); err != nil {
f.Log.Error("Error writing database.yml: %v", err)
return err
}
f.BestPracticeWarnings()
if err := f.DeleteVendorBundle(); err != nil {
f.Log.Error("Error deleting vendor/bundle: %v", err)
return err
}
if err := f.CopyToAppBin(); err != nil {
f.Log.Error("Error creating files in bin: %v", err)
return err
}
if err := f.PrecompileAssets(); err != nil {
f.Log.Error("Error precompiling assets: %v", err)
return err
}
data, err := f.GenerateReleaseYaml()
if err != nil {
f.Log.Error("Error generating release YAML: %v", err)
return err
}
releasePath := filepath.Join(f.Stager.BuildDir(), "tmp", "ruby-buildpack-release-step.yml")
if err := libbuildpack.NewYAML().Write(releasePath, data); err != nil {
f.Log.Error("Error writing release YAML: %v", err)
return err
}
return nil
}
func (f *Finalizer) Setup() error {
var err error
f.Gem12Factor, err = f.Versions.HasGem("rails_12factor")
if err != nil {
return err
}
f.GemStdoutLogging, err = f.Versions.HasGem("rails_stdout_logging")
if err != nil {
return err
}
f.GemStaticAssets, err = f.Versions.HasGem("rails_serve_static_assets")
if err != nil {
return err
}
f.RailsVersion, err = f.Versions.GemMajorVersion("rails")
if err != nil {
return err
}
return nil
}
func (f *Finalizer) AssertGemfileLockExists(gemfileName string) error {
if exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), fmt.Sprintf("%s.lock", gemfileName))); err != nil {
return err
} else if !exists {
return errors.New(fmt.Sprintf("%s.lock required", gemfileName))
}
return nil
}
func (f *Finalizer) RestoreGemfileLock(gemfileName string) error {
source := filepath.Join(f.Stager.DepDir(), fmt.Sprintf("%s.lock", gemfileName))
f.Log.Debug("Restore GemfileLock; %s", source)
if exists, err := libbuildpack.FileExists(source); err != nil {
return err
} else if exists {
target := filepath.Join(f.Stager.BuildDir(), fmt.Sprintf("%s.lock", gemfileName))
f.Log.Debug("RestoreGemfileLock; exists, copy to %s", target)
return os.Rename(source, target)
}
return nil
}
func (f *Finalizer) RestoreBundleConfig() error {
source := filepath.Join(f.Stager.DepDir(), "bundle_config")
f.Log.Debug("RestoreBundleConfig; %s", source)
if exists, err := libbuildpack.FileExists(source); err != nil {
return err
} else if exists {
target := filepath.Join(f.Stager.BuildDir(), ".bundle", "config")
f.Log.Debug("RestoreBundleConfig; exists, copy to %s", target)
os.MkdirAll(filepath.Join(f.Stager.BuildDir(), ".bundle"), 0755)
return os.Rename(source, target)
}
return nil
}
func (f *Finalizer) WriteDatabaseYml() error {
if exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), "config")); err != nil {
return err
} else if !exists {
return nil
}
if rails41Plus, err := f.Versions.HasGemVersion("activerecord", ">=4.1.0.beta"); err != nil {
return fmt.Errorf("Error in determining Gem version: %v", err)
} else if rails41Plus {
return nil
}
f.Log.BeginStep("Writing config/database.yml to read from DATABASE_URL")
if err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), "config", "database.yml"), []byte(config_database_yml), 0644); err != nil {
return err
}
return nil
}
func (f *Finalizer) databaseUrl() string {
if os.Getenv("DATABASE_URL") != "" {
return os.Getenv("DATABASE_URL")
}
gems := map[string]string{
"pg": "postgres",
"jdbc-postgres": "postgres",
"mysql": "mysql",
"mysql2": "mysql2",
"sqlite3": "sqlite3",
"sqlite3-ruby": "sqlite3",
}
scheme := ""
for k, v := range gems {
if a, err := f.Versions.HasGem(k); err == nil && a {
if err != nil {
fmt.Printf("Err in HasGem: %v", err)
}
scheme = v
break
}
}
return fmt.Sprintf("%s://user:pass@127.0.0.1/dbname", scheme)
}
func (f *Finalizer) hasPrecompiledAssets() (bool, error) {
globs := []string{".sprockets-manifest-*.json", "manifest-*.json"}
if f.RailsVersion < 4 {
globs = []string{"manifest.yml"}
}
for _, glob := range globs {
if matches, err := filepath.Glob(filepath.Join(f.Stager.BuildDir(), "public", "assets", glob)); err != nil {
return false, err
} else if len(matches) > 0 {
return true, nil
}
}
return false, nil
}
func (f *Finalizer) PrecompileAssets() error {
if exists, err := f.hasPrecompiledAssets(); err != nil {
return err
} else if exists {
f.Log.Info("Detected assets manifest file, assuming assets were compiled locally")
return nil
}
cmd := exec.Command("bundle", "exec", "rake", "-n", "assets:precompile")
cmd.Dir = f.Stager.BuildDir()
if err := f.Command.Run(cmd); err != nil {
return nil
}
env := append(os.Environ(), fmt.Sprintf("DATABASE_URL=%s", f.databaseUrl()))
if _, exists := os.LookupEnv("SECRET_KEY_BASE"); !exists {
env = append(env, "SECRET_KEY_BASE=dummy-staging-key")
}
f.Log.BeginStep("Precompiling assets")
startTime := time.Now()
cmd = exec.Command("bundle", "exec", "rake", "assets:precompile")
cmd.Dir = f.Stager.BuildDir()
cmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(" "))
cmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(" "))
cmd.Env = env
err := f.Command.Run(cmd)
if err != nil {
return err
}
f.Log.Info("Asset precompilation completed (%v)", time.Since(startTime))
if f.RailsVersion >= 4 {
cleanCmd := exec.Command("bundle", "exec", "rake", "-n", "assets:clean")
cleanCmd.Dir = f.Stager.BuildDir()
if err := f.Command.Run(cleanCmd); err != nil {
return nil
}
f.Log.Info("Cleaning assets")
cmd = exec.Command("bundle", "exec", "rake", "assets:clean")
cmd.Dir = f.Stager.BuildDir()
cmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(" "))
cmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(" "))
cmd.Env = env
err = f.Command.Run(cmd)
}
return err
}
func (f *Finalizer) InstallPlugins() error {
if f.Gem12Factor {
return nil
}
if f.RailsVersion == 4 {
if !(f.GemStdoutLogging && f.GemStaticAssets) {
f.Log.Protip("Include 'rails_12factor' gem to enable all platform features", "https://devcenter.heroku.com/articles/rails-integration-gems")
}
return nil
}
if f.RailsVersion == 2 || f.RailsVersion == 3 {
if err := f.installPluginStdoutLogger(); err != nil {
return err
}
if err := f.installPluginServeStaticAssets(); err != nil {
return err
}
}
return nil
}
func (f *Finalizer) installPluginStdoutLogger() error {
if f.GemStdoutLogging {
return nil
}
f.Log.BeginStep("Injecting plugin 'rails_log_stdout'")
code := `
begin
STDOUT.sync = true
def Rails.cloudfoundry_stdout_logger
logger = Logger.new(STDOUT)
logger = ActiveSupport::TaggedLogging.new(logger) if defined?(ActiveSupport::TaggedLogging)
level = ENV['LOG_LEVEL'].to_s.upcase
level = 'INFO' unless %w[DEBUG INFO WARN ERROR FATAL UNKNOWN].include?(level)
logger.level = Logger.const_get(level)
logger
end
Rails.logger = Rails.application.config.logger = Rails.cloudfoundry_stdout_logger
rescue Exception => ex
puts %Q{WARNING: Exception during rails_log_stdout init: #{ex.message}}
end
`
if err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), "vendor", "plugins", "rails_log_stdout"), 0755); err != nil {
return fmt.Errorf("Error creating rails_log_stdout plugin directory: %v", err)
}
if err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), "vendor", "plugins", "rails_log_stdout", "init.rb"), []byte(code), 0644); err != nil {
return fmt.Errorf("Error writing rails_log_stdout plugin file: %v", err)
}
return nil
}
func (f *Finalizer) installPluginServeStaticAssets() error {
if f.GemStaticAssets {
return nil
}
f.Log.BeginStep("Injecting plugin 'rails3_serve_static_assets'")
code := "Rails.application.class.config.serve_static_assets = true\n"
if err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), "vendor", "plugins", "rails3_serve_static_assets"), 0755); err != nil {
return fmt.Errorf("Error creating rails3_serve_static_assets plugin directory: %v", err)
}
if err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), "vendor", "plugins", "rails3_serve_static_assets", "init.rb"), []byte(code), 0644); err != nil {
return fmt.Errorf("Error writing rails3_serve_static_assets plugin file: %v", err)
}
return nil
}
func (f *Finalizer) BestPracticeWarnings() {
if os.Getenv("RAILS_ENV") != "production" {
f.Log.Warning("You are deploying to a non-production environment: %s", os.Getenv("RAILS_ENV"))
}
}
func (f *Finalizer) DeleteVendorBundle() error {
if exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), "vendor", "bundle")); err != nil {
return err
} else if exists {
f.Log.Warning("Removing `vendor/bundle`.\nChecking in `vendor/bundle` is not supported. Please remove this directory and add it to your .gitignore. To vendor your gems with Bundler, use `bundle pack` instead.")
return os.RemoveAll(filepath.Join(f.Stager.BuildDir(), "vendor", "bundle"))
}
return nil
}
func (f *Finalizer) CopyToAppBin() error {
f.Log.BeginStep("Copy binaries to app/bin directory")
binDir := filepath.Join(f.Stager.BuildDir(), "bin")
if err := os.MkdirAll(binDir, 0755); err != nil {
return fmt.Errorf("Could not create /app/bin directory: %v", err)
}
files, err := ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), "binstubs"))
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("Could not read dep/binstubs directory: %v", err)
}
files = []os.FileInfo{}
}
for _, file := range files {
source := filepath.Join(f.Stager.DepDir(), "binstubs", file.Name())
target := filepath.Join(binDir, file.Name())
if exists, err := libbuildpack.FileExists(target); err != nil {
return fmt.Errorf("Checking existence: %v", err)
} else if !exists {
if err := libbuildpack.CopyFile(source, target); err != nil {
return fmt.Errorf("CopyFile: %v", err)
}
}
}
files, err = ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), "bin"))
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("Could not read dep/bin directory: %v", err)
}
files = []os.FileInfo{}
}
for _, file := range files {
target := filepath.Join(binDir, file.Name())
if exists, err := libbuildpack.FileExists(target); err != nil {
return fmt.Errorf("Checking existence: %v", err)
} else if !exists {
contents := fmt.Sprintf("#!/usr/bin/env ruby\nKernel.exec \"#{ENV['DEPS_DIR']}/%s/bin/%s\", *ARGV\n", f.Stager.DepsIdx(), file.Name())
if err := ioutil.WriteFile(target, []byte(contents), 0755); err != nil {
return fmt.Errorf("WriteFile: %v", err)
}
}
}
return nil
}