forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
f5.go
1823 lines (1491 loc) · 54.8 KB
/
f5.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package f5
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"strings"
"github.com/golang/glog"
)
const (
// Default F5 partition path to use for syncing route config.
F5DefaultPartitionPath = "/Common"
)
// Error implements the error interface.
func (err F5Error) Error() string {
var msg string
if err.err != nil {
msg = fmt.Sprintf("error: %v", err.err)
} else if err.Message != nil {
msg = fmt.Sprintf("HTTP code: %d; error from F5: %s",
err.httpStatusCode, *err.Message)
} else {
msg = fmt.Sprintf("HTTP code: %d.", err.httpStatusCode)
}
return fmt.Sprintf("Encountered an error on %s request to URL %s: %s",
err.verb, err.url, msg)
}
// passthroughRoute represents a passthrough route for the F5 router's internal
// state. In the F5 BIG-IP host itself, we must store this information using
// two datagroups: one that makes routename to hostname so that we can
// reconstruct this state when initializing the router, and one that maps
// hostname to poolname for use by the iRule that handles passthrough routes.
type passthroughRoute struct {
hostname string
poolname string
}
// f5LTM represents an F5 BIG-IP instance.
type f5LTM struct {
// f5LTMCfg contains the configuration parameters for an F5 BIG-IP instance.
f5LTMCfg
// poolMembers maps pool name to set of pool members, where the pool
// name is a string and the set of members of a pool is represented by
// a map with value type bool. A pool member will be identified by
// a string of the format "ipaddress:port".
poolMembers map[string]map[string]bool
// routes maps vserver name to set of routes.
routes map[string]map[string]bool
// passthroughRoutes maps routename to passthroughroute{hostname, poolname}.
passthroughRoutes map[string]passthroughRoute
}
// f5LTMCfg holds configuration for connecting to and issueing iControl
// requests against an F5 BIG-IP instance.
type f5LTMCfg struct {
// host specifies the hostname or IP address of the F5 BIG-IP host.
host string
// username specifies the username with which we should authenticate with the
// F5 BIG-IP host.
username string
// password specifies the password with which we should authenticate with the
// F5 BIG-IP host.
password string
// httpVserver specifies the name of the vserver object for which we should
// manipulate policy to add and remove HTTP routes.
httpVserver string
// httpsVserver specifies the name of the vserver object for which we should
// manipulate policy to add and remove HTTPS routes.
httpsVserver string
// privkey specifies the path to the SSH private-key file for F5 BIG-IP. The
// file must exist with this pathname inside the F5 router's filesystem
// namespace. The F5 router uses this key to copy certificates and keys to
// the F5 BIG-IP host.
privkey string
// insecure specifies whether we should perform strict certificate validation
// for connections to the F5 BIG-IP host.
insecure bool
// partitionPath specifies the F5 partition path to use. Partitions
// are normally used to create an access control boundary for
// F5 users and applications.
partitionPath string
}
const (
// policy is the name of the local traffic policy associated with the vservers
// for insecure (plaintext, HTTP) routes. We add and delete rules to and from
// this policy to configure vhost-based routing.
httpPolicyName = "openshift_insecure_routes"
// https_policy is the name of the local traffic policy associated with the
// vservers for secure (TLS/SSL, HTTPS) routes.
httpsPolicyName = "openshift_secure_routes"
// passthroughRoutesDataGroupName is the name of the datagroup that will be used
// by our iRule for routing SSL-passthrough routes (see below).
passthroughRoutesDataGroupName = "ssl_passthrough_route_dg"
// passthroughHostsDataGroupName is the name of the datagroup that will be used
// by our iRule for routing SSL-passthrough routes (see below).
passthroughHostsDataGroupName = "ssl_passthrough_servername_dg"
// sslPassthroughIRuleName is the name assigned to the sslPassthroughIRule
// iRule.
sslPassthroughIRuleName = "openshift_passthrough_irule"
// sslPassthroughIRule is an iRule that examines the servername in TLS
// connections and routes requests to the corresponding pool if one exists.
//
// You probably will not read the following TCL code. However, if you do, you
// may wonder, "What's up with this 'if { a - b == abs(a - b) }' nonsense?
// Why not simply use 'if { a > b }'? WHAT IS THIS NIMWITTERY?!?" Rest
// assured, there is *no* nimwittery here! In fact, the explanation for this
// curiosity is an incompatibility between Google's JSON encoder and F5's JSON
// decoder: The former produces escape sequences for the characters <, >, and
// & (specifically, \u003c, \u003e, and \u0026) that confuse the latter. Thus
// as long as we are using Google's JSON encoding library and F5's iControl
// REST API, we must avoid using the <, >, and & characters.
sslPassthroughIRule = `
when CLIENT_ACCEPTED {
TCP::collect
}
when CLIENT_DATA {
# Byte 0 is the content type.
# Bytes 1-2 are the TLS version.
# Bytes 3-4 are the TLS payload length.
# Bytes 5-$tls_payload_len are the TLS payload.
binary scan [TCP::payload] cSS tls_content_type tls_version tls_payload_len
switch $tls_version {
"769" -
"770" -
"771" {
# Content type of 22 indicates the TLS payload contains a handshake.
if { $tls_content_type == 22 } {
# Byte 5 (the first byte of the handshake) indicates the handshake
# record type, and a value of 1 signifies that the handshake record is
# a ClientHello.
binary scan [TCP::payload] @5c tls_handshake_record_type
if { $tls_handshake_record_type == 1 } {
# Bytes 6-8 are the handshake length (which we ignore).
# Bytes 9-10 are the TLS version (which we ignore).
# Bytes 11-42 are random data (which we ignore).
# Byte 43 is the session ID length. Following this are three
# variable-length fields which we shall skip over.
set record_offset 43
# Skip the session ID.
binary scan [TCP::payload] @${record_offset}c tls_session_id_len
incr record_offset [expr {1 + $tls_session_id_len}]
# Skip the cipher_suites field.
binary scan [TCP::payload] @${record_offset}S tls_cipher_suites_len
incr record_offset [expr {2 + $tls_cipher_suites_len}]
# Skip the compression_methods field.
binary scan [TCP::payload] @${record_offset}c tls_compression_methods_len
incr record_offset [expr {1 + $tls_compression_methods_len}]
# Get the number of extensions, and store the extensions.
binary scan [TCP::payload] @${record_offset}S tls_extensions_len
incr record_offset 2
binary scan [TCP::payload] @${record_offset}a* tls_extensions
for { set extension_start 0 }
{ $tls_extensions_len - $extension_start == abs($tls_extensions_len - $extension_start) }
{ incr extension_start 4 } {
# Bytes 0-1 of the extension are the extension type.
# Bytes 2-3 of the extension are the extension length.
binary scan $tls_extensions @${extension_start}SS extension_type extension_len
# Extension type 00 is the ServerName extension.
if { $extension_type == "00" } {
# Bytes 4-5 of the extension are the SNI length (we ignore this).
# Byte 6 of the extension is the SNI type.
set sni_type_offset [expr {$extension_start + 6}]
binary scan $tls_extensions @${sni_type_offset}S sni_type
# Type 0 is host_name.
if { $sni_type == "0" } {
# Bytes 7-8 of the extension are the SNI data (host_name)
# length.
set sni_len_offset [expr {$extension_start + 7}]
binary scan $tls_extensions @${sni_len_offset}S sni_len
# Bytes 9-$sni_len are the SNI data (host_name).
set sni_start [expr {$extension_start + 9}]
binary scan $tls_extensions @${sni_start}A${sni_len} tls_servername
}
}
incr extension_start $extension_len
}
if { [info exists tls_servername] } {
set servername_lower [string tolower $tls_servername]
if { [class match $servername_lower equals ssl_passthrough_servername_dg] } {
pool [class match -value $servername_lower equals ssl_passthrough_servername_dg]
SSL::disable
HTTP::disable
}
}
}
}
}
}
TCP::release
}
`
)
// newF5LTM makes a new f5LTM object.
func newF5LTM(cfg f5LTMCfg) (*f5LTM, error) {
if cfg.insecure == true {
glog.Warning("Strict certificate verification is *DISABLED*")
}
if cfg.httpVserver == "" {
glog.Warning("No vserver was specified for HTTP connections;" +
" HTTP routes will not be configured")
}
if cfg.httpsVserver == "" {
glog.Warning("No vserver was specified for HTTPS connections;" +
" HTTPS routes will not be configured")
}
privkeyFileName := ""
if cfg.privkey == "" {
glog.Warning("No SSH key provided for the F5 BIG-IP host;" +
" TLS configuration for applications is disabled")
} else {
// The following is a workaround that will be required until
// https://github.com/kubernetes/kubernetes/issues/4789 "Fine-grained
// control of secret data in volume" is resolved.
// When the oadm command launches the F5 router, oadm copies the SSH private
// key to a Secret object and mounts a secrets volume containing the Secret
// object into the F5 router's container. The ssh and scp commands require
// that the key file mode prohibit access from any user but the owner.
// Currently, there is no way to specify the file mode for files in
// a secrets volume when defining the volume, the default file mode is 0444
// (too permissive for ssh/scp), and the volume is read-only so it is
// impossible to change the file mode. Consequently, we must make a copy of
// the key and change the file mode of the copy so that the ssh/scp commands
// will accept it.
oldPrivkeyFile, err := os.Open(cfg.privkey)
if err != nil {
glog.Errorf("Error opening file for F5 BIG-IP private key"+
" from secrets volume: %v", err)
return nil, err
}
newPrivkeyFile, err := ioutil.TempFile("", "privkey")
if err != nil {
glog.Errorf("Error creating tempfile for F5 BIG-IP private key: %v", err)
return nil, err
}
_, err = io.Copy(newPrivkeyFile, oldPrivkeyFile)
if err != nil {
glog.Errorf("Error writing private key for F5 BIG-IP to tempfile: %v",
err)
return nil, err
}
err = oldPrivkeyFile.Close()
if err != nil {
// Warn because closing the old file should succeed, but continue because
// we should be OK if the copy succeeded.
glog.Warningf("Error closing file for private key for F5 BIG-IP"+
" from secrets volume: %v", err)
}
err = newPrivkeyFile.Close()
if err != nil {
glog.Errorf("Error closing tempfile for private key for F5 BIG-IP: %v",
err)
return nil, err
}
// The chmod should not be necessary because ioutil.TempFile() creates files
// with restrictive permissions, but we do it anyway to be sure.
err = os.Chmod(newPrivkeyFile.Name(), 0400)
if err != nil {
glog.Warningf("Could not chmod the tempfile for F5 BIG-IP"+
" private key: %v", err)
}
privkeyFileName = newPrivkeyFile.Name()
}
partitionPath := F5DefaultPartitionPath
if len(cfg.partitionPath) > 0 {
partitionPath = cfg.partitionPath
}
// Ensure path is rooted.
partitionPath = path.Join("/", partitionPath)
router := &f5LTM{
f5LTMCfg: f5LTMCfg{
host: cfg.host,
username: cfg.username,
password: cfg.password,
httpVserver: cfg.httpVserver,
httpsVserver: cfg.httpsVserver,
privkey: privkeyFileName,
insecure: cfg.insecure,
partitionPath: partitionPath,
},
poolMembers: map[string]map[string]bool{},
routes: map[string]map[string]bool{},
}
return router, nil
}
//
// Helper routines for REST calls.
//
// rest_request makes a REST request to the F5 BIG-IP host's F5 iControl REST
// API.
//
// One of three things can happen as a result of a request to F5 iControl REST:
//
// (1) The request succeeds and F5 returns an HTTP 200 response, possibly with
// a result payload, which should have the fields defined in the
// result argument. In this case, rest_request decodes the payload into
// the result argument and returns nil.
//
// (2) The request fails and F5 returns an HTTP 4xx or 5xx response with a
// response payload containing a code (which should be the same as the
// HTTP response code) and a string message. In this case, rest_request
// decodes the response payload and returns an F5Error with the URL, HTTP
// verb, HTTP status code, and error information from the response payload.
//
// (3) The REST call fails in some other way, such as a socket error or an
// error decoding the result payload. In this case, rest_request returns
// an F5Error with the URL, HTTP verb, HTTP status code (if any), and error
// value.
func (f5 *f5LTM) rest_request(verb string, url string, payload io.Reader,
result interface{}) error {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: f5.insecure},
}
errorResult := F5Error{verb: verb, url: url}
req, err := http.NewRequest(verb, url, payload)
if err != nil {
errorResult.err = fmt.Errorf("http.NewRequest failed: %v", err)
return errorResult
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(f5.username, f5.password)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
errorResult.err = fmt.Errorf("client.Do failed: %v", err)
return errorResult
}
defer resp.Body.Close()
errorResult.httpStatusCode = resp.StatusCode
decoder := json.NewDecoder(resp.Body)
if resp.StatusCode >= 400 {
if resp.StatusCode == 404 {
// Just return the error without trying to decode the message
// body—F5 sometimes returns an HTML response in the case of a 404
// (even though we *ask* for JSON and F5 *usually* obliges).
return errorResult
}
err = decoder.Decode(&errorResult)
if err != nil {
errorResult.err = fmt.Errorf("Decoder.Decode failed: %v", err)
}
return errorResult
} else if result != nil {
err = decoder.Decode(result)
if err != nil {
errorResult.err = fmt.Errorf("Decoder.Decode failed: %v", err)
return errorResult
}
}
return nil
}
// rest_request_payload is a helper for F5 operations that take
// a payload.
func (f5 *f5LTM) rest_request_payload(verb string, url string,
payload interface{}, result interface{}) error {
jsonStr, err := json.Marshal(payload)
if err != nil {
return F5Error{verb: verb, url: url, err: err}
}
encodedPayload := bytes.NewBuffer(jsonStr)
return f5.rest_request(verb, url, encodedPayload, result)
}
// get issues a GET request against the F5 iControl REST API.
func (f5 *f5LTM) get(url string, result interface{}) error {
return f5.rest_request("GET", url, nil, result)
}
// post issues a POST request against the F5 iControl REST API.
func (f5 *f5LTM) post(url string, payload interface{}, result interface{}) error {
return f5.rest_request_payload("POST", url, payload, result)
}
// patch issues a PATCH request against the F5 iControl REST API.
func (f5 *f5LTM) patch(url string, payload interface{}, result interface{}) error {
return f5.rest_request_payload("PATCH", url, payload, result)
}
// delete issues a DELETE request against the F5 iControl REST API.
func (f5 *f5LTM) delete(url string, result interface{}) error {
return f5.rest_request("DELETE", url, nil, result)
}
//
// Routines for controlling F5.
//
// ensurePolicyExists checks whether the specified policy exists and creates it
// if not.
func (f5 *f5LTM) ensurePolicyExists(policyName string) error {
glog.V(4).Infof("Checking whether policy %s exists...", policyName)
policyUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/policy/%s",
f5.host, policyName)
err := f5.get(policyUrl, nil)
if err != nil && err.(F5Error).httpStatusCode != 404 {
// 404 is expected, but anything else really is an error.
return err
}
if err == nil {
glog.V(4).Infof("Policy %s already exists; nothing to do.", policyName)
return nil
}
glog.V(4).Infof("Policy %s does not exist; creating it now...", policyName)
policiesUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/policy", f5.host)
policyPayload := f5Policy{
Name: policyName,
Controls: []string{"forwarding"},
Requires: []string{"http"},
Strategy: "best-match",
}
err = f5.post(policiesUrl, policyPayload, nil)
if err != nil {
return err
}
// We need a rule in the policy in order to be able to add the policy to the
// vservers, so create a no-op rule now.
glog.V(4).Infof("Policy %s created. Adding no-op rule...", policyName)
rulesUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/policy/%s/rules",
f5.host, policyName)
rulesPayload := f5Rule{
Name: "default_noop",
}
err = f5.post(rulesUrl, rulesPayload, nil)
if err != nil {
return err
}
glog.V(4).Infof("No-op rule added to policy %s.", policyName)
return nil
}
// ensureVserverHasPolicy checks whether the specified policy is associated with
// the specified vserver and associates the policy with the vserver if not.
func (f5 *f5LTM) ensureVserverHasPolicy(vserverName, policyName string) error {
glog.V(4).Infof("Checking whether vserver %s has policy %s...",
vserverName, policyName)
// We could use fmt.Sprintf("https://%s/mgmt/tm/ltm/virtual/%s/policies/%s",
// f5.host, vserverName, policyName) here, except that F5 iControl REST
// returns a 200 even if the policy does not exist.
vserverPoliciesUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/virtual/%s/policies",
f5.host, vserverName)
res := f5VserverPolicies{}
err := f5.get(vserverPoliciesUrl, &res)
if err != nil {
return err
}
for _, policy := range res.Policies {
if policy.Name == policyName {
glog.V(4).Infof("Vserver %s has policy %s associated with it;"+
" nothing to do.", vserverName, policyName)
return nil
}
}
glog.V(4).Infof("Adding policy %s to vserver %s...", policyName, vserverName)
vserverPoliciesPayload := f5VserverPolicy{
Name: policyName,
}
err = f5.post(vserverPoliciesUrl, vserverPoliciesPayload, nil)
if err != nil {
return err
}
glog.V(4).Infof("Policy %s added to vserver %s.", policyName, vserverName)
return nil
}
// ensureDatagroupExists checks whether the specified data-group exists and
// creates it if not.
//
// Note that ensureDatagroupExists assumes that the value-type of the data-group
// should be "string".
func (f5 *f5LTM) ensureDatagroupExists(datagroupName string) error {
glog.V(4).Infof("Checking whether datagroup %s exists...", datagroupName)
datagroupUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/data-group/internal/%s",
f5.host, datagroupName)
err := f5.get(datagroupUrl, nil)
if err != nil && err.(F5Error).httpStatusCode != 404 {
// 404 is expected, but anything else really is an error.
return err
}
if err == nil {
glog.V(4).Infof("Datagroup %s exists; nothing to do.",
datagroupName)
return nil
}
glog.V(4).Infof("Creating datagroup %s...", datagroupName)
datagroupsUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/data-group/internal",
f5.host)
datagroupPayload := f5Datagroup{
Name: datagroupName,
Type: "string",
}
err = f5.post(datagroupsUrl, datagroupPayload, nil)
if err != nil {
return err
}
glog.V(4).Infof("Datagroup %s created.", datagroupName)
return nil
}
// ensureIRuleExists checks whether an iRule with the specified name exists and
// creates an iRule with that name and the given code if not.
func (f5 *f5LTM) ensureIRuleExists(iRuleName, iRule string) error {
glog.V(4).Infof("Checking whether iRule %s exists...", iRuleName)
iRuleUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/rule/%s", f5.host, iRuleName)
err := f5.get(iRuleUrl, nil)
if err != nil && err.(F5Error).httpStatusCode != 404 {
// 404 is expected, but anything else really is an error.
return err
}
if err == nil {
glog.V(4).Infof("iRule %s already exists; nothing to do.", iRuleName)
return nil
}
glog.V(4).Infof("IRule %s does not exist; creating it now...", iRuleName)
iRulesUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/rule", f5.host)
iRulePayload := f5IRule{
Name: iRuleName,
Code: iRule,
}
err = f5.post(iRulesUrl, iRulePayload, nil)
if err != nil {
return err
}
glog.V(4).Infof("IRule %s created.", iRuleName)
return nil
}
// ensureVserverHasIRule checks whether the specified iRule is associated with
// the specified vserver and associates the iRule with the vserver if not.
func (f5 *f5LTM) ensureVserverHasIRule(vserverName, iRuleName string) error {
glog.V(4).Infof("Checking whether vserver %s has iRule %s...",
vserverName, iRuleName)
vserverUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/virtual/%s",
f5.host, vserverName)
res := f5VserverIRules{}
err := f5.get(vserverUrl, &res)
if err != nil {
return err
}
commonIRuleName := fmt.Sprintf("%s/%s", f5.partitionPath, iRuleName)
for _, name := range res.Rules {
if name == commonIRuleName {
glog.V(4).Infof("Vserver %s has iRule %s associated with it;"+
" nothing to do.",
vserverName, iRuleName)
return nil
}
}
glog.V(4).Infof("Adding iRule %s to vserver %s...", iRuleName, vserverName)
vserverRulesPayload := f5VserverIRules{
Rules: []string{sslPassthroughIRuleName},
}
err = f5.patch(vserverUrl, vserverRulesPayload, nil)
if err != nil {
return err
}
glog.V(4).Infof("IRule %s added to vserver %s.", iRuleName, vserverName)
return nil
}
// checkPartitionPathExists checks if the partition path exists.
func (f5 *f5LTM) checkPartitionPathExists(pathName string) (bool, error) {
glog.V(4).Infof("Checking if partition path %q exists...", pathName)
// F5 iControl REST API expects / characters in the path to be
// escaped as ~.
uri := fmt.Sprintf("https://%s/mgmt/tm/sys/folder/%s",
f5.host, strings.Replace(pathName, "/", "~", -1))
err := f5.get(uri, nil)
if err != nil {
if err.(F5Error).httpStatusCode != 404 {
glog.Errorf("partition path %q error: %v", pathName, err)
return false, err
}
// 404 is ok means that the path doesn't exist == !err.
return false, nil
}
glog.V(4).Infof("Partition path %q exists.", pathName)
return true, nil
}
// addPartitionPath adds a new partition path to the folder heirarchy.
func (f5 *f5LTM) addPartitionPath(pathName string) (bool, error) {
glog.V(4).Infof("Creating partition path %q ...", pathName)
uri := fmt.Sprintf("https://%s/mgmt/tm/sys/folder", f5.host)
payload := f5AddPartitionPathPayload{Name: pathName}
err := f5.post(uri, payload, nil)
if err != nil {
if err.(F5Error).httpStatusCode != 409 {
glog.Errorf("Error adding partition path %q error: %v", pathName, err)
return false, err
}
// If the path already exists, don't return an error.
glog.Warningf("Partition path %q not added as it already exists.", pathName)
return false, nil
}
return true, nil
}
// ensurePartitionPathExists checks whether the specified partition path
// hierarchy exists and creates it if it does not.
func (f5 *f5LTM) ensurePartitionPathExists(pathName string) error {
glog.V(4).Infof("Ensuring partition path %s exists...", pathName)
exists, err := f5.checkPartitionPathExists(pathName)
if err != nil {
return err
}
if exists {
return nil
}
// We have to loop thru the path hierarchy and add components
// individually if they don't exist.
// Get path components - we need to remove the leading empty path
// component after splitting (make it absolute if it is not already
// and skip the first element).
// As an example, for a path named "/a/b/c", strings.Split returns
// []string{"", "a", "b", "c"}
// and we skip the empty string.
p := "/"
pathComponents := strings.Split(path.Join("/", pathName)[1:], "/")
for _, v := range pathComponents {
p = path.Join(p, v)
exists, err := f5.checkPartitionPathExists(p)
if err != nil {
return err
}
if !exists {
if _, err := f5.addPartitionPath(p); err != nil {
return err
}
}
}
glog.V(4).Infof("Partition path %s added.", pathName)
return nil
}
// Initialize ensures that OpenShift-specific configuration is in place on the
// F5 BIG-IP host. In particular, Initialize creates policies for HTTP and
// HTTPS traffic, as well as an iRule and data-groups for passthrough routes,
// and associates these objects with the appropriate vservers, if necessary.
func (f5 *f5LTM) Initialize() error {
err := f5.ensurePartitionPathExists(f5.partitionPath)
if err != nil {
return err
}
err = f5.ensurePolicyExists(httpPolicyName)
if err != nil {
return err
}
if f5.httpVserver != "" {
err = f5.ensureVserverHasPolicy(f5.httpVserver, httpPolicyName)
if err != nil {
return err
}
}
err = f5.ensurePolicyExists(httpsPolicyName)
if err != nil {
return err
}
err = f5.ensureDatagroupExists(passthroughRoutesDataGroupName)
if err != nil {
return err
}
err = f5.ensureDatagroupExists(passthroughHostsDataGroupName)
if err != nil {
return err
}
if f5.httpsVserver != "" {
err = f5.ensureVserverHasPolicy(f5.httpsVserver, httpsPolicyName)
if err != nil {
return err
}
err = f5.ensureIRuleExists(sslPassthroughIRuleName, sslPassthroughIRule)
if err != nil {
return err
}
err = f5.ensureVserverHasIRule(f5.httpsVserver, sslPassthroughIRuleName)
if err != nil {
return err
}
}
glog.V(4).Infof("F5 initialization is complete.")
return nil
}
// CreatePool creates a pool named poolname on F5 BIG-IP.
func (f5 *f5LTM) CreatePool(poolname string) error {
url := fmt.Sprintf("https://%s/mgmt/tm/ltm/pool", f5.host)
// The http monitor is still used from the /Common partition.
// From @Miciah: In the future, we should allow the administrator
// to specify a different monitor to use.
payload := f5Pool{
Mode: "round-robin",
Monitor: "/Common/http",
Name: poolname,
}
err := f5.post(url, payload, nil)
if err != nil {
return err
}
// We don't really need to initialise f5.poolMembers[poolname] because
// we always check whether it is initialised before using it, but
// initialising it to an empty map here saves a REST call later the first
// time f5.PoolHasMember is invoked with poolname.
f5.poolMembers[poolname] = map[string]bool{}
glog.V(4).Infof("Pool %s created.", poolname)
return nil
}
// DeletePool deletes the specified pool from F5 BIG-IP, and deletes
// f5.poolMembers[poolname].
func (f5 *f5LTM) DeletePool(poolname string) error {
url := fmt.Sprintf("https://%s/mgmt/tm/ltm/pool/%s", f5.host, poolname)
err := f5.delete(url, nil)
if err != nil {
return err
}
// Note: We *must* use delete here rather than merely assigning false because
// len() includes false items, and we want len() to return an accurate count
// of members. Also, we probably save some memory by using delete.
delete(f5.poolMembers, poolname)
glog.V(4).Infof("Pool %s deleted.", poolname)
return nil
}
// GetPoolMembers returns f5.poolMembers[poolname], first initializing it from
// F5 if it is zero.
func (f5 *f5LTM) GetPoolMembers(poolname string) (map[string]bool, error) {
members, ok := f5.poolMembers[poolname]
if ok {
return members, nil
}
url := fmt.Sprintf("https://%s/mgmt/tm/ltm/pool/%s/members",
f5.host, poolname)
res := f5PoolMemberset{}
err := f5.get(url, &res)
if err != nil {
return nil, err
}
// Note that we do not initialise f5.poolMembers[poolname] unless we know that
// the pool exists (i.e., the above GET request for the pool succeeds).
f5.poolMembers[poolname] = map[string]bool{}
for _, member := range res.Members {
f5.poolMembers[poolname][member.Name] = true
}
return f5.poolMembers[poolname], nil
}
// PoolExists checks whether the specified pool exists. Internally, PoolExists
// uses f5.poolMembers[poolname], as a side effect initialising it if it is
// zero.
func (f5 *f5LTM) PoolExists(poolname string) (bool, error) {
_, err := f5.GetPoolMembers(poolname)
if err == nil {
return true, nil
}
if err.(F5Error).httpStatusCode == 404 {
return false, nil
}
return false, err
}
// PoolHasMember checks whether the given member is in the specified pool on F5
// BIG-IP. Internally, PoolHasMember uses f5.poolMembers[poolname], causing it
// to be initialised first if it is zero.
func (f5 *f5LTM) PoolHasMember(poolname, member string) (bool, error) {
members, err := f5.GetPoolMembers(poolname)
if err != nil {
return false, err
}
return members[member], nil
}
// AddPoolMember adds the given member to the specified pool on F5 BIG-IP, and
// updates f5.poolMembers[poolname].
func (f5 *f5LTM) AddPoolMember(poolname, member string) error {
hasMember, err := f5.PoolHasMember(poolname, member)
if err != nil {
return err
}
if hasMember {
glog.V(4).Infof("Pool %s already has member %s.\n", poolname, member)
return nil
}
glog.V(4).Infof("Adding pool member %s to pool %s.", member, poolname)
url := fmt.Sprintf("https://%s/mgmt/tm/ltm/pool/%s/members",
f5.host, poolname)
payload := f5PoolMember{
Name: member,
}
err = f5.post(url, payload, nil)
if err != nil {
return err
}
members, err := f5.GetPoolMembers(poolname)
if err != nil {
return err
}
members[member] = true
glog.V(4).Infof("Added pool member %s to pool %s.",
member, poolname)
return nil
}
// DeletePoolMember deletes the given member from the specified pool on F5
// BIG-IP, and updates f5.poolMembers[poolname].
func (f5 *f5LTM) DeletePoolMember(poolname, member string) error {
// The invocation of f5.PoolHasMember has the side effect that it will
// initialise f5.poolMembers[poolname], which is used below, if necessary.
hasMember, err := f5.PoolHasMember(poolname, member)
if err != nil {
return err
}
if !hasMember {
glog.V(4).Infof("Pool %s does not have member %s.\n", poolname, member)
return nil
}
url := fmt.Sprintf("https://%s/mgmt/tm/ltm/pool/%s/members/%s",
f5.host, poolname, member)
err = f5.delete(url, nil)
if err != nil {
return err
}