-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
234 lines (215 loc) · 5.48 KB
/
main.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
package main
import (
"bufio"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/pkg/errors"
)
type authError struct {
Err error
}
func (e *authError) Error() string {
return "Failed to find AWS Credentials"
}
func (e *authError) Unwrap() error {
return e.Err
}
func requireIntrospectorComposition(ctx context.Context, cli *client.Client) types.Container {
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{
Filters: filters.NewArgs(filters.Arg("label", "introspector-cli")),
})
if err != nil {
panic(err)
}
if len(containers) > 1 {
panic("More than one Introspector CLI found running")
}
if len(containers) == 0 {
panic("Could not find Introspector CLI container running")
}
return containers[0]
}
func loadAwsCredentials(ctx context.Context) (map[string]string, error) {
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return nil, &authError{err}
}
creds, err := cfg.Credentials.Retrieve(ctx)
if err != nil {
return nil, &authError{err}
}
env := make(map[string]string)
env["AWS_ACCESS_KEY_ID"] = creds.AccessKeyID
env["AWS_SECRET_ACCESS_KEY"] = creds.SecretAccessKey
if len(creds.SessionToken) > 0 {
env["AWS_SESSION_TOKEN"] = creds.SessionToken
}
return env, nil
}
func needsAwsCredential(userCmd []string) bool {
for _, token := range userCmd {
if token == "--help" || token == "-h" {
return false
}
}
if len(userCmd) >= 3 {
if userCmd[0] == "account" && userCmd[1] == "aws" && (userCmd[2] == "import" || userCmd[2] == "remap") {
return true
}
}
return false
}
func needsGcpCredential(userCmd []string) bool {
if len(userCmd) >= 3 {
if userCmd[0] == "account" && userCmd[1] == "gcp" && (userCmd[2] == "import" || userCmd[2] == "remap" || userCmd[2] == "credential") {
return true
}
}
return false
}
func runFileCommand(filename string, rest []string) ([]string, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
cmd := []string{"run", string(bytes)}
cmd = append(cmd, rest...)
return cmd, nil
}
func unrollRunCommands(cmd []string) ([][]string, error) {
if len(cmd) < 2 || cmd[0] != "run" {
return [][]string{cmd}, nil
}
queryTarget := cmd[1]
info, err := os.Stat(queryTarget)
if os.IsNotExist(err) {
// Let introspector handle whatever
return [][]string{cmd}, nil
} else if err != nil {
return nil, errors.Wrapf(err, "Failed to stat %v", queryTarget)
}
if info.IsDir() {
infos, err := ioutil.ReadDir(queryTarget)
if err != nil {
return nil, errors.Wrapf(err, "Failed to ReadDir(%v)", queryTarget)
}
cmds := [][]string{}
for _, info := range infos {
if strings.HasSuffix(info.Name(), ".sql") {
filename := filepath.Join(queryTarget, info.Name())
subCommand, err := runFileCommand(filename, cmd[2:])
if err != nil {
return nil, err
}
cmds = append(cmds, subCommand)
}
}
return cmds, nil
}
runCommand, err := runFileCommand(queryTarget, cmd[2:])
if err != nil {
return nil, err
}
return [][]string{runCommand}, nil
}
func cmdPassthrough(ctx context.Context, cli *client.Client, introspector types.Container, userCmd []string) error {
var env map[string]string
cmd := append([]string{"python", "introspector.py"}, userCmd...)
if needsAwsCredential((userCmd)) {
awsEnv, err := loadAwsCredentials(ctx)
if err != nil {
return err
}
env = awsEnv
}
envStrings := []string{}
for key, val := range env {
envStrings = append(envStrings, fmt.Sprintf("%v=%v", key, val))
}
execResp, err := cli.ContainerExecCreate(ctx, introspector.ID, types.ExecConfig{
Cmd: cmd,
WorkingDir: "/app",
AttachStderr: true,
AttachStdout: true,
AttachStdin: true,
Env: envStrings,
})
if err != nil {
return err
}
resp, err := cli.ContainerExecAttach(ctx, execResp.ID, types.ExecStartCheck{})
if err != nil {
return err
}
defer resp.Close()
// read the output
outputDone := make(chan error)
go func() {
// StdCopy demultiplexes the stream into two buffers
_, err = stdcopy.StdCopy(os.Stdout, os.Stderr, resp.Reader)
outputDone <- err
}()
stdin := bufio.NewScanner(os.Stdin)
go func() {
for stdin.Scan() {
resp.Conn.Write(stdin.Bytes())
resp.Conn.Write([]byte("\n"))
}
}()
select {
case err := <-outputDone:
if err != nil {
return err
}
break
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func main() {
cmd := os.Args[1:]
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
_, err = cli.ServerVersion(ctx)
if err != nil {
if client.IsErrConnectionFailed((err)) {
fmt.Println("Cannot find docker server. Is it installed and running?")
os.Exit(1)
}
panic(err)
}
introspector := requireIntrospectorComposition(ctx, cli)
cmds, err := unrollRunCommands(cmd)
if err != nil {
panic(err)
}
for _, cmd := range cmds {
err = cmdPassthrough(ctx, cli, introspector, cmd)
if err != nil {
var authErr *authError
if errors.As(err, &authErr) {
fmt.Println("Failed to find AWS Credentials. Please ensure that your enviroment is correctly configued as described here: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html")
os.Exit(1)
} else {
panic(err)
}
}
}
}