From beea1c2218f8b0521dbdffd375698dd700b14721 Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Wed, 14 Jul 2021 18:52:57 -0400 Subject: [PATCH] http: emit indented JSON in the metrics stream endpoint To remove the need to decode and re-encode in the CLI --- agent/agent_endpoint.go | 3 ++- command/debug/debug.go | 16 +++++----------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/agent/agent_endpoint.go b/agent/agent_endpoint.go index 8af3e1ee76..b284c80297 100644 --- a/agent/agent_endpoint.go +++ b/agent/agent_endpoint.go @@ -181,7 +181,7 @@ func (s *HTTPHandlers) AgentMetricsStream(resp http.ResponseWriter, req *http.Re flusher, ok := resp.(http.Flusher) if !ok { - return nil, fmt.Errorf("Streaming not supported") + return nil, fmt.Errorf("streaming not supported") } resp.WriteHeader(http.StatusOK) @@ -196,6 +196,7 @@ func (s *HTTPHandlers) AgentMetricsStream(resp http.ResponseWriter, req *http.Re encoder: json.NewEncoder(resp), flusher: flusher, } + enc.encoder.SetIndent("", " ") s.agent.baseDeps.MetricsHandler.Stream(req.Context(), enc) return nil, nil } diff --git a/command/debug/debug.go b/command/debug/debug.go index 45d3642441..a0ec146f5f 100644 --- a/command/debug/debug.go +++ b/command/debug/debug.go @@ -2,6 +2,7 @@ package debug import ( "archive/tar" + "bufio" "compress/gzip" "context" "encoding/json" @@ -529,17 +530,10 @@ func (c *cmd) captureMetrics(ctx context.Context, timestampDir string) error { } defer fh.Close() - decoder := json.NewDecoder(stream) - encoder := json.NewEncoder(fh) - // TODO: is More() correct here? - for decoder.More() { - var raw interface{} - if err := decoder.Decode(&raw); err != nil { - return fmt.Errorf("failed to decode metrics: %w", err) - } - if err := encoder.Encode(raw); err != nil { - return fmt.Errorf("failed to write metrics to file: %w", err) - } + b := bufio.NewReader(stream) + _, err = b.WriteTo(fh) + if err != nil && !errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("failed to copy metrics to file: %w", err) } return nil }