-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
8 changed files
with
2,063 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
package expv2 | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"sync" | ||
"time" | ||
|
||
"github.com/golang/snappy" | ||
"github.com/sirupsen/logrus" | ||
"google.golang.org/protobuf/proto" | ||
|
||
"go.k6.io/k6/lib/consts" | ||
"go.k6.io/k6/output/cloud/expv2/pbcloud" | ||
) | ||
|
||
type httpDoer interface { | ||
Do(*http.Request) (*http.Response, error) | ||
} | ||
|
||
// MetricsClient is a wrapper around the cloudapi.Client that is also capable of pushing | ||
type MetricsClient struct { | ||
httpClient httpDoer | ||
logger logrus.FieldLogger | ||
host string | ||
userAgent string | ||
|
||
pushBufferPool sync.Pool | ||
} | ||
|
||
// NewMetricsClient creates and initializes a new MetricsClient. | ||
func NewMetricsClient(logger logrus.FieldLogger, host string) *MetricsClient { | ||
return &MetricsClient{ | ||
httpClient: &http.Client{Timeout: 5 * time.Second}, | ||
logger: logger, | ||
host: host, | ||
userAgent: fmt.Sprintf("k6cloud/v%s", consts.Version), | ||
pushBufferPool: sync.Pool{ | ||
New: func() interface{} { | ||
return &bytes.Buffer{} | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
// Push pushes the provided metric samples for the given referenceID | ||
func (mc *MetricsClient) Push(ctx context.Context, referenceID string, samples *pbcloud.MetricSet) error { | ||
if referenceID == "" { | ||
return fmt.Errorf("a Reference ID of the test run is required") | ||
} | ||
start := time.Now() | ||
url := fmt.Sprintf("%s/v2/metrics/%s", mc.host, referenceID) | ||
|
||
b, err := newRequestBody(samples) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
buf, _ := mc.pushBufferPool.Get().(*bytes.Buffer) | ||
buf.Reset() | ||
defer mc.pushBufferPool.Put(buf) | ||
|
||
_, err = buf.Write(b) | ||
if err != nil { | ||
return err | ||
} | ||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf) | ||
if err != nil { | ||
return err | ||
} | ||
req.Header.Set("User-Agent", mc.userAgent) | ||
req.Header.Set("Content-Type", "application/x-protobuf") | ||
req.Header.Set("Content-Encoding", "snappy") | ||
req.Header.Set("K6-Metrics-Protocol-Version", "2.0") | ||
|
||
// TODO: Add authentication | ||
// req.Header.Set("Authorization", fmt.Sprintf("Token %s", c.token)) | ||
|
||
resp, err := mc.httpClient.Do(req) | ||
if err != nil { | ||
return fmt.Errorf("failed to push metrics: %w", err) | ||
} | ||
defer func() { | ||
_ = resp.Body.Close() | ||
}() | ||
if resp.StatusCode != http.StatusOK { | ||
return fmt.Errorf("failed to push metrics: push metrics response got an unexpected status code: %s", resp.Status) | ||
} | ||
mc.logger.WithField("t", time.Since(start)).WithField("size", len(b)). | ||
Debug("Pushed part to cloud") | ||
return nil | ||
} | ||
|
||
func newRequestBody(data *pbcloud.MetricSet) ([]byte, error) { | ||
b, err := proto.Marshal(data) | ||
if err != nil { | ||
return nil, fmt.Errorf("encoding series as protobuf write request failed: %w", err) | ||
} | ||
if snappy.MaxEncodedLen(len(b)) < 0 { | ||
return nil, fmt.Errorf("the protobuf message is too large to be handled by Snappy encoder; "+ | ||
"size: %d, limit: %d", len(b), 0xffffffff) | ||
} | ||
return snappy.Encode(nil, b), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
package expv2 | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"go.k6.io/k6/lib/testutils" | ||
"go.k6.io/k6/output/cloud/expv2/pbcloud" | ||
) | ||
|
||
type httpDoerFunc func(*http.Request) (*http.Response, error) | ||
|
||
func (fn httpDoerFunc) Do(r *http.Request) (*http.Response, error) { | ||
return fn(r) | ||
} | ||
|
||
func TestMetricsClientPush(t *testing.T) { | ||
t.Parallel() | ||
|
||
done := make(chan struct{}, 1) | ||
reqs := 0 | ||
h := func(rw http.ResponseWriter, r *http.Request) { | ||
defer close(done) | ||
reqs++ | ||
|
||
assert.Equal(t, "/v2/metrics/test-ref-id", r.URL.Path) | ||
assert.Equal(t, http.MethodPost, r.Method) | ||
assert.Contains(t, r.Header.Get("User-Agent"), "k6cloud/v0.4") | ||
assert.Equal(t, "application/x-protobuf", r.Header.Get("Content-Type")) | ||
assert.Equal(t, "snappy", r.Header.Get("Content-Encoding")) | ||
assert.Equal(t, "2.0", r.Header.Get("K6-Metrics-Protocol-Version")) | ||
|
||
b, err := io.ReadAll(r.Body) | ||
require.NoError(t, err) | ||
assert.NotEmpty(t, b) | ||
} | ||
|
||
ts := httptest.NewServer(http.HandlerFunc(h)) | ||
defer ts.Close() | ||
|
||
mc := NewMetricsClient(testutils.NewLogger(t), ts.URL) | ||
mc.httpClient = ts.Client() | ||
|
||
mset := pbcloud.MetricSet{} | ||
err := mc.Push(context.TODO(), "test-ref-id", &mset) | ||
<-done | ||
require.NoError(t, err) | ||
assert.Equal(t, 1, reqs) | ||
} | ||
|
||
func TestMetricsClientPushUnexpectedStatus(t *testing.T) { | ||
t.Parallel() | ||
|
||
h := func(rw http.ResponseWriter, _ *http.Request) { | ||
rw.WriteHeader(http.StatusInternalServerError) | ||
} | ||
ts := httptest.NewServer(http.HandlerFunc(h)) | ||
defer ts.Close() | ||
|
||
mc := NewMetricsClient(testutils.NewLogger(t), ts.URL) | ||
mc.httpClient = ts.Client() | ||
|
||
err := mc.Push(context.TODO(), "test-ref-id", nil) | ||
assert.ErrorContains(t, err, "500 Internal Server Error") | ||
} | ||
|
||
func TestMetricsClientPushError(t *testing.T) { | ||
t.Parallel() | ||
|
||
httpClientMock := func(_ *http.Request) (*http.Response, error) { | ||
return nil, fmt.Errorf("fake generated error") | ||
} | ||
|
||
mc := NewMetricsClient(testutils.NewLogger(t), "") | ||
mc.httpClient = httpDoerFunc(httpClientMock) | ||
|
||
err := mc.Push(context.TODO(), "test-ref-id", nil) | ||
assert.ErrorContains(t, err, "fake generated error") | ||
} |
Oops, something went wrong.