forked from moby/buildkit
/
registry.go
110 lines (96 loc) · 2.01 KB
/
registry.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
package integration
import (
"bufio"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"time"
"github.com/pkg/errors"
)
func newRegistry(dir string) (url string, cl func() error, err error) {
if err := lookupBinary("registry"); err != nil {
return "", nil, err
}
deferF := &multiCloser{}
cl = deferF.F()
defer func() {
if err != nil {
deferF.F()()
cl = nil
}
}()
if dir == "" {
tmpdir, err := ioutil.TempDir("", "test-registry")
if err != nil {
return "", nil, err
}
deferF.append(func() error { return os.RemoveAll(tmpdir) })
dir = tmpdir
}
if _, err := os.Stat(filepath.Join(dir, "config.yaml")); err != nil {
if !os.IsNotExist(err) {
return "", nil, err
}
template := fmt.Sprintf(`version: 0.1
loglevel: debug
storage:
filesystem:
rootdirectory: %s
http:
addr: 127.0.0.1:0
`, filepath.Join(dir, "data"))
if err := ioutil.WriteFile(filepath.Join(dir, "config.yaml"), []byte(template), 0600); err != nil {
return "", nil, err
}
}
cmd := exec.Command("registry", "serve", filepath.Join(dir, "config.yaml"))
rc, err := cmd.StdoutPipe()
if err != nil {
return "", nil, err
}
if stop, err := startCmd(cmd, nil); err != nil {
return "", nil, err
} else {
deferF.append(stop)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
url, err = detectPort(ctx, rc)
if err != nil {
return "", nil, err
}
return
}
func detectPort(ctx context.Context, rc io.ReadCloser) (string, error) {
r := regexp.MustCompile("listening on 127\\.0\\.0\\.1:(\\d+)")
s := bufio.NewScanner(rc)
found := make(chan struct{})
defer func() {
close(found)
go io.Copy(ioutil.Discard, rc)
}()
go func() {
select {
case <-ctx.Done():
select {
case <-found:
return
default:
rc.Close()
}
case <-found:
}
}()
for s.Scan() {
res := r.FindSubmatch(s.Bytes())
if len(res) > 1 {
return "localhost:" + string(res[1]), nil
}
}
return "", errors.Errorf("no listening address found")
}