Skip to content

[usage] Upload usage reports to cloud storage #11519

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

Merged
merged 2 commits into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
37 changes: 33 additions & 4 deletions components/usage/pkg/contentservice/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ package contentservice
import (
"context"
"fmt"
"io"
"net/http"

"github.com/gitpod-io/gitpod/common-go/log"
"github.com/gitpod-io/gitpod/content-service/api"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

type Interface interface {
GetSignedUploadUrl(ctx context.Context) (string, error)
UploadFile(ctx context.Context, filename string, body io.Reader) error
}

type Client struct {
Expand All @@ -25,7 +28,33 @@ func New(url string) *Client {
return &Client{url: url}
}

func (c *Client) GetSignedUploadUrl(ctx context.Context) (string, error) {
func (c *Client) UploadFile(ctx context.Context, filename string, body io.Reader) error {
url, err := c.getSignedUploadUrl(ctx, filename)
if err != nil {
return fmt.Errorf("failed to obtain signed upload URL: %w", err)
}

req, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
return fmt.Errorf("failed to construct http request: %w", err)
}

req.Header.Set("Content-Encoding", "gzip")
Copy link
Member

Choose a reason for hiding this comment

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

Does this cause the content to be gzipped on the server? I would've expected you set this to indicate that the content you're uploading is gzip but I don't see us compressing in this implementation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

See this comment.


log.Infof("Uploading %q to object storage...", filename)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to make http request: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected http response code: %s", resp.Status)
}
log.Info("Upload complete")

return nil
}

func (c *Client) getSignedUploadUrl(ctx context.Context, key string) (string, error) {
conn, err := grpc.Dial(c.url, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return "", fmt.Errorf("failed to dial content-service gRPC server: %w", err)
Expand All @@ -34,9 +63,9 @@ func (c *Client) GetSignedUploadUrl(ctx context.Context) (string, error) {

uc := api.NewUsageReportServiceClient(conn)

resp, err := uc.UploadURL(ctx, &api.UsageReportUploadURLRequest{Name: "some-name"})
resp, err := uc.UploadURL(ctx, &api.UsageReportUploadURLRequest{Name: key})
if err != nil {
return "", fmt.Errorf("failed to obtain signed upload URL: %w", err)
return "", fmt.Errorf("failed RPC to content service: %w", err)
}

return resp.Url, nil
Expand Down
9 changes: 7 additions & 2 deletions components/usage/pkg/contentservice/noop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@

package contentservice

import "context"
import (
"context"
"io"
)

type NoOpClient struct{}

func (c *NoOpClient) GetSignedUploadUrl(ctx context.Context) (string, error) { return "", nil }
func (c *NoOpClient) UploadFile(ctx context.Context, filename string, body io.Reader) error {
return nil
}
35 changes: 12 additions & 23 deletions components/usage/pkg/controller/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@
package controller

import (
"bytes"
"compress/gzip"
"context"
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"time"

"github.com/gitpod-io/gitpod/common-go/log"
Expand Down Expand Up @@ -76,36 +75,26 @@ func (u *UsageReconciler) Reconcile() (err error) {
}
log.WithField("usage_reconcile_status", status).Info("Reconcile completed.")

// For now, write the report to a temp directory so we can manually retrieve it
dir := os.TempDir()
f, err := ioutil.TempFile(dir, fmt.Sprintf("%s-*", now.Format(time.RFC3339)))
if err != nil {
return fmt.Errorf("failed to create temporary file: %w", err)
}
defer f.Close()

enc := json.NewEncoder(f)
err = enc.Encode(report)
reportBytes := &bytes.Buffer{}
gz := gzip.NewWriter(reportBytes)
err = json.NewEncoder(gz).Encode(report)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is where the json report is gzipped.

Copy link
Member

Choose a reason for hiding this comment

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

I'd recommend moving this into the Storage Client. As it stands it's confusing because the client sets the content type gzipped, but nothing in the API signature indicates it should be gzipped ahead of it.

Ideally, the Client takes a bytes buffer and wraps it in a gzip writer, then writes the whole thing as a stream

Copy link
Member

Choose a reason for hiding this comment

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

Or even can take an io.Writer which is a much better interface for wrapping

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The UploadFile method really should only take usage reports - this object storage signed upload URL that it obtains will place the file in the usage-report bucket.

As such, I've renamed the method on the interface and changed its argument to be a report rather than an io.Reader (aa9f2d4)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also moved the json encoding and compression of the report away from the caller and into the method.

if err != nil {
return fmt.Errorf("failed to marshal report to JSON: %w", err)
}

stat, err := f.Stat()
filePath := filepath.Join(dir, stat.Name())
err = gz.Close()
if err != nil {
return fmt.Errorf("failed to get file stats: %w", err)
return fmt.Errorf("failed to compress usage report: %w", err)
}
log.Infof("Wrote usage report into %s", filePath)

uploadURL, err := u.contentService.GetSignedUploadUrl(ctx)
err = db.CreateUsageRecords(ctx, u.conn, usageReportToUsageRecords(report, u.pricer, u.nowFunc().UTC()))
if err != nil {
return fmt.Errorf("failed to obtain signed upload URL: %w", err)
return fmt.Errorf("failed to write usage records to database: %s", err)
}
log.Infof("signed upload url: %s", uploadURL)

err = db.CreateUsageRecords(ctx, u.conn, usageReportToUsageRecords(report, u.pricer, u.nowFunc().UTC()))
filename := fmt.Sprintf("%s.gz", now.Format(time.RFC3339))
err = u.contentService.UploadFile(ctx, filename, reportBytes)
if err != nil {
return fmt.Errorf("failed to write usage records to database: %s", err)
return fmt.Errorf("failed to upload usage report: %w", err)
}

return nil
Expand Down