-
Notifications
You must be signed in to change notification settings - Fork 224
/
attach.go
343 lines (285 loc) · 8.54 KB
/
attach.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 postgres
import (
"context"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/flypg"
"github.com/superfly/flyctl/helpers"
"github.com/superfly/flyctl/internal/app"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/command/apps"
"github.com/superfly/flyctl/internal/flag"
mach "github.com/superfly/flyctl/internal/machine"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/iostreams"
)
type AttachParams struct {
DbName string
AppName string
PgAppName string
DbUser string
VariableName string
Force bool
}
func newAttach() *cobra.Command {
const (
short = "Attach a postgres cluster to an app"
long = short + "\n"
usage = "attach [POSTGRES APP]"
)
cmd := command.New(usage, short, long, runAttach,
command.RequireSession,
command.RequireAppName,
)
cmd.Args = cobra.ExactArgs(1)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.String{
Name: "database-name",
Description: "The designated database name for this consuming app.",
},
flag.String{
Name: "database-user",
Description: "The database user to create. By default, we will use the name of the consuming app.",
},
flag.String{
Name: "variable-name",
Default: "DATABASE_URL",
Description: "The environment variable name that will be added to the consuming app. ",
},
flag.Yes(),
)
return cmd
}
func runAttach(ctx context.Context) error {
var (
pgAppName = flag.FirstArg(ctx)
appName = app.NameFromContext(ctx)
client = client.FromContext(ctx).API()
)
pgApp, err := client.GetAppCompact(ctx, pgAppName)
if err != nil {
return fmt.Errorf("failed retrieving postgres app %s: %w", pgAppName, err)
}
if !pgApp.IsPostgresApp() {
return fmt.Errorf("app %s is not a postgres app", pgAppName)
}
app, err := client.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
// Build context around the postgres app
ctx, err = apps.BuildContext(ctx, pgApp)
if err != nil {
return err
}
params := AttachParams{
AppName: app.Name,
PgAppName: pgApp.Name,
DbName: flag.GetString(ctx, "database-name"),
DbUser: flag.GetString(ctx, "database-user"),
VariableName: flag.GetString(ctx, "variable-name"),
Force: flag.GetBool(ctx, "yes"),
}
switch pgApp.PlatformVersion {
case "machines":
return machineAttachCluster(ctx, params)
case "nomad":
return nomadAttachCluster(ctx, pgApp, params)
default:
return fmt.Errorf("platform is not supported")
}
}
// AttachCluster is mean't to be called from an external package.
func AttachCluster(ctx context.Context, params AttachParams) error {
var (
client = client.FromContext(ctx).API()
pgAppName = params.PgAppName
appName = params.AppName
)
pgApp, err := client.GetAppCompact(ctx, pgAppName)
if err != nil {
return fmt.Errorf("failed retrieving postgres app %s: %w", pgAppName, err)
}
if !pgApp.IsPostgresApp() {
return fmt.Errorf("app %s is not a postgres app", pgAppName)
}
ctx, err = apps.BuildContext(ctx, pgApp)
if err != nil {
return err
}
// Verify that the target app exists.
_, err = client.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
switch pgApp.PlatformVersion {
case "machines":
return machineAttachCluster(ctx, params)
case "nomad":
return nomadAttachCluster(ctx, pgApp, params)
default:
return fmt.Errorf("platform is not supported")
}
}
func nomadAttachCluster(ctx context.Context, pgApp *api.AppCompact, params AttachParams) error {
var (
MinPostgresHaVersion = "0.0.19"
client = client.FromContext(ctx).API()
)
if err := hasRequiredVersionOnNomad(pgApp, MinPostgresHaVersion, MinPostgresHaVersion); err != nil {
return err
}
agentclient, err := agent.Establish(ctx, client)
if err != nil {
return errors.Wrap(err, "can't establish agent")
}
pgInstances, err := agentclient.Instances(ctx, pgApp.Organization.Slug, pgApp.Name)
if err != nil {
return fmt.Errorf("failed to lookup 6pn ip for %s app: %v", pgApp.Name, err)
}
if len(pgInstances.Addresses) == 0 {
return fmt.Errorf("no 6pn ips found for %s app", pgApp.Name)
}
leaderIP, err := leaderIpFromNomadInstances(ctx, pgInstances.Addresses)
if err != nil {
return err
}
return runAttachCluster(ctx, leaderIP, params)
}
func machineAttachCluster(ctx context.Context, params AttachParams) error {
// Minimum image version requirements
var (
MinPostgresHaVersion = "0.0.19"
MinPostgresStandaloneVersion = "0.0.7"
MinPostgresFlexVersion = "0.0.3"
)
machines, err := mach.ListActive(ctx)
if err != nil {
return fmt.Errorf("machines could not be retrieved %w", err)
}
if len(machines) == 0 {
return fmt.Errorf("no active machines found")
}
if err := hasRequiredVersionOnMachines(machines, MinPostgresHaVersion, MinPostgresFlexVersion, MinPostgresStandaloneVersion); err != nil {
return err
}
leader, err := pickLeader(ctx, machines)
if err != nil {
return err
}
return runAttachCluster(ctx, leader.PrivateIP, params)
}
func runAttachCluster(ctx context.Context, leaderIP string, params AttachParams) error {
var (
client = client.FromContext(ctx).API()
dialer = agent.DialerFromContext(ctx)
io = iostreams.FromContext(ctx)
appName = params.AppName
pgAppName = params.PgAppName
dbName = params.DbName
dbUser = params.DbUser
varName = params.VariableName
force = params.Force
)
if dbName == "" {
dbName = appName
}
if dbUser == "" {
dbUser = appName
}
dbUser = strings.ToLower(strings.ReplaceAll(dbUser, "-", "_"))
if varName == "" {
varName = "DATABASE_URL"
}
dbName = strings.ToLower(strings.ReplaceAll(dbName, "-", "_"))
input := api.AttachPostgresClusterInput{
AppID: appName,
PostgresClusterAppID: pgAppName,
ManualEntry: true,
DatabaseName: api.StringPointer(dbName),
DatabaseUser: api.StringPointer(dbUser),
VariableName: api.StringPointer(varName),
}
pgclient := flypg.NewFromInstance(leaderIP, dialer)
fmt.Fprintln(io.Out, "Checking for existing attachments")
secrets, err := client.GetAppSecrets(ctx, input.AppID)
if err != nil {
return err
}
for _, secret := range secrets {
if secret.Name == *input.VariableName {
return fmt.Errorf("consumer app %q already contains a secret named %s", input.AppID, *input.VariableName)
}
}
// Check to see if database exists
dbExists, err := pgclient.DatabaseExists(ctx, *input.DatabaseName)
if err != nil {
return err
}
if dbExists && !force {
confirm := false
msg := fmt.Sprintf("Database %q already exists. Continue with the attachment process?", *input.DatabaseName)
confirm, err := prompt.Confirm(ctx, msg)
if err != nil {
return err
}
if !confirm {
return nil
}
}
// Check to see if user exists
usrExists, err := pgclient.UserExists(ctx, *input.DatabaseUser)
if err != nil {
return err
}
if usrExists {
return fmt.Errorf("database user %q already exists. Please specify a new database user via --database-user", *input.DatabaseUser)
}
fmt.Fprintln(io.Out, "Registering attachment")
// Create attachment
_, err = client.AttachPostgresCluster(ctx, input)
if err != nil {
return err
}
// Create database if it doesn't already exist
if !dbExists {
fmt.Fprintln(io.Out, "Creating database")
err := pgclient.CreateDatabase(ctx, *input.DatabaseName)
if err != nil {
if flypg.ErrorStatus(err) >= 500 {
return err
}
return fmt.Errorf("error running database-create: %w", err)
}
}
// Create user
pwd, err := helpers.RandString(15)
if err != nil {
return err
}
fmt.Fprintln(io.Out, "Creating user")
err = pgclient.CreateUser(ctx, *input.DatabaseUser, pwd, true)
if err != nil {
return fmt.Errorf("failed executing create-user: %w", err)
}
connectionString := fmt.Sprintf(
"postgres://%s:%s@top2.nearest.of.%s.internal:5432/%s?sslmode=disable",
*input.DatabaseUser, pwd, input.PostgresClusterAppID, *input.DatabaseName,
)
s := map[string]string{}
s[*input.VariableName] = connectionString
_, err = client.SetSecrets(ctx, input.AppID, s)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "\nPostgres cluster %s is now attached to %s\n", input.PostgresClusterAppID, input.AppID)
fmt.Fprintf(io.Out, "The following secret was added to %s:\n %s=%s\n", input.AppID, *input.VariableName, connectionString)
return nil
}