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 // Download fetches the requested telemetry UploadConfig using "go mod
29 // download". If envOverlay is provided, it is appended to the environment used
30 // for invoking the go command.
31 //
32 // The second result is the canonical version of the requested configuration.
33 func Download(version string, envOverlay []string) (*telemetry.UploadConfig, string, error) {
34 if version == "" {
35 version = "latest"
36 }
37 modVer := ModulePath + "@" + version
38 var stdout, stderr bytes.Buffer
39 cmd := exec.Command("go", "mod", "download", "-json", modVer)
40 cmd.Env = append(os.Environ(), envOverlay...)
41 cmd.Stdout = &stdout
42 cmd.Stderr = &stderr
43 if err := cmd.Run(); err != nil {
44 var info struct {
45 Error string
46 }
47 if err := json.Unmarshal(stdout.Bytes(), &info); err == nil && info.Error != "" {
48 return nil, "", fmt.Errorf("failed to download config module: %v", info.Error)
49 }
50 return nil, "", fmt.Errorf("failed to download config module: %w\n%s", err, &stderr)
51 }
52
53 var info struct {
54 Dir string
55 Version string
56 Error string
57 }
58 if err := json.Unmarshal(stdout.Bytes(), &info); err != nil || info.Dir == "" {
59 return nil, "", fmt.Errorf("failed to download config module (invalid JSON): %w", err)
60 }
61 data, err := os.ReadFile(filepath.Join(info.Dir, configFileName))
62 if err != nil {
63 return nil, "", fmt.Errorf("invalid config module: %w", err)
64 }
65 cfg := new(telemetry.UploadConfig)
66 if err := json.Unmarshal(data, cfg); err != nil {
67 return nil, "", fmt.Errorf("invalid config: %w", err)
68 }
69 return cfg, info.Version, nil
70 }