-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
222 lines (189 loc) · 5.53 KB
/
main.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
package main
import (
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
const usage = `
Attempt to connect to all TCP services linked by the environement variable
declared like _HOST and _PORT and wait for them to accept a TCP connection.
When the _legacy_ option is specified, it finds all TCP services linked to
a Docker container via their environment variables.
When an <httpport> is specified, for services running on <httpport>, after
a successful TCP connect, do an HTTP request and wait until it's done. This
is useful for slow-starting services that only start up when they receive
their first request.
When timeout is over and TCP connect or HTTP request were unsucecssful, exit
with status 1.
`
// Service holds the information for a docker service
type Service struct {
Name string
Address string
Port int
}
// AddressAndPort represent the address and the port in the following format
// address:port
func (s Service) AddressAndPort() string {
return fmt.Sprintf("%s:%d", s.Address, s.Port)
}
var timeout = flag.Int64("timeout", 60, "time to wait for all services to be up (seconds)")
var httpPort = flag.Int("httpport", 0, "wait for an http request if target port is given port")
var ignorePort = flag.Int("ignoreport", 0, "don't wait for services on this port to be up")
var legacy = flag.Bool("legacy", false, "use docker link environment variables")
func main() {
setupUsage()
flag.Parse()
services := deduplicateServices(loadServicesFromEnv())
log.Printf("Waiting for %d services to be ready...", len(services))
begin := time.Now()
var wg sync.WaitGroup
cancel := make(chan struct{})
for _, service := range services {
if service.Port == *ignorePort {
continue
}
wg.Add(1)
go func(service Service) {
waitForTcpConn(service, cancel)
if *httpPort == service.Port {
waitForHttpRequest(service, cancel)
}
wg.Done()
}(service)
}
timer := time.AfterFunc(time.Duration(*timeout)*time.Second, func() {
close(cancel)
})
wg.Wait()
// There's a race here that might result in assuming that a timeout happened
// although none happened. It appears when the timer fires after the connection
// succeeded, but before the check via Stop() below.
// That shouldn't happen very often and the service was pretty short of timing out
// anyway, so I guess that's ok for now.
if !timer.Stop() {
log.Printf("Error: One or more services timed out after %d second(s)", *timeout)
os.Exit(1)
}
log.Printf("All services are up after %v!", time.Now().Sub(begin))
}
func setupUsage() {
flag.CommandLine.Usage = func() {
flag.Usage()
fmt.Fprint(os.Stderr, usage)
}
}
func loadServicesFromEnv() []Service {
services := make([]Service, 0)
hostSuffix := "_HOST"
portSuffix := "_PORT"
offset := 5
if *legacy {
hostSuffix = "_TCP_ADDR"
portSuffix = "_TCP_PORT"
offset = 9
}
for _, line := range os.Environ() {
keyAndValue := strings.SplitN(line, "=", 2)
addrKey := keyAndValue[0]
if strings.HasSuffix(addrKey, hostSuffix) {
addr := os.Getenv(addrKey)
name := addrKey[:len(addrKey)-offset] // cut off "_HOST"
portKey := name + portSuffix
portStr := os.Getenv(portKey)
port, err := strconv.Atoi(portStr)
if err != nil {
log.Printf("Failed to convert %v to int, value: '%v' - skipping service '%v'",
portKey, portStr, name)
continue
}
services = append(services, Service{Name: name, Address: addr, Port: port})
}
}
return services
}
func deduplicateServices(services []Service) []Service {
grouped := make(map[string][]Service)
for _, service := range services {
key := fmt.Sprintf("%s:%v", service.Address, service.Port)
if _, ok := grouped[key]; !ok {
grouped[key] = make([]Service, 0)
}
grouped[key] = append(grouped[key], service)
}
chosen := make([]Service, 0)
for _, serviceList := range grouped {
chosenForGroup := serviceList[0]
for _, service := range serviceList {
if len(service.Name) < len(chosenForGroup.Name) {
chosenForGroup = service
}
}
chosen = append(chosen, chosenForGroup)
}
return chosen
}
func waitForTcpConn(service Service, cancel <-chan struct{}) {
var cancelled int32 = 0
go func() {
<-cancel
atomic.StoreInt32(&cancelled, 1)
}()
var conn net.Conn
err := errors.New("init")
for err != nil {
conn, err = net.DialTimeout("tcp", service.AddressAndPort(), 1*time.Second)
if cancelled == 1 && err != nil {
log.Printf("TCP: Service %v (%v) timed out. Last error: %v",
service.Name, service.AddressAndPort(), err)
return
}
time.Sleep(200 * time.Millisecond)
}
conn.Close()
log.Printf("TCP: Service %v (%v) is up", service.Name, service.AddressAndPort())
}
func waitForHttpRequest(service Service, cancel <-chan struct{}) {
url := url.URL{
Scheme: "http",
Host: service.AddressAndPort(),
Path: "/",
}
err := errors.New("init")
for err != nil {
req, reqErr := http.NewRequest("GET", url.String(), nil)
if reqErr != nil {
log.Printf("Warning: Failed to create request for URL '%s' - skipping service '%s'",
url.String(), service.Name)
return
}
tr := &http.Transport{}
client := &http.Client{Transport: tr}
c := make(chan error, 1)
go func() {
_, err := client.Do(req)
c <- err
}()
select {
case <-cancel:
tr.CancelRequest(req)
log.Printf("HTTP: Service %v (%v) timed out. Last error: %v",
service.Name, service.AddressAndPort(), err)
<-c
return
case err = <-c:
}
time.Sleep(200 * time.Millisecond)
}
log.Printf("HTTP: Service %v (%v) is up", service.Name, service.AddressAndPort())
}