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 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
51 changes: 47 additions & 4 deletions components/usage/pkg/contentservice/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@
package contentservice

import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"net/http"

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

type Interface interface {
GetSignedUploadUrl(ctx context.Context) (string, error)
UploadUsageReport(ctx context.Context, filename string, report map[db.AttributionID][]db.WorkspaceInstanceForUsage) error
}

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

func (c *Client) GetSignedUploadUrl(ctx context.Context) (string, error) {
func (c *Client) UploadUsageReport(ctx context.Context, filename string, report map[db.AttributionID][]db.WorkspaceInstanceForUsage) error {
url, err := c.getSignedUploadUrl(ctx, filename)
if err != nil {
return fmt.Errorf("failed to obtain signed upload URL: %w", err)
}

reportBytes := &bytes.Buffer{}
gz := gzip.NewWriter(reportBytes)
err = json.NewEncoder(gz).Encode(report)
if err != nil {
return fmt.Errorf("failed to marshal report to JSON: %w", err)
}
err = gz.Close()
if err != nil {
return fmt.Errorf("failed to compress usage report: %w", err)
}

req, err := http.NewRequest(http.MethodPut, url, reportBytes)
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 +77,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
10 changes: 8 additions & 2 deletions components/usage/pkg/contentservice/noop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@

package contentservice

import "context"
import (
"context"

"github.com/gitpod-io/gitpod/usage/pkg/db"
)

type NoOpClient struct{}

func (c *NoOpClient) GetSignedUploadUrl(ctx context.Context) (string, error) { return "", nil }
func (c *NoOpClient) UploadUsageReport(ctx context.Context, filename string, report map[db.AttributionID][]db.WorkspaceInstanceForUsage) error {
return nil
}
35 changes: 5 additions & 30 deletions components/usage/pkg/controller/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,8 @@ package controller
import (
"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 +72,15 @@ 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)
if err != nil {
return fmt.Errorf("failed to marshal report to JSON: %w", err)
}

stat, err := f.Stat()
filePath := filepath.Join(dir, stat.Name())
if err != nil {
return fmt.Errorf("failed to get file stats: %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.UploadUsageReport(ctx, filename, report)
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