-
Notifications
You must be signed in to change notification settings - Fork 132
/
block_fastly_service_v1_backend.go
398 lines (365 loc) · 12.4 KB
/
block_fastly_service_v1_backend.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 fastly
import (
"fmt"
"log"
"strings"
gofastly "github.com/fastly/go-fastly/v2/fastly"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type BackendServiceAttributeHandler struct {
*DefaultServiceAttributeHandler
}
func NewServiceBackend(sa ServiceMetadata) ServiceAttributeDefinition {
return &BackendServiceAttributeHandler{
&DefaultServiceAttributeHandler{
key: "backend",
serviceMetadata: sa,
},
}
}
func (h *BackendServiceAttributeHandler) Process(d *schema.ResourceData, latestVersion int, conn *gofastly.Client) error {
ob, nb := d.GetChange(h.GetKey())
if ob == nil {
ob = new(schema.Set)
}
if nb == nil {
nb = new(schema.Set)
}
obs := ob.(*schema.Set)
nbs := nb.(*schema.Set)
setDiff := NewSetDiff(func(backend interface{}) (interface{}, error) {
// Use the backend name as key
return backend.(map[string]interface{})["name"], nil
})
diffResult, err := setDiff.Diff(obs, nbs)
if err != nil {
return err
}
// DELETE old Backends
for _, bRaw := range diffResult.Deleted {
bf := bRaw.(map[string]interface{})
opts := h.createDeleteBackendInput(d.Id(), latestVersion, bf)
log.Printf("[DEBUG] Fastly Backend removal opts: %#v", opts)
err := conn.DeleteBackend(&opts)
if errRes, ok := err.(*gofastly.HTTPError); ok {
if errRes.StatusCode != 404 {
return err
}
} else if err != nil {
return err
}
}
// ADD new Backends
for _, dRaw := range diffResult.Added {
df := dRaw.(map[string]interface{})
opts := h.buildCreateBackendInput(d.Id(), latestVersion, df)
log.Printf("[DEBUG] Create Backend Opts: %#v", opts)
_, err := conn.CreateBackend(&opts)
if err != nil {
return err
}
}
// UPDATE existing backends
for _, dRaw := range diffResult.Modified {
df := dRaw.(map[string]interface{})
opts := h.buildUpdateBackendInput(d.Id(), latestVersion, df)
log.Printf("[DEBUG] Update Backend Opts: %#v", opts)
_, err := conn.UpdateBackend(&opts)
if err != nil {
return err
}
}
return nil
}
func (h *BackendServiceAttributeHandler) createDeleteBackendInput(service string, latestVersion int, bf map[string]interface{}) gofastly.DeleteBackendInput {
return gofastly.DeleteBackendInput{
Service: service,
Version: latestVersion,
Name: bf["name"].(string),
}
}
func (h *BackendServiceAttributeHandler) buildCreateBackendInput(service string, latestVersion int, df map[string]interface{}) gofastly.CreateBackendInput {
opts := gofastly.CreateBackendInput{
Service: service,
Version: latestVersion,
Name: df["name"].(string),
Address: df["address"].(string),
OverrideHost: df["override_host"].(string),
AutoLoadbalance: gofastly.CBool(df["auto_loadbalance"].(bool)),
SSLCheckCert: gofastly.CBool(df["ssl_check_cert"].(bool)),
SSLHostname: df["ssl_hostname"].(string),
SSLCACert: df["ssl_ca_cert"].(string),
SSLCertHostname: df["ssl_cert_hostname"].(string),
SSLSNIHostname: df["ssl_sni_hostname"].(string),
UseSSL: gofastly.CBool(df["use_ssl"].(bool)),
SSLClientKey: df["ssl_client_key"].(string),
SSLClientCert: df["ssl_client_cert"].(string),
MaxTLSVersion: df["max_tls_version"].(string),
MinTLSVersion: df["min_tls_version"].(string),
SSLCiphers: strings.Split(df["ssl_ciphers"].(string), ","),
Shield: df["shield"].(string),
Port: uint(df["port"].(int)),
BetweenBytesTimeout: uint(df["between_bytes_timeout"].(int)),
ConnectTimeout: uint(df["connect_timeout"].(int)),
ErrorThreshold: uint(df["error_threshold"].(int)),
FirstByteTimeout: uint(df["first_byte_timeout"].(int)),
MaxConn: uint(df["max_conn"].(int)),
Weight: uint(df["weight"].(int)),
HealthCheck: df["healthcheck"].(string),
}
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
opts.RequestCondition = df["request_condition"].(string)
}
return opts
}
func (h *BackendServiceAttributeHandler) buildUpdateBackendInput(service string, latestVersion int, df map[string]interface{}) gofastly.UpdateBackendInput {
opts := gofastly.UpdateBackendInput{
Service: service,
Version: latestVersion,
Name: df["name"].(string),
Address: df["address"].(string),
OverrideHost: df["override_host"].(string),
AutoLoadbalance: gofastly.CBool(df["auto_loadbalance"].(bool)),
SSLCheckCert: gofastly.CBool(df["ssl_check_cert"].(bool)),
SSLHostname: df["ssl_hostname"].(string),
SSLCACert: df["ssl_ca_cert"].(string),
SSLCertHostname: df["ssl_cert_hostname"].(string),
SSLSNIHostname: df["ssl_sni_hostname"].(string),
UseSSL: gofastly.CBool(df["use_ssl"].(bool)),
SSLClientKey: df["ssl_client_key"].(string),
SSLClientCert: df["ssl_client_cert"].(string),
MaxTLSVersion: df["max_tls_version"].(string),
MinTLSVersion: df["min_tls_version"].(string),
SSLCiphers: strings.Split(df["ssl_ciphers"].(string), ","),
Shield: df["shield"].(string),
Port: uint(df["port"].(int)),
BetweenBytesTimeout: uint(df["between_bytes_timeout"].(int)),
ConnectTimeout: uint(df["connect_timeout"].(int)),
ErrorThreshold: uint(df["error_threshold"].(int)),
FirstByteTimeout: uint(df["first_byte_timeout"].(int)),
MaxConn: uint(df["max_conn"].(int)),
Weight: uint(df["weight"].(int)),
HealthCheck: df["healthcheck"].(string),
}
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
opts.RequestCondition = df["request_condition"].(string)
}
return opts
}
func (h *BackendServiceAttributeHandler) Read(d *schema.ResourceData, s *gofastly.ServiceDetail, conn *gofastly.Client) error {
log.Printf("[DEBUG] Refreshing Backends for (%s)", d.Id())
backendList, err := conn.ListBackends(&gofastly.ListBackendsInput{
Service: d.Id(),
Version: s.ActiveVersion.Number,
})
if err != nil {
return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err)
}
bl := flattenBackend(backendList, h.GetServiceMetadata())
if err := d.Set(h.GetKey(), bl); err != nil {
log.Printf("[WARN] Error setting Backends for (%s): %s", d.Id(), err)
}
return nil
}
func (h *BackendServiceAttributeHandler) Register(s *schema.Resource) error {
var blockAttributes = map[string]*schema.Schema{
// required fields
"name": {
Type: schema.TypeString,
Required: true,
Description: "A name for this Backend",
},
"address": {
Type: schema.TypeString,
Required: true,
Description: "An IPv4, hostname, or IPv6 address for the Backend",
},
// Optional fields, defaults where they exist
"auto_loadbalance": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Should this Backend be load balanced",
},
"between_bytes_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 10000,
Description: "How long to wait between bytes in milliseconds",
},
"connect_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 1000,
Description: "How long to wait for a timeout in milliseconds",
},
"error_threshold": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: "Number of errors to allow before the Backend is marked as down",
},
"first_byte_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 15000,
Description: "How long to wait for the first bytes in milliseconds",
},
"healthcheck": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "The healthcheck name that should be used for this Backend",
},
"max_conn": {
Type: schema.TypeInt,
Optional: true,
Default: 200,
Description: "Maximum number of connections for this Backend",
},
"port": {
Type: schema.TypeInt,
Optional: true,
Default: 80,
Description: "The port number Backend responds on. Default 80",
},
"override_host": {
Type: schema.TypeString,
Optional: true,
Description: "The hostname to override the Host header",
},
"shield": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "The POP of the shield designated to reduce inbound load.",
},
"use_ssl": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether or not to use SSL to reach the Backend",
},
"max_tls_version": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Maximum allowed TLS version on SSL connections to this backend.",
},
"min_tls_version": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Minimum allowed TLS version on SSL connections to this backend.",
},
"ssl_ciphers": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Comma sepparated list of ciphers",
},
"ssl_check_cert": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Be strict on checking SSL certs",
},
"ssl_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "SSL certificate hostname",
Deprecated: "Use ssl_cert_hostname and ssl_sni_hostname instead.",
},
"ssl_ca_cert": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "CA certificate attached to origin.",
},
"ssl_cert_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "SSL certificate hostname for cert verification",
},
"ssl_sni_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "SSL certificate hostname for SNI verification",
},
"ssl_client_cert": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "SSL certificate file for client connections to the backend.",
Sensitive: true,
},
"ssl_client_key": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "SSL key file for client connections to backend.",
Sensitive: true,
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
Description: "The portion of traffic to send to a specific origins. Each origin receives weight/total of the traffic.",
},
}
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
blockAttributes["request_condition"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Name of a condition, which if met, will select this backend during a request.",
}
}
s.Schema[h.GetKey()] = &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: blockAttributes,
},
}
return nil
}
func flattenBackend(backendList []*gofastly.Backend, sa ServiceMetadata) []map[string]interface{} {
bl := make([]map[string]interface{}, 0, len(backendList))
for _, b := range backendList {
backend := map[string]interface{}{
"name": b.Name,
"address": b.Address,
"auto_loadbalance": b.AutoLoadbalance,
"between_bytes_timeout": int(b.BetweenBytesTimeout),
"connect_timeout": int(b.ConnectTimeout),
"error_threshold": int(b.ErrorThreshold),
"first_byte_timeout": int(b.FirstByteTimeout),
"max_conn": int(b.MaxConn),
"port": int(b.Port),
"override_host": b.OverrideHost,
"shield": b.Shield,
"ssl_check_cert": b.SSLCheckCert,
"ssl_hostname": b.SSLHostname,
"ssl_ca_cert": b.SSLCACert,
"ssl_client_key": b.SSLClientKey,
"ssl_client_cert": b.SSLClientCert,
"max_tls_version": b.MaxTLSVersion,
"min_tls_version": b.MinTLSVersion,
"ssl_ciphers": strings.Join(b.SSLCiphers, ","),
"use_ssl": b.UseSSL,
"ssl_cert_hostname": b.SSLCertHostname,
"ssl_sni_hostname": b.SSLSNIHostname,
"weight": int(b.Weight),
"healthcheck": b.HealthCheck,
}
if sa.serviceType == ServiceTypeVCL {
backend["request_condition"] = b.RequestCondition
}
bl = append(bl, backend)
}
return bl
}