-
Notifications
You must be signed in to change notification settings - Fork 224
/
rails.go
312 lines (262 loc) · 7.8 KB
/
rails.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
package scanner
import (
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
var healthcheck_channel = make(chan string)
var bundle, ruby string
func configureRails(sourceDir string, config *ScannerConfig) (*SourceInfo, error) {
// `bundle init` will create a file with a commented out rails gem,
// so checking for that can produce a false positive. Look for
// Rails three other ways...
rails := checksPass(sourceDir+"/bin", fileExists("rails")) ||
checksPass(sourceDir, dirContains("config.ru", "Rails")) ||
checksPass(sourceDir, dirContains("Gemfile.lock", " rails "))
if !rails {
return nil, nil
}
// find absolute pat to bundle, ruby executables
// see: https://tip.golang.org/doc/go1.19#os-exec-path
var err error
bundle, err = exec.LookPath("bundle")
if err != nil {
if errors.Is(err, exec.ErrDot) {
bundle, err = filepath.Abs(bundle)
}
if err != nil {
return nil, errors.Wrap(err, "failure finding bundle executable")
}
}
ruby, err = exec.LookPath("ruby")
if err != nil {
if errors.Is(err, exec.ErrDot) {
ruby, err = filepath.Abs(ruby)
}
if err != nil {
return nil, errors.Wrap(err, "failure finding ruby executable")
}
}
// verify that the bundle will install before proceeding
args := []string{"install"}
if checksPass(sourceDir, fileExists("Gemfile.lock")) {
args = append(args, "--quiet")
}
cmd := exec.Command(bundle, args...)
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, errors.Wrap(err, "Failed to install bundle, exiting")
}
s := &SourceInfo{
Family: "Rails",
Callback: RailsCallback,
ConsoleCommand: "/rails/bin/rails console",
}
// don't prompt for pg, redis if litestack is in the Gemfile
if checksPass(sourceDir, dirContains("Gemfile", "litestack")) {
s.SkipDatabase = true
}
// master.key comes with Rails apps from v5.2 onwards, but may not be present
// if the app does not use Rails encrypted credentials. Rails v6 added
// support for multi-environment credentials. Use the Rails searching
// sequence for production credentials to determine the RAILS_MASTER_KEY.
masterKey, err := os.ReadFile("config/credentials/production.key")
if err != nil {
masterKey, err = os.ReadFile("config/master.key")
}
if err == nil {
s.Secrets = []Secret{
{
Key: "RAILS_MASTER_KEY",
Help: "Secret key for accessing encrypted credentials",
Value: string(masterKey),
},
}
} else {
// find absolute path to rake executable
rake, err := exec.LookPath("rake")
if err != nil {
if errors.Is(err, exec.ErrDot) {
rake, err = filepath.Abs(rake)
}
if err != nil {
return nil, errors.Wrap(err, "failure finding rake executable")
}
}
// support Rails 4 through 5.1 applications, or ones that started out
// there and never were fully upgraded.
out, err := exec.Command(rake, "secret").Output()
if err == nil {
s.Secrets = []Secret{
{
Key: "SECRET_KEY_BASE",
Help: "Secret key used to verify the integrity of signed cookies",
Value: strings.TrimSpace(string(out)),
},
}
}
}
s.SkipDeploy = true
s.DeployDocs = `
Your Rails app is prepared for deployment.
Before proceeding, please review the posted Rails FAQ:
https://fly.io/docs/rails/getting-started/dockerfiles/.
Once ready: run 'fly deploy' to deploy your Rails app.
`
// fetch healthcheck route in a separate thread
go func() {
ruby, err := exec.LookPath("ruby")
if err != nil {
healthcheck_channel <- ""
return
}
out, err := exec.Command(ruby, "./bin/rails", "runner",
"puts Rails.application.routes.url_helpers.rails_health_check_path").Output()
if err == nil {
healthcheck_channel <- strings.TrimSpace(string(out))
} else {
healthcheck_channel <- ""
}
}()
return s, nil
}
func RailsCallback(appName string, srcInfo *SourceInfo, options map[string]bool) error {
// install dockerfile-rails gem, if not already included
gemfile, err := os.ReadFile("Gemfile")
if err != nil {
panic(err)
} else if !strings.Contains(string(gemfile), "dockerfile-rails") {
cmd := exec.Command(bundle, "add", "dockerfile-rails",
"--optimistic", "--group", "development", "--skip-install")
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to add dockerfile-rails gem, exiting")
}
cmd = exec.Command(bundle, "install", "--quiet")
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to install dockerfile-rails gem, exiting")
}
}
// ensure Gemfile.lock includes the x86_64-linux platform
if out, err := exec.Command(bundle, "platform").Output(); err == nil {
if !strings.Contains(string(out), "x86_64-linux") {
cmd := exec.Command(bundle, "lock", "--add-platform", "x86_64-linux")
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to add x86_64-linux platform, exiting")
}
}
}
// generate Dockerfile if it doesn't already exist
_, err = os.Stat("Dockerfile")
if errors.Is(err, fs.ErrNotExist) {
flyToml := "fly.toml"
_, err := os.Stat(flyToml)
if os.IsNotExist(err) {
// "touch" fly.toml
file, err := os.Create(flyToml)
if err != nil {
log.Fatal(err)
}
file.Close()
// inform caller of the presence of this file
srcInfo.MergeConfig = &MergeConfigStruct{
Name: flyToml,
Temporary: true,
}
}
args := []string{"./bin/rails", "generate", "dockerfile",
"--label=fly_launch_runtime:rails"}
if options["postgresql"] {
args = append(args, "--postgresql", "--no-prepare")
}
if options["redis"] {
args = append(args, "--redis")
}
cmd := exec.Command(ruby, args...)
cmd.Stdin = nil
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to generate Dockerfile")
}
} else {
if options["postgresql"] && !strings.Contains(string(gemfile), "pg") {
cmd := exec.Command(bundle, "add", "pg")
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to install pg gem")
}
}
if options["redis"] && !strings.Contains(string(gemfile), "redis") {
cmd := exec.Command(bundle, "add", "redis")
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Failed to install redis gem")
}
}
}
// read dockerfile
dockerfile, err := os.ReadFile("Dockerfile")
if err != nil {
return errors.Wrap(err, "Dockerfile not found")
}
// extract port
port := 3000
re := regexp.MustCompile(`(?m)^EXPOSE\s+(?P<port>\d+)`)
m := re.FindStringSubmatch(string(dockerfile))
for i, name := range re.SubexpNames() {
if len(m) > 0 && name == "port" {
port, err = strconv.Atoi(m[i])
if err != nil {
panic(err)
}
}
}
srcInfo.Port = port
// extract volume - handle both plain string and JSON format, but only allow one path
re = regexp.MustCompile(`(?m)^VOLUME\s+(\[\s*")?(\/[\w\/]*?(\w+))("\s*\])?\s*$`)
m = re.FindStringSubmatch(string(dockerfile))
if len(m) > 0 {
srcInfo.Volumes = []Volume{
{
Source: m[3], // last part of path
Destination: m[2], // full path
},
}
}
// extract workdir
workdir := "$"
re = regexp.MustCompile(`(?m).*^WORKDIR\s+(?P<dir>/\S+)`)
m = re.FindStringSubmatch(string(dockerfile))
for i, name := range re.SubexpNames() {
if len(m) > 0 && name == "dir" {
workdir = m[i]
}
}
// add Statics if workdir is found and doesn't contain a variable reference
if !strings.Contains(workdir, "$") {
srcInfo.Statics = []Static{
{
GuestPath: workdir + "/public",
UrlPrefix: "/",
},
}
}
// add HealthCheck (if found)
srcInfo.HttpCheckPath = <-healthcheck_channel
if srcInfo.HttpCheckPath != "" {
srcInfo.HttpCheckHeaders = map[string]string{"X-Forwarded-Proto": "https"}
}
return nil
}