-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
85 lines (73 loc) · 1.73 KB
/
client.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
package main
import (
"math"
"net"
"os"
"time"
)
func runClient(sock string, m interface{}) error {
b, err := EncodeMessage(m)
if err != nil {
return err
}
didFail := func(l []error) bool {
if len(l) > 10 {
return true
} else {
return false
}
}
conn, errs := tryConnect("unix", sock, expBackoff(2, 100*time.Millisecond), []error{}, didFail)
if errs != nil {
return errs[0]
}
unixConn := conn.(*net.UnixConn)
defer unixConn.Close()
// Write the message and send EOF.
_, err = unixConn.Write(b)
if err != nil {
return err
}
if err := unixConn.CloseWrite(); err != nil {
return err
}
// Wait for remote to close the connection.
_, err = unixConn.Read([]byte{0})
if err != nil && err.Error() != "EOF" {
return err
}
return nil
}
func tryConnect(network, addr string, retryDelay func([]error) time.Duration, prevErrors []error, hasFailed func([]error) bool) (net.Conn, []error) {
if hasFailed(prevErrors) {
return nil, prevErrors
} else {
conn, conn_err := net.Dial("unix", addr)
if conn != nil {
return conn, nil
}
errors := append(prevErrors, conn_err)
dur := retryDelay(errors)
time.Sleep(dur)
return tryConnect(network, addr, retryDelay, errors, hasFailed)
}
return nil, nil
}
func RunQueueClient(sock string, tag string) error {
return runClient(sock, &QueueMessage{
DrvPath: os.Getenv("DRV_PATH"),
OutPaths: os.Getenv("OUT_PATHS"),
Tag: tag,
})
}
func RunWaitClient(sock string, tag string) error {
return runClient(sock, &WaitMessage{
Tag: tag,
})
}
func expBackoff(factor uint, start time.Duration) func(l []error) time.Duration {
return func(l []error) time.Duration {
n := len(l)
return time.Duration(int(math.Pow(float64(factor), float64(n)))) * start
}
}