-
Notifications
You must be signed in to change notification settings - Fork 224
/
flapsutil.go
78 lines (66 loc) · 2.13 KB
/
flapsutil.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
package flapsutil
import (
"context"
"fmt"
"net"
"net/url"
"os"
"strings"
fly "github.com/superfly/fly-go"
"github.com/superfly/fly-go/flaps"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/internal/buildinfo"
"github.com/superfly/flyctl/internal/config"
)
func NewClientWithOptions(ctx context.Context, opts flaps.NewClientOpts) (*flaps.Client, error) {
// Connect over wireguard depending on FLAPS URL.
if strings.TrimSpace(strings.ToLower(os.Getenv("FLY_FLAPS_BASE_URL"))) == "peer" {
orgSlug, err := resolveOrgSlugForApp(ctx, opts.AppCompact, opts.AppName)
if err != nil {
return nil, fmt.Errorf("failed to resolve org for app '%s': %w", opts.AppName, err)
}
client := fly.ClientFromContext(ctx)
agentclient, err := agent.Establish(ctx, client)
if err != nil {
return nil, fmt.Errorf("error establishing agent: %w", err)
}
dialer, err := agentclient.Dialer(ctx, orgSlug)
if err != nil {
return nil, fmt.Errorf("flaps: can't build tunnel for %s: %w", orgSlug, err)
}
opts.DialContext = dialer.DialContext
flapsBaseUrlString := fmt.Sprintf("http://[%s]:4280", resolvePeerIP(dialer.State().Peer.Peerip))
if opts.BaseURL, err = url.Parse(flapsBaseUrlString); err != nil {
return nil, fmt.Errorf("failed to parse flaps url '%s' with error: %w", flapsBaseUrlString, err)
}
}
if opts.UserAgent == "" {
opts.UserAgent = buildinfo.UserAgent()
}
if opts.Tokens == nil {
opts.Tokens = config.Tokens(ctx)
}
return flaps.NewWithOptions(ctx, opts)
}
func resolveOrgSlugForApp(ctx context.Context, app *fly.AppCompact, appName string) (string, error) {
app, err := resolveApp(ctx, app, appName)
if err != nil {
return "", err
}
return app.Organization.Slug, nil
}
func resolveApp(ctx context.Context, app *fly.AppCompact, appName string) (*fly.AppCompact, error) {
var err error
if app == nil {
client := fly.ClientFromContext(ctx)
app, err = client.GetAppCompact(ctx, appName)
}
return app, err
}
func resolvePeerIP(ip string) string {
peerIP := net.ParseIP(ip)
var natsIPBytes [16]byte
copy(natsIPBytes[0:], peerIP[0:6])
natsIPBytes[15] = 3
return net.IP(natsIPBytes[:]).String()
}