This repository has been archived by the owner on Jun 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
370 lines (303 loc) · 8.33 KB
/
service.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Package discovery contains domain logic for service discovery.
package discovery
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/url"
"regexp"
"sort"
"strings"
"time"
"k8s.io/apimachinery/pkg/labels"
)
var (
nameRegexp = regexp.MustCompile("^[[:alnum:]_-]+$")
labelRegexp = regexp.MustCompile("[a-zA-Z_][a-zA-Z0-9_]*.")
)
const (
dnsResolveTimeout = 10 * time.Second
)
// Service contains all information for service discovery.
type Service struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
Endpoint *url.URL `json:"endpoint,omitempty"`
Selector string `json:"selector,omitempty"`
Servers []string `json:"servers,omitempty"`
Labels Labels `json:"labels,omitempty"`
Description string `json:"description,omitempty"`
Modified time.Time `json:"modified,omitempty"`
}
// NewService creates a new service with ID and timestamp.
func NewService(name, endpoint string) (*Service, error) {
u, err := url.ParseRequestURI(endpoint)
if err != nil {
return nil, fmt.Errorf("'%s' is not a valid url: %v", endpoint, err)
}
s := &Service{
Name: name,
Namespace: DefaultNamespace().Name,
Endpoint: u,
Modified: time.Now(),
}
if err := s.Validate(); err != nil {
return nil, err
}
return s, nil
}
// MustNewService panics if endpoint or name is not valid.
func MustNewService(name, endpoint string) *Service {
s, err := NewService(name, endpoint)
if err != nil {
panic(err)
}
return s
}
// Validate checks if a services values are valid.
func (s Service) Validate() error {
if s.Name == "" {
return errors.New("name cannot be empty")
}
if !nameRegexp.MatchString(s.Name) {
return errors.New("name must only contain 'a-z', 'A-Z', '0-9', '-' and '_'")
}
if s.Namespace == "" {
return errors.New("namespace cannot be empty")
}
if !nameRegexp.MatchString(s.Namespace) {
return errors.New("namespace must only contain 'a-z', 'A-Z', '0-9', '-' and '_'")
}
if s.Endpoint == nil {
return errors.New("endpoint cannot be null")
}
return s.Labels.Validate()
}
// HasServer returns true if service has serverName in its Servers slice.
func (s Service) HasServer(serverName string) bool {
for _, name := range s.Servers {
if name == serverName {
return true
}
}
return false
}
// Header creates the header for csv or table output.
func (s Service) Header() []string {
return []string{"NAME", "NAMESPACE", "ID", "ENDPOINT", "SERVERS", "LABELS", "SELECTOR", "MODIFIED", "DESCRIPTION"}
}
// Row creates a row for csv or table output.
func (s Service) Row() []string {
return []string{s.Name, s.Namespace, s.ID, s.Endpoint.String(), strings.Join(s.Servers, ","), s.Labels.String(), s.Selector, s.Modified.Format(time.RFC3339), s.Description}
}
// UnmarshalJSON is a custom json unmarshaller.
func (s *Service) UnmarshalJSON(j []byte) error {
raw := struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Labels Labels `json:"labels,omitempty"`
Servers []string `json:"servers,omitempty"`
Selector string `json:"selector,omitempty"`
Description string `json:"description,omitempty"`
Modified time.Time `json:"modified,omitempty"`
}{}
err := json.Unmarshal(j, &raw)
if err != nil {
return err
}
s.ID = raw.ID
s.Name = raw.Name
s.Namespace = raw.Namespace
s.Labels = raw.Labels
s.Selector = raw.Selector
s.Servers = raw.Servers
s.Description = raw.Description
s.Modified = raw.Modified
if raw.Endpoint == "" {
s.Endpoint = nil
return nil
}
u, err := url.Parse(raw.Endpoint)
if err != nil {
return err
}
s.Endpoint = u
return nil
}
// MarshalJSON is a custom JSON marshaler.
func (s Service) MarshalJSON() ([]byte, error) {
ep := ""
if s.Endpoint != nil {
ep = s.Endpoint.String()
}
raw := struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Labels Labels `json:"labels,omitempty"`
Servers []string `json:"servers,omitempty"`
Selector string `json:"selector,omitempty"`
Description string `json:"description,omitempty"`
Modified time.Time `json:"modified,omitempty"`
}{
ID: s.ID,
Name: s.Name,
Namespace: s.Namespace,
Endpoint: ep,
Labels: s.Labels,
Servers: s.Servers,
Selector: s.Selector,
Description: s.Description,
Modified: s.Modified,
}
return json.Marshal(raw)
}
// KeyVals represents the service as slice of interface.
func (s Service) KeyVals() []interface{} {
return []interface{}{
"id", s.ID,
"name", s.Name,
"namespace", s.Namespace,
"endpoint", s.Endpoint,
"modified", s.Modified,
"selector", s.Selector,
"description", s.Description,
}
}
// Services is a slice of Services
type Services []Service
// FilterFunc is a function to filter services. If function returns true
// service is selected else omitted.
type FilterFunc func(Service) bool
// Filter filters Services with FilterFunc.
func (s Services) Filter(filters ...FilterFunc) Services {
services := Services{}
for i := range s {
selectService := true
for _, f := range filters {
selectService = selectService && f(s[i])
}
if selectService {
services = append(services, s[i])
}
}
return services
}
// ServiceByName filters Services by Name.
func ServiceByName(r *regexp.Regexp) FilterFunc {
return func(s Service) bool {
return r.MatchString(s.Name)
}
}
// ServiceByEndpoint filters Services by Endpoint.
func ServiceByEndpoint(r *regexp.Regexp) FilterFunc {
return func(s Service) bool {
return r.MatchString(s.Endpoint.String())
}
}
// ServiceByServer filters Services by Server.
func ServiceByServer(r *regexp.Regexp) FilterFunc {
return func(s Service) bool {
for _, srv := range s.Servers {
if r.MatchString(srv) {
return true
}
}
return false
}
}
// ServiceBySelector filters Services by Selector.
func ServiceBySelector(selector labels.Selector) FilterFunc {
return func(s Service) bool {
return selector.Matches(s.Labels)
}
}
// SortByEndpoint sorts services by endpoint.
func (s Services) SortByEndpoint() {
sort.Slice(s, func(i, j int) bool {
return s[i].Endpoint.String() < s[j].Endpoint.String()
})
}
// SortByDate sorts servers by modification date.
func (s Services) SortByDate() {
sort.Slice(s, func(i, j int) bool {
return s[j].Modified.Before(s[i].Modified)
})
}
// UnResolved returns services that cannot be resolved
// using the local resolver.
func (s Services) UnResolved() (Services, error) {
unresolved := make(Services, 0, len(s))
for i := range s {
isResolvable, err := s[i].isResolvable()
if err != nil {
return Services{}, err
}
if !isResolvable {
unresolved = append(unresolved, s[i])
}
}
return unresolved, nil
}
func (s Service) isResolvable() (bool, error) {
host := strings.Split(s.Endpoint.Host, ":")[0]
ctx, cancel := context.WithTimeout(context.Background(), dnsResolveTimeout)
defer cancel()
_, err := net.DefaultResolver.LookupHost(ctx, host)
if err != nil {
var dnsError *net.DNSError
if errors.As(err, &dnsError) {
if dnsError.IsNotFound {
return false, nil
}
}
return false, err
}
return true, nil
}
// Labels represents key value pairs.
type Labels map[string]string
func (l Labels) String() string {
keys := []string{}
for k := range l {
keys = append(keys, k)
}
sort.Strings(keys)
s := ""
sep := ""
for _, k := range keys {
if len(s) > 0 {
sep = ","
}
s = s + sep + k + "=" + l[k]
}
return s
}
// Has returs true if Labels contains key.
func (l Labels) Has(key string) bool {
_, ok := l[key]
return ok
}
// Get gets the value for key.
func (l Labels) Get(key string) string {
return l[key]
}
// Validate validates the label names.
func (l Labels) Validate() error {
for labelName, labelValue := range l {
match := labelRegexp.FindString(labelName)
if match != labelName {
return fmt.Errorf("label name '%s' is not valid: label names must contain only ASCII letters, numbers and underscores", labelName)
}
if labelValue == "" {
return fmt.Errorf("label value for '%s' cannot be empty string", labelName)
}
}
return nil
}