Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/configstore/download.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 configstore abstracts interaction with the telemetry config server.
6 // Telemetry config (golang.org/x/telemetry/config) is distributed as a go
7 // module containing go.mod and config.json. Programs that upload collected
8 // counters download the latest config using `go mod download`. This provides
9 // verification of downloaded configuration and cacheability.
10 package configstore
11
12 import (
13 "bytes"
14 "encoding/json"
15 "fmt"
16 "os"
17 "os/exec"
18 "path/filepath"
19
20 "golang.org/x/telemetry/internal/telemetry"
21 )
22
23 const (
24 ModulePath = "golang.org/x/telemetry/config"
25 configFileName = "config.json"
26 )
27
28 // needNoConsole is used on windows to set the windows.CREATE_NO_WINDOW
29 // creation flag.
30 var needNoConsole = func(cmd *exec.Cmd) {}
31
32 // Download fetches the requested telemetry UploadConfig using "go mod
33 // download". If envOverlay is provided, it is appended to the environment used
34 // for invoking the go command.
35 //
36 // The second result is the canonical version of the requested configuration.
37 func Download(version string, envOverlay []string) (*telemetry.UploadConfig, string, error) {
38 if version == "" {
39 version = "latest"
40 }
41 modVer := ModulePath + "@" + version
42 var stdout, stderr bytes.Buffer
43 cmd := exec.Command("go", "mod", "download", "-json", modVer)
44 needNoConsole(cmd)
45 cmd.Env = append(os.Environ(), envOverlay...)
46 cmd.Stdout = &stdout
47 cmd.Stderr = &stderr
48 if err := cmd.Run(); err != nil {
49 var info struct {
50 Error string
51 }
52 if err := json.Unmarshal(stdout.Bytes(), &info); err == nil && info.Error != "" {
53 return nil, "", fmt.Errorf("failed to download config module: %v", info.Error)
54 }
55 return nil, "", fmt.Errorf("failed to download config module: %w\n%s", err, &stderr)
56 }
57
58 var info struct {
59 Dir string
60 Version string
61 Error string
62 }
63 if err := json.Unmarshal(stdout.Bytes(), &info); err != nil || info.Dir == "" {
64 return nil, "", fmt.Errorf("failed to download config module (invalid JSON): %w", err)
65 }
66 data, err := os.ReadFile(filepath.Join(info.Dir, configFileName))
67 if err != nil {
68 return nil, "", fmt.Errorf("invalid config module: %w", err)
69 }
70 cfg := new(telemetry.UploadConfig)
71 if err := json.Unmarshal(data, cfg); err != nil {
72 return nil, "", fmt.Errorf("invalid config: %w", err)
73 }
74 return cfg, info.Version, nil
75 }