-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathsupport.go
More file actions
1235 lines (1100 loc) · 35.1 KB
/
Copy pathsupport.go
File metadata and controls
1235 lines (1100 loc) · 35.1 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package support
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"path"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/mod/semver"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"tailscale.com/ipn/ipnstate"
"tailscale.com/net/netcheck"
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/sloghuman"
"github.com/coder/coder/v2/coderd/healthcheck/derphealth"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/codersdk/healthsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/tailnet"
)
// Bundle is a set of information discovered about a deployment.
// Even though we do attempt to sanitize data, it may still contain
// sensitive information and should thus be treated as secret.
type Bundle struct {
Deployment Deployment `json:"deployment"`
Network Network `json:"network"`
Workspace Workspace `json:"workspace"`
Agent Agent `json:"agent"`
Logs []string `json:"logs"`
CLILogs []byte `json:"cli_logs"`
NamedTemplate TemplateDump `json:"named_template"`
Pprof Pprof `json:"pprof"`
}
type Deployment struct {
BuildInfo *codersdk.BuildInfoResponse `json:"build"`
Config *codersdk.DeploymentConfig `json:"config"`
Experiments codersdk.Experiments `json:"experiments"`
HealthReport *healthsdk.HealthcheckReport `json:"health_report"`
Licenses []codersdk.License `json:"licenses"`
Stats *codersdk.DeploymentStats `json:"stats"`
Entitlements *codersdk.Entitlements `json:"entitlements"`
HealthSettings *healthsdk.HealthSettings `json:"health_settings"`
Workspaces *codersdk.WorkspacesResponse `json:"workspaces"`
Prometheus []byte `json:"prometheus"`
}
type Network struct {
ConnectionInfo workspacesdk.AgentConnectionInfo
CoordinatorDebug string `json:"coordinator_debug"`
Netcheck *derphealth.Report `json:"netcheck"`
TailnetDebug string `json:"tailnet_debug"`
Interfaces healthsdk.InterfacesReport `json:"interfaces"`
}
type Netcheck struct {
Report *netcheck.Report `json:"report"`
Error string `json:"error"`
Logs []string `json:"logs"`
}
type Workspace struct {
Workspace codersdk.Workspace `json:"workspace"`
Parameters []codersdk.WorkspaceBuildParameter `json:"parameters"`
Template codersdk.Template `json:"template"`
TemplateVersion codersdk.TemplateVersion `json:"template_version"`
TemplateFileBase64 string `json:"template_file_base64"`
BuildLogs []codersdk.ProvisionerJobLog `json:"build_logs"`
}
type Agent struct {
Agent *codersdk.WorkspaceAgent `json:"agent"`
ConnectionInfo *workspacesdk.AgentConnectionInfo `json:"connection_info"`
ListeningPorts *codersdk.WorkspaceAgentListeningPortsResponse `json:"listening_ports"`
Logs []byte `json:"logs"`
ClientMagicsockHTML []byte `json:"client_magicsock_html"`
AgentMagicsockHTML []byte `json:"agent_magicsock_html"`
Manifest *agentsdk.Manifest `json:"manifest"`
PeerDiagnostics *tailnet.PeerDiagnostics `json:"peer_diagnostics"`
PingResult *ipnstate.PingResult `json:"ping_result"`
Prometheus []byte `json:"prometheus"`
StartupLogs []codersdk.WorkspaceAgentLog `json:"startup_logs"`
}
type TemplateDump struct {
Template codersdk.Template `json:"template"`
TemplateVersion codersdk.TemplateVersion `json:"template_version"`
TemplateFileBase64 string `json:"template_file_base64"`
}
type Pprof struct {
Server *PprofCollection `json:"server,omitempty"`
Agent *PprofCollection `json:"agent,omitempty"`
}
type PprofCollection struct {
Heap []byte `json:"heap,omitempty"`
Allocs []byte `json:"allocs,omitempty"`
Profile []byte `json:"profile,omitempty"`
Block []byte `json:"block,omitempty"`
Mutex []byte `json:"mutex,omitempty"`
Goroutine []byte `json:"goroutine,omitempty"`
Threadcreate []byte `json:"threadcreate,omitempty"`
Trace []byte `json:"trace,omitempty"`
Cmdline string `json:"cmdline,omitempty"`
Symbol string `json:"symbol,omitempty"`
CollectedAt time.Time `json:"collected_at"`
EndpointURL string `json:"endpoint_url"`
}
// Deps is a set of dependencies for discovering information
type Deps struct {
// Source from which to obtain information.
Client *codersdk.Client
// Log is where to log any informational or warning messages.
Log slog.Logger
// WorkspaceID is the optional workspace against which to run connection tests.
WorkspaceID uuid.UUID
// AgentID is the optional agent ID against which to run connection tests.
// Defaults to the first agent of the workspace, if not specified.
AgentID uuid.UUID
// WorkspacesTotalCap limits the TOTAL number of workspaces aggregated into the bundle.
// > 0 => cap at this number (default flag value should be 1000 via CLI).
// <= 0 => no cap (fetch/keep all available workspaces).
WorkspacesTotalCap int
// TemplateID optionally specifies a template to capture (active version).
TemplateID uuid.UUID
// CollectPprof toggles server and agent pprof collection.
CollectPprof bool
}
func DeploymentInfo(ctx context.Context, client *codersdk.Client, log slog.Logger, workspacesCap int) Deployment {
// Note: each goroutine assigns to a different struct field, hence no mutex.
var (
d Deployment
eg errgroup.Group
)
eg.Go(func() error {
bi, err := client.BuildInfo(ctx)
if err != nil {
return xerrors.Errorf("fetch build info: %w", err)
}
d.BuildInfo = &bi
return nil
})
eg.Go(func() error {
dc, err := client.DeploymentConfig(ctx)
if err != nil {
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusForbidden || cerr.StatusCode() == http.StatusUnauthorized) {
log.Warn(ctx, "unable to fetch deployment config",
slog.F("status", cerr.StatusCode()))
return nil
}
return xerrors.Errorf("fetch deployment config: %w", err)
}
d.Config = dc
return nil
})
eg.Go(func() error {
hr, err := healthsdk.New(client).DebugHealth(ctx)
if err != nil {
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusForbidden || cerr.StatusCode() == http.StatusUnauthorized) {
log.Warn(ctx, "unable to fetch health report",
slog.F("status", cerr.StatusCode()))
return nil
}
return xerrors.Errorf("fetch health report: %w", err)
}
d.HealthReport = &hr
return nil
})
eg.Go(func() error {
exp, err := client.Experiments(ctx)
if err != nil {
return xerrors.Errorf("fetch experiments: %w", err)
}
d.Experiments = exp
return nil
})
eg.Go(func() error {
licenses, err := client.Licenses(ctx)
if err != nil {
// Ignore 404 because AGPL doesn't have this endpoint
if cerr, ok := codersdk.AsError(err); ok && cerr.StatusCode() != http.StatusNotFound {
return xerrors.Errorf("fetch license status: %w", err)
}
}
if licenses == nil {
licenses = make([]codersdk.License, 0)
}
d.Licenses = licenses
return nil
})
// Deployment stats
eg.Go(func() error {
stats, err := client.DeploymentStats(ctx)
if err != nil {
// If unauthorized or forbidden, log and continue
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusForbidden || cerr.StatusCode() == http.StatusUnauthorized || cerr.StatusCode() == http.StatusBadRequest) {
log.Warn(ctx, "unable to fetch deployment stats")
return nil
}
return xerrors.Errorf("fetch deployment stats: %w", err)
}
d.Stats = &stats
return nil
})
// Entitlements
eg.Go(func() error {
ents, err := client.Entitlements(ctx)
if err != nil {
// Ignore 404 or enterprise-not-enabled
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusNotFound || cerr.StatusCode() == http.StatusForbidden) {
log.Warn(ctx, "unable to fetch entitlements")
return nil
}
return xerrors.Errorf("fetch entitlements: %w", err)
}
d.Entitlements = &ents
return nil
})
// Health settings
eg.Go(func() error {
settings, err := healthsdk.New(client).HealthSettings(ctx)
if err != nil {
// If not accessible, log and continue
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusForbidden || cerr.StatusCode() == http.StatusUnauthorized) {
log.Warn(ctx, "unable to fetch health settings")
return nil
}
return xerrors.Errorf("fetch health settings: %w", err)
}
d.HealthSettings = &settings
return nil
})
// List workspaces (paginated)
eg.Go(func() error {
var (
offset int
limit = 200
all []codersdk.Workspace
count int
)
capTotal := workspacesCap
for {
resp, err := client.Workspaces(ctx, codersdk.WorkspaceFilter{Offset: offset, Limit: limit})
if err != nil {
// Log and continue if forbidden; otherwise return error
if cerr, ok := codersdk.AsError(err); ok && (cerr.StatusCode() == http.StatusForbidden || cerr.StatusCode() == http.StatusUnauthorized) {
log.Warn(ctx, "unable to list workspaces")
break
}
return xerrors.Errorf("list workspaces: %w", err)
}
if d.Workspaces == nil {
d.Workspaces = &resp
}
// sanitize env vars on agents in each workspace before appending
for i := range resp.Workspaces {
ws := &resp.Workspaces[i]
for _, res := range ws.LatestBuild.Resources {
for _, agt := range res.Agents {
// safe to call even if map is nil (range in sanitizeEnv would be empty)
sanitizeEnv(agt.EnvironmentVariables)
}
}
}
all = append(all, resp.Workspaces...)
count = resp.Count
// Stop early once we've reached the cap; trim any overflow from the last page.
if capTotal > 0 && len(all) >= capTotal {
if len(all) > capTotal {
all = all[:capTotal]
}
break
}
if offset+len(resp.Workspaces) >= count || len(resp.Workspaces) == 0 {
break
}
offset += len(resp.Workspaces)
}
if d.Workspaces != nil {
// Replace with aggregated list
d.Workspaces.Workspaces = all
// Preserve server-reported total so Run() can log accurate truncation.
d.Workspaces.Count = count
}
return nil
})
if err := eg.Wait(); err != nil {
log.Error(ctx, "fetch deployment information", slog.Error(err))
}
if d.Config != nil && d.Config.Values != nil {
prometheusCfg := d.Config.Values.Prometheus
if prometheusCfg.Enable.Value() {
metrics, err := fetchPrometheusMetrics(ctx, client, log)
if err != nil {
log.Warn(ctx, "fetch coderd prometheus metrics", slog.Error(err))
} else {
d.Prometheus = metrics
}
}
}
return d
}
func fetchPrometheusMetrics(ctx context.Context, client *codersdk.Client, log slog.Logger) ([]byte, error) {
if client == nil {
return nil, xerrors.New("nil client")
}
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
resp, err := client.Request(reqCtx, http.MethodGet, "/api/v2/debug/metrics", nil)
if err != nil {
return nil, xerrors.Errorf("request metrics: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, xerrors.Errorf("read metrics body: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debug(ctx, "coderd prometheus metrics fetch non-200",
slog.F("status", resp.StatusCode), slog.F("body_len", len(body)))
return nil, xerrors.Errorf("unexpected status code %d", resp.StatusCode)
}
trimmed := bytes.TrimSpace(body)
if len(trimmed) == 0 {
return nil, xerrors.New("empty prometheus metrics response")
}
return append([]byte(nil), trimmed...), nil
}
func NetworkInfo(ctx context.Context, client *codersdk.Client, log slog.Logger) Network {
var (
n Network
eg errgroup.Group
)
eg.Go(func() error {
coordResp, err := client.Request(ctx, http.MethodGet, "/api/v2/debug/coordinator", nil)
if err != nil {
return xerrors.Errorf("fetch coordinator debug page: %w", err)
}
defer coordResp.Body.Close()
if coordResp.StatusCode == http.StatusForbidden || coordResp.StatusCode == http.StatusUnauthorized {
_, _ = io.Copy(io.Discard, coordResp.Body)
log.Warn(ctx, "unable to fetch coordinator debug page",
slog.F("status", coordResp.StatusCode))
return nil
}
bs, err := io.ReadAll(coordResp.Body)
if err != nil {
return xerrors.Errorf("read coordinator debug page: %w", err)
}
n.CoordinatorDebug = string(bs)
return nil
})
eg.Go(func() error {
tailResp, err := client.Request(ctx, http.MethodGet, "/api/v2/debug/tailnet", nil)
if err != nil {
return xerrors.Errorf("fetch tailnet debug page: %w", err)
}
defer tailResp.Body.Close()
if tailResp.StatusCode == http.StatusForbidden || tailResp.StatusCode == http.StatusUnauthorized {
_, _ = io.Copy(io.Discard, tailResp.Body)
log.Warn(ctx, "unable to fetch tailnet debug page",
slog.F("status", tailResp.StatusCode))
return nil
}
bs, err := io.ReadAll(tailResp.Body)
if err != nil {
return xerrors.Errorf("read tailnet debug page: %w", err)
}
n.TailnetDebug = string(bs)
return nil
})
eg.Go(func() error {
// Need connection info to get DERP map for netcheck
connInfo, err := workspacesdk.New(client).AgentConnectionInfoGeneric(ctx)
if err != nil {
log.Warn(ctx, "unable to fetch generic agent connection info")
return nil
}
n.ConnectionInfo = connInfo
var rpt derphealth.Report
rpt.Run(ctx, &derphealth.ReportOptions{
DERPMap: connInfo.DERPMap,
})
n.Netcheck = &rpt
return nil
})
eg.Go(func() error {
rpt, err := healthsdk.RunInterfacesReport()
if err != nil {
return xerrors.Errorf("run interfaces report: %w", err)
}
n.Interfaces = rpt
return nil
})
if err := eg.Wait(); err != nil {
log.Error(ctx, "fetch network information", slog.Error(err))
}
return n
}
func WorkspaceInfo(ctx context.Context, client *codersdk.Client, log slog.Logger, workspaceID uuid.UUID) Workspace {
var (
w Workspace
eg errgroup.Group
)
if workspaceID == uuid.Nil {
log.Error(ctx, "no workspace id specified")
return w
}
// dependency, cannot fetch concurrently
ws, err := client.Workspace(ctx, workspaceID)
if err != nil {
log.Error(ctx, "fetch workspace", slog.Error(err), slog.F("workspace_id", workspaceID))
return w
}
for _, res := range ws.LatestBuild.Resources {
for _, agt := range res.Agents {
sanitizeEnv(agt.EnvironmentVariables)
}
}
w.Workspace = ws
eg.Go(func() error {
buildLogCh, closer, err := client.WorkspaceBuildLogsAfter(ctx, ws.LatestBuild.ID, 0)
if err != nil {
return xerrors.Errorf("fetch provisioner job logs: %w", err)
}
defer closer.Close()
for log := range buildLogCh {
w.BuildLogs = append(w.BuildLogs, log)
}
return nil
})
eg.Go(func() error {
if w.Workspace.TemplateActiveVersionID == uuid.Nil {
return xerrors.Errorf("workspace has nil template active version id")
}
tv, err := client.TemplateVersion(ctx, w.Workspace.TemplateActiveVersionID)
if err != nil {
return xerrors.Errorf("fetch template active version id")
}
w.TemplateVersion = tv
if tv.Job.FileID == uuid.Nil {
return xerrors.Errorf("template file id is nil")
}
raw, ctype, err := client.DownloadWithFormat(ctx, tv.Job.FileID, codersdk.FormatZip)
if err != nil {
return err
}
if ctype != codersdk.ContentTypeZip {
return xerrors.Errorf("expected content-type %s, got %s", codersdk.ContentTypeZip, ctype)
}
b64encoded := base64.StdEncoding.EncodeToString(raw)
w.TemplateFileBase64 = b64encoded
return nil
})
eg.Go(func() error {
if w.Workspace.TemplateID == uuid.Nil {
return xerrors.Errorf("workspace has nil version id")
}
tpl, err := client.Template(ctx, w.Workspace.TemplateID)
if err != nil {
return xerrors.Errorf("fetch template")
}
w.Template = tpl
return nil
})
eg.Go(func() error {
if ws.LatestBuild.ID == uuid.Nil {
return xerrors.Errorf("workspace has nil latest build id")
}
params, err := client.WorkspaceBuildParameters(ctx, ws.LatestBuild.ID)
if err != nil {
return xerrors.Errorf("fetch workspace build parameters: %w", err)
}
w.Parameters = params
return nil
})
if err := eg.Wait(); err != nil {
log.Error(ctx, "fetch workspace information", slog.Error(err))
}
return w
}
func AgentInfo(ctx context.Context, client *codersdk.Client, log slog.Logger, agentID uuid.UUID) Agent {
var (
a Agent
eg errgroup.Group
)
if agentID == uuid.Nil {
log.Error(ctx, "no agent id specified")
return a
}
eg.Go(func() error {
agt, err := client.WorkspaceAgent(ctx, agentID)
if err != nil {
return xerrors.Errorf("fetch workspace agent: %w", err)
}
sanitizeEnv(agt.EnvironmentVariables)
a.Agent = &agt
return nil
})
eg.Go(func() error {
agentLogCh, closer, err := client.WorkspaceAgentLogsAfter(ctx, agentID, 0, false)
if err != nil {
return xerrors.Errorf("fetch agent startup logs: %w", err)
}
defer closer.Close()
var logs []codersdk.WorkspaceAgentLog
for logChunk := range agentLogCh {
logs = append(logs, logChunk...)
}
a.StartupLogs = logs
return nil
})
// to simplify control flow, fetching information directly from
// the agent is handled in a separate function
closer := connectedAgentInfo(ctx, client, log, agentID, &eg, &a)
defer closer()
if err := eg.Wait(); err != nil {
log.Error(ctx, "fetch agent information", slog.Error(err))
}
return a
}
func connectedAgentInfo(ctx context.Context, client *codersdk.Client, log slog.Logger, agentID uuid.UUID, eg *errgroup.Group, a *Agent) (closer func()) {
conn, err := workspacesdk.New(client).
DialAgent(ctx, agentID, &workspacesdk.DialAgentOptions{
Logger: log.Named("dial-agent"),
BlockEndpoints: false,
})
closer = func() {}
if err != nil {
log.Error(ctx, "dial agent", slog.Error(err))
return closer
}
if !conn.AwaitReachable(ctx) {
log.Error(ctx, "timed out waiting for agent")
return closer
}
closer = func() {
if err := conn.Close(); err != nil {
log.Error(ctx, "failed to close agent connection", slog.Error(err))
}
<-conn.TailnetConn().Closed()
}
eg.Go(func() error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost/", nil)
if err != nil {
return xerrors.Errorf("create request: %w", err)
}
rr := httptest.NewRecorder()
conn.TailnetConn().MagicsockServeHTTPDebug(rr, req)
a.ClientMagicsockHTML = rr.Body.Bytes()
return nil
})
eg.Go(func() error {
promRes, err := conn.PrometheusMetrics(ctx)
if err != nil {
return xerrors.Errorf("fetch agent prometheus metrics: %w", err)
}
a.Prometheus = promRes
return nil
})
eg.Go(func() error {
_, _, pingRes, err := conn.Ping(ctx)
if err != nil {
return xerrors.Errorf("ping agent: %w", err)
}
a.PingResult = pingRes
return nil
})
eg.Go(func() error {
pds := conn.GetPeerDiagnostics()
a.PeerDiagnostics = &pds
return nil
})
eg.Go(func() error {
msBytes, err := conn.DebugMagicsock(ctx)
if err != nil {
return xerrors.Errorf("get agent magicsock page: %w", err)
}
a.AgentMagicsockHTML = msBytes
return nil
})
eg.Go(func() error {
manifestRes, err := conn.DebugManifest(ctx)
if err != nil {
return xerrors.Errorf("fetch manifest: %w", err)
}
if err := json.NewDecoder(bytes.NewReader(manifestRes)).Decode(&a.Manifest); err != nil {
return xerrors.Errorf("decode agent manifest: %w", err)
}
sanitizeEnv(a.Manifest.EnvironmentVariables)
return nil
})
eg.Go(func() error {
logBytes, err := conn.DebugLogs(ctx)
if err != nil {
return xerrors.Errorf("fetch coder agent logs: %w", err)
}
a.Logs = logBytes
return nil
})
eg.Go(func() error {
lps, err := conn.ListeningPorts(ctx)
if err != nil {
return xerrors.Errorf("get listening ports: %w", err)
}
a.ListeningPorts = &lps
return nil
})
return closer
}
func PprofInfo(ctx context.Context, client *codersdk.Client, log slog.Logger) *PprofCollection {
if client == nil {
return nil
}
var (
p PprofCollection
eg errgroup.Group
)
if client.URL != nil {
if u, err := client.URL.Parse("/api/v2/debug/pprof"); err == nil {
p.EndpointURL = u.String()
}
}
if p.EndpointURL == "" {
p.EndpointURL = "/api/v2/debug/pprof"
}
p.CollectedAt = time.Now()
const basePath = "/api/v2/debug/pprof"
endpoints := map[string]func([]byte){
"/allocs": func(data []byte) {
p.Allocs = compressData(data)
},
"/heap": func(data []byte) {
p.Heap = compressData(data)
},
"/profile?seconds=30": func(data []byte) {
p.Profile = compressData(data)
},
"/block": func(data []byte) {
p.Block = compressData(data)
},
"/mutex": func(data []byte) {
p.Mutex = compressData(data)
},
"/goroutine": func(data []byte) {
p.Goroutine = compressData(data)
},
"/threadcreate": func(data []byte) {
p.Threadcreate = compressData(data)
},
"/trace?seconds=30": func(data []byte) {
p.Trace = compressData(data)
},
"/cmdline": func(data []byte) {
p.Cmdline = string(data)
},
"/symbol": func(data []byte) {
p.Symbol = string(data)
},
}
for endpoint, setter := range endpoints {
eg.Go(func() error {
timeout := 10 * time.Second
if strings.Contains(endpoint, "seconds=30") {
timeout = 45 * time.Second
}
reqCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
resp, err := client.Request(reqCtx, http.MethodGet, basePath+endpoint, nil)
if err != nil {
log.Warn(reqCtx, "failed to fetch pprof data", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Warn(reqCtx, "pprof endpoint returned non-200 status",
slog.F("endpoint", endpoint), slog.F("status", resp.StatusCode))
return nil
}
data, err := io.ReadAll(resp.Body)
if err != nil {
log.Warn(reqCtx, "failed to read pprof response", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
setter(data)
return nil
})
}
if err := eg.Wait(); err != nil {
log.Error(ctx, "failed to collect some pprof data", slog.Error(err))
}
return &p
}
func compressData(data []byte) []byte {
if len(data) == 0 {
return data
}
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := gz.Write(data); err != nil {
return data // Return uncompressed if compression fails
}
if err := gz.Close(); err != nil {
return data
}
return buf.Bytes()
}
// PprofInfoFromArchive uses the consolidated /api/v2/debug/profile endpoint
// to collect pprof data in a single request. The server temporarily enables
// block/mutex profiling, runs time-based profiles for the given duration,
// takes snapshots, and returns a tar.gz archive.
func PprofInfoFromArchive(ctx context.Context, client *codersdk.Client, log slog.Logger, duration time.Duration) (*PprofCollection, error) {
if client == nil {
return nil, xerrors.New("client is nil")
}
body, err := client.DebugCollectProfile(ctx, codersdk.DebugProfileOptions{
Duration: duration,
// Use the server defaults plus trace.
Profiles: []string{"cpu", "heap", "allocs", "block", "mutex", "goroutine", "threadcreate", "trace"},
})
if err != nil {
return nil, xerrors.Errorf("fetch consolidated profile: %w", err)
}
defer body.Close()
data, err := io.ReadAll(body)
if err != nil {
return nil, xerrors.Errorf("read profile archive: %w", err)
}
var p PprofCollection
if client.URL != nil {
if u, err := client.URL.Parse("/api/v2/debug/profile"); err == nil {
p.EndpointURL = u.String()
}
}
if p.EndpointURL == "" {
p.EndpointURL = "/api/v2/debug/profile"
}
p.CollectedAt = time.Now()
// Parse the tar.gz archive and populate the PprofCollection.
gr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, xerrors.Errorf("open gzip reader: %w", err)
}
defer gr.Close()
tr := tar.NewReader(gr)
for {
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, xerrors.Errorf("read tar entry %q: %w", hdr.Name, err)
}
content, err := io.ReadAll(tr)
if err != nil {
log.Warn(ctx, "failed to read tar entry", slog.F("name", hdr.Name), slog.Error(err))
continue
}
// Files in the archive are named like "cpu.prof", "heap.prof",
// "trace.out", etc. Compress binary profile data for storage in
// the bundle, matching what PprofInfo() does.
base := path.Base(hdr.Name)
switch base {
case "cpu.prof":
p.Profile = compressData(content)
case "heap.prof":
p.Heap = compressData(content)
case "allocs.prof":
p.Allocs = compressData(content)
case "block.prof":
p.Block = compressData(content)
case "mutex.prof":
p.Mutex = compressData(content)
case "goroutine.prof":
p.Goroutine = compressData(content)
case "threadcreate.prof":
p.Threadcreate = compressData(content)
case "trace.out":
p.Trace = compressData(content)
default:
log.Debug(ctx, "unknown profile in archive", slog.F("name", hdr.Name))
}
}
return &p, nil
}
func PprofInfoFromAgent(ctx context.Context, conn workspacesdk.AgentConn, log slog.Logger) *PprofCollection {
if conn == nil {
return nil
}
var (
p PprofCollection
eg errgroup.Group
)
p.EndpointURL = "agent"
p.CollectedAt = time.Now()
// Define agent pprof endpoints - these go through the agent connection
endpoints := map[string]func([]byte){
"/debug/pprof/allocs": func(data []byte) {
p.Allocs = compressData(data)
},
"/debug/pprof/heap": func(data []byte) {
p.Heap = compressData(data)
},
"/debug/pprof/profile?seconds=30": func(data []byte) {
p.Profile = compressData(data)
},
"/debug/pprof/block": func(data []byte) {
p.Block = compressData(data)
},
"/debug/pprof/mutex": func(data []byte) {
p.Mutex = compressData(data)
},
"/debug/pprof/goroutine": func(data []byte) {
p.Goroutine = compressData(data)
},
"/debug/pprof/threadcreate": func(data []byte) {
p.Threadcreate = compressData(data)
},
"/debug/pprof/trace?seconds=30": func(data []byte) {
p.Trace = compressData(data)
},
"/debug/pprof/cmdline": func(data []byte) {
p.Cmdline = string(data)
},
"/debug/pprof/symbol": func(data []byte) {
p.Symbol = string(data)
},
}
// Collect each endpoint in parallel
for endpoint, setter := range endpoints {
eg.Go(func() error {
// Set longer timeout for profile and trace endpoints (they take 30 seconds)
timeout := 10 * time.Second
if strings.Contains(endpoint, "seconds=30") {
timeout = 45 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Use the agent's direct HTTP capability
// Agent pprof server runs on 127.0.0.1:6060 by default
netConn, err := conn.DialContext(ctx, "tcp", "127.0.0.1:6060")
if err != nil {
log.Warn(ctx, "failed to dial agent pprof endpoint", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
defer netConn.Close()
// Create HTTP client using the connection
client := &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return netConn, nil
},
},
Timeout: timeout,
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:6060"+endpoint, nil)
if err != nil {
log.Warn(ctx, "failed to create agent pprof request", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
resp, err := client.Do(req)
if err != nil {
log.Warn(ctx, "failed to fetch agent pprof data", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Warn(ctx, "agent pprof endpoint returned non-200 status", slog.F("endpoint", endpoint), slog.F("status", resp.StatusCode))
return nil
}
data, err := io.ReadAll(resp.Body)
if err != nil {
log.Warn(ctx, "failed to read agent pprof response", slog.F("endpoint", endpoint), slog.Error(err))
return nil
}
setter(data)
return nil
})
}
if err := eg.Wait(); err != nil {
log.Error(ctx, "failed to collect some agent pprof data", slog.Error(err))
}
return &p
}