generated from roerohan/Template
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathservices.go
67 lines (57 loc) · 1.18 KB
/
services.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
package main
import (
"fmt"
"net"
"strings"
"sync"
"time"
)
// Services is a string array storing
// the services that are to be waited for
type Services []string
// Set is used to append a string
// to the service, to implement
// the interface flag.Value
func (s *Services) Set(value string) error {
*s = append(*s, value)
return nil
}
// String returns a string
// representation of the flag,
// to implement the interface
// flag.Value
func (s *Services) String() string {
return strings.Join(*s, ", ")
}
// Wait waits for all services
func (s *Services) Wait(tSeconds int) bool {
t := time.Duration(tSeconds) * time.Second
now := time.Now()
var wg sync.WaitGroup
wg.Add(len(*s))
success := make(chan bool, 1)
go func() {
for _, service := range services {
go waitOne(service, &wg, now)
}
wg.Wait()
success <- true
}()
select {
case <-success:
return true
case <-time.After(t):
return false
}
}
func waitOne(service string, wg *sync.WaitGroup, start time.Time) {
defer wg.Done()
for {
_, err := net.Dial("tcp", service)
if err == nil {
Log(fmt.Sprintf("%s is available after %s", service, time.Since(start)))
break
}
time.Sleep(time.Second)
}
}