aboutsummaryrefslogtreecommitdiff
path: root/ui/build/cipd.go
blob: ba7ca3190302686c58464ce89ac300c001e166b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Copyright 2025 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package build

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
)

const (
	cipdProxyPolicyPath = "build/soong/ui/build/cipd_proxy_policy.txtpb"
	cipdProxyUrlKey     = "CIPD_PROXY_URL"
)

type cipdProxy struct {
	cmd      *Cmd
	wg       sync.WaitGroup
	stopping atomic.Bool
}

func cipdPath(config Config) string {
	return filepath.Join("prebuilts/cipd", config.HostPrebuiltTag(), "cipd")
}

func shouldRunCIPDProxy(config Config) bool {
	cipdPath := cipdPath(config)
	_, err := os.Stat(cipdPath)
	return err == nil
}

func startCIPDProxyServer(ctx Context, config Config) *cipdProxy {
	ctx.Status.Status("Starting CIPD proxy server...")

	cipdArgs := []string{"proxy", "-proxy-policy", cipdProxyPolicyPath}
	adcFlagAdded := false

	if config.UseRBE() {
		// Determine RBE authentication mechanism and propagate to CIPD flags.
		authType, authValue := config.rbeAuth()
		switch authType {
		case "RBE_credential_file":
			cipdArgs = append(cipdArgs, "-service-account-json", authValue)
		case "RBE_credentials_helper", "RBE_use_google_prod_creds":
			helperPath := filepath.Join(config.rbeDir(), "credshelper")

			var credHelperArgsParts []string
			// RBE_credentials_helper_args contains space-separated arguments for the helper
			// and need to be formatted as repeated 'args:"..."' for the -credential-helper spec.
			// e.g. "--f=foo --b=bar" -> 'args:"--f=foo" args:"--b=bar"'.
			if rbeArgsStr, ok := config.environ.Get("RBE_credentials_helper_args"); ok && rbeArgsStr != "" {
				argList := strings.Fields(rbeArgsStr)
				for _, arg := range argList {
					credHelperArgsParts = append(credHelperArgsParts, fmt.Sprintf("args:%q", arg))
				}
			} else {
				credHelperArgsParts = append(credHelperArgsParts, fmt.Sprintf("args:%q", "--auth_source=automaticAuth"))
				credHelperArgsParts = append(credHelperArgsParts, fmt.Sprintf("args:%q", "--gcert_refresh_timeout=20"))
			}
			helperSpec := fmt.Sprintf("protocol:RECLIENT exec:'%s' %s", helperPath, strings.Join(credHelperArgsParts, " "))
			cipdArgs = append(cipdArgs, "-credential-helper", helperSpec)
		case "RBE_use_application_default_credentials", "RBE_use_gce_credentials":
			fallthrough
		default:
			cipdArgs = append(cipdArgs, "-application-default-credentials=always")
			adcFlagAdded = true
		}
	} else {
		ctx.Printf("No RBE configuration detected. You may need to use application default credentials.")
	}

	if !adcFlagAdded {
		// RBE instructions for non-corp machines set both RBE_credentials_helper and
		// RBE_use_application_default_credentials. Pass that along to CIPD as well.
		// Even if USE_RBE=false, CIPD can still use ADC.
		if useAdcStr, ok := config.environ.Get("RBE_use_application_default_credentials"); ok {
			parsedVal, err := strconv.ParseBool(useAdcStr)
			if err == nil && parsedVal {
				cipdArgs = append(cipdArgs, "-application-default-credentials=always")
			}
		}
	}

	cipdCmd := fmt.Sprintf("cipd %s", strings.Join(cipdArgs, " "))
	ctx.Printf("Starting CIPD proxy server with: %s", cipdCmd)

	cmd := Command(ctx, config, "cipd", cipdPath(config), cipdArgs...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal(err)
	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}
	cp := cipdProxy{cmd: cmd}
	cp.wg.Add(1)
	go func() {
		// Log any error output from cipd until it exits.
		defer cp.wg.Done()

		bufReader := bufio.NewReader(stderr)
		for {
			l, err := bufReader.ReadString('\n')
			if err != nil {
				if errors.Is(err, io.EOF) {
					if !cp.stopping.Load() {
						err := cmd.Wait()
						ctx.Printf("cipd: unexpected EOF, process exited with %v", err)
					}
					break
				}
				ctx.Fatalf("cipd: %v %v", l, err)
			}
			ctx.Printf("cipd: %v", l)
		}
	}()

	bufReader := bufio.NewReader(stdout)
	for {
		l, err := bufReader.ReadString('\n')
		if errors.Is(err, io.EOF) {
			ctx.Printf("cipd: unexpected EOF: %v\n", l)
			// The stderr goroutine will handle the EOF
			cp.wg.Wait()
		}

		if err != nil {
			log.Fatalf("Got %v reading from cipd process", err)
		}
		if strings.HasPrefix(l, cipdProxyUrlKey) {
			proxyUrl := strings.TrimSpace(l[len(cipdProxyUrlKey)+1:])
			config.environ.Set(cipdProxyUrlKey, proxyUrl)
			ctx.Println("Started CIPD proxy listening on", proxyUrl)
			break
		}
	}
	return &cp
}

func (c *cipdProxy) Stop() {
	c.stopping.Store(true)
	c.cmd.Process.Kill()
	c.wg.Wait()
}