-
Notifications
You must be signed in to change notification settings - Fork 339
/
parentabstraction.go
398 lines (345 loc) · 14.9 KB
/
parentabstraction.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package atscfg
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import (
"errors"
"strconv"
"strings"
)
// ParentAbstraction contains all the data necessary to build either parent.config or strategies.yaml.
type ParentAbstraction struct {
Services []*ParentAbstractionService
// Peers is the list of peer proxy caches to be used in a strategy peering group.
// a cache will only have one set of peers for potential use in all delivery services.
Peers []*ParentAbstractionServiceParent
}
// ParentAbstractionService represents a single delivery service's parent data.
// For parent.config, this becomes a single dest_domain= line.
// For strategies, this becomes a strategy along with its corresponding groups and hosts.
type ParentAbstractionService struct {
// Name is a unique name for the service.
// It can be anything unique, but should probably be the Traffic ops Delivery Service name.
Name string
// Comment is a text comment about the service, not including the comment syntax (e.g. # or //).
// Should be empty if !opt.AddComments.
Comment string
// DestDomain is the FQDN of the remap.config target.
// Becomes parent.config dest_domain directive
// Becomes strategies.yaml TODO
DestDomain string
// Port is the port of the remap.config target,
// which MUST be valid, and is implicitly 80 for http targets and 443 for https targets.
// Becomes parent.config port directive
// Becomes strategies.yaml TODO
Port int
// Parents is the list of parents, either parent proxy caches or origins.
// This is a sorted array. Parents will be inserted into the config file in the order they appear.
// Becomes parent.config parent= directive members
// Becomes strategies.yaml TODO
Parents []*ParentAbstractionServiceParent
// Parents is the list of secondary parents, either parent proxy caches or origins,
// to be used if the primary parents fail. See SecondaryMode.
// Becomes parent.config secondary_parent= directive members
// Becomes strategies.yaml TODO
SecondaryParents []*ParentAbstractionServiceParent
// SecondaryMode is how to try SecondaryParents if primary Parents fail.
// Becomes parent.config secondary_mode directive
// Becomes strategies.yaml TODO
SecondaryMode ParentAbstractionServiceParentSecondaryMode
// CachePeerResult is used only when the RetryPolicy is set to
// 'consistent_hash' and the SecondaryMode is set to 'peering'.
// In the case that it's used and set to 'true', query results
// from peer caches will not be cached locally.
CachePeerResult bool
// GoDirect is whether to go direct to parents via normal HTTP requests.
// False means to make proxy requests to the parents.
// Becomes parent.config go_direct and parent_is_proxy directives
// Becomes strategies.yaml TODO
GoDirect bool
// IgnoreQueryStringInParentSelection is whether to use the query string of the request
// when selecting a parent, e.g. via Consistent Hash.
// Becomes parent.config qstring directive
// Becomes strategies.yaml TODO
IgnoreQueryStringInParentSelection bool
// MarkdownResponseCodes is the list of HTTP response codes from the parent
// to consider as errors and mark the parent as unhealthy. Typically 5xx codes.
// Becomes parent.config unavailable_server_retry_responses directive
// Becomes strategies.yaml TODO
MarkdownResponseCodes []int
// ErrorResponseCodes is the list of HTTP response codes from the parent
// to consider as errors, but NOT mark the parent unhealthy. Typically 4xx codes.
// Becomes parent.config unavailable_server_retry_responses directive
// Becomes strategies.yaml TODO
ErrorResponseCodes []int
// MaxSimpleRetries is the maximum number of non-markdown errors to attempt
// before returning the error to the client. See ErrorResponseCodes
// Becomes parent.config max_simple_retries
// Becomes strategies.yaml TODO
MaxSimpleRetries int
// MaxMarkdownRetries is the maximum number of markdown errors to attempt
// before returning the error to the client. See MarkdownResponseCodes
// Becomes parent.config max_unavailable_server_retries
// Becomes strategies.yaml TODO
MaxMarkdownRetries int
// RetryPolicy is how to retry primary versus secondary parents.
// Becomes parent.config round_robin directive
// Becomes strategies.yaml TODO
RetryPolicy ParentAbstractionServiceRetryPolicy
// Weight is the weight of this parent relative to other parents in consistent hash (and potentially other non-sequential) parent selection. The default is 0.999
// Becomes parent.config weight directive
// Becomes strategies.yaml TODO
Weight float64
}
// ParentAbstractionServices implements sort.Interface
type ParentAbstractionServices []*ParentAbstractionService
func (ps ParentAbstractionServices) Len() int { return len(ps) }
func (ps ParentAbstractionServices) Swap(i, j int) { ps[i], ps[j] = ps[j], ps[i] }
func (ps ParentAbstractionServices) Less(i, j int) bool {
if ps[i].DestDomain != ps[j].DestDomain {
return ps[i].DestDomain < ps[j].DestDomain
}
return ps[i].Port < ps[j].Port
}
type ParentAbstractionServiceParentSecondaryMode string
const ParentAbstractionServiceParentSecondaryModeExhaust = ParentAbstractionServiceParentSecondaryMode("exhaust")
const ParentAbstractionServiceParentSecondaryModeAlternate = ParentAbstractionServiceParentSecondaryMode("alternate")
const ParentAbstractionServiceParentSecondaryModePeering = ParentAbstractionServiceParentSecondaryMode("peering")
const ParentAbstractionServiceParentSecondaryModeInvalid = ParentAbstractionServiceParentSecondaryMode("")
const ParentAbstractionServiceParentSecondaryModeDefault = ParentAbstractionServiceParentSecondaryModeAlternate
// ToParentDotConfigVal returns the ATS parent.config secondary_mode= value for the enum.
// If the mode is invalid, ParentAbstractionServiceParentSecondaryModeDefault is returned without error.
func (mo ParentAbstractionServiceParentSecondaryMode) ToParentDotConfigVal() string {
switch mo {
case ParentAbstractionServiceParentSecondaryModeExhaust:
return "2"
case ParentAbstractionServiceParentSecondaryModeAlternate:
return "1"
default:
return ParentAbstractionServiceParentSecondaryModeDefault.ToParentDotConfigVal()
}
}
type ParentAbstractionServiceRetryPolicy string
const ParentAbstractionServiceRetryPolicyRoundRobinIP = ParentAbstractionServiceRetryPolicy("round_robin_ip")
const ParentAbstractionServiceRetryPolicyRoundRobinStrict = ParentAbstractionServiceRetryPolicy("round_robin_strict")
const ParentAbstractionServiceRetryPolicyFirst = ParentAbstractionServiceRetryPolicy("first")
const ParentAbstractionServiceRetryPolicyLatched = ParentAbstractionServiceRetryPolicy("latched")
const ParentAbstractionServiceRetryPolicyConsistentHash = ParentAbstractionServiceRetryPolicy("consistent_hash")
const ParentAbstractionServiceRetryPolicyInvalid = ParentAbstractionServiceRetryPolicy("")
const DefaultParentAbstractionServiceRetryPolicy = ParentAbstractionServiceRetryPolicyConsistentHash
func ParentSelectAlgorithmToParentAbstractionServiceRetryPolicy(alg string) ParentAbstractionServiceRetryPolicy {
switch strings.TrimSpace(strings.ToLower(alg)) {
case "true":
return ParentAbstractionServiceRetryPolicyRoundRobinIP
case "strict":
return ParentAbstractionServiceRetryPolicyRoundRobinStrict
case "false":
return ParentAbstractionServiceRetryPolicyFirst
case "consistent_hash":
return ParentAbstractionServiceRetryPolicyConsistentHash
case "latched":
return ParentAbstractionServiceRetryPolicyLatched
default:
return ParentAbstractionServiceRetryPolicyInvalid
}
}
// ToParentDotConfigFormat returns the ATS parent.config round_robin= value for the policy.
// If the policy is invalid, the default is returned without error.
func (po ParentAbstractionServiceRetryPolicy) ToParentDotConfigFormat() string {
switch po {
case ParentAbstractionServiceRetryPolicyRoundRobinIP:
return "true"
case ParentAbstractionServiceRetryPolicyRoundRobinStrict:
return "strict"
case ParentAbstractionServiceRetryPolicyFirst:
return "false"
case ParentAbstractionServiceRetryPolicyLatched:
return "latched"
case ParentAbstractionServiceRetryPolicyConsistentHash:
return "consistent_hash"
default:
return "consistent_hash"
}
}
// ParentSelectParamQStringHandlingToBool returns whether the param is to use the query string in the parent select algorithm or not.
// If the parameter value is not valid, returns nil.
func ParentSelectParamQStringHandlingToBool(paramVal string) *bool {
switch strings.TrimSpace(strings.ToLower(paramVal)) {
case "consider":
v := true
return &v
case "ignore":
v := false
return &v
}
return nil
}
type ParentAbstractionServiceParent struct {
// FQDN is the parent FQDN that ATS will use. Note this may be an IP.
FQDN string
Port int
Weight float64
}
// Key returns a unique key that can be used to compare parents for equality.
func (sp ParentAbstractionServiceParent) Key() string {
return sp.FQDN + ":" + strconv.Itoa(sp.Port)
}
func RemoveParentDuplicates(inputs []*ParentAbstractionServiceParent, seens map[string]struct{}) ([]*ParentAbstractionServiceParent, map[string]struct{}) {
if seens == nil {
seens = make(map[string]struct{})
}
uniques := []*ParentAbstractionServiceParent{}
for _, input := range inputs {
key := input.Key()
if _, ok := seens[key]; !ok {
uniques = append(uniques, input)
seens[key] = struct{}{}
}
}
return uniques, seens
}
func ParseRetryResponses(resp string) ([]int, error) {
resp = strings.TrimSpace(resp)
if len(resp) > 2 && resp[0] == '"' {
resp = resp[1 : len(resp)-1]
}
codes := []int{}
codeStrs := strings.Split(resp, ",")
for _, codeStr := range codeStrs {
codeStr = strings.TrimSpace(codeStr)
if codeStr == "" {
continue
}
code, err := strconv.Atoi(codeStr)
if err != nil {
return nil, errors.New("malformed")
}
codes = append(codes, code)
}
return codes, nil
}
var DefaultSimpleRetryCodes = []int{404}
var DefaultUnavailableServerRetryCodes = []int{503}
const DefaultIgnoreQueryStringInParentSelection = false
func parentAbstractionToParentDotConfig(pa *ParentAbstraction, opt *ParentConfigOpts, atsMajorVersion int) (string, []string, error) {
warnings := []string{}
txt := ""
// parent.config dest_domain directives must be unique.
// This is the "duplicate origin problem"
processedOriginsToDSNames := map[string]string{}
for _, svc := range pa.Services {
if existingDS, ok := processedOriginsToDSNames[svc.DestDomain]; ok {
warnings = append(warnings, "duplicate origin! DS '"+svc.Name+"' and '"+existingDS+"' share origin '"+svc.DestDomain+"': skipping '"+svc.Name+"'!")
continue
}
svcLine, svcWarns, err := svc.ToParentDotConfigLine(opt, atsMajorVersion)
warnings = append(warnings, svcWarns...)
if err != nil {
// TODO add DS name
// TODO don't error? No single delivery service should be able to break others.
return "", warnings, errors.New("creating parent.config line from service: " + err.Error())
}
txt += svcLine + "\n"
processedOriginsToDSNames[svc.DestDomain] = svc.Name
}
return txt, warnings, nil
}
func (svc *ParentAbstractionService) ToParentDotConfigLine(opt *ParentConfigOpts, atsMajorVersion int) (string, []string, error) {
warnings := []string{}
txt := ""
if opt.AddComments && svc.Comment != "" {
txt += LineCommentParentDotConfig + " " + svc.Comment + "\n"
}
txt += `dest_domain=` + svc.DestDomain
if svc.Port != 0 {
txt += ` port=` + strconv.Itoa(svc.Port)
}
if atsMajorVersion >= 6 && svc.RetryPolicy == ParentAbstractionServiceRetryPolicyConsistentHash && len(svc.SecondaryParents) > 0 {
// TODO add quotes
if len(svc.Parents) > 0 {
txt += ` parent="` + ParentAbstractionServiceParentsToParentDotConfigLine(svc.Parents) + `"`
}
if len(svc.SecondaryParents) > 0 {
txt += ` secondary_parent="` + ParentAbstractionServiceParentsToParentDotConfigLine(svc.SecondaryParents) + `"`
}
txt += ` secondary_mode=` + svc.SecondaryMode.ToParentDotConfigVal()
} else {
parents := []*ParentAbstractionServiceParent{}
for _, pa := range svc.Parents {
parents = append(parents, pa)
}
for _, pa := range svc.SecondaryParents {
parents = append(parents, pa)
}
if len(parents) > 0 {
txt += ` parent="` + ParentAbstractionServiceParentsToParentDotConfigLine(parents) + `"`
}
}
txt += ` round_robin=` + svc.RetryPolicy.ToParentDotConfigFormat()
txt += ` go_direct=` + strconv.FormatBool(svc.GoDirect)
txt += ` qstring=`
if !svc.IgnoreQueryStringInParentSelection {
txt += `consider`
} else {
txt += `ignore`
}
txt += ` parent_is_proxy=` + strconv.FormatBool(!svc.GoDirect)
if svc.MaxSimpleRetries > 0 && svc.MaxMarkdownRetries > 0 {
txt += ` parent_retry=both`
} else if svc.MaxSimpleRetries > 0 {
txt += ` parent_retry=simple_retry`
} else if svc.MaxMarkdownRetries > 0 {
txt += ` parent_retry=unavailable_server_retry`
}
if svc.MaxSimpleRetries > 0 {
txt += ` max_simple_retries=` + strconv.Itoa(svc.MaxSimpleRetries)
}
if svc.MaxMarkdownRetries > 0 {
txt += ` max_unavailable_server_retries=` + strconv.Itoa(svc.MaxMarkdownRetries)
}
if len(svc.ErrorResponseCodes) > 0 {
if atsMajorVersion >= 9 {
txt += ` simple_server_retry_responses="` + strings.Join(intsToStrs(svc.ErrorResponseCodes), `,`) + `"`
} else {
warnings = append(warnings, "Service '"+svc.Name+"' had simple retry codes '"+strings.Join(intsToStrs(svc.ErrorResponseCodes), ",")+"' but ATS version "+strconv.Itoa(atsMajorVersion)+" < 9 does not support custom simple retry codes, omitting!")
}
}
if len(svc.MarkdownResponseCodes) > 0 {
txt += ` unavailable_server_retry_responses="` + strings.Join(intsToStrs(svc.MarkdownResponseCodes), `,`) + `"`
}
// txt += ` unavailable_server_retry_responses=` + unavailableServerRetryResponses
return txt, warnings, nil
}
func intsToStrs(is []int) []string {
strs := []string{}
for _, i := range is {
strs = append(strs, strconv.Itoa(i))
}
return strs
}
func (pa *ParentAbstractionServiceParent) ToParentDotConfigFormat() string {
return pa.FQDN + ":" + strconv.Itoa(pa.Port) + "|" + strconv.FormatFloat(pa.Weight, 'f', -1, 64)
}
const ParentDotConfigParentSeparator = `;`
func ParentAbstractionServiceParentsToParentDotConfigLine(parents []*ParentAbstractionServiceParent) string {
parentStrs := []string{}
for _, parent := range parents {
parentStrs = append(parentStrs, parent.ToParentDotConfigFormat())
}
return strings.Join(parentStrs, ParentDotConfigParentSeparator)
}