Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/upload/reports.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 "crypto/rand"
9 "encoding/binary"
10 "encoding/json"
11 "fmt"
12 "math"
13 "os"
14 "path/filepath"
15 "strings"
16 "time"
17
18 "golang.org/x/telemetry/internal/config"
19 "golang.org/x/telemetry/internal/counter"
20 "golang.org/x/telemetry/internal/telemetry"
21 )
22
23 // reports generates reports from inactive count files
24 func (u *uploader) reports(todo *work) ([]string, error) {
25 if mode, _ := u.dir.Mode(); mode == "off" {
26 return nil, nil // no reports
27 }
28 thisInstant := u.startTime
29 today := thisInstant.Format("2006-01-02")
30 lastWeek := latestReport(todo.uploaded)
31 if lastWeek >= today { //should never happen
32 lastWeek = ""
33 }
34 u.logger.Printf("Last week: %s, today: %s", lastWeek, today)
35 countFiles := make(map[string][]string) // expiry date string->filenames
36 earliest := make(map[string]time.Time) // earliest begin time for any counter
37 for _, f := range todo.countfiles {
38 begin, end, err := u.counterDateSpan(f)
39 if err != nil {
40 // This shouldn't happen: we should have already skipped count files that
41 // don't contain valid start or end times.
42 u.logger.Printf("BUG: failed to parse expiry for collected count file: %v", err)
43 continue
44 }
45
46 if end.Before(thisInstant) {
47 expiry := end.Format(dateFormat)
48 countFiles[expiry] = append(countFiles[expiry], f)
49 if earliest[expiry].IsZero() || earliest[expiry].After(begin) {
50 earliest[expiry] = begin
51 }
52 }
53 }
54 for expiry, files := range countFiles {
55 if notNeeded(expiry, *todo) {
56 u.logger.Printf("Files for %s not needed, deleting %v", expiry, files)
57 // The report already exists.
58 // There's another check in createReport.
59 u.deleteFiles(files)
60 continue
61 }
62 fname, err := u.createReport(earliest[expiry], expiry, files, lastWeek)
63 if err != nil {
64 u.logger.Printf("Failed to create report for %s: %v", expiry, err)
65 continue
66 }
67 if fname != "" {
68 u.logger.Printf("Ready to upload: %s", filepath.Base(fname))
69 todo.readyfiles = append(todo.readyfiles, fname)
70 }
71 }
72 return todo.readyfiles, nil
73 }
74
75 // latestReport returns the YYYY-MM-DD of the last report uploaded
76 // or the empty string if there are no reports.
77 func latestReport(uploaded map[string]bool) string {
78 var latest string
79 for name := range uploaded {
80 if strings.HasSuffix(name, ".json") {
81 if name > latest {
82 latest = name
83 }
84 }
85 }
86 if latest == "" {
87 return ""
88 }
89 // strip off the .json
90 return latest[:len(latest)-len(".json")]
91 }
92
93 // notNeeded returns true if the report for date has already been created
94 func notNeeded(date string, todo work) bool {
95 if todo.uploaded != nil && todo.uploaded[date+".json"] {
96 return true
97 }
98 // maybe the report is already in todo.readyfiles
99 for _, f := range todo.readyfiles {
100 if strings.Contains(f, date) {
101 return true
102 }
103 }
104 return false
105 }
106
107 func (u *uploader) deleteFiles(files []string) {
108 for _, f := range files {
109 if err := os.Remove(f); err != nil {
110 // this could be a race condition.
111 // conversely, on Windows, err may be nil and
112 // the file not deleted if anyone has it open.
113 u.logger.Printf("%v failed to remove %s", err, f)
114 }
115 }
116 }
117
118 // createReport for all the count files for the same date.
119 // returns the absolute path name of the file containing the report
120 func (u *uploader) createReport(start time.Time, expiryDate string, countFiles []string, lastWeek string) (string, error) {
121 uploadOK := true
122 mode, asof := u.dir.Mode()
123 if mode != "on" {
124 u.logger.Printf("No upload config or mode %q is not 'on'", mode)
125 uploadOK = false // no config, nothing to upload
126 }
127 if u.tooOld(expiryDate, u.startTime) {
128 u.logger.Printf("Expiry date %s is too old", expiryDate)
129 uploadOK = false
130 }
131 // If the mode is recorded with an asof date, don't upload if the report
132 // includes any data on or before the asof date.
133 if !asof.IsZero() && !asof.Before(start) {
134 u.logger.Printf("As-of date %s is not before start %s", asof, start)
135 uploadOK = false
136 }
137 // TODO(rfindley): check that all the x.Meta are consistent for GOOS, GOARCH, etc.
138 report := &telemetry.Report{
139 Config: u.configVersion,
140 X: computeRandom(), // json encodes all the bits
141 Week: expiryDate,
142 LastWeek: lastWeek,
143 }
144 if report.X > u.config.SampleRate && u.config.SampleRate > 0 {
145 u.logger.Printf("X: %f > SampleRate:%f, not uploadable", report.X, u.config.SampleRate)
146 uploadOK = false
147 }
148 var succeeded bool
149 for _, f := range countFiles {
150 fok := false
151 x, err := u.parseCountFile(f)
152 if err != nil {
153 u.logger.Printf("Unparseable count file %s: %v", filepath.Base(f), err)
154 continue
155 }
156 prog := findProgReport(x.Meta, report)
157 for k, v := range x.Count {
158 if counter.IsStackCounter(k) {
159 // stack
160 prog.Stacks[k] += int64(v)
161 } else {
162 // counter
163 prog.Counters[k] += int64(v)
164 }
165 succeeded = true
166 fok = true
167 }
168 if !fok {
169 u.logger.Printf("no counters found in %s", f)
170 }
171 }
172 if !succeeded {
173 return "", fmt.Errorf("none of the %d count files for %s contained counters", len(countFiles), expiryDate)
174 }
175 // 1. generate the local report
176 localContents, err := json.MarshalIndent(report, "", " ")
177 if err != nil {
178 return "", fmt.Errorf("failed to marshal report for %s: %v", expiryDate, err)
179 }
180 // check that the report can be read back
181 // TODO(pjw): remove for production?
182 var report2 telemetry.Report
183 if err := json.Unmarshal(localContents, &report2); err != nil {
184 return "", fmt.Errorf("failed to unmarshal local report for %s: %v", expiryDate, err)
185 }
186
187 var uploadContents []byte
188 if uploadOK {
189 // 2. create the uploadable version
190 cfg := config.NewConfig(u.config)
191 upload := &telemetry.Report{
192 Week: report.Week,
193 LastWeek: report.LastWeek,
194 X: report.X,
195 Config: report.Config,
196 }
197 for _, p := range report.Programs {
198 // does the uploadConfig want this program?
199 // if so, copy over the Stacks and Counters
200 // that the uploadConfig mentions.
201 if !cfg.HasGoVersion(p.GoVersion) || !cfg.HasProgram(p.Program) || !cfg.HasVersion(p.Program, p.Version) {
202 continue
203 }
204 x := &telemetry.ProgramReport{
205 Program: p.Program,
206 Version: p.Version,
207 GOOS: p.GOOS,
208 GOARCH: p.GOARCH,
209 GoVersion: p.GoVersion,
210 Counters: make(map[string]int64),
211 Stacks: make(map[string]int64),
212 }
213 upload.Programs = append(upload.Programs, x)
214 for k, v := range p.Counters {
215 if cfg.HasCounter(p.Program, k) && report.X <= cfg.Rate(p.Program, k) {
216 x.Counters[k] = v
217 }
218 }
219 // and the same for Stacks
220 // this can be made more efficient, when it matters
221 for k, v := range p.Stacks {
222 before, _, _ := strings.Cut(k, "\n")
223 if cfg.HasStack(p.Program, before) && report.X <= cfg.Rate(p.Program, before) {
224 x.Stacks[k] = v
225 }
226 }
227 }
228
229 uploadContents, err = json.MarshalIndent(upload, "", " ")
230 if err != nil {
231 return "", fmt.Errorf("failed to marshal upload report for %s: %v", expiryDate, err)
232 }
233 }
234 localFileName := filepath.Join(u.dir.LocalDir(), "local."+expiryDate+".json")
235 uploadFileName := filepath.Join(u.dir.LocalDir(), expiryDate+".json")
236
237 /* Prepare to write files */
238 // if either file exists, someone has been here ahead of us
239 // (there is still a race, but this check shortens the open window)
240 if _, err := os.Stat(localFileName); err == nil {
241 u.deleteFiles(countFiles)
242 return "", fmt.Errorf("local report %s already exists", localFileName)
243 }
244 if _, err := os.Stat(uploadFileName); err == nil {
245 u.deleteFiles(countFiles)
246 return "", fmt.Errorf("report %s already exists", uploadFileName)
247 }
248 // write the uploadable file
249 var errUpload, errLocal error
250 if uploadOK {
251 _, errUpload = exclusiveWrite(uploadFileName, uploadContents)
252 }
253 // write the local file
254 _, errLocal = exclusiveWrite(localFileName, localContents)
255 /* Wrote the files */
256
257 // even though these errors won't occur, what should happen
258 // if errUpload == nil and it is ok to upload, and errLocal != nil?
259 if errLocal != nil {
260 return "", fmt.Errorf("failed to write local file %s (%v)", localFileName, errLocal)
261 }
262 if errUpload != nil {
263 return "", fmt.Errorf("failed to write upload file %s (%v)", uploadFileName, errUpload)
264 }
265 u.logger.Printf("Created %s, deleting %d count files", filepath.Base(uploadFileName), len(countFiles))
266 u.deleteFiles(countFiles)
267 if uploadOK {
268 return uploadFileName, nil
269 }
270 return "", nil
271 }
272
273 // exclusiveWrite attempts to create filename exclusively, and if successful,
274 // writes content to the resulting file handle.
275 //
276 // It returns a boolean indicating whether the exclusive handle was acquired,
277 // and an error indicating whether the operation succeeded.
278 // If the file already exists, exclusiveWrite returns (false, nil).
279 func exclusiveWrite(filename string, content []byte) (_ bool, rerr error) {
280 f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
281 if err != nil {
282 if os.IsExist(err) {
283 return false, nil
284 }
285 return false, err
286 }
287 defer func() {
288 if err := f.Close(); err != nil && rerr == nil {
289 rerr = err
290 }
291 }()
292 if _, err := f.Write(content); err != nil {
293 return false, err
294 }
295 return true, nil
296 }
297
298 // return an existing ProgremReport, or create anew
299 func findProgReport(meta map[string]string, report *telemetry.Report) *telemetry.ProgramReport {
300 for _, prog := range report.Programs {
301 if prog.Program == meta["Program"] && prog.Version == meta["Version"] &&
302 prog.GoVersion == meta["GoVersion"] && prog.GOOS == meta["GOOS"] &&
303 prog.GOARCH == meta["GOARCH"] {
304 return prog
305 }
306 }
307 prog := telemetry.ProgramReport{
308 Program: meta["Program"],
309 Version: meta["Version"],
310 GoVersion: meta["GoVersion"],
311 GOOS: meta["GOOS"],
312 GOARCH: meta["GOARCH"],
313 Counters: make(map[string]int64),
314 Stacks: make(map[string]int64),
315 }
316 report.Programs = append(report.Programs, &prog)
317 return &prog
318 }
319
320 // computeRandom returns a cryptographic random float64 in the range [0, 1],
321 // with 52 bits of precision.
322 func computeRandom() float64 {
323 for {
324 b := make([]byte, 8)
325 _, err := rand.Read(b)
326 if err != nil {
327 panic(fmt.Sprintf("rand.Read failed: %v", err))
328 }
329 // and turn it into a float64
330 x := math.Float64frombits(binary.LittleEndian.Uint64(b))
331 if math.IsNaN(x) || math.IsInf(x, 0) {
332 continue
333 }
334 x = math.Abs(x)
335 if x < 0x1p-1000 { // avoid underflow patterns
336 continue
337 }
338 frac, _ := math.Frexp(x) // 52 bits of randomness
339 return frac*2 - 1
340 }
341 }