/
client.go
231 lines (210 loc) · 5.08 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
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
// Copyright 2019 Luis Guillén Civera <luisguillenc@gmail.com>. See LICENSE.
package resolvcheck
import (
"context"
"errors"
"fmt"
"net"
"time"
"github.com/golang/protobuf/ptypes"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/status"
"github.com/luids-io/api/dnsutil"
"github.com/luids-io/api/dnsutil/grpc/pb"
"github.com/luids-io/api/xlist"
"github.com/luids-io/core/yalogi"
)
// Client provides a grpc client.
type Client struct {
opts clientOpts
logger yalogi.Logger
//grpc connection
conn *grpc.ClientConn
client pb.ResolvCheckClient
//control
closed bool
//cache
cache *cache
}
// ClientOption encapsules options for client.
type ClientOption func(*clientOpts)
type clientOpts struct {
logger yalogi.Logger
closeConn bool
//client mapping
cmap *ClientMap
//cache opts
useCache bool
ttl int
negativettl int
cacheCleanup time.Duration
}
var defaultClientOpts = clientOpts{
logger: yalogi.LogNull,
closeConn: true,
cmap: NewClientMap(),
cacheCleanup: defaultCacheCleanups,
}
// CloseConnection option closes grpc connection on shutdown.
func CloseConnection(b bool) ClientOption {
return func(o *clientOpts) {
o.closeConn = b
}
}
// SetLogger option allows set a custom logger.
func SetLogger(l yalogi.Logger) ClientOption {
return func(o *clientOpts) {
if l != nil {
o.logger = l
}
}
}
// SetClientMap option allows set a client mapper.
func SetClientMap(cmap *ClientMap) ClientOption {
return func(o *clientOpts) {
if cmap != nil {
o.cmap = cmap
}
}
}
// SetCache option sets cache ttl and negative ttl.
func SetCache(ttl, negativettl int) ClientOption {
return func(o *clientOpts) {
if ttl >= xlist.NeverCache && negativettl >= xlist.NeverCache {
o.ttl = ttl
o.negativettl = negativettl
o.useCache = true
}
}
}
// SetCacheCleanUps option sets interval between cache cleanups.
func SetCacheCleanUps(d time.Duration) ClientOption {
return func(o *clientOpts) {
if d > 0 {
o.cacheCleanup = d
}
}
}
// NewClient returns a new Client.
func NewClient(conn *grpc.ClientConn, opt ...ClientOption) *Client {
opts := defaultClientOpts
for _, o := range opt {
o(&opts)
}
c := &Client{
opts: opts,
logger: opts.logger,
conn: conn,
client: pb.NewResolvCheckClient(conn),
}
if opts.useCache {
c.cache = newCache(opts.ttl, opts.negativettl, opts.cacheCleanup)
}
return c
}
// Check implements dnsutil.ResolvChecker interface.
func (c *Client) Check(ctx context.Context, client, resolved net.IP, name string) (dnsutil.CacheResponse, error) {
if c.closed {
c.logger.Warnf("client.dnsutil.resolvcheck: check(%v,%v,%s): client is closed", client, resolved, name)
return dnsutil.CacheResponse{}, dnsutil.ErrUnavailable
}
if c.opts.useCache {
resp, ok := c.cache.get(client, resolved, name)
if ok {
return resp, nil
}
}
//exec query
response, err := c.doCheck(ctx, client, resolved, name)
if c.opts.useCache && err == nil {
c.cache.set(client, resolved, name, response)
}
return response, err
}
//mapping errors
func (c *Client) mapError(err error) error {
st, ok := status.FromError(err)
if !ok {
return err
}
switch st.Code() {
case codes.Canceled:
return dnsutil.ErrCanceledRequest
case codes.InvalidArgument:
return dnsutil.ErrBadRequest
case codes.Unimplemented:
return dnsutil.ErrNotSupported
case codes.Internal:
return dnsutil.ErrInternal
case codes.Unavailable:
return dnsutil.ErrUnavailable
default:
return dnsutil.ErrUnavailable
}
}
//Flush cache if set.
func (c *Client) Flush() {
if !c.closed && c.opts.useCache {
c.cache.flush()
}
}
//Close closes the client.
func (c *Client) Close() error {
if c.closed {
return errors.New("client closed")
}
c.closed = true
if c.opts.useCache {
c.cache.flush()
c.cache = nil
}
if c.opts.closeConn {
return c.conn.Close()
}
return nil
}
// Ping checks connectivity with the api.
func (c *Client) Ping() error {
if c.closed {
return errors.New("client closed")
}
st := c.conn.GetState()
switch st {
case connectivity.TransientFailure:
return fmt.Errorf("connection state: %v", st)
case connectivity.Shutdown:
return fmt.Errorf("connection state: %v", st)
}
return nil
}
func (c *Client) doCheck(ctx context.Context, client, resolved net.IP, name string) (dnsutil.CacheResponse, error) {
//exec query
response, err := c.client.Check(ctx,
&pb.ResolvCheckRequest{
ClientIp: c.opts.cmap.Get(client).String(),
ResolvedIp: resolved.String(),
Name: name,
})
if err != nil {
c.logger.Warnf("client.dnsutil.resolvcheck: check(%v,%v,%s): %v", client, resolved, name, err)
return dnsutil.CacheResponse{}, c.mapError(err)
}
//process response
resp := dnsutil.CacheResponse{}
resp.Result = response.GetResult()
tstamp := response.GetLastTs()
if tstamp != nil {
resp.Last, _ = ptypes.Timestamp(tstamp)
}
tstamp = response.GetStoreTs()
if tstamp != nil {
resp.Store, _ = ptypes.Timestamp(tstamp)
}
return resp, nil
}
//API returns API service name implemented.
func (c *Client) API() string {
return ServiceName()
}