This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
pg.go
356 lines (306 loc) · 9.4 KB
/
pg.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
package main
import (
"fmt"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"text/tabwriter"
"github.com/heroku/hk/Godeps/_workspace/src/github.com/bgentry/heroku-go"
)
var cmdPgList = &Command{
Run: runPgList,
Usage: "pg-list",
NeedsApp: true,
Category: "pg",
Short: "list Heroku Postgres databases" + extra,
Long: `
Pg-list shows the name, plan, state, and connection count for
all Heroku Postgres databases on an app. Forks and followers are
shown in a tree under the database they follow.
The database configured as your DATABASE_URL is indicated with
an asterisk (*). Exclamation marks (!!) indicate databases which
are due for maintenance.
Examples:
$ hk pg-list
* heroku-postgresql-crimson crane available 5
└───> heroku-postgresql-copper ronin available 3
$ hk pg-list
heroku-postgresql-green standard-tengu available 3
* heroku-postgresql-olive standard-tengu available 3
├───> heroku-postgresql-gray standard-tengu available !! 3
├─ ─┤ heroku-postgresql-rose standard-tengu available 3
│ └───> heroku-postgresql-white standard-tengu available 3
└─ ─┤ heroku-postgresql-teal standard-tengu available 3
`,
}
func runPgList(cmd *Command, args []string) {
if len(args) != 0 {
cmd.PrintUsage()
os.Exit(2)
}
appname := mustApp()
// list all addons
addons, err := client.AddonList(appname, nil)
must(err)
// locate Heroku Postgres addons
hpgprefix := hpgAddonName() + "-"
hpgs := make(map[string]*heroku.Addon)
for i := range addons {
if strings.HasPrefix(addons[i].Name, hpgprefix) {
hpgs[addons[i].Name] = &addons[i]
}
}
if len(hpgs) == 0 {
return // no Heroku Postgres databases to list
}
// fetch app's config concurrently in case we need to resolve DB names
var appConf map[string]string
confch := make(chan map[string]string, 1)
errch := make(chan error, len(hpgs)+1)
go func(appname string) {
if config, err := client.ConfigVarInfo(appname); err != nil {
errch <- err
} else {
confch <- config
}
}(appname)
// fetch info for each database concurrently
var dbinfos []*fullDBInfo
dbinfoch := make(chan fullDBInfo, len(hpgs))
for name, addon := range hpgs {
go func(name string, addon *heroku.Addon) {
db := pgclient.NewDB(addon.ProviderId, addon.Plan.Name)
if dbinfo, err := db.Info(); err != nil {
errch <- err
} else {
dbinfoch <- fullDBInfo{Name: name, DBInfo: dbinfo}
}
}(name, addon)
}
// wait for db info repsonses and app config response
for i := 0; i < len(hpgs)+1; i++ {
select {
case err := <-errch:
printFatal(err.Error())
case dbinfo := <-dbinfoch:
dbinfos = append(dbinfos, &dbinfo)
case appConf = <-confch:
}
}
addonMap := newPgAddonMap(addons, appConf)
dbinfos = sortedDBInfoTree(dbinfos, addonMap)
w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
defer w.Flush()
printDBTree(w, dbinfos, addonMap)
}
var cmdPgInfo = &Command{
Run: runPgInfo,
Usage: "pg-info [<dbname>]",
NeedsApp: true,
Category: "pg",
Short: "show Heroku Postgres database info" + extra,
Long: `
Pg-info shows general information about a Heroku Postgres
database. If no dbname is provided, the command defaults to the
app's primary database (DATABASE_URL).
Examples:
$ hk pg-info
Name: heroku-postgresql-crimson
Env Vars: DATABASE_URL, HEROKU_POSTGRESQL_CRIMSON_URL
Plan: Crane
Status: Available
Data Size: 6.3 MB
Tables: 3
PG Version: 9.1.11
Connections: 5
Fork/Follow: Available
Rollback: Unsupported
Created: 2013-11-19 20:40 UTC
Followers: none
Forks: heroku-postgresql-copper
Maintenance: not required
$ hk pg-info heroku-postgresql-crimson
...
$ hk pg-info crimson
...
`,
}
func runPgInfo(cmd *Command, args []string) {
if len(args) > 1 {
cmd.PrintUsage()
os.Exit(2)
}
appname := mustApp()
var addonName string
if len(args) > 0 {
addonName = ensurePrefix(args[0], hpgAddonName()+"-")
}
_, dbi, addonMap := mustGetDBInfoAndAddonMap(addonName, appname)
printPgInfo(addonName, dbi, &addonMap)
}
func printPgInfo(name string, dbi fullDBInfo, addonMap *pgAddonMap) {
w := tabwriter.NewWriter(os.Stdout, 1, 2, 2, ' ', 0)
defer w.Flush()
listRec(w, "Name:", dbi.Name)
envNames := strings.Join(addonMap.FindEnvsFromValue(dbi.DBInfo.ResourceURL), ", ")
listRec(w, "Env Vars:", envNames)
// List info items returned by PG API
for _, ie := range dbi.DBInfo.Info {
if len(ie.Values) == 0 {
listRec(w, ie.Name+":", "none")
} else {
for n, val := range ie.Values {
label := ie.Name + ":"
if n != 0 {
label = ""
}
// try to resolve the value to an addon name if PG API says we should
if ie.ResolveDBName {
valstr := val.(string)
if addonName, ok := addonMap.FindAddonFromValue(valstr); ok {
// resolved it to an addon name, print that instead
valstr = addonName
} else {
// Couldn't resolve to an addon name. Try to parse the URL so we
// can display only its Host and Path (without creds).
if u, err := url.Parse(valstr); err == nil && u.User != nil {
valstr = u.Host + u.Path
}
}
listRec(w, label, valstr)
continue
}
listRec(w, label, val)
}
}
}
}
var cmdPgUnfollow = &Command{
Run: runPgUnfollow,
Usage: "pg-unfollow <dbname>",
NeedsApp: true,
Category: "pg",
Short: "stop a replica postgres database from following" + extra,
Long: `
Pg-unfollow stops a Heroku Postgres database follower from
following, turning it into a read/write database. The command
will prompt for confirmation, or accept confirmation via stdin.
Examples:
$ hk pg-unfollow heroku-postgresql-blue
warning: heroku-postgresql-blue on myapp will permanently stop following heroku-postgresql-red.
warning: This cannot be undone. Please type "heroku-postgresql-blue" to continue:
> heroku-postgresql-blue
Unfollowed heroku-postgresql-blue on myapp.
$ hk pg-unfollow blue
warning: heroku-postgresql-blue on myapp will permanently stop following heroku-postgresql-red.
warning: This cannot be undone. Please type "blue" to continue:
> blue
Unfollowed heroku-postgresql-blue on myapp.
$ echo blue | hk pg-unfollow blue
Unfollowed heroku-postgresql-blue on myapp.
`,
}
func runPgUnfollow(cmd *Command, args []string) {
if len(args) != 1 {
cmd.PrintUsage()
os.Exit(2)
}
appname := mustApp()
addonName := ensurePrefix(args[0], hpgAddonName()+"-")
db, dbi, addonMap := mustGetDBInfoAndAddonMap(addonName, appname)
if !dbi.DBInfo.IsFollower() {
printFatal("%s is not following another database.", addonName)
}
parentName := getResolvedInfoValue(dbi.DBInfo, "Following", &addonMap)
printWarning("%s on %s will permanently stop following %s.", addonName, appname, parentName)
warning := fmt.Sprintf("This cannot be undone. Please type %q to continue:", args[0])
mustConfirm(warning, args[0])
must(db.Unfollow())
fmt.Printf("Unfollowed %s on %s.\n", addonName, appname)
}
var commandNamePsql string
var cmdPsql = &Command{
Run: runPsql,
Usage: "psql [-c <command>] [<dbname>]",
NeedsApp: true,
Category: "pg",
Short: "open a psql shell to a Heroku Postgres database" + extra,
Long: `
Psql opens a PostgreSQL shell to a Heroku Postgres database
using the locally-installed psql command.
Examples:
$ hk psql
psql (9.3.1, server 9.1.11)
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
Type "help" for help.
d1234abcdefghi=>
$ hk psql crimson
...
$ hk psql heroku-postgresql-crimson
...
`,
}
func init() {
cmdPsql.Flag.StringVarP(&commandNamePsql, "command", "c", "", "SQL command to run")
}
func runPsql(cmd *Command, args []string) {
if len(args) > 1 {
cmd.PrintUsage()
os.Exit(2)
}
configName := "DATABASE_URL"
if len(args) == 1 {
configName = dbNameToPgEnv(args[0])
}
appname := mustApp()
// Make sure psql is installed
if _, err := exec.LookPath("psql"); err != nil {
printFatal("Local psql command not found. For help installing psql, see http://devcenter.heroku.com/articles/local-postgresql")
}
// fetch app's config to get the URL
config, err := client.ConfigVarInfo(appname)
must(err)
// get URL
urlstr, exists := config[configName]
if !exists {
printFatal("Env %s not found", configName)
}
u, err := url.Parse(urlstr)
if err != nil {
printFatal("Invalid URL at env " + configName)
}
// handle custom port
hostname := u.Host
portnum := 5432
if colIndex := strings.Index(u.Host, ":"); colIndex != -1 {
hostname = u.Host[:colIndex]
portnum, err = strconv.Atoi(u.Host[colIndex+1:])
if err != nil {
printFatal("Invalid port in %s: %s", configName, u.Host[colIndex+1:])
}
}
if u.User == nil || u.User.Username() == "" {
printFatal("Missing credentials in %s", configName)
}
// construct and run psql command
psqlArgs := []string{
"psql",
"-U", u.User.Username(),
"-h", hostname,
"-p", strconv.Itoa(portnum),
}
if commandNamePsql != "" {
psqlArgs = append(psqlArgs, "-c")
psqlArgs = append(psqlArgs, commandNamePsql)
}
psqlArgs = append(psqlArgs, u.Path[1:])
pgenv := os.Environ()
pass, _ := u.User.Password()
pgenv = append(pgenv, "PGPASSWORD="+pass)
pgenv = append(pgenv, "PGSSLMODE=require")
if err := runCommand("psql", psqlArgs, pgenv); err != nil {
printFatal("Error running psql: %s", err)
}
}