Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/upload/upload.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package upload
6
7 import (
8 "bytes"
9 "net/http"
10 "os"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "time"
15 )
16
17 var (
18 dateRE = regexp.MustCompile(`(\d\d\d\d-\d\d-\d\d)[.]json$`)
19 dateFormat = "2006-01-02"
20 // TODO(rfindley): use dateFormat throughout.
21 )
22
23 // uploadReportDate returns the date component of the upload file name, or "" if the
24 // date was unmatched.
25 func (u *uploader) uploadReportDate(fname string) time.Time {
26 match := dateRE.FindStringSubmatch(fname)
27 if match == nil || len(match) < 2 {
28 u.logger.Printf("malformed report name: missing date: %q", filepath.Base(fname))
29 return time.Time{}
30 }
31 d, err := time.Parse(dateFormat, match[1])
32 if err != nil {
33 u.logger.Printf("malformed report name: bad date: %q", filepath.Base(fname))
34 return time.Time{}
35 }
36 return d
37 }
38
39 func (u *uploader) uploadReport(fname string) {
40 thisInstant := u.startTime
41 // TODO(rfindley): use uploadReportDate here, once we've done a gopls release.
42
43 // first make sure it is not in the future
44 today := thisInstant.Format("2006-01-02")
45 match := dateRE.FindStringSubmatch(fname)
46 if match == nil || len(match) < 2 {
47 u.logger.Printf("Report name %q missing date", filepath.Base(fname))
48 } else if match[1] > today {
49 u.logger.Printf("Report date for %q is later than today (%s)", filepath.Base(fname), today)
50 return // report is in the future, which shouldn't happen
51 }
52 buf, err := os.ReadFile(fname)
53 if err != nil {
54 u.logger.Printf("%v reading %s", err, fname)
55 return
56 }
57 if u.uploadReportContents(fname, buf) {
58 // anything left to do?
59 }
60 }
61
62 // try to upload the report, 'true' if successful
63 func (u *uploader) uploadReportContents(fname string, buf []byte) bool {
64 fdate := strings.TrimSuffix(filepath.Base(fname), ".json")
65 fdate = fdate[len(fdate)-len("2006-01-02"):]
66
67 newname := filepath.Join(u.dir.UploadDir(), fdate+".json")
68 if _, err := os.Stat(newname); err == nil {
69 // Another process uploaded but failed to clean up (or hasn't yet cleaned
70 // up). Ensure that cleanup occurs.
71 _ = os.Remove(fname)
72 return false
73 }
74
75 // Lock the upload, to prevent duplicate uploads.
76 {
77 lockname := newname + ".lock"
78 lockfile, err := os.OpenFile(lockname, os.O_CREATE|os.O_EXCL, 0666)
79 if err != nil {
80 u.logger.Printf("Failed to acquire lock %s: %v", lockname, err)
81 return false
82 }
83 _ = lockfile.Close()
84 defer os.Remove(lockname)
85 }
86
87 endpoint := u.uploadServerURL + "/" + fdate
88 b := bytes.NewReader(buf)
89 resp, err := http.Post(endpoint, "application/json", b)
90 if err != nil {
91 u.logger.Printf("Error upload %s to %s: %v", filepath.Base(fname), endpoint, err)
92 return false
93 }
94 // hope for a 200, remove file on a 4xx, otherwise it will be retried by another process
95 if resp.StatusCode != 200 {
96 u.logger.Printf("Failed to upload %s to %s: %s", filepath.Base(fname), endpoint, resp.Status)
97 if resp.StatusCode >= 400 && resp.StatusCode < 500 {
98 err := os.Remove(fname)
99 if err == nil {
100 u.logger.Printf("Removed local/%s", filepath.Base(fname))
101 } else {
102 u.logger.Printf("Error removing local/%s: %v", filepath.Base(fname), err)
103 }
104 }
105 return false
106 }
107 // Store a copy of the uploaded report in the uploaded directory.
108 if err := os.WriteFile(newname, buf, 0644); err == nil {
109 os.Remove(fname) // if it exists
110 }
111 u.logger.Printf("Uploaded %s to %q", fdate+".json", endpoint)
112 return true
113 }