forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
f5.go
2227 lines (1830 loc) · 67.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"
"net/http"
"os"
"os/exec"
"path"
"strings"
"github.com/golang/glog"
knet "k8s.io/apimachinery/pkg/util/net"
)
const (
// Default F5 partition path to use for syncing route config.
F5DefaultPartitionPath = "/Common"
F5VxLANTunnelName = "vxlan5000"
F5VxLANProfileName = "vxlan-ose"
HTTP_CONFLICT_CODE = 409
)
// 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
}
// reencryptRoute represents a reencrypt route for the F5 router's internal state
// similar to the passthrough route
type reencryptRoute 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
// reencryptRoutes maps routename to passthroughroute{hostname, poolname}.
reencryptRoutes map[string]reencryptRoute
}
// f5LTMCfg holds configuration for connecting to and issuing 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
// vxlanGateway is the ip address assigned to the local tunnel interface
// inside F5 box. This address is the one that the packets generated from F5
// will carry. The pods will return the packets to this address itself.
// It is important that the gateway be one of the ip addresses of the subnet
// that has been generated for F5.
vxlanGateway string
// internalAddress is the ip address of the vtep interface used to connect to
// VxLAN overlay. It is the hostIP address listed in the subnet generated for F5
internalAddress string
// setupOSDNVxLAN is the boolean that conveys if F5 needs to setup a VxLAN
// to hook up with openshift-sdn
setupOSDNVxLAN bool
}
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"
// reencryptRoutesDataGroupName is the name of the datagroup that will be used
// by our iRule for routing SSL-passthrough routes (see below).
reencryptRoutesDataGroupName = "ssl_reencrypt_route_dg"
// reencryptHostsDataGroupName is the name of the datagroup that will be used
// by our iRule for routing SSL-passthrough routes (see below).
reencryptHostsDataGroupName = "ssl_reencrypt_servername_dg"
// 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]
SSL::disable serverside
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
}
elseif { [class match $servername_lower equals ssl_reencrypt_servername_dg] } {
pool [class match -value $servername_lower equals ssl_reencrypt_servername_dg]
SSL::enable serverside
}
}
}
}
}
}
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)
setupOSDNVxLAN := (len(cfg.vxlanGateway) != 0 && len(cfg.internalAddress) != 0)
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,
vxlanGateway: cfg.vxlanGateway,
internalAddress: cfg.internalAddress,
setupOSDNVxLAN: setupOSDNVxLAN,
},
poolMembers: map[string]map[string]bool{},
routes: map[string]map[string]bool{},
}
return router, nil
}
//
// Helper routines for REST calls.
//
// restRequest 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 JSON result payload, which should have the fields defined in the
// result argument. In this case, restRequest 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. Usually, this payload is JSON containing a numeric
// code (which should be the same as the HTTP response code) and a string
// message. However, in some cases, the F5 iControl REST API returns an
// HTML response payload instead. restRequest attempts to decode the
// response payload as JSON but ignores decoding failures on the assumption
// that a failure to decode means that the response was in HTML. Finally,
// restRequest returns an F5Error with the URL, HTTP verb, HTTP status
// code, and (if the response was JSON) 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, restRequest returns
// an F5Error with the URL, HTTP verb, HTTP status code (if any), and error
// value.
func (f5 *f5LTM) restRequest(verb string, url string, payload io.Reader,
result interface{}) error {
tr := knet.SetTransportDefaults(&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}
glog.V(4).Infof("Request sent: %v\n", req)
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 {
// F5 sometimes returns an HTML response even though we ask for JSON.
// If decoding fails, assume we got an HTML response and ignore both
// the response and the error.
decoder.Decode(&errorResult)
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
}
// restRequestPayload is a helper for F5 operations that take
// a payload.
func (f5 *f5LTM) restRequestPayload(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.restRequest(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.restRequest("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.restRequestPayload("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.restRequestPayload("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.restRequest("DELETE", url, nil, result)
}
//
// iControl REST resource helper methods.
//
// encodeiControlUriPathComponent returns an encoded resource path for use
// in the URI for the iControl REST calls.
// For example for a path /Common/foo, the corresponding encoded iControl
// URI path component would be ~Common~foo and this can then be used in the
// iControl REST calls ala:
// https://<ip>:<port>/mgmt/tm/ltm/policy/~Common~foo/rules
func encodeiControlUriPathComponent(pathName string) string {
return strings.Replace(pathName, "/", "~", -1)
}
// iControlUriResourceId returns an encoded resource id (resource path
// including the partition), which can be used the iControl REST calls.
// For example, for a policy named openshift_secure_routes policy in the
// /Common partition, the encoded resource id would be:
// ~Common~openshift_secure_routes
// which can then be used as a resource specifier in the URI ala:
// https://<ip>:<port>/mgmt/tm/ltm/policy/~Common~openshift_secure_routes/rules
func (f5 *f5LTM) iControlUriResourceId(resourceName string) string {
resourcePath := path.Join(f5.partitionPath, resourceName)
return encodeiControlUriPathComponent(resourcePath)
}
//
// Routines for controlling F5.
//
// ensureVxLANTunnel sets up the VxLAN tunnel profile and tunnel+selfIP
func (f5 *f5LTM) ensureVxLANTunnel() error {
glog.V(4).Infof("Checking and installing VxLAN setup")
// create the profile
url := fmt.Sprintf("https://%s/mgmt/tm/net/tunnels/vxlan", f5.host)
profilePayload := f5CreateVxLANProfilePayload{
Name: F5VxLANProfileName,
Partition: f5.partitionPath,
FloodingType: "multipoint",
Port: 4789,
}
err := f5.post(url, profilePayload, nil)
if err != nil && err.(F5Error).httpStatusCode != HTTP_CONFLICT_CODE {
// error HTTP_CONFLICT_CODE is fine, it just means the tunnel profile already exists
glog.V(4).Infof("Error while creating vxlan tunnel - %v", err)
return err
}
// create the tunnel
url = fmt.Sprintf("https://%s/mgmt/tm/net/tunnels/tunnel", f5.host)
tunnelPayload := f5CreateVxLANTunnelPayload{
Name: F5VxLANTunnelName,
Partition: f5.partitionPath,
Key: 0,
LocalAddress: f5.internalAddress,
Mode: "bidirectional",
Mtu: "0",
Profile: path.Join(f5.partitionPath, F5VxLANProfileName),
Tos: "preserve",
Transparent: "disabled",
UsePmtu: "enabled",
}
err = f5.post(url, tunnelPayload, nil)
if err != nil && err.(F5Error).httpStatusCode != HTTP_CONFLICT_CODE {
// error HTTP_CONFLICT_CODE is fine, it just means the tunnel already exists
return err
}
selfUrl := fmt.Sprintf("https://%s/mgmt/tm/net/self", f5.host)
netSelfPayload := f5CreateNetSelfPayload{
Name: f5.vxlanGateway,
Partition: f5.partitionPath,
Address: f5.vxlanGateway,
AddressSource: "from-user",
Floating: "disabled",
InheritedTrafficGroup: "false",
TrafficGroup: path.Join("/Common", "traffic-group-local-only"), // Traffic group is global
Unit: 0,
Vlan: path.Join(f5.partitionPath, F5VxLANTunnelName),
AllowService: "all",
}
// create the net self IP
err = f5.post(selfUrl, netSelfPayload, nil)
if err != nil && err.(F5Error).httpStatusCode != HTTP_CONFLICT_CODE {
// error HTTP_CONFLICT_CODE is ok, netSelf already exists
return err
}
return nil
}
// 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)
policyResourceId := f5.iControlUriResourceId(policyName)
policyUrl := fmt.Sprintf("https://%s/mgmt/tm/ltm/policy/%s",
f5.host, policyResourceId)
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)
policyPath := path.Join(f5.partitionPath, policyName)
if f5.setupOSDNVxLAN {
// if vxlan needs to be setup, it will only happen
// with ver12, for which we need to use a different payload
policyPayload := f5Ver12Policy{
Name: policyPath,
TmPartition: f5.partitionPath,
Controls: []string{"forwarding"},
Requires: []string{"http"},
Strategy: "best-match",
Legacy: true,
}
err = f5.post(policiesUrl, policyPayload, nil)
} else {
policyPayload := f5Policy{
Name: policyPath,
Partition: f5.partitionPath,
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, policyResourceId)
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)
vserverResourceId := f5.iControlUriResourceId(vserverName)
// We could use fmt.Sprintf("https://%s/mgmt/tm/ltm/virtual/%s/policies/%s",
// f5.host, vserverResourceId, 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, vserverResourceId)
res := f5VserverPolicies{}
err := f5.get(vserverPoliciesUrl, &res)
if err != nil {
return err
}
policyPath := path.Join(f5.partitionPath, policyName)
for _, policy := range res.Policies {
if policy.FullPath == policyPath {
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: policyPath,
Partition: f5.partitionPath,
}
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,
f5.iControlUriResourceId(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,
Partition: f5.partitionPath,
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, f5.iControlUriResourceId(vserverName))
res := f5VserverIRules{}
err := f5.get(vserverUrl, &res)
if err != nil {
return err
}
commonIRuleName := path.Join("/", 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)
sslPassthroughIRulePath := path.Join(f5.partitionPath, sslPassthroughIRuleName)
vserverRulesPayload := f5VserverIRules{
Rules: []string{sslPassthroughIRulePath},
}
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)
uri := fmt.Sprintf("https://%s/mgmt/tm/sys/folder/%s",
f5.host, encodeiControlUriPathComponent(pathName))
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 hierarchy.
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 != HTTP_CONFLICT_CODE {
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 through 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(reencryptRoutesDataGroupName)
if err != nil {
return err
}
err = f5.ensureDatagroupExists(reencryptHostsDataGroupName)
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
}
}
if f5.setupOSDNVxLAN {