-
Notifications
You must be signed in to change notification settings - Fork 240
/
cmd.go
106 lines (85 loc) · 2.44 KB
/
cmd.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
package flypg
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/internal/command/ssh"
"github.com/superfly/flyctl/iostreams"
)
type updateRequest struct {
PGParameters map[string]string `json:"pgParameters,omitempty"`
}
type commandResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Data string `json:"data"`
}
type Command struct {
ctx context.Context
app *api.AppCompact
dialer agent.Dialer
io *iostreams.IOStreams
}
func NewCommand(ctx context.Context, app *api.AppCompact) (*Command, error) {
client := client.FromContext(ctx).API()
agentclient, err := agent.Establish(ctx, client)
if err != nil {
return nil, fmt.Errorf("error establishing agent: %w", err)
}
dialer, err := agentclient.Dialer(ctx, app.Organization.Slug)
if err != nil {
return nil, fmt.Errorf("ssh: can't build tunnel for %s: %s", app.Organization.Slug, err)
}
return &Command{
ctx: ctx,
app: app,
dialer: dialer,
io: iostreams.FromContext(ctx),
}, nil
}
func (pc *Command) UpdateSettings(ctx context.Context, leaderIp string, config map[string]string) error {
payload := updateRequest{PGParameters: config}
configBytes, err := json.Marshal(payload)
if err != nil {
return err
}
subCmd := fmt.Sprintf("update --patch '%s'", string(configBytes))
cmd := fmt.Sprintf("stolonctl-run %s", encodeCommand(subCmd))
resp, err := ssh.RunSSHCommand(ctx, pc.app, pc.dialer, leaderIp, cmd)
if err != nil {
return err
}
var result commandResponse
if err := json.Unmarshal(resp, &result); err != nil {
return err
}
if !result.Success {
return fmt.Errorf(result.Message)
}
return nil
}
func (pc *Command) UnregisterMember(ctx context.Context, leaderIP string, standbyIP string) error {
payload := encodeCommand(standbyIP)
cmd := fmt.Sprintf("pg_unregister %s", payload)
resp, err := ssh.RunSSHCommand(ctx, pc.app, pc.dialer, leaderIP, cmd)
if err != nil {
return err
}
var result commandResponse
if err := json.Unmarshal(resp, &result); err != nil {
return err
}
if !result.Success {
return fmt.Errorf(result.Message)
}
return nil
}
// encodeCommand will base64 encode a command string so it can be passed
// in with exec.Command.
func encodeCommand(command string) string {
return base64.StdEncoding.Strict().EncodeToString([]byte(command))
}