Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/configgen/main.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 //go:generate go run . -w
6
7 //go:build go1.22
8
9 // Package configgen generates the upload config file stored in the config.json
10 // file of golang.org/x/telemetry/config based on the chartconfig stored in
11 // config.txt.
12 package main
13
14 import (
15 "bytes"
16 "encoding/json"
17 "flag"
18 "fmt"
19 "go/version"
20 "log"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "regexp"
25 "slices"
26 "sort"
27 "strings"
28
29 "golang.org/x/mod/semver"
30 "golang.org/x/telemetry/internal/chartconfig"
31 "golang.org/x/telemetry/internal/telemetry"
32 )
33
34 var (
35 write = flag.Bool("w", false, "if set, write the config file; otherwise, print to stdout")
36 force = flag.Bool("f", false, "if set, force the write of the config file even if the current content is still valid")
37
38 // SamplingRate is the fraction of otherwise uploadable reports that will be uploaded
39 SamplingRate = 1.0
40 )
41
42 func main() {
43 flag.Parse()
44
45 gcfgs, err := chartconfig.Load()
46 if err != nil {
47 log.Fatal(err)
48 }
49
50 // The padding heuristics below are based on the example of gopls.
51 //
52 // The goal is to pad enough versions for a quarter.
53 uCfg, err := generate(gcfgs, padding{
54 // 6 releases into the future translates to approximately three months for gopls.
55 releases: 6,
56 // We may release gopls 1.0, but won't release 2.0 in a three month timespan!
57 maj: 1,
58 // We don't usually do more than one minor release a month.
59 majmin: 3,
60 // Since golang/go#55267, which committed to adhering to semver, gopls
61 // hasn't had more than 5 patches per minor version.
62 patch: 6,
63 // Gopls has never had more than 4 prereleases.
64 pre: 4,
65 })
66
67 if err != nil {
68 log.Fatal(err)
69 }
70 cfgJSON, err := json.MarshalIndent(uCfg, "", "\t")
71 if err != nil {
72 log.Fatal(err)
73 }
74
75 if !*write {
76 fmt.Println(string(cfgJSON))
77 os.Exit(0)
78 }
79
80 configFile, err := configFile()
81 if err != nil {
82 log.Fatalf("finding config file: %v", err)
83 }
84
85 if !*force {
86 currentCfg, err := readConfig(configFile)
87 if err != nil {
88 log.Fatal(err)
89 }
90 // Guarantee that we have enough padding to do two patches releases tomorrow.
91 minCfg, err := generate(gcfgs, padding{
92 releases: 2,
93 maj: 1,
94 majmin: 1, // we're not ever going to do more than one major/minor release in a day
95 patch: 2,
96 pre: 2, // in a single day, we wouldn't prep more than two prereleases per version
97 })
98 if err != nil {
99 log.Fatal(err)
100 }
101 if contains(currentCfg, minCfg) {
102 fmt.Fprintln(os.Stderr, "not writing the config file as it is still valid; use -f to force")
103 os.Exit(0)
104 }
105 }
106 if err := os.WriteFile(configFile, cfgJSON, 0666); err != nil {
107 log.Fatal(err)
108 }
109 }
110
111 // configFile returns the path to the x/telemetry/config config.json file in
112 // this repo.
113 //
114 // The file must already exist: this won't be a valid location if running from
115 // the module cache; this functionality only works when executed from the
116 // telemetry repo.
117 func configFile() (string, error) {
118 out, err := exec.Command("go", "list", "-f", "{{.Dir}}", "golang.org/x/telemetry/internal/configgen").Output()
119 if err != nil {
120 return "", err
121 }
122 dir := strings.TrimSpace(string(out))
123 configFile := filepath.Join(dir, "..", "..", "config", "config.json")
124 if _, err := os.Stat(configFile); err != nil {
125 return "", err
126 }
127 return configFile, nil
128 }
129
130 func readConfig(file string) (*telemetry.UploadConfig, error) {
131 data, err := os.ReadFile(file)
132 if err != nil {
133 return nil, fmt.Errorf("reading config file: %v", err)
134 }
135 cfg := new(telemetry.UploadConfig)
136 if err := json.Unmarshal(data, cfg); err != nil {
137 return nil, fmt.Errorf("unmarshalling config file: %v", err)
138 }
139 return cfg, nil
140 }
141
142 // generate computes the upload config from chart configs and module
143 // information, returning the resulting formatted JSON.
144 func generate(gcfgs []chartconfig.ChartConfig, padding padding) (*telemetry.UploadConfig, error) {
145 ucfg := &telemetry.UploadConfig{
146 GOOS: goos(),
147 GOARCH: goarch(),
148 // the probability of uploading a report
149 SampleRate: SamplingRate,
150 }
151 var err error
152 ucfg.GoVersion, err = goVersions()
153 if err != nil {
154 return nil, fmt.Errorf("querying go info: %v", err)
155 }
156
157 for i, r := range gcfgs {
158 if err := ValidateChartConfig(r); err != nil {
159 // TODO(rfindley): this is a poor way to identify the faulty record. We
160 // should probably store position information in the ChartConfig.
161 return nil, fmt.Errorf("chart config #%d (%q): %v", i, r.Title, err)
162 }
163 }
164
165 var (
166 programs = make(map[string]*telemetry.ProgramConfig) // package path -> config
167 minVersions = make(map[string]string) // package path -> min version required, or "" for all
168 )
169 for _, gcfg := range gcfgs {
170 pcfg := programs[gcfg.Program]
171 if pcfg == nil {
172 pcfg = &telemetry.ProgramConfig{
173 Name: gcfg.Program,
174 }
175 programs[gcfg.Program] = pcfg
176 minVersions[gcfg.Program] = gcfg.Version
177 }
178 minVersions[gcfg.Program] = minVersion(minVersions[gcfg.Program], gcfg.Version)
179 ccfg := telemetry.CounterConfig{
180 Name: gcfg.Counter,
181 Rate: 1.0, // TODO(rfindley): how should rate be configured?
182 Depth: gcfg.Depth,
183 }
184 if gcfg.Depth > 0 {
185 pcfg.Stacks = append(pcfg.Stacks, ccfg)
186 } else {
187 pcfg.Counters = append(pcfg.Counters, ccfg)
188 }
189 }
190
191 for _, p := range programs {
192 minVersion := minVersions[p.Name]
193
194 // Collect eligible program versions. If p is a toolchain tool (cmd/go,
195 // cmd/compile, etc), these come out of the Go versions queried above.
196 // Otherwise, they come from the proxy.
197 //
198 // In both of these cases, the versions should be valid, but we verify
199 // anyway as otherwise the version comparison is meaningless.
200 // (and in fact, there is an invalid go1.9.2rc2 version in the proxy)
201 if telemetry.IsToolchainProgram(p.Name) {
202 // Note: no need to pad versions for toolchain programs, since the
203 // toolchain is released infrequently.
204 // (and in any case, version padding only works for semantic versions)
205 for _, v := range ucfg.GoVersion {
206 if !version.IsValid(v) {
207 // The proxy toolchain versions list go1.9.2rc2, which is invalid.
208 // Skip it. Note: this also filters out "devel", but that is added
209 // back below.
210 continue
211 }
212
213 if minVersion == "" || version.Compare(minVersion, v) <= 0 {
214 p.Versions = append(p.Versions, v)
215 }
216 }
217 } else {
218 versions, err := listProxyVersions(p.Name)
219 if err != nil {
220 return nil, fmt.Errorf("listing versions for %q: %v", p.Name, err)
221 }
222 // Filter proxy versions in place.
223 i := 0
224 for _, v := range versions {
225 if !semver.IsValid(v) {
226 return nil, fmt.Errorf("invalid semver %q returned from proxy for %q", v, p.Name)
227 }
228 if minVersion == "" || semver.Compare(minVersion, v) <= 0 {
229 versions[i] = v
230 i++
231 }
232 }
233 p.Versions = padVersions(versions[:i], prereleasesForProgram(p.Name), padding)
234 }
235 // Allow collecting counters for devel versions of gopls and toolchain
236 // programs.
237 // TODO(golang/go#62271): revert once no longer needed
238 if p.Name == "golang.org/x/tools/gopls" || telemetry.IsToolchainProgram(p.Name) {
239 p.Versions = append(p.Versions, "devel") // added at the end.
240 }
241 ucfg.Programs = append(ucfg.Programs, p)
242 }
243 sort.Slice(ucfg.Programs, func(i, j int) bool {
244 return ucfg.Programs[i].Name < ucfg.Programs[j].Name
245 })
246
247 return ucfg, nil
248 }
249
250 // contains reports whether outer contains all program versions of inner, and
251 // is otherwise equivalent to inner.
252 func contains(outer, inner *telemetry.UploadConfig) bool {
253 if !slices.Equal(outer.GOARCH, inner.GOARCH) {
254 return false
255 }
256 if !slices.Equal(outer.GOOS, inner.GOOS) {
257 return false
258 }
259 if !slices.Equal(outer.GoVersion, inner.GoVersion) {
260 return false
261 }
262
263 for _, pi := range inner.Programs {
264 i := slices.IndexFunc(outer.Programs, func(po *telemetry.ProgramConfig) bool {
265 return po.Name == pi.Name
266 })
267 if i < 0 {
268 return false
269 }
270 po := outer.Programs[i]
271 if !sliceContains(po.Versions, pi.Versions) {
272 return false
273 }
274 if !slices.Equal(po.Counters, pi.Counters) {
275 return false
276 }
277 if !slices.Equal(po.Stacks, pi.Stacks) {
278 return false
279 }
280 }
281 for _, po := range outer.Programs {
282 if !slices.ContainsFunc(inner.Programs, func(pi *telemetry.ProgramConfig) bool {
283 return pi.Name == po.Name
284 }) {
285 return false
286 }
287 }
288 return true
289 }
290
291 func sliceContains[T comparable](outer, inner []T) bool {
292 m := toMap(outer)
293 for _, v := range inner {
294 if !m[v] {
295 return false
296 }
297 }
298 return true
299 }
300
301 func toMap[T comparable](s []T) map[T]bool {
302 m := make(map[T]bool)
303 for _, v := range s {
304 m[v] = true
305 }
306 return m
307 }
308
309 // prereleasesForProgram returns the set of prereleases to use for the provided
310 // program. We may need to customize this for the conventions of different
311 // programs.
312 func prereleasesForProgram(program string) []string {
313 // Surely eight prereleases is enough for any program... :)
314 return []string{"pre.1", "pre.2", "pre.3", "pre.4", "pre.5", "pre.6", "pre.7", "pre.8"}
315 }
316
317 // minVersion returns the lesser semantic version of v1 and v2.
318 //
319 // As a special case, the empty string is treated as an absolute minimum
320 // (empty => all versions are greater).
321 func minVersion(v1, v2 string) string {
322 if v1 == "" || v2 == "" {
323 return ""
324 }
325 if semver.Compare(v1, v2) > 0 {
326 return v2
327 }
328 return v1
329 }
330
331 // goos returns a sorted slice of known GOOS values.
332 func goos() []string {
333 var gooses []string
334 for goos := range knownOS {
335 gooses = append(gooses, goos)
336 }
337 sort.Strings(gooses)
338 return gooses
339 }
340
341 // goarch returns a sorted slice of known GOARCH values.
342 func goarch() []string {
343 var arches []string
344 for arch := range knownArch {
345 arches = append(arches, arch)
346 }
347 sort.Strings(arches)
348 return arches
349 }
350
351 // goInfo queries the proxy for information about go distributions, including
352 // versions, GOOS, and GOARCH values.
353 func goVersions() ([]string, error) {
354 // Trick: read Go distribution information from the module versions of
355 // golang.org/toolchain. These define the set of valid toolchains, and
356 // therefore are a reasonable source for version information.
357 //
358 // A more authoritative source for this information may be
359 // https://go.dev/dl?mode=json&include=all.
360 proxyVersions, err := listProxyVersions("golang.org/toolchain")
361 if err != nil {
362 return nil, fmt.Errorf("listing toolchain versions: %v", err)
363 }
364 var goVersionRx = regexp.MustCompile(`^-(go.+)\.[^.]+-[^.]+$`)
365 verSet := make(map[string]struct{})
366 for _, v := range proxyVersions {
367 pre := semver.Prerelease(v)
368 match := goVersionRx.FindStringSubmatch(pre)
369 if match == nil {
370 return nil, fmt.Errorf("proxy version %q does not match prerelease regexp %q", v, goVersionRx)
371 }
372 verSet[match[1]] = struct{}{}
373 }
374 var vers []string
375 for v := range verSet {
376 vers = append(vers, v)
377 }
378 sort.Sort(byGoVersion(vers))
379 // TODO(golang/go#62271): temporarily monitor 'devel'.
380 vers = append(vers, "devel")
381 return vers, nil
382 }
383
384 type byGoVersion []string
385
386 func (vs byGoVersion) Len() int { return len(vs) }
387 func (vs byGoVersion) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] }
388 func (vs byGoVersion) Less(i, j int) bool {
389 cmp := version.Compare(vs[i], vs[j])
390 if cmp != 0 {
391 return cmp < 0
392 }
393 // To ensure that we have a stable sort, order equivalent Go versions lexically.
394 return vs[i] < vs[j]
395 }
396
397 // versionsForTesting contains versions to use for testing, rather than
398 // querying the proxy.
399 var versionsForTesting map[string][]string
400
401 // listProxyVersions queries the Go module mirror for published versions of the
402 // given modulePath.
403 //
404 // modulePath must be lower-case (or already escaped): this function doesn't do
405 // any escaping of upper-cased letters, as is required by the proxy prototol
406 // (https://go.dev/ref/mod#goproxy-protocol).
407 func listProxyVersions(modulePath string) ([]string, error) {
408 if vers, ok := versionsForTesting[modulePath]; ok {
409 return vers, nil
410 }
411 cmd := exec.Command("go", "list", "-m", "--versions", modulePath)
412 var stderr bytes.Buffer
413 cmd.Stderr = &stderr
414 out, err := cmd.Output()
415 if err != nil {
416 return nil, fmt.Errorf("listing versions: %v (stderr: %v)", err, stderr.String())
417 }
418 fields := strings.Fields(strings.TrimSpace(string(out)))
419 if len(fields) == 0 {
420 return nil, fmt.Errorf("invalid version list output: %q", string(out))
421 }
422 return fields[1:], nil
423 }
424
425 // padding defines constraints on additional versions to pad.
426 //
427 // These constraints help restrict version padding to "reasonable" versions,
428 // based on heuristics such as "we never do more than 3 prereleases for a given
429 // version" or "we never have more than 5 patch versions" or "we can't do more
430 // than 10 total releases over that time period". See the field documentation
431 // for details.
432 type padding struct {
433 releases int // bounds on the total number of releases
434 maj int // bounds the number of new major versions
435 majmin int // bounds the number of new major+minor versions
436 patch int // bounds the number of new patch versions
437 pre int // the number of prereleases to pad per release
438 }
439
440 // padVersions pads the existing version list with potential next versions, so
441 // that we don't have to wait an additional day to start getting reports for a
442 // newly tagged version.
443 //
444 // The prereleases argument may be supplied to provide a set of potential
445 // prerelease candidates. For example, if the program releases prereleases of
446 // the form "-pre.N", prereleases should be {"pre.1", "pre.2", ...}. For each
447 // potential next release version, the next two prerelease versions will be
448 // selected out of the provided set of prereleases.
449 func padVersions(versions []string, prereleasePatterns []string, padding padding) []string {
450 versions = slices.Clone(versions)
451 semver.Sort(versions)
452
453 latestRelease := "v0.0.0"
454 all := make(map[string]bool) // for de-duplicating padded versions
455 for _, v := range versions {
456 cv := semver.Canonical(v)
457 all[cv] = true
458 if semver.Prerelease(cv) == "" && semver.Compare(latestRelease, cv) < 0 {
459 latestRelease = cv
460 }
461 }
462
463 parsedLatest, ok := parseSemver(latestRelease)
464 if !ok {
465 // "can't happen", since the latest release version should always be canonical.
466 panic(fmt.Sprintf("unable to parse latest release version %q", latestRelease))
467 }
468
469 // Pad the latest version only.
470 //
471 // This assumes that the program in question doesn't patch older releases
472 // (as is the case with gopls). If that assumption ever changes, we may need
473 // to apply padding to older versions as well.
474 versionsToPad := []semversion{parsedLatest}
475
476 var maj, min, patch int
477 for _, toPad := range versionsToPad {
478 for majPadding := 0; majPadding <= padding.maj; majPadding++ {
479 maj = toPad.major + majPadding
480 for minPadding := 0; minPadding+majPadding <= padding.majmin; minPadding++ {
481 if majPadding == 0 {
482 min = toPad.minor + minPadding
483 } else {
484 min = minPadding
485 }
486 for patchPadding := 0; patchPadding <= padding.patch; patchPadding++ {
487 releases := majPadding + minPadding + patchPadding
488 if releases == 0 || releases > padding.releases {
489 continue
490 }
491 if majPadding == 0 && minPadding == 0 {
492 patch = toPad.patch + patchPadding
493 } else {
494 patch = patchPadding
495 }
496
497 v := fmt.Sprintf("v%d.%d.%d", maj, min, patch)
498 if all[v] {
499 // This guard is future proofing: we may have seen this version
500 // before if we are ever padding something other than the latest
501 // version.
502 continue
503 }
504 versions = append(versions, v)
505
506 // We may already have prereleases at this version. Don't pad
507 // additional prereleases, under the assumption that we don't
508 // typically have more than padding.pre prereleases.
509 nextPrerelease := 0
510 for i, patt := range prereleasePatterns {
511 pre := fmt.Sprintf("%s-%s", v, patt)
512 if all[pre] {
513 nextPrerelease = i + 1
514 }
515 }
516 for i := nextPrerelease; i < len(prereleasePatterns) && i < padding.pre; i++ {
517 pre := fmt.Sprintf("%s-%s", v, prereleasePatterns[i])
518 versions = append(versions, pre)
519 }
520 }
521 }
522 }
523 }
524
525 semver.Sort(versions)
526 return versions
527 }
528
529 // version is a parsed semantic version.
530 type semversion struct {
531 major, minor, patch int
532 pre string
533 }
534
535 // parseSemver attempts to parse semver components out of the provided semver
536 // v. If v is not valid semver in canonical form, parseSemver returns _, _, _,
537 // _, false.
538 func parseSemver(v string) (_ semversion, ok bool) {
539 var parsed semversion
540 v, parsed.pre, _ = strings.Cut(v, "-")
541 if _, err := fmt.Sscanf(v, "v%d.%d.%d", &parsed.major, &parsed.minor, &parsed.patch); err == nil {
542 ok = true
543 }
544 return parsed, ok
545 }