Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GZIP compression to collector endpoint #95

Merged
merged 2 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions collector/collector.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package collector

import (
"compress/gzip"
"context"
"encoding/binary"
"fmt"
Expand All @@ -22,6 +23,11 @@ import (
"github.com/castai/egressd/pb"
)

var (
acceptEncoding = http.CanonicalHeaderKey("Accept-Encoding")
contentEncoding = http.CanonicalHeaderKey("Content-Encoding")
)

func CurrentTimeGetter() func() time.Time {
return func() time.Time {
return time.Now()
Expand Down Expand Up @@ -139,10 +145,20 @@ func (c *Collector) GetRawNetworkMetricsHandler(w http.ResponseWriter, req *http
w.WriteHeader(http.StatusInternalServerError)
return
}
if _, err := w.Write(batchBytes); err != nil {
c.log.Errorf("write batch: %v", err)
return

enc := req.Header.Get(acceptEncoding)
if strings.Contains(strings.ToLower(enc), "gzip") {
if err := c.writeGzipBody(w, batchBytes); err != nil {
c.log.Errorf("write batch %v", err)
return
}
} else {
if err := c.writePlainBody(w, batchBytes); err != nil {
c.log.Errorf("write batch %v", err)
return
}
}

if c.cfg.SendTrafficDelta {
// reset metric tx/rx values, so only delta numbers will be sent with the next batch
for _, m := range c.podMetrics {
Expand All @@ -154,6 +170,32 @@ func (c *Collector) GetRawNetworkMetricsHandler(w http.ResponseWriter, req *http
}
}

func (c *Collector) writeGzipBody(w http.ResponseWriter, body []byte) error {
writer, err := gzip.NewWriterLevel(w, gzip.BestCompression)
if err != nil {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: It's probably not worth checking the error in this case.

The error returned will be nil if the level is valid.

https://pkg.go.dev/compress/gzip#NewWriterLevel

http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return fmt.Errorf("cannot create gzip writer: %w", err)
}
defer writer.Close()

w.Header().Add(contentEncoding, "gzip")

if _, err := writer.Write(body); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return err
}

return nil
}

func (c *Collector) writePlainBody(w http.ResponseWriter, body []byte) error {
if _, err := w.Write(body); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return err
}
return nil
}

// collect aggregates conntract records into reduced pod metrics.
func (c *Collector) collect() error {
start := time.Now()
Expand Down
27 changes: 23 additions & 4 deletions collector/collector_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package collector

import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"sort"
Expand Down Expand Up @@ -420,11 +422,19 @@ func TestCollector__GetRawNetworkMetricsHandler(t *testing.T) {

w := httptest.NewRecorder()
// scrape pods metrics and prepare them to be sent
coll.GetRawNetworkMetricsHandler(w, &http.Request{})
coll.GetRawNetworkMetricsHandler(w, &http.Request{Header: http.Header{
"Accept-Encoding": []string{"gzip"},
}})
r.Equal(200, w.Code)

batch := &pb.RawNetworkMetricBatch{}
err := proto.Unmarshal(w.Body.Bytes(), batch)
gzreader, err := gzip.NewReader(w.Body)
r.NoError(err)

body, err := io.ReadAll(gzreader)
r.NoError(err)

err = proto.Unmarshal(body, batch)
r.NoError(err)
r.Len(batch.Items, 2)
sort.Slice(batch.Items, func(i, j int) bool {
Expand Down Expand Up @@ -507,11 +517,20 @@ func TestCollector__GetRawNetworkMetricsHandler(t *testing.T) {

w := httptest.NewRecorder()
// scrape pods metrics and prepare them to be sent
coll.GetRawNetworkMetricsHandler(w, &http.Request{})
coll.GetRawNetworkMetricsHandler(w, &http.Request{Header: http.Header{
"Accept-Encoding": []string{"gzip"},
}})
r.Equal(200, w.Code)

batch := &pb.RawNetworkMetricBatch{}
err := proto.Unmarshal(w.Body.Bytes(), batch)

gzreader, err := gzip.NewReader(w.Body)
r.NoError(err)

body, err := io.ReadAll(gzreader)
r.NoError(err)

err = proto.Unmarshal(body, batch)
r.NoError(err)
r.Len(batch.Items, 2)
sort.Slice(batch.Items, func(i, j int) bool {
Expand Down
Loading