-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
client.go
61 lines (52 loc) · 1.01 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
package api
import (
"errors"
"net/rpc"
"sync"
)
var ErrDaemonOffline = errors.New("daemon offline")
type Client struct {
sockPath string
rpcClient *rpc.Client
waits sync.WaitGroup
}
func NewClient(sockPath string) *Client {
return &Client{sockPath, nil, sync.WaitGroup{}}
}
func (c *Client) SockPath() string {
return c.sockPath
}
func (c *Client) Waits() *sync.WaitGroup {
return &c.waits
}
func (c *Client) CallDaemon(f string, req, res interface{}) error {
err := c.connect()
if err != nil {
return err
}
err = c.rpcClient.Call(ServiceName+"."+f, req, res)
if err == rpc.ErrShutdown {
// Clear rpcClient so as to reconnect next time
c.rpcClient = nil
}
return err
}
func (c *Client) Close() error {
c.waits.Wait()
rc := c.rpcClient
c.rpcClient = nil
if rc != nil {
return rc.Close()
}
return nil
}
func (c *Client) connect() error {
if c.rpcClient == nil {
rpcClient, err := rpc.Dial("unix", c.sockPath)
if err != nil {
return err
}
c.rpcClient = rpcClient
}
return nil
}