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_helper.go
293 lines (265 loc) · 7.67 KB
/
pg_helper.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
package main
import (
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/heroku/hk/Godeps/_workspace/src/github.com/bgentry/heroku-go"
"github.com/heroku/hk/Godeps/_workspace/src/github.com/mgutz/ansi"
"github.com/heroku/hk/postgresql"
)
// the names of heroku postgres addons vary in dev environments
func hpgAddonName() string {
if e := os.Getenv("SHOGUN"); e != "" {
return "shogun-" + e
}
if e := os.Getenv("HEROKU_POSTGRESQL_ADDON_NAME"); e != "" {
return e
}
return "heroku-postgresql"
}
// addon options that Heroku Postgres needs resolved from database names to
// full postgres URLs
var hpgOptNames = []string{"fork", "follow", "rollback"}
// resolve addon options whose names are in hpgOptNames into their full URLs
func hpgAddonOptResolve(opts *map[string]string, appEnv map[string]string) error {
if opts != nil {
for _, k := range hpgOptNames {
val, ok := (*opts)[k]
if ok && !strings.HasPrefix(val, "postgres://") {
envName := dbNameToPgEnv(val)
url, exists := appEnv[envName]
if !exists {
return fmt.Errorf("could not resolve %s option %q to a %s addon", k, val, hpgAddonName())
}
(*opts)[k] = url
}
}
}
return nil
}
func pgEnvToDBName(key string) string {
return strings.ToLower(strings.Replace(strings.TrimSuffix(key, "_URL"), "_", "-", -1))
}
func dbNameToPgEnv(name string) string {
return ensureSuffix(ensurePrefix(
strings.ToUpper(strings.Replace(name, "-", "_", -1)),
strings.ToUpper(strings.Replace(hpgAddonName()+"_", "-", "_", -1)),
), "_URL")
}
type pgAddonMap struct {
addonToEnv map[string][]string
appConf map[string]string
}
func (p *pgAddonMap) FindAddonFromValue(value string) (key string, ok bool) {
for addonName, envs := range p.addonToEnv {
for _, e := range envs {
if p.appConf[e] == value {
return addonName, true
}
}
}
return "", false
}
func (p *pgAddonMap) FindEnvsFromValue(value string) []string {
addonName, ok := p.FindAddonFromValue(value)
if !ok {
return []string{}
}
return p.addonToEnv[addonName]
}
func newPgAddonMap(addons []heroku.Addon, appConf map[string]string) pgAddonMap {
m := make(map[string][]string)
for _, addon := range addons {
if strings.HasPrefix(addon.Name, hpgAddonName()+"-") {
if len(addon.ConfigVars) > 0 {
m[addon.Name] = addon.ConfigVars
includesDbURL := false
for _, k := range addon.ConfigVars {
if k == "DATABASE_URL" {
includesDbURL = true
}
}
// add DATABASE_URL if it's not already included and the values match
if !includesDbURL && appConf["DATABASE_URL"] == appConf[addon.ConfigVars[0]] {
m[addon.Name] = append([]string{"DATABASE_URL"}, m[addon.Name]...)
}
}
}
}
return pgAddonMap{m, appConf}
}
// Fetches an app's addon list and config, and returns the postgres database
// info (and addon map) for the database specified by addonName. If addonName is
// "", default to whichever addon matches DATABASE_URL, if any.
func mustGetDBInfoAndAddonMap(addonName, appname string) (postgresql.DB, fullDBInfo, pgAddonMap) {
// 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, 1)
go func(appname string) {
if config, err := client.ConfigVarInfo(appname); err != nil {
errch <- err
} else {
confch <- config
}
}(appname)
// list all addons
addons, err := client.AddonList(appname, nil)
must(err)
// we'll need this from a couple places below
var addonMap pgAddonMap
waitForAddonMap := func() {
select {
case appConf = <-confch:
addonMap = newPgAddonMap(addons, appConf)
case err := <-errch:
printFatal(err.Error())
}
}
// locate specific addon
var addon *heroku.Addon
// default to whichever addon is DATABASE_URL if one isn't specified
if addonName == "" {
// block on getting the addon map since we need it to determine which addon
// is the DATABASE_URL
waitForAddonMap()
dbURL := appConf["DATABASE_URL"]
if dbURL == "" {
printFatal("app has no DATABASE_URL, please specify a database name")
}
var ok bool
addonName, ok = addonMap.FindAddonFromValue(dbURL)
if !ok {
printFatal("no addon matches DATABASE_URL")
}
}
for i := range addons {
if addons[i].Name == addonName {
addon = &addons[i]
break
}
}
if addon == nil {
printFatal("addon %s not found", addonName)
}
db := pgclient.NewDB(addon.ProviderId, addon.Plan.Name)
dbi, err := db.Info()
must(err)
if appConf == nil {
waitForAddonMap() // might not have this yet if addonName was "" to start
}
return db, fullDBInfo{Name: addonName, DBInfo: dbi}, addonMap
}
type fullDBInfo struct {
Name string
DBInfo postgresql.DBInfo
Parent *fullDBInfo
Children []*fullDBInfo
}
func (f *fullDBInfo) MaintenanceString() string {
valstr, _ := f.DBInfo.Info.GetString("Maintenance")
if valstr != "" && valstr != "not required" {
return " " + ansi.Color("!!", "red+b") + ansi.ColorCode("reset")
}
return ""
}
// fullDBInfosByName implements sort.Interface for []*fullDBInfo based on the
// Name field.
type fullDBInfosByName []*fullDBInfo
func (f fullDBInfosByName) Len() int { return len(f) }
func (f fullDBInfosByName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f fullDBInfosByName) Less(i, j int) bool { return f[i].Name < f[j].Name }
func sortedDBInfoTree(dbinfos []*fullDBInfo, addonMap pgAddonMap) (result []*fullDBInfo) {
sort.Sort(fullDBInfosByName(dbinfos))
// get all children organized under their parents
for _, info := range dbinfos {
parentName := getResolvedInfoValue(info.DBInfo, "Forked From", &addonMap)
if parentName == "" {
parentName = getResolvedInfoValue(info.DBInfo, "Following", &addonMap)
}
if parentName != "" {
for _, parent := range dbinfos {
if parent.Name == parentName {
parent.Children = append(parent.Children, info)
info.Parent = parent
break
}
}
}
}
// keep items that have no parent
for i := 0; i < len(dbinfos); i++ {
if dbinfos[i].Parent == nil {
result = append(result, dbinfos[i])
}
}
return
}
func printDBTree(w io.Writer, dbinfos []*fullDBInfo, addonMap pgAddonMap) {
for _, info := range dbinfos {
name := info.Name
if info.Parent != nil {
name = printTreeElements(info) + name
}
dburlMarker := " "
if stringsIndex(addonMap.addonToEnv[info.Name], "DATABASE_URL") != -1 {
dburlMarker = "* "
}
status, _ := info.DBInfo.Info.GetString("Status")
listRec(w,
dburlMarker+name,
info.DBInfo.Plan,
strings.ToLower(status)+info.MaintenanceString(),
info.DBInfo.NumConnections,
)
if len(info.Children) > 0 {
printDBTree(w, info.Children, addonMap)
}
}
}
const (
treeMiddleBranch = "├─"
treeLastBranch = "└─"
treeForkSymbol = " ─┤"
treeFollowSymbol = "──>"
treeIndentMiddle = "│ "
treeIndentLast = " "
)
func printTreeElements(info *fullDBInfo) string {
if info == nil || info.Parent == nil {
return ""
}
prefix := ""
for curInfo, p := info, info.Parent; p != nil; curInfo, p = p, p.Parent {
prefix = treePrefix(p, curInfo, prefix == "") + prefix
}
symbol := treeForkSymbol
if info.DBInfo.IsFollower() {
symbol = treeFollowSymbol
}
return prefix + symbol + " "
}
func treePrefix(parent, info *fullDBInfo, firstLevel bool) string {
if parent.Children[len(parent.Children)-1] == info {
// this is the parent's last child
if firstLevel {
return treeLastBranch
}
return treeIndentLast
}
if firstLevel {
return treeMiddleBranch
}
return treeIndentMiddle
}
func getResolvedInfoValue(dbi postgresql.DBInfo, key string, addonMap *pgAddonMap) string {
val, resolve := dbi.Info.GetString(key)
if val != "" && resolve {
if addonName, ok := addonMap.FindAddonFromValue(val); ok {
return addonName
}
}
return val
}