-
Notifications
You must be signed in to change notification settings - Fork 33
/
envtest.go
292 lines (266 loc) · 7.4 KB
/
envtest.go
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// SPDX-FileCopyrightText: 2021 SAP SE or an SAP affiliate company and Gardener contributors.
//
// SPDX-License-Identifier: Apache-2.0
package testreg
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/cli/cli/config/types"
)
type Environment struct {
RegistryBinaryPath string
RegistryConfiguration RegistryConfiguration
ReadinessTimeout time.Duration
Stdout io.Writer
Stderr io.Writer
Certificate *Certificate
// Contains the host information as soon as the registry is started.
// The host is of the format "ip:port"
Addr string
// Transport to communicate with the registry.
// Includes the trusted ca.
Transport *http.Transport
// BasicAuth defines the basic auth credentials to access the registry.
BasicAuth *BasicAuth
configDir string
configPath string
cancelCtx context.CancelFunc
cmd *exec.Cmd
mu *sync.RWMutex
stopped bool
err error
}
// BasicAuth defines auth credentials that consists of a username and a password.
type BasicAuth struct {
Username string
Password string
}
const DefaultRegistryBinaryPath = "./tmp/test/bin/registry"
type Options struct {
RegistryBinaryPath string
RegistryConfiguration RegistryConfiguration
ReadinessTimeout *time.Duration
Stdout io.Writer
Stderr io.Writer
}
func (opts *Options) Default() {
if len(opts.RegistryBinaryPath) == 0 {
opts.RegistryBinaryPath = DefaultRegistryBinaryPath
}
if opts.ReadinessTimeout == nil {
d := 30 * time.Second
opts.ReadinessTimeout = &d
}
if opts.Stdout == nil {
opts.Stdout = bytes.NewBuffer(make([]byte, 0))
}
if opts.Stderr == nil {
opts.Stderr = bytes.NewBuffer(make([]byte, 0))
}
}
// New creates a new test registry environment
func New(opts Options) *Environment {
opts.Default()
return &Environment{
RegistryBinaryPath: opts.RegistryBinaryPath,
RegistryConfiguration: opts.RegistryConfiguration,
ReadinessTimeout: *opts.ReadinessTimeout,
Stdout: opts.Stdout,
Stderr: opts.Stderr,
mu: &sync.RWMutex{},
}
}
func (e *Environment) Start(ctx context.Context) error {
ctx, e.cancelCtx = context.WithCancel(ctx)
if err := e.setup(); err != nil {
return err
}
if err := e.runRegistry(ctx); err != nil {
return err
}
// wait until registry is healthy
if err := e.WaitForRegistryToBeHealthy(); err != nil {
if buf, ok := e.Stdout.(*bytes.Buffer); ok {
fmt.Println("Stdout:")
fmt.Println(buf.String())
}
if buf, ok := e.Stderr.(*bytes.Buffer); ok {
fmt.Println("Stderr:")
fmt.Println(buf.String())
}
return err
}
return nil
}
func (e *Environment) Close() error {
e.mu.RLock()
if !e.stopped {
e.cancelCtx()
}
e.mu.RUnlock()
// wait until the process is stopped.
for {
e.mu.RLock()
stopped := e.stopped
e.mu.RUnlock()
if stopped {
break
}
time.Sleep(2 * time.Second)
}
if err := os.RemoveAll(e.configDir); err != nil {
return fmt.Errorf("unable to remove config dir %q: %w", e.configDir, err)
}
return e.err
}
// GetConfigFileBytes returns the docker configfile containing the registry auth for the registry.
func (e *Environment) GetConfigFileBytes() ([]byte, error) {
cf := configfile.ConfigFile{}
cf.AuthConfigs = map[string]types.AuthConfig{
e.Addr: {
Username: e.BasicAuth.Username,
Password: e.BasicAuth.Password,
},
}
return json.Marshal(cf)
}
// setups creates all necessary files for the registry.
// This includes the configuration and the certificates.
func (e *Environment) setup() error {
configPath, err := os.MkdirTemp(os.TempDir(), "registry-")
if err != nil {
return fmt.Errorf("unable to create temporary config path: %w", err)
}
e.configDir = configPath
if err := e.RegistryConfiguration.Default(configPath); err != nil {
return err
}
if e.RegistryConfiguration.HTTPConfig.TLS == nil {
// create certificates
e.Certificate, err = GenerateCertificates()
if err != nil {
return err
}
var (
caPath = filepath.Join(e.configDir, "ca.pem")
certPath = filepath.Join(e.configDir, "e.Certificate.pem")
keyPath = filepath.Join(e.configDir, "key.pem")
)
if err := os.WriteFile(caPath, e.Certificate.CA, os.ModePerm); err != nil {
return fmt.Errorf("unable to write ca to %q: %w", caPath, err)
}
if err := os.WriteFile(certPath, e.Certificate.Cert, os.ModePerm); err != nil {
return fmt.Errorf("unable to write ca to %q: %w", certPath, err)
}
if err := os.WriteFile(keyPath, e.Certificate.Key, os.ModePerm); err != nil {
return fmt.Errorf("unable to write ca to %q: %w", keyPath, err)
}
caCertPool, err := x509.SystemCertPool()
if err != nil {
caCertPool = x509.NewCertPool()
}
caCertPool.AppendCertsFromPEM(e.Certificate.CA)
e.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: caCertPool,
},
}
e.RegistryConfiguration.HTTPConfig.TLS = &HTTPTLSConfig{
Cert: certPath,
Key: keyPath,
}
}
if e.RegistryConfiguration.Auth.Httpasswd == nil {
httpasswdPath := filepath.Join(e.configDir, "httpasswd")
e.BasicAuth = &BasicAuth{
Username: "testuser",
Password: RandString(10),
}
if err := os.WriteFile(
httpasswdPath,
[]byte(CreateHtpasswd(e.BasicAuth.Username, e.BasicAuth.Password)),
os.ModePerm); err != nil {
return fmt.Errorf("unable to write httpasswd file to %q: %w", httpasswdPath, err)
}
e.RegistryConfiguration.Auth.Httpasswd = &HttpasswdAuth{
Realm: "basic-realm",
Path: httpasswdPath,
}
}
configBytes, err := json.Marshal(e.RegistryConfiguration)
if err != nil {
return fmt.Errorf("unable to marshal registry config: %w", err)
}
e.configPath = filepath.Join(e.configDir, "config.json")
if err := os.WriteFile(e.configPath, configBytes, os.ModePerm); err != nil {
return fmt.Errorf("unable to write configuration file %q: %w", e.configPath, err)
}
return nil
}
func (e *Environment) runRegistry(ctx context.Context) error {
e.cmd = exec.CommandContext(ctx, e.RegistryBinaryPath, "serve", e.configPath)
e.cmd.Stdout = e.Stdout
e.cmd.Stderr = e.Stderr
if err := e.cmd.Start(); err != nil {
return fmt.Errorf("unable to start registry: %w", err)
}
e.Addr = e.RegistryConfiguration.HTTPConfig.Addr
go func() {
defer func() {
e.mu.Lock()
e.stopped = true
e.mu.Unlock()
}()
if err := e.cmd.Wait(); err != nil {
if ctx.Err() == context.Canceled {
return
}
e.err = fmt.Errorf("error while running %q: %w", e.cmd.String(), err)
}
}()
return nil
}
func (e *Environment) WaitForRegistryToBeHealthy() error {
start := time.Now()
for {
if e.err != nil {
return e.err
}
err := e.doHealthCheck()
if err == nil {
return nil
}
if time.Now().After(start.Add(e.ReadinessTimeout)) {
return fmt.Errorf("timed out waiting for the registry to become healthy: %w", err)
}
time.Sleep(5 * time.Second)
}
}
func (e *Environment) doHealthCheck() error {
if len(e.Addr) == 0 {
return errors.New("no addr to perform a heath check defined")
}
client := http.DefaultClient
client.Transport = e.Transport
res, err := client.Get("https://" + e.Addr)
if err != nil {
return fmt.Errorf("error while doing health check request: %w", err)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("health check returned status code %d but expected 200", res.StatusCode)
}
return nil
}