-
Notifications
You must be signed in to change notification settings - Fork 84
Retry failed snapshot submission #822
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
Open
seanlinsley
wants to merge
3
commits into
main
Choose a base branch
from
retry-queue
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -3,59 +3,27 @@ package output | |
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "encoding/xml" | ||
| "fmt" | ||
| "io" | ||
| "mime" | ||
| "mime/multipart" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/pganalyze/collector/config" | ||
| "github.com/pganalyze/collector/state" | ||
| "github.com/pganalyze/collector/util" | ||
| ) | ||
|
|
||
| func uploadSnapshot(ctx context.Context, httpClient *http.Client, grant *state.Grant, logger *util.Logger, data []byte, filename string) (string, error) { | ||
| var err error | ||
|
|
||
| func uploadSnapshot(ctx context.Context, httpClient *http.Client, grant *state.Grant, logger *util.Logger, data []byte) error { | ||
| if !grant.ValidForS3Until.After(time.Now()) { | ||
| return "", fmt.Errorf("Error - can't upload without valid S3 grant") | ||
| } | ||
|
|
||
| if grant.S3URL == "" && grant.LocalDir != "" { | ||
| location := grant.LocalDir + filename | ||
| err = os.MkdirAll(filepath.Dir(location), 0755) | ||
| if err != nil { | ||
| logger.PrintError("Error creating target directory: %s", err) | ||
| return "", err | ||
| } | ||
|
|
||
| err = os.WriteFile(location, data, 0644) | ||
| if err != nil { | ||
| logger.PrintError("Error writing local file: %s", err) | ||
| return "", err | ||
| } | ||
| return location, nil | ||
| return fmt.Errorf("Error - can't upload without valid S3 grant") | ||
| } | ||
|
|
||
| logger.PrintVerbose("Successfully prepared S3 request - size of request body: %.4f MB", float64(len(data))/1024.0/1024.0) | ||
|
|
||
| return uploadToS3(ctx, httpClient, grant.S3URL, grant.S3Fields, data, filename) | ||
| return uploadToS3(ctx, httpClient, grant.S3URL, grant.S3Fields, data) | ||
| } | ||
|
|
||
| type s3UploadResponse struct { | ||
| Location string | ||
| Bucket string | ||
| Key string | ||
| } | ||
|
|
||
| func uploadToS3(ctx context.Context, httpClient *http.Client, S3URL string, S3Fields map[string]string, data []byte, filename string) (string, error) { | ||
| func uploadToS3(ctx context.Context, httpClient *http.Client, S3URL string, S3Fields map[string]string, data []byte) error { | ||
| var err error | ||
| var formBytes bytes.Buffer | ||
|
|
||
|
|
@@ -64,110 +32,37 @@ func uploadToS3(ctx context.Context, httpClient *http.Client, S3URL string, S3Fi | |
| for key, val := range S3Fields { | ||
| err = writer.WriteField(key, val) | ||
| if err != nil { | ||
| return "", err | ||
| return err | ||
| } | ||
| } | ||
|
|
||
| part, _ := writer.CreateFormFile("file", filename) | ||
| part, _ := writer.CreateFormFile("file", "snapshot") | ||
| _, err = part.Write(data) | ||
| if err != nil { | ||
| return "", err | ||
| return err | ||
| } | ||
|
|
||
| writer.Close() | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "POST", S3URL, &formBytes) | ||
| if err != nil { | ||
| return "", err | ||
| return err | ||
| } | ||
| req.Header.Set("Content-Type", writer.FormDataContentType()) | ||
|
|
||
| resp, err := httpClient.Do(req) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusCreated { | ||
| return "", fmt.Errorf("Bad S3 upload return code %s (expected 201 Created), body: %s", resp.Status, body) | ||
| } | ||
|
|
||
| var s3Resp s3UploadResponse | ||
| err = xml.Unmarshal(body, &s3Resp) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| return s3Resp.Key, nil | ||
| } | ||
|
|
||
| func submitSnapshot(ctx context.Context, server *state.Server, opts state.CollectionOpts, logger *util.Logger, s3Location string, collectedAt time.Time, compact bool) error { | ||
| requestURL := server.Config.APIBaseURL + "/v2/snapshots" | ||
|
|
||
| if opts.TestRun { | ||
| requestURL = server.Config.APIBaseURL + "/v2/snapshots/test" | ||
| } else if compact { | ||
| requestURL = server.Config.APIBaseURL + "/v2/snapshots/compact" | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I dropped this function primarily so that the snapshot UUID and collected timestamp no longer need to be retained. |
||
| } | ||
|
|
||
| data := url.Values{ | ||
| "s3_location": {s3Location}, | ||
| "collected_at": {fmt.Sprintf("%d", collectedAt.Unix())}, | ||
| } | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, "POST", requestURL, strings.NewReader(data.Encode())) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| req.Header = config.APIHeaders(server.Config, opts.TestRun, opts.StartedAt) | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
| req.Header.Add("Accept", "application/json,text/plain") | ||
|
|
||
| resp, err := server.Config.HTTPClientWithRetry.Do(req) | ||
| if err != nil { | ||
| return util.CleanHTTPError(err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return fmt.Errorf("Error when submitting: %s\n", body) | ||
| } | ||
|
|
||
| if opts.TestRun { | ||
| contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) | ||
| if err != nil { | ||
| return fmt.Errorf("Error decoding response: %s\n", err) | ||
| } | ||
|
|
||
| var msg string | ||
|
|
||
| if contentType == "application/json" { | ||
| var jsonBody struct { | ||
| Message string `json:"message"` | ||
| } | ||
| err = json.Unmarshal(body, &jsonBody) | ||
| if err != nil { | ||
| return fmt.Errorf("Error decoding response: %s\n", err) | ||
| } | ||
| msg = jsonBody.Message | ||
| } else { | ||
| msg = string(body) | ||
| } | ||
|
|
||
| if len(msg) > 0 { | ||
| logger.PrintInfo(" %s", msg) | ||
| } | ||
| if resp.StatusCode != http.StatusCreated { | ||
| return fmt.Errorf("Bad S3 upload return code %s (expected 201 Created), body: %s", resp.Status, body) | ||
| } | ||
|
|
||
| return nil | ||
|
|
||
This file contains hidden or 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 hidden or 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,36 @@ | ||
| package state | ||
|
|
||
| import ( | ||
| "sync/atomic" | ||
| ) | ||
|
|
||
| // MemoryLimit tracks a shared byte counter against a configurable cap. | ||
| // Callers use Add/Remove to adjust the counter and Size to inspect it. | ||
| // OverLimit reports whether the current usage has exceeded the cap. | ||
| type MemoryLimit struct { | ||
| bytes atomic.Int64 | ||
| limit int64 | ||
| } | ||
|
|
||
| // Global memory limit for all snapshot queues | ||
| var QueueMemory = NewMemoryLimit(200 * 1024 * 1024) | ||
|
|
||
| func NewMemoryLimit(cap int64) *MemoryLimit { | ||
| return &MemoryLimit{limit: cap} | ||
| } | ||
|
|
||
| func (m *MemoryLimit) Add(n int64) int64 { | ||
| return m.bytes.Add(n) | ||
| } | ||
|
|
||
| func (m *MemoryLimit) Remove(n int64) int64 { | ||
| return m.bytes.Add(-n) | ||
| } | ||
|
|
||
| func (m *MemoryLimit) Size() int64 { | ||
| return m.bytes.Load() | ||
| } | ||
|
|
||
| func (m *MemoryLimit) OverLimit() bool { | ||
| return m.bytes.Load() > m.limit | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is
LocalDirstill in use?