-
Notifications
You must be signed in to change notification settings - Fork 240
/
postgres.go
267 lines (209 loc) · 8.28 KB
/
postgres.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
package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/logrusorgru/aurora"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/cmd/presenters"
"github.com/superfly/flyctl/cmdctx"
"github.com/superfly/flyctl/docstrings"
"github.com/superfly/flyctl/helpers"
"github.com/superfly/flyctl/internal/client"
)
func newPostgresCommand(client *client.Client) *Command {
domainsStrings := docstrings.Get("postgres")
cmd := BuildCommandKS(nil, nil, domainsStrings, client, requireSession)
cmd.Aliases = []string{"pg"}
listStrings := docstrings.Get("postgres.list")
listCmd := BuildCommandKS(cmd, runPostgresList, listStrings, client, requireSession)
listCmd.Args = cobra.MaximumNArgs(1)
createStrings := docstrings.Get("postgres.create")
createCmd := BuildCommandKS(cmd, runCreatePostgresCluster, createStrings, client, requireSession)
createCmd.AddStringFlag(StringFlagOpts{Name: "organization", Description: "the organization that will own the app"})
createCmd.AddStringFlag(StringFlagOpts{Name: "name", Description: "the name of the new app"})
createCmd.AddStringFlag(StringFlagOpts{Name: "region", Description: "the region to launch the new app in"})
createCmd.AddStringFlag(StringFlagOpts{Name: "password", Description: "the superuser password. one will be generated for you if you leave this blank"})
createCmd.AddStringFlag(StringFlagOpts{Name: "volume-size", Description: "the size in GB for volumes"})
createCmd.AddStringFlag(StringFlagOpts{Name: "vm-size", Description: "the size of the VM"})
attachStrngs := docstrings.Get("postgres.attach")
attachCmd := BuildCommandKS(cmd, runAttachPostgresCluster, attachStrngs, client, requireSession, requireAppName)
attachCmd.AddStringFlag(StringFlagOpts{Name: "postgres-app", Description: "the postgres cluster to attach to the app"})
attachCmd.AddStringFlag(StringFlagOpts{Name: "database-name", Description: "database to use, defaults to a new database with the same name as the app"})
attachCmd.AddStringFlag(StringFlagOpts{Name: "variable-name", Description: "the env variable name that will be added to the app. Defaults to DATABASE_URL"})
detachStrngs := docstrings.Get("postgres.detach")
detachCmd := BuildCommandKS(cmd, runDetachPostgresCluster, detachStrngs, client, requireSession, requireAppName)
detachCmd.AddStringFlag(StringFlagOpts{Name: "postgres-app", Description: "the postgres cluster to detach from the app"})
dbStrings := docstrings.Get("postgres.db")
dbCmd := BuildCommandKS(cmd, nil, dbStrings, client, requireSession)
listDBStrings := docstrings.Get("postgres.db.list")
listDBCmd := BuildCommandKS(dbCmd, runListPostgresDatabases, listDBStrings, client, requireSession, requireAppNameAsArg)
listDBCmd.Args = cobra.ExactArgs(1)
usersStrings := docstrings.Get("postgres.users")
usersCmd := BuildCommandKS(cmd, nil, usersStrings, client, requireSession)
usersListStrings := docstrings.Get("postgres.users.list")
usersListCmd := BuildCommandKS(usersCmd, runListPostgresUsers, usersListStrings, client, requireSession, requireAppNameAsArg)
usersListCmd.Args = cobra.ExactArgs(1)
return cmd
}
func runPostgresList(ctx *cmdctx.CmdContext) error {
apps, err := ctx.Client.API().GetApps(api.StringPointer("postgres_cluster"))
if err != nil {
return err
}
if ctx.OutputJSON() {
ctx.WriteJSON(apps)
return nil
}
return ctx.Render(&presenters.Apps{Apps: apps})
}
func runCreatePostgresCluster(ctx *cmdctx.CmdContext) error {
name, _ := ctx.Config.GetString("name")
if name == "" {
n, err := inputAppName("")
if err != nil {
return err
}
name = n
}
orgSlug, _ := ctx.Config.GetString("organization")
org, err := selectOrganization(ctx.Client.API(), orgSlug)
if err != nil {
return err
}
regionCode, _ := ctx.Config.GetString("region")
region, err := selectRegion(ctx.Client.API(), regionCode)
if err != nil {
return err
}
vmSizeName, _ := ctx.Config.GetString("vm-size")
vmSize, err := selectVMSize(ctx.Client.API(), vmSizeName)
if err != nil {
return err
}
volumeSize := ctx.Config.GetInt("volume-size")
if volumeSize == 0 {
s, err := volumeSizeInput(ctx.Client.API(), 10)
if err != nil {
return err
}
volumeSize = s
}
input := api.CreatePostgresClusterInput{
OrganizationID: org.ID,
Name: name,
Region: api.StringPointer(region.Code),
VMSize: api.StringPointer(vmSize.Name),
VolumeSizeGB: api.IntPointer(volumeSize),
}
fmt.Fprintf(ctx.Out, "Creating postgres cluster %s in organization %s\n", name, org.Slug)
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Writer = os.Stderr
s.Prefix = "Launching..."
s.Start()
payload, err := ctx.Client.API().CreatePostgresCluster(input)
if err != nil {
return err
}
s.FinalMSG = fmt.Sprintf("Postgres cluster %s created\n", payload.App.Name)
s.Stop()
fmt.Printf(" Username: %s\n", payload.Username)
fmt.Printf(" Password: %s\n", payload.Password)
fmt.Printf(" Hostname: %s.internal\n", payload.App.Name)
fmt.Printf(" Proxy Port: 5432\n")
fmt.Printf(" PG Port: 5433\n")
fmt.Println(aurora.Italic("Save your credentials in a secure place, you won't be able to see them again!"))
fmt.Println()
cancelCtx := createCancellableContext()
ctx.AppName = payload.App.Name
err = watchDeployment(cancelCtx, ctx)
if isCancelledError(err) {
err = nil
}
if err == nil {
fmt.Println()
fmt.Println(aurora.Bold("Connect to postgres"))
fmt.Printf("Any app within the %s organization can connect to postgres using the above credentials and the hostname \"%s.internal.\"\n", org.Slug, payload.App.Name)
fmt.Printf("For example: postgres://%s:%s@%s.internal:%d\n", payload.Username, payload.Password, payload.App.Name, 5432)
fmt.Println()
fmt.Println("See the postgres docs for more information on next steps, managing postgres, connecting from outside fly: https://fly.io/docs/reference/postgres/")
}
return err
}
func runAttachPostgresCluster(ctx *cmdctx.CmdContext) error {
postgresAppName, _ := ctx.Config.GetString("postgres-app")
appName := ctx.AppName
input := api.AttachPostgresClusterInput{
AppID: appName,
PostgresClusterAppID: postgresAppName,
}
if dbName, _ := ctx.Config.GetString("database-name"); dbName != "" {
input.DatabaseName = api.StringPointer(dbName)
}
if varName, _ := ctx.Config.GetString("variable-name"); varName != "" {
input.VariableName = api.StringPointer(varName)
}
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Writer = os.Stderr
s.Prefix = "Attaching..."
s.Start()
payload, err := ctx.Client.API().AttachPostgresCluster(input)
if err != nil {
return err
}
s.Stop()
fmt.Printf("Postgres cluster %s is now attached to %s\n", payload.PostgresClusterApp.Name, payload.App.Name)
fmt.Printf("The following secret was added to %s:\n %s=%s\n", payload.App.Name, payload.EnvironmentVariableName, payload.ConnectionString)
return nil
}
func runDetachPostgresCluster(ctx *cmdctx.CmdContext) error {
postgresAppName, _ := ctx.Config.GetString("postgres-app")
appName := ctx.AppName
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Writer = os.Stderr
s.Prefix = "Detaching..."
s.Start()
err := ctx.Client.API().DetachPostgresCluster(postgresAppName, appName)
if err != nil {
return err
}
s.FinalMSG = fmt.Sprintf("Postgres cluster %s is now detached from %s\n", postgresAppName, appName)
s.Stop()
return nil
}
func runListPostgresDatabases(ctx *cmdctx.CmdContext) error {
databases, err := ctx.Client.API().ListPostgresDatabases(ctx.AppName)
if err != nil {
return err
}
if ctx.OutputJSON() {
ctx.WriteJSON(databases)
return nil
}
table := helpers.MakeSimpleTable(ctx.Out, []string{"Name", "Users"})
for _, database := range databases {
table.Append([]string{database.Name, strings.Join(database.Users, ",")})
}
table.Render()
return nil
}
func runListPostgresUsers(ctx *cmdctx.CmdContext) error {
users, err := ctx.Client.API().ListPostgresUsers(ctx.AppName)
if err != nil {
return err
}
if ctx.OutputJSON() {
ctx.WriteJSON(users)
return nil
}
table := helpers.MakeSimpleTable(ctx.Out, []string{"Username", "Superuser", "Databases"})
for _, user := range users {
table.Append([]string{user.Username, strconv.FormatBool(user.IsSuperuser), strings.Join(user.Databases, ",")})
}
table.Render()
return nil
}