-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
azurite.go
96 lines (83 loc) · 2.1 KB
/
azurite.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
package helpers
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"testing"
"time"
"github.com/moby/buildkit/util/testutil/integration"
"github.com/pkg/errors"
)
const (
azuriteBin = "azurite-blob"
)
type AzuriteOpts struct {
AccountName string
AccountKey string
}
func NewAzuriteServer(t *testing.T, sb integration.Sandbox, opts AzuriteOpts) (address string, cl func() error, err error) {
t.Helper()
if _, err := exec.LookPath(azuriteBin); err != nil {
return "", nil, errors.Wrapf(err, "failed to lookup %s binary", azuriteBin)
}
deferF := &integration.MultiCloser{}
cl = deferF.F()
defer func() {
if err != nil {
deferF.F()()
cl = nil
}
}()
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
return "", nil, err
}
addr := l.Addr().String()
if err = l.Close(); err != nil {
return "", nil, err
}
host, port, err := net.SplitHostPort(addr)
if err != nil {
return "", nil, err
}
address = fmt.Sprintf("http://%s/%s", addr, opts.AccountName)
// start server
cmd := exec.Command(azuriteBin, "--disableProductStyleUrl", "--blobHost", host, "--blobPort", port, "--location", t.TempDir())
cmd.Env = append(os.Environ(), []string{
"AZURITE_ACCOUNTS=" + opts.AccountName + ":" + opts.AccountKey,
}...)
azuriteStop, err := integration.StartCmd(cmd, sb.Logs())
if err != nil {
return "", nil, err
}
if err = waitAzurite(sb.Context(), address, 15*time.Second); err != nil {
azuriteStop()
return "", nil, errors.Wrapf(err, "azurite did not start up: %s", integration.FormatLogs(sb.Logs()))
}
deferF.Append(azuriteStop)
return
}
func waitAzurite(ctx context.Context, address string, d time.Duration) error {
step := 1 * time.Second
i := 0
for {
req, err := http.NewRequest("GET", fmt.Sprintf("%s?comp=list", address), nil)
if err != nil {
return errors.Wrapf(err, "failed to create request")
}
req = req.WithContext(ctx)
if resp, err := http.DefaultClient.Do(req); err == nil {
resp.Body.Close()
break
}
i++
if time.Duration(i)*step > d {
return errors.Errorf("failed dialing: %s", address)
}
time.Sleep(step)
}
return nil
}