-
Notifications
You must be signed in to change notification settings - Fork 0
/
couchdb.go
273 lines (230 loc) · 5.59 KB
/
couchdb.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package runner
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/pkg/errors"
"github.com/tedsuo/ifrit"
)
const CouchDBDefaultImage = "hyperledger/fabric-couchdb:latest"
// CouchDB manages the execution of an instance of a dockerized CounchDB
// for tests.
type CouchDB struct {
Client *docker.Client
Image string
HostIP string
HostPort int
ContainerPort docker.Port
Name string
StartTimeout time.Duration
ErrorStream io.Writer
OutputStream io.Writer
containerID string
hostAddress string
containerAddress string
address string
mutex sync.Mutex
stopped bool
}
// Run runs a CouchDB container. It implements the ifrit.Runner interface
func (c *CouchDB) Run(sigCh <-chan os.Signal, ready chan<- struct{}) error {
if c.Image == "" {
c.Image = CouchDBDefaultImage
}
if c.Name == "" {
c.Name = DefaultNamer()
}
if c.HostIP == "" {
c.HostIP = "127.0.0.1"
}
if c.ContainerPort == docker.Port("") {
c.ContainerPort = docker.Port("5984/tcp")
}
if c.StartTimeout == 0 {
c.StartTimeout = DefaultStartTimeout
}
if c.Client == nil {
client, err := docker.NewClientFromEnv()
if err != nil {
return err
}
c.Client = client
}
hostConfig := &docker.HostConfig{
AutoRemove: true,
PortBindings: map[docker.Port][]docker.PortBinding{
c.ContainerPort: []docker.PortBinding{{
HostIP: c.HostIP,
HostPort: strconv.Itoa(c.HostPort),
}},
},
}
container, err := c.Client.CreateContainer(
docker.CreateContainerOptions{
Name: c.Name,
Config: &docker.Config{Image: c.Image},
HostConfig: hostConfig,
},
)
if err != nil {
return err
}
c.containerID = container.ID
err = c.Client.StartContainer(container.ID, nil)
if err != nil {
return err
}
defer c.Stop()
container, err = c.Client.InspectContainer(container.ID)
if err != nil {
return err
}
c.hostAddress = net.JoinHostPort(
container.NetworkSettings.Ports[c.ContainerPort][0].HostIP,
container.NetworkSettings.Ports[c.ContainerPort][0].HostPort,
)
c.containerAddress = net.JoinHostPort(
container.NetworkSettings.IPAddress,
c.ContainerPort.Port(),
)
streamCtx, streamCancel := context.WithCancel(context.Background())
defer streamCancel()
go c.streamLogs(streamCtx)
containerExit := c.wait()
ctx, cancel := context.WithTimeout(context.Background(), c.StartTimeout)
defer cancel()
select {
case <-ctx.Done():
return errors.Wrapf(ctx.Err(), "database in container %s did not start", c.containerID)
case <-containerExit:
return errors.New("container exited before ready")
case <-c.ready(ctx, c.hostAddress):
c.address = c.hostAddress
case <-c.ready(ctx, c.containerAddress):
c.address = c.containerAddress
}
cancel()
close(ready)
for {
select {
case err := <-containerExit:
return err
case <-sigCh:
if err := c.Stop(); err != nil {
return err
}
}
}
}
func endpointReady(ctx context.Context, url string) bool {
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return false
}
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
return err == nil && resp.StatusCode == http.StatusOK
}
func (c *CouchDB) ready(ctx context.Context, addr string) <-chan struct{} {
readyCh := make(chan struct{})
url := fmt.Sprintf("http://%s/", addr)
go func() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
if endpointReady(ctx, url) {
close(readyCh)
return
}
select {
case <-ticker.C:
case <-ctx.Done():
return
}
}
}()
return readyCh
}
func (c *CouchDB) wait() <-chan error {
exitCh := make(chan error)
go func() {
exitCode, err := c.Client.WaitContainer(c.containerID)
if err == nil {
err = fmt.Errorf("couchdb: process exited with %d", exitCode)
}
exitCh <- err
}()
return exitCh
}
func (c *CouchDB) streamLogs(ctx context.Context) {
if c.ErrorStream == nil && c.OutputStream == nil {
return
}
logOptions := docker.LogsOptions{
Context: ctx,
Container: c.containerID,
Follow: true,
ErrorStream: c.ErrorStream,
OutputStream: c.OutputStream,
Stderr: c.ErrorStream != nil,
Stdout: c.OutputStream != nil,
}
err := c.Client.Logs(logOptions)
if err != nil {
fmt.Fprintf(c.ErrorStream, "log stream ended with error: %s", err)
}
}
// Address returns the address successfully used by the readiness check.
func (c *CouchDB) Address() string {
return c.address
}
// HostAddress returns the host address where this CouchDB instance is available.
func (c *CouchDB) HostAddress() string {
return c.hostAddress
}
// ContainerAddress returns the container address where this CouchDB instance
// is available.
func (c *CouchDB) ContainerAddress() string {
return c.containerAddress
}
// ContainerID returns the container ID of this CouchDB
func (c *CouchDB) ContainerID() string {
return c.containerID
}
// Start starts the CouchDB container using an ifrit runner
func (c *CouchDB) Start() error {
p := ifrit.Invoke(c)
select {
case <-p.Ready():
return nil
case err := <-p.Wait():
return err
}
}
// Stop stops and removes the CouchDB container
func (c *CouchDB) Stop() error {
c.mutex.Lock()
if c.stopped {
c.mutex.Unlock()
return errors.Errorf("container %s already stopped", c.containerID)
}
c.stopped = true
c.mutex.Unlock()
err := c.Client.StopContainer(c.containerID, 0)
if err != nil {
return err
}
return nil
}