-
Notifications
You must be signed in to change notification settings - Fork 223
/
diag.go
262 lines (214 loc) · 5.44 KB
/
diag.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
package diag
import (
"archive/zip"
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/spf13/cobra"
"github.com/superfly/flyctl/internal/build/imgsrc"
"github.com/superfly/flyctl/internal/buildinfo"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/config"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/flyutil"
"github.com/superfly/flyctl/internal/state"
"github.com/superfly/flyctl/iostreams"
)
var urlrx = regexp.MustCompile(`https://.*?/[0-9]+/([a-z0-9-]+).zip\\?`)
func New() (cmd *cobra.Command) {
var (
short = `Send diagnostic information about your applications back to Fly.io.`
long = `Send diagnostic information about your applications back to Fly.io,
to help diagnose problems.
This command will collect some local system information and a few files
that you'd be sending us anyways in order to deploy, notably any Dockerfiles
you might have associated with this application.
`
)
cmd = command.New("diag", short, long, Run,
command.RequireSession,
command.LoadAppNameIfPresent,
)
cmd.Args = cobra.NoArgs
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.Bool{
Name: "force",
Default: false,
Description: "Send diagnostics even if we can't find your local Fly.io app",
},
)
return
}
func Run(ctx context.Context) (err error) {
var (
isForce = flag.GetBool(ctx, "force")
ios = iostreams.FromContext(ctx)
color = ios.ColorScheme()
)
_, err = os.Stat("./fly.toml")
if err != nil && !isForce {
fmt.Printf(`Can't find "fly.toml" in your local directory.
Run this command from your app's local directory, or
add the --force flag to send us best-effort diagnostics.`)
return err
}
fts := []struct {
name string
fn func(context.Context, *zip.Writer) error
expect bool
}{
{"fly.toml", fetchFlyToml, true},
{"config.yml", fetchConfigYaml, true},
{"Dockerfile", fetchDockerfile, false},
{"fly agent logs", fetchAgentLogs, false},
{"local diagnostics", fetchLocalDiag, true},
}
zbuf := &bytes.Buffer{}
zip := zip.NewWriter(zbuf)
for _, ft := range fts {
fmt.Printf("Collecting %s... ", ft.name)
if err = ft.fn(ctx, zip); err != nil {
if ft.expect {
fmt.Printf(color.Red(fmt.Sprintf("FAILED: %s\n", err)))
} else {
fmt.Printf("skipping\n")
}
} else {
fmt.Printf(color.Green("ok\n"))
}
}
zip.Close()
client := flyutil.ClientFromContext(ctx)
url, err := client.CreateDoctorUrl(context.Background())
if err != nil {
return fmt.Errorf("create doctor URL: %w", err)
}
m := urlrx.FindStringSubmatch(url)
if m == nil {
return fmt.Errorf("malformed S3 URL (this is a bug, tell us)")
}
req, err := http.NewRequest(http.MethodPut, url, zbuf)
if err != nil {
return fmt.Errorf("request doctor URL: %w", err)
}
req.Header.Set("Content-Type", "application/zip")
_, err = http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("put archive to doctor URL: %w", err)
}
fmt.Printf("\nYour Diagnostic Code (safe to share): %s\n", m[1])
return nil
}
func cp(z *zip.Writer, name string, f io.Reader) error {
zf, err := z.Create(name)
if err != nil {
return err
}
_, err = io.Copy(zf, f)
return err
}
func fetchFlyToml(ctx context.Context, z *zip.Writer) error {
f, err := os.Open("fly.toml")
if err != nil {
return err
}
defer f.Close()
return cp(z, "fly.toml", f)
}
func grepv(r io.Reader, excludes []string) *bytes.Buffer {
buf := &bytes.Buffer{}
rdr := bufio.NewReader(r)
for {
line, err := rdr.ReadString('\n')
if err != nil {
break
}
exclude := false
for _, xcl := range excludes {
if strings.Contains(line, xcl) {
exclude = true
break
}
}
if !exclude {
buf.WriteString(line)
}
}
return buf
}
func fetchConfigYaml(ctx context.Context, z *zip.Writer) error {
path := filepath.Join(state.ConfigDirectory(ctx), config.FileName)
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return cp(z, "config.yml", grepv(f, []string{"_token:", "private"}))
}
func fetchAgentLogs(ctx context.Context, z *zip.Writer) error {
logs, err := filepath.Glob(fmt.Sprintf("%s/.fly/agent-logs/*.log", os.Getenv("HOME")))
if err != nil {
// swallow this error, agent logs are best-effort
return nil
}
for _, logfile := range logs {
f, err := os.Open(logfile)
if err != nil {
continue
}
cp(z, "agent/"+path.Base(logfile),
grepv(f, []string{"private", "password" /* who knows, whatever */}))
}
return nil
}
func fetchDockerfile(ctx context.Context, z *zip.Writer) error {
f, err := os.Open("Dockerfile")
if err != nil {
return err
}
defer f.Close()
return cp(z, "Dockerfile", f)
}
func fetchLocalDiag(ctx context.Context, z *zip.Writer) error {
diags := map[string]interface{}{}
diags["version"] = buildinfo.Info()
client, err := imgsrc.NewLocalDockerClient()
if err == nil {
_, err = client.Ping(ctx)
}
if err == nil {
diags["docker"] = "present"
} else {
diags["docker"] = err.Error()
}
if _, err = os.Stat("fly.toml"); err == nil {
var size int64
err = filepath.Walk(".", func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
diags["treesize"] = size
if err != nil {
diags["tree_errs"] = err.Error()
}
}
buf := &bytes.Buffer{}
json.NewEncoder(buf).Encode(diags)
return cp(z, "diag.json", buf)
}