-
Notifications
You must be signed in to change notification settings - Fork 234
/
proxy.go
93 lines (72 loc) · 2.2 KB
/
proxy.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
package redis
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/gql"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/flyutil"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/proxy"
"github.com/superfly/flyctl/terminal"
)
func newProxy() (cmd *cobra.Command) {
const (
long = `Proxy to a Redis database`
short = long
usage = "proxy"
)
cmd = command.New(usage, short, long, runProxy, command.RequireSession)
flag.Add(cmd,
flag.Org(),
flag.Region(),
)
return cmd
}
func runProxy(ctx context.Context) (err error) {
localProxyPort := "16379"
params, password, err := getRedisProxyParams(ctx, localProxyPort)
if err != nil {
return err
}
terminal.Infof("Proxying redis to port \"%s\" with password \"%s\"", localProxyPort, password)
return proxy.Connect(ctx, params)
}
func getRedisProxyParams(ctx context.Context, localProxyPort string) (*proxy.ConnectParams, string, error) {
client := flyutil.ClientFromContext(ctx)
var index int
var options []string
result, err := gql.ListAddOns(ctx, client.GenqClient(), "upstash_redis")
if err != nil {
return nil, "", err
}
databases := result.AddOns.Nodes
for _, database := range databases {
options = append(options, fmt.Sprintf("%s (%s) %s", database.Name, database.PrimaryRegion, database.Organization.Slug))
}
err = prompt.Select(ctx, &index, "Select a database to connect to", "", options...)
if err != nil {
return nil, "", err
}
response, err := gql.GetAddOn(ctx, client.GenqClient(), databases[index].Name, string(gql.AddOnTypeUpstashRedis))
if err != nil {
return nil, "", err
}
database := response.AddOn
agentclient, err := agent.Establish(ctx, client)
if err != nil {
return nil, "", err
}
dialer, err := agentclient.ConnectToTunnel(ctx, database.Organization.Slug, "", false)
if err != nil {
return nil, "", err
}
return &proxy.ConnectParams{
Ports: []string{localProxyPort, "6379"},
OrganizationSlug: database.Organization.Slug,
Dialer: dialer,
RemoteHost: database.PrivateIp,
}, database.Password, nil
}