forked from jwilder/dockerize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
313 lines (265 loc) · 7.77 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"golang.org/x/net/context"
)
const defaultWaitRetryInterval = time.Second
type sliceVar []string
type hostFlagsVar []string
type Context struct {
}
type HttpHeader struct {
name string
value string
}
func (c *Context) Env() map[string]string {
env := make(map[string]string)
for _, i := range os.Environ() {
sep := strings.Index(i, "=")
env[i[0:sep]] = i[sep+1:]
}
return env
}
var (
buildVersion string
version bool
poll bool
wg sync.WaitGroup
templatesFlag sliceVar
templateDirsFlag sliceVar
stdoutTailFlag sliceVar
stderrTailFlag sliceVar
headersFlag sliceVar
delimsFlag string
delims []string
headers []HttpHeader
urls []url.URL
waitFlag hostFlagsVar
waitRetryInterval time.Duration
waitTimeoutFlag time.Duration
dependencyChan chan struct{}
noOverwriteFlag bool
ctx context.Context
cancel context.CancelFunc
)
func (i *hostFlagsVar) String() string {
return fmt.Sprint(*i)
}
func (i *hostFlagsVar) Set(value string) error {
*i = append(*i, value)
return nil
}
func (s *sliceVar) Set(value string) error {
*s = append(*s, value)
return nil
}
func (s *sliceVar) String() string {
return strings.Join(*s, ",")
}
func waitForDependencies() {
dependencyChan := make(chan struct{})
go func() {
for _, u := range urls {
log.Println("Waiting for:", u.String())
switch u.Scheme {
case "file":
wg.Add(1)
go func(u url.URL) {
defer wg.Done()
ticker := time.NewTicker(waitRetryInterval)
defer ticker.Stop()
var err error
for range ticker.C {
if _, err = os.Stat(u.Path); err == nil {
log.Printf("File %s had been generated\n", u.String())
return
} else if os.IsNotExist(err) {
continue
} else {
log.Printf("Problem with check file %s exist: %v. Sleeping %s\n", u.String(), err.Error(), waitRetryInterval)
}
}
}(u)
case "tcp", "tcp4", "tcp6":
waitForSocket(u.Scheme, u.Host, waitTimeoutFlag)
case "unix":
waitForSocket(u.Scheme, u.Path, waitTimeoutFlag)
case "http", "https":
wg.Add(1)
go func(u url.URL) {
client := &http.Client{
Timeout: waitTimeoutFlag,
}
defer wg.Done()
for {
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
log.Printf("Problem with dial: %v. Sleeping %s\n", err.Error(), waitRetryInterval)
time.Sleep(waitRetryInterval)
}
if len(headers) > 0 {
for _, header := range headers {
req.Header.Add(header.name, header.value)
}
}
resp, err := client.Do(req)
if err != nil {
log.Printf("Problem with request: %s. Sleeping %s\n", err.Error(), waitRetryInterval)
time.Sleep(waitRetryInterval)
} else if err == nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
log.Printf("Received %d from %s\n", resp.StatusCode, u.String())
return
} else {
log.Printf("Received %d from %s. Sleeping %s\n", resp.StatusCode, u.String(), waitRetryInterval)
time.Sleep(waitRetryInterval)
}
}
}(u)
default:
log.Fatalf("invalid host protocol provided: %s. supported protocols are: tcp, tcp4, tcp6 and http", u.Scheme)
}
}
wg.Wait()
close(dependencyChan)
}()
select {
case <-dependencyChan:
break
case <-time.After(waitTimeoutFlag):
log.Fatalf("Timeout after %s waiting on dependencies to become available: %v", waitTimeoutFlag, waitFlag)
}
}
func waitForSocket(scheme, addr string, timeout time.Duration) {
wg.Add(1)
go func() {
defer wg.Done()
for {
conn, err := net.DialTimeout(scheme, addr, waitTimeoutFlag)
if err != nil {
log.Printf("Problem with dial: %v. Sleeping %s\n", err.Error(), waitRetryInterval)
time.Sleep(waitRetryInterval)
}
if conn != nil {
log.Printf("Connected to %s://%s\n", scheme, addr)
return
}
}
}()
}
func usage() {
println(`Usage: dockerize [options] [command]
Utility to simplify running applications in docker containers
Options:`)
flag.PrintDefaults()
println(`
Arguments:
command - command to be executed
`)
println(`Examples:
`)
println(` Generate /etc/nginx/nginx.conf using nginx.tmpl as a template, tail /var/log/nginx/access.log
and /var/log/nginx/error.log, waiting for a website to become available on port 8000 and start nginx.`)
println(`
dockerize -template nginx.tmpl:/etc/nginx/nginx.conf \
-stdout /var/log/nginx/access.log \
-stderr /var/log/nginx/error.log \
-wait tcp://web:8000 nginx
`)
println(`For more information, see https://github.com/jwilder/dockerize`)
}
func main() {
flag.BoolVar(&version, "version", false, "show version")
flag.BoolVar(&poll, "poll", false, "enable polling")
flag.Var(&templatesFlag, "template", "Template (/template:/dest). Can be passed multiple times. Does also support directories")
flag.BoolVar(&noOverwriteFlag, "no-overwrite", false, "Do not overwrite destination file if it already exists.")
flag.Var(&stdoutTailFlag, "stdout", "Tails a file to stdout. Can be passed multiple times")
flag.Var(&stderrTailFlag, "stderr", "Tails a file to stderr. Can be passed multiple times")
flag.StringVar(&delimsFlag, "delims", "", `template tag delimiters. default "{{":"}}" `)
flag.Var(&headersFlag, "wait-http-header", "HTTP headers, colon separated. e.g \"Accept-Encoding: gzip\". Can be passed multiple times")
flag.Var(&waitFlag, "wait", "Host (tcp/tcp4/tcp6/http/https/unix/file) to wait for before this container starts. Can be passed multiple times. e.g. tcp://db:5432")
flag.DurationVar(&waitTimeoutFlag, "timeout", 10*time.Second, "Host wait timeout")
flag.DurationVar(&waitRetryInterval, "wait-retry-interval", defaultWaitRetryInterval, "Duration to wait before retrying")
flag.Usage = usage
flag.Parse()
if version {
fmt.Println(buildVersion)
return
}
if flag.NArg() == 0 && flag.NFlag() == 0 {
usage()
os.Exit(1)
}
if delimsFlag != "" {
delims = strings.Split(delimsFlag, ":")
if len(delims) != 2 {
log.Fatalf("bad delimiters argument: %s. expected \"left:right\"", delimsFlag)
}
}
for _, host := range waitFlag {
u, err := url.Parse(host)
if err != nil {
log.Fatalf("bad hostname provided: %s. %s", host, err.Error())
}
urls = append(urls, *u)
}
for _, h := range headersFlag {
//validate headers need -wait options
if len(waitFlag) == 0 {
log.Fatalf("-wait-http-header \"%s\" provided with no -wait option", h)
}
const errMsg = "bad HTTP Headers argument: %s. expected \"headerName: headerValue\""
if strings.Contains(h, ":") {
parts := strings.Split(h, ":")
if len(parts) != 2 {
log.Fatalf(errMsg, headersFlag)
}
headers = append(headers, HttpHeader{name: strings.TrimSpace(parts[0]), value: strings.TrimSpace(parts[1])})
} else {
log.Fatalf(errMsg, headersFlag)
}
}
for _, t := range templatesFlag {
template, dest := t, ""
if strings.Contains(t, ":") {
parts := strings.Split(t, ":")
if len(parts) != 2 {
log.Fatalf("bad template argument: %s. expected \"/template:/dest\"", t)
}
template, dest = parts[0], parts[1]
}
fi, err := os.Stat(template)
if err != nil {
log.Fatalf("unable to stat %s, error: %s", template, err)
}
if fi.IsDir() {
generateDir(template, dest)
} else {
generateFile(template, dest)
}
}
waitForDependencies()
// Setup context
ctx, cancel = context.WithCancel(context.Background())
if flag.NArg() > 0 {
wg.Add(1)
go runCmd(ctx, cancel, flag.Arg(0), flag.Args()[1:]...)
}
for _, out := range stdoutTailFlag {
wg.Add(1)
go tailFile(ctx, out, poll, os.Stdout)
}
for _, err := range stderrTailFlag {
wg.Add(1)
go tailFile(ctx, err, poll, os.Stderr)
}
wg.Wait()
}