/
ixate.go
1747 lines (1617 loc) · 53.9 KB
/
ixate.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
// Copyright 2021 Google LLC
//
// Licensed 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
//
// https://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.
package ate
import (
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"net"
"os"
"path"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/net/context"
log "github.com/golang/glog"
"github.com/openconfig/ondatra/binding"
"github.com/openconfig/ondatra/binding/ixweb"
"github.com/openconfig/ondatra/internal/ixconfig"
"github.com/openconfig/ondatra/internal/ixgnmi"
"github.com/openconfig/ondatra/internal/rawapis"
gpb "github.com/openconfig/gnmi/proto/gnmi"
opb "github.com/openconfig/ondatra/proto"
)
type operState uint
type routeTableFormat string
// OperStatus represents the status of a completed IxNetwork operation.
type OperStatus string
const (
operStateOff operState = iota
operStateProtocolsOn
operStateTrafficOn
routeTableFormatCisco routeTableFormat = "cisco"
routeTableFormatJuniper routeTableFormat = "juniper"
routeTableFormatCSV routeTableFormat = "csv"
// OperStatusSuccess indicates a successful operation.
OperStatusSuccess OperStatus = "success"
// OperStatusFailure indicates a failed operation.
OperStatusFailure OperStatus = "failure"
importRetries = 5
// IxNetwork has an undocumented maximum number of DeviceGroups.
maxIntfs = 256
bgpPeerV4NotifyOp = "topology/deviceGroup/ethernet/ipv4/bgpIpv4Peer/operations/breaktcpsession"
bgpPeerV6NotifyOp = "topology/deviceGroup/ethernet/ipv6/bgpIpv6Peer/operations/breaktcpsession"
bgpPeerV4GracefulRestartOp = "topology/deviceGroup/ethernet/ipv4/bgpIpv4Peer/operations/gracefulrestart"
bgpPeerV6GracefulRestartOp = "topology/deviceGroup/ethernet/ipv6/bgpIpv6Peer/operations/gracefulrestart"
startLACPOp = "lag/protocolStack/ethernet/lagportlacp/port/operations/start"
stopLACPOp = "lag/protocolStack/ethernet/lagportlacp/port/operations/stop"
)
var (
syncedOpArgs = ixweb.OpArgs{"sync"}
macRE = regexp.MustCompile(`^([0-9a-f]{2}:){5}([0-9a-f]{2})$`)
resolveMacsFn = resolveMacs
// TODO(team): Lower timeouts after chassis hardware upgrades.
peersImportTimeout = time.Minute
trafficImportTimeout = 4 * time.Minute
topoImportTimeout = 3 * time.Minute
sleepFn = time.Sleep
syncRouteTableFilesAndImportFn = syncRouteTableFilesAndImport
validateProtocolStartFn = validateProtocolStart
resetIxiaTrafficCfgFn = resetIxiaTrafficCfg
genTrafficFn = genTraffic
updateFlowsFn = updateFlows
configureTrafficFn = configureTraffic
applyTrafficFn = applyTraffic
startTrafficFn = startTraffic
)
type cfgClient interface {
Session() session
NodeID(ixconfig.IxiaCfgNode) (string, error)
ExportConfig(context.Context) (*ixconfig.Ixnetwork, error)
ImportConfig(context.Context, *ixconfig.Ixnetwork, ixconfig.IxiaCfgNode, bool) error
UpdateIDs(context.Context, *ixconfig.Ixnetwork, ...ixconfig.IxiaCfgNode) error
}
type session interface {
ID() int
AbsPath(string) string
Delete(context.Context, string) error
Get(context.Context, string, any) error
Patch(context.Context, string, any) error
Post(context.Context, string, any, any) error
Errors(context.Context) ([]*ixweb.Error, error)
Files() files
Stats() stats
}
type files interface {
List(context.Context, string) ([]string, error)
Upload(context.Context, string, []byte) error
Delete(context.Context, string) error
}
type stats interface {
Views(context.Context) (map[string]view, error)
ConfigEgressView(context.Context, []string, int) (*ixweb.StatView, error)
}
type view interface {
FetchTable(context.Context, ...string) (ixweb.StatTable, error)
}
type clientWrapper struct {
*ixconfig.Client
}
func (cw *clientWrapper) Session() session {
return &sessionWrapper{cw.Client.Session()}
}
func unwrapClient(c cfgClient) *ixconfig.Client {
return c.(*clientWrapper).Client
}
type sessionWrapper struct {
*ixweb.Session
}
func (sw *sessionWrapper) Files() files {
return sw.Session.Files()
}
func (sw *sessionWrapper) Stats() stats {
return &statsWrapper{sw.Session.Stats()}
}
type statsWrapper struct {
*ixweb.Stats
}
func (sw *statsWrapper) Views(ctx context.Context) (map[string]view, error) {
views, err := sw.Stats.Views(ctx)
if err != nil {
return nil, err
}
m := make(map[string]view, len(views))
for c, v := range views {
m[c] = &viewWrapper{v}
}
return m, nil
}
type viewWrapper struct {
*ixweb.StatView
}
func (vw *viewWrapper) FetchTable(ctx context.Context, drilldowns ...string) (ixweb.StatTable, error) {
return vw.StatView.FetchTable(ctx, drilldowns...)
}
// CfgComponents represents the physical ATE components in use for the session and
// their association with configured interfaces/protocols.
type CfgComponents struct {
Host string
Linecards []uint64
Ports []string
PortToInterfaces map[string][]string
InterfaceToProtocols map[string][]string
}
func (c *CfgComponents) String() string {
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
return fmt.Sprintf("<error marshaling JSON: %v>", err)
}
return string(b)
}
// OperResult represents the status of an operation and the configuration context in which it executed.
type OperResult struct {
Path string
Status OperStatus
Start time.Time
End time.Time
OpErr error
SessionErrs []*ixweb.Error
Components *CfgComponents
}
func (o *OperResult) String() string {
b, err := json.MarshalIndent(o, "", " ")
if err != nil {
return fmt.Sprintf("<error marshaling JSON: %v>", err)
}
return string(b)
}
// IPv4/6 route tables specified by local path.
type routeTables struct {
format routeTableFormat
ipv4, ipv6 string
overwriteNexthop bool
}
type intf struct {
deviceGroup *ixconfig.TopologyDeviceGroup
ipv4 *ixconfig.TopologyIpv4
ipv6 *ixconfig.TopologyIpv6
ipv4Loopback *ixconfig.TopologyIpv4Loopback
ipv6Loopback *ixconfig.TopologyIpv6Loopback
rsvpLSPs map[string]*ixconfig.TopologyRsvpteLsps
link ixconfig.IxiaCfgNode
isrToNetworkGroup map[string]*ixconfig.TopologyNetworkGroup
netToNetworkGroup map[string]*ixconfig.TopologyNetworkGroup
netToRouteTables map[string]*routeTables
ethMac string
resolvedIpv4Mac string
resolvedIpv6Mac string
hasVLAN bool
idToBGPv4Peer map[uint32]*ixconfig.TopologyBgpIpv4Peer
idToBGPv6Peer map[uint32]*ixconfig.TopologyBgpIpv6Peer
}
func (i *intf) String() string {
return fmt.Sprintf("%+v", *i)
}
func newIxATE(ctx context.Context, name string, ixn *binding.IxNetwork) (*ixATE, error) {
ix := &ixATE{
name: name,
c: &clientWrapper{ixconfig.New(ixn.Session)},
chassisHost: ixn.ChassisHost,
syslogHost: ixn.SyslogHost,
}
if ix.chassisHost == "" {
ix.chassisHost = name
}
ix.resetClientCfg()
// Merge the initial config to set global preferences like syslog streaming,
// but do not overwrite to avoid intefering with interactive debugging.
if err := ix.importConfig(ctx, ix.cfg, false, time.Minute, "minimal initial config reset"); err != nil {
return nil, fmt.Errorf("could not set minimal initial config for session: %w", err)
}
return ix, nil
}
// ixATE provides an ATE interface backed by an IxNetwork session.
type ixATE struct {
c cfgClient
name string
syslogHost string
chassisHost string
cfgPushCount int
cfg *ixconfig.Ixnetwork
routeTableToIxFile map[string]string // Mapping of route tables (by local path) to IxNetwork file name.
ports map[string]*ixconfig.Vport
lags map[string]*ixconfig.Lag
lagPorts map[*ixconfig.Lag][]*ixconfig.Vport
intfs map[string]*intf
flowToTrafficItem map[string]*ixconfig.TrafficTrafficItem
ingressTrackFlows []string
egressTrackFlowCounts map[string]int
convergenceTracking bool
// Operational state is updated as needed on successful API calls.
operState operState
mu sync.Mutex
gclient *ixgnmi.Client
}
func linkToPorts(ix *ixATE, link ixconfig.IxiaCfgNode) ([]string, error) {
var ports []string
switch l := link.(type) {
case *ixconfig.Vport:
ports = []string{*l.Name}
case *ixconfig.Lag:
vports := ix.lagPorts[l]
for _, vp := range vports {
ports = append(ports, *vp.Name)
}
default:
return nil, fmt.Errorf("link node is not a Vport or Lag link: %v(%T)", link, link)
}
return ports, nil
}
func (ix *ixATE) logOp(ctx context.Context, path string, opErr error, start, end time.Time) {
components := &CfgComponents{
Host: ix.name,
PortToInterfaces: map[string][]string{},
InterfaceToProtocols: map[string][]string{},
}
linecards := map[uint64]bool{}
for port := range ix.ports {
components.Ports = append(components.Ports, port)
lc, err := strconv.ParseUint(strings.Split(port, "/")[0], 10, 64)
if err != nil {
log.Errorf("Could not parse linecard from port %q: %v", port, err)
continue
}
linecards[lc] = true
}
for lc := range linecards {
components.Linecards = append(components.Linecards, lc)
}
for name, intf := range ix.intfs {
ports, err := linkToPorts(ix, intf.link)
if err != nil {
log.Errorf("Could not compute ports for intf %q", name)
continue
}
for _, port := range ports {
components.PortToInterfaces[port] = append(components.PortToInterfaces[port], name)
}
var protocolsForIntf []string
if v4 := intf.ipv4; v4 != nil {
protocolsForIntf = append(protocolsForIntf, "IPv4")
if len(v4.BgpIpv4Peer) != 0 {
protocolsForIntf = append(protocolsForIntf, "BGPOnV4")
}
}
if v6 := intf.ipv6; v6 != nil {
protocolsForIntf = append(protocolsForIntf, "IPv6")
if len(v6.BgpIpv6Peer) != 0 {
protocolsForIntf = append(protocolsForIntf, "BGPOnV6")
}
}
if intf.ipv4Loopback != nil {
protocolsForIntf = append(protocolsForIntf, "IPv4Loopback")
}
if intf.ipv6Loopback != nil {
protocolsForIntf = append(protocolsForIntf, "IPv6Loopback")
}
if len(intf.deviceGroup.IsisL3Router) != 0 {
protocolsForIntf = append(protocolsForIntf, "IS-IS")
}
if len(intf.rsvpLSPs) != 0 {
protocolsForIntf = append(protocolsForIntf, "RSVP")
}
components.InterfaceToProtocols[name] = protocolsForIntf
}
status := OperStatusSuccess
if opErr != nil {
status = OperStatusFailure
}
opResult := &OperResult{
Path: path,
Status: status,
Start: start,
End: end,
OpErr: opErr,
SessionErrs: ix.sessionErrors(ctx),
Components: components,
}
log.Infof(opResult.String())
}
func (ix *ixATE) runOp(ctx context.Context, path string, in any, out any) error {
start := time.Now()
err := ix.c.Session().Post(ctx, path, in, out)
end := time.Now()
ix.logOp(ctx, path, err, start, end)
return err
}
// Resets traffic configuration on this client. Does not make any changes on the Ixia.
func (ix *ixATE) resetClientTrafficCfg() {
ix.cfg.Traffic = nil
ix.flowToTrafficItem = make(map[string]*ixconfig.TrafficTrafficItem)
ix.ingressTrackFlows = nil
ix.egressTrackFlowCounts = make(map[string]int)
ix.convergenceTracking = false
}
// Removes traffic configuration on the Ixia.
func resetIxiaTrafficCfg(ctx context.Context, ix *ixATE) error {
if err := ix.stopAllTraffic(ctx); err != nil {
return err
}
if err := ix.runOp(ctx, "operations/clearstats", ixweb.OpArgs{}, nil); err != nil {
return fmt.Errorf("could not clear stats: %w", err)
}
if err := ix.c.Session().Delete(ctx, "traffic/trafficItem"); err != nil {
return fmt.Errorf("could not delete IxNetwork traffic items: %w", err)
}
return nil
}
// Resets all configuration on this client. Does not make any changes on the Ixia.
func (ix *ixATE) resetClientCfg() {
ix.cfg = &ixconfig.Ixnetwork{}
if ix.syslogHost != "" {
ix.cfg.Globals = &ixconfig.Globals{
Preferences: &ixconfig.GlobalsPreferences{
StreamLogsToSyslogServer: ixconfig.Bool(true),
SyslogHost: ixconfig.String(ix.syslogHost),
},
}
}
ix.routeTableToIxFile = make(map[string]string)
ix.ports = make(map[string]*ixconfig.Vport)
ix.lags = make(map[string]*ixconfig.Lag)
ix.lagPorts = make(map[*ixconfig.Lag][]*ixconfig.Vport)
ix.intfs = make(map[string]*intf)
ix.resetClientTrafficCfg()
}
// sessionErrors returns the errors reported by the IxNetwork session.
// Does not fail if there was an error querying the session ('nil' is
// returned both in this case and if there were no errors.)
func (ix *ixATE) sessionErrors(ctx context.Context) []*ixweb.Error {
errors, err := ix.c.Session().Errors(ctx)
if err != nil {
log.Errorf("Could not fetch errors for IxNetwork session: %v", err)
return nil
}
var sErrs []*ixweb.Error
for _, e := range errors {
if e.Level == "kError" {
sErrs = append(sErrs, e)
}
}
return sErrs
}
// importConfig is a wrapper around the config client ImportConfig method.
// It writes configs as test artifacts before pushing.
func (ix *ixATE) importConfig(ctx context.Context, node ixconfig.IxiaCfgNode, overwrite bool, timeout time.Duration, desc string) error {
log.Infof("Importing config for %s", desc)
ix.cfgPushCount++
fileSuffix := ".json"
if overwrite {
fileSuffix = "_overwrite" + fileSuffix
}
desc = strings.ReplaceAll(desc, " ", "_")
fileName := fmt.Sprintf("ixnetwork-config-%s-%02d-%s-%s", ix.name, ix.cfgPushCount, desc, fileSuffix)
outputDir := os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR")
if outputDir == "" {
outputDir = os.TempDir()
}
filePath := path.Join(outputDir, fileName)
defer func() {
// Record the pushed config after XPaths have been updated by ix.c.ImportConfig.
jsonStr, err := json.MarshalIndent(node, "", " ")
if err != nil {
log.Errorf("could not marshal IxNetwork config for logging to file: %v", err)
}
if err := os.WriteFile(filePath, jsonStr, 0644); err != nil {
log.Errorf("could not log IxNetwork config to file: %v", err)
}
log.Infof("IxNetwork config push attempt logged to file %s", filePath)
}()
const importDelay = 15 * time.Second
importCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for i := 0; i < importRetries; i++ {
start := time.Now()
err := ix.c.ImportConfig(importCtx, ix.cfg, node, overwrite)
end := time.Now()
ix.logOp(ctx, "importconfig", err, start, end)
// If no error or if there is an error and the request did not timeout.
if err == nil || importCtx.Err() != context.DeadlineExceeded {
return err
}
log.Warningf("Slow import config, canceling and retrying ...")
sleepFn(importDelay)
importCtx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
return errors.New("timeout importing config")
}
func (ix *ixATE) configureTopology(ics []*opb.InterfaceConfig) error {
if len(ix.ports) == 0 {
return errors.New("no ports configured for topology, check if (*Topology).Update called before (*Topology).Push")
}
ix.cfg.Topology = nil
ifsByLink := groupByLink(ics)
for _, ifs := range ifsByLink {
if err := ix.addTopology(ifs); err != nil {
return err
}
for _, ifc := range ifs {
// TODO(greg-dennis): Add MACsec to the 'golden' ixiajsoncfg PushTopology tests.
if err := ix.addMACsecProtocol(ifc); err != nil {
return err
}
if err := ix.addIPProtocols(ifc); err != nil {
return err
}
if err := ix.addIPLoopbackProtocols(ifc); err != nil {
return err
}
if err := ix.addISISProtocols(ifc); err != nil {
return err
}
if err := ix.addBGPProtocols(ifc); err != nil {
return err
}
if err := ix.addRSVPProtocols(ifc); err != nil {
return err
}
if err := ix.addDHCPProtocols(ifc); err != nil {
return err
}
if err := ix.addNetworks(ifc); err != nil {
return err
}
}
}
return nil
}
func groupByLink(ics []*opb.InterfaceConfig) [][]*opb.InterfaceConfig {
linkToIntfs := make(map[string][]*opb.InterfaceConfig)
for _, ic := range ics {
var linkStr string
switch link := ic.GetLink().(type) {
// Add "port/" or "link/" prefix so they are sorted deterministically below.
case *opb.InterfaceConfig_Port:
linkStr = "port/" + link.Port
case *opb.InterfaceConfig_Lag:
linkStr = "link/" + link.Lag
}
linkToIntfs[linkStr] = append(linkToIntfs[linkStr], ic)
}
var links []string
for link := range linkToIntfs {
links = append(links, link)
}
sort.Strings(links) // Deterministic ordering for deterministic configs.
var icGroups [][]*opb.InterfaceConfig
for _, fp := range links {
intfs := linkToIntfs[fp]
sort.Slice(intfs, func(i, j int) bool {
return strings.Compare(intfs[i].GetName(), intfs[j].GetName()) < 0
})
icGroups = append(icGroups, intfs)
}
return icGroups
}
func importBgpRoutes(ctx context.Context, ix *ixATE, node ixconfig.IxiaCfgNode, rt *routeTables, isV6 bool) error {
rtFile := rt.ipv4
pools := "ipv4PrefixPools"
rp := "bgpIPRouteProperty"
if isV6 {
rtFile = rt.ipv6
pools = "ipv6PrefixPools"
rp = "bgpV6IPRouteProperty"
}
nextHop := "preserveFromFile"
if rt.overwriteNexthop {
nextHop = "overwriteTestersAddress"
}
nodeID, err := ix.c.NodeID(node)
if err != nil {
return err
}
importPath := fmt.Sprintf("topology/deviceGroup/networkGroup/%s/%s/operations/importbgproutes", pools, rp)
return ix.runOp(ctx, importPath, ixweb.OpArgs{
nodeID,
"replicate", // Replicate routes on each configured peer.
false, // Import all routes, not just the 'best' routes.
nextHop,
rt.format,
ix.routeTableToIxFile[rtFile],
}, nil)
}
// Uploads needed route table files to the Ixia chassis as necessary and then imports routes into the corresponding network groups.
func syncRouteTableFilesAndImport(ctx context.Context, ix *ixATE) error {
// Uploaded Ondatra route table file names take the format "ondatra_route_table_<epoch seconds>_<CRC32 hash>
const rtFilePrefix = "ondatra_route_table_"
toSync := map[string]bool{}
brps := []ixconfig.IxiaCfgNode{}
for _, intf := range ix.intfs {
for net, rt := range intf.netToRouteTables {
ng := intf.netToNetworkGroup[net]
if rt.ipv4 != "" && ix.routeTableToIxFile[rt.ipv4] == "" {
brps = append(brps, ng.Ipv4PrefixPools[0].BgpIPRouteProperty[0])
toSync[rt.ipv4] = true
}
if rt.ipv6 != "" && ix.routeTableToIxFile[rt.ipv6] == "" {
brps = append(brps, ng.Ipv6PrefixPools[0].BgpV6IPRouteProperty[0])
toSync[rt.ipv6] = true
}
}
}
if len(toSync) == 0 {
// Return early to avoid further lookups.
return nil
}
hashToFile := map[string]string{}
for f := range toSync {
b, err := os.ReadFile(f)
if err != nil {
return fmt.Errorf("could not read route table file at %s for hashing: %w", f, err)
}
hashToFile[fmt.Sprintf("%d", crc32.ChecksumIEEE(b))] = f
}
rtFiles, err := ix.c.Session().Files().List(ctx, rtFilePrefix+"*")
if err != nil {
return fmt.Errorf("could not query for files on Ixia chassis: %w", err)
}
now := time.Now()
for _, f := range rtFiles {
fdata := strings.Split(strings.TrimPrefix(f, rtFilePrefix), "_")
if len(fdata) != 2 {
return fmt.Errorf("unexpected format for Ixia route table file %s", f)
}
ftime, err := strconv.Atoi(fdata[0])
if err != nil {
return fmt.Errorf("unexpected timestamp format for Ixia route table file %s", f)
}
if time.Unix(int64(ftime), 0).Before(now.Add(-24 * 7 * time.Hour)) {
if err := ix.c.Session().Files().Delete(ctx, f); err != nil {
return fmt.Errorf("could not delete out-of-date route table file %s: %w", f, err)
}
continue
}
if hf := hashToFile[fdata[1]]; hf != "" {
delete(hashToFile, fdata[1])
ix.routeTableToIxFile[hf] = f
}
}
for h, f := range hashToFile {
b, err := os.ReadFile(f)
if err != nil {
return fmt.Errorf("could not read route table file at %s for upload: %w", f, err)
}
fn := fmt.Sprintf("%s%d_%s", rtFilePrefix, now.Unix(), h)
if err := ix.c.Session().Files().Upload(ctx, fn, b); err != nil {
return fmt.Errorf("could not upload route table file at %s to %s: %w", f, fn, err)
}
ix.routeTableToIxFile[f] = fn
}
if err := ix.c.UpdateIDs(ctx, ix.cfg, brps...); err != nil {
return fmt.Errorf("could not update IDs for importing routes: %w", err)
}
for _, intf := range ix.intfs {
for net, rt := range intf.netToRouteTables {
ng := intf.netToNetworkGroup[net]
if rt.ipv4 != "" {
if err := importBgpRoutes(ctx, ix, ng.Ipv4PrefixPools[0].BgpIPRouteProperty[0], rt, false); err != nil {
return fmt.Errorf("errors importing BGP IPv4 routes for network %s: %w", net, err)
}
}
if rt.ipv6 != "" {
if err := importBgpRoutes(ctx, ix, ng.Ipv6PrefixPools[0].BgpV6IPRouteProperty[0], rt, true); err != nil {
return fmt.Errorf("errors importing BGP IPv6 routes for network %s: %w", net, err)
}
}
}
}
return nil
}
func (ix *ixATE) updateTopology(ctx context.Context, ics []*opb.InterfaceConfig) error {
if err := ix.configureTopology(ics); err != nil {
return err
}
// Full topology updates can take some time, use a 3 minute timeout.
if err := ix.importConfig(ctx, ix.cfg, false, topoImportTimeout, "topology and protocols configuration"); err != nil {
return err
}
return syncRouteTableFilesAndImportFn(ctx, ix)
}
// PushTopology configures the IxNetwork session with the specified topology.
func (ix *ixATE) PushTopology(ctx context.Context, top *Topology) error {
if err := validateInterfaces(top.Interfaces); err != nil {
return err
}
ix.resetClientCfg()
if err := ix.addPorts(top); err != nil {
return err
}
if err := ix.importConfig(ctx, ix.cfg, true, topoImportTimeout, "port configuration"); err != nil {
return err
}
if lags := top.LAGs; len(lags) > 0 {
if err := ix.addLAGs(lags); err != nil {
return err
}
if err := ix.importConfig(ctx, ix.cfg, false, topoImportTimeout, "LAG configuration"); err != nil {
return err
}
}
// Avoid a possible race condition with repeated config imports (b/191984474).
sleepFn(45 * time.Second)
if err := ix.updateTopology(ctx, top.Interfaces); err != nil {
return err
}
ix.operState = operStateOff
return nil
}
// UpdateTopology updates IxNetwork session to the specified topology.
func (ix *ixATE) UpdateTopology(ctx context.Context, top *Topology) error {
if err := validateInterfaces(top.Interfaces); err != nil {
return err
}
if err := ix.updateTopology(ctx, top.Interfaces); err != nil {
return err
}
// Protocols/traffic are stopped after updating topology, restart as needed.
if ix.operState != operStateOff {
if err := ix.startProtocols(ctx); err != nil {
return err
}
if ix.operState == operStateTrafficOn {
if err := genTrafficFn(ctx, ix); err != nil {
return err
}
if err := startTrafficFn(ctx, ix); err != nil {
return err
}
}
}
return nil
}
type stateRsp interface {
Up() bool
}
type protocolRsp struct {
SessionStatus []string
}
func (r *protocolRsp) Up() bool {
return len(r.SessionStatus) > 0 && r.SessionStatus[0] == "up"
}
type lspRsp struct {
State []string
}
func (r *lspRsp) Up() bool {
if len(r.State) == 0 {
return false
}
for _, s := range r.State {
if s != "up" {
return false
}
}
return true
}
func checkUp(ctx context.Context, ix *ixATE, nodes []ixconfig.IxiaCfgNode, r stateRsp, retries int) ([]ixconfig.IxiaCfgNode, error) {
const retryWait = 10 * time.Second
notUp := func(nodes []ixconfig.IxiaCfgNode) ([]ixconfig.IxiaCfgNode, error) {
var notUp []ixconfig.IxiaCfgNode
for _, n := range nodes {
nodeID, err := ix.c.NodeID(n)
if err != nil {
return nil, err
}
if err := ix.c.Session().Get(ctx, nodeID, r); err != nil {
return nil, fmt.Errorf("could not fetch element at %q to check session status: %w", nodeID, err)
}
if !r.Up() {
notUp = append(notUp, n)
}
}
return notUp, nil
}
nodes, err := notUp(nodes)
for i := 0; i < retries && err == nil && len(nodes) > 0; i++ {
sleepFn(retryWait)
nodes, err = notUp(nodes)
}
return nodes, err
}
func failedNodesWithPorts(ix *ixATE, msg string, nodes []ixconfig.IxiaCfgNode, nodeToLink map[ixconfig.IxiaCfgNode]ixconfig.IxiaCfgNode) ([]string, error) {
if len(nodes) == 0 {
return nil, nil
}
var idsAndPorts []string
failedPorts := map[string]bool{}
for _, n := range nodes {
nodeID, err := ix.c.NodeID(n)
if err != nil {
return nil, err
}
ports, err := linkToPorts(ix, nodeToLink[n])
if err != nil {
return nil, fmt.Errorf("error finding ports for link on interface for node %q: %w", nodeID, err)
}
for _, p := range ports {
failedPorts[p] = true
}
idsAndPorts = append(idsAndPorts, fmt.Sprintf("%s (on %v)", nodeID, ports))
}
var failedPortsList []string
for p := range failedPorts {
failedPortsList = append(failedPortsList, p)
}
return failedPortsList, fmt.Errorf("%s: %v", msg, idsAndPorts)
}
// Waits for protocols to start, restarting any that initially fail and rechecking as necessary.
// Returns a list of ports where protocols did not start (if there are no other errors).
func validateProtocolStart(ctx context.Context, ix *ixATE) ([]string, error) {
const (
retryWait = 10 * time.Second
maxRetriesLSPs = 60
)
maxRetriesProtocols := 5
if len(ix.routeTableToIxFile) > 0 {
// Protocols may need extra time to start on large-scale route imports.
maxRetriesProtocols = 30
}
topo := struct {
ProtocolActionsInProgress []string
Status string
}{}
started := func() (bool, error, bool) {
if err := ix.c.Session().Get(ctx, "globals/topology", &topo); err != nil {
return false, fmt.Errorf("could not fetch global topology to check protocol status: %w", err), false
}
if topo.Status == "started" && len(topo.ProtocolActionsInProgress) == 0 {
return true, nil, false
}
// TODO(team): Remove IS-IS/Lag check after Ixias updated to 9.20update1
for _, intf := range ix.intfs {
// Checks for the known index out of bounds error if there is any IS-IS config on any LAG.
// Still returns 'false' as the 'started' result for the function to trigger the retry
// loop to ensure protocols start.
if strings.Contains(intf.link.XPath().String(), "lag") && len(intf.isrToNetworkGroup) > 0 {
var appErrs []struct{ Name string }
if err := ix.c.Session().Get(ctx, "globals/appErrors/error", &appErrs); err != nil {
return false, fmt.Errorf("could not fetch global errors: %w", err), false
}
for _, e := range appErrs {
if strings.Contains(e.Name, "Index was outside the bounds of the array") {
log.Warning("Ignoring protocol status error because of known 'Index was outside the bounds of the array' issue configuring IS-IS on LAGs")
return false, nil, true
}
}
}
}
return false, nil, false
}
// Wait for protocols to start.
start, err, isrAndLagErr := started()
for i := 0; i < maxRetriesProtocols && err == nil && !start; i++ {
sleepFn(retryWait)
start, err, isrAndLagErr = started()
}
if err != nil {
return nil, err
}
if !start && !isrAndLagErr {
return nil, errors.New("protocols did not start in time")
}
var protocolNodes []ixconfig.IxiaCfgNode
var ingressLSPNodes []ixconfig.IxiaCfgNode
nodeToLink := map[ixconfig.IxiaCfgNode]ixconfig.IxiaCfgNode{}
for _, intf := range ix.intfs {
nodeToLink[intf.deviceGroup.Ethernet[0]] = intf.link
protocolNodes = append(protocolNodes, intf.deviceGroup.Ethernet[0])
if intf.ipv4 != nil {
nodeToLink[intf.ipv4] = intf.link
protocolNodes = append(protocolNodes, intf.ipv4)
}
if intf.ipv6 != nil {
nodeToLink[intf.ipv6] = intf.link
protocolNodes = append(protocolNodes, intf.ipv6)
}
for _, lsps := range intf.rsvpLSPs {
if *(lsps.RsvpP2PIngressLsps.Active.SingleValue.Value) == "true" {
nodeToLink[lsps.RsvpP2PIngressLsps] = intf.link
ingressLSPNodes = append(ingressLSPNodes, lsps.RsvpP2PIngressLsps)
}
}
}
var cfgNodes []ixconfig.IxiaCfgNode
cfgNodes = append(cfgNodes, protocolNodes...)
cfgNodes = append(cfgNodes, ingressLSPNodes...)
if err := ix.c.UpdateIDs(ctx, ix.cfg, cfgNodes...); err != nil {
return nil, fmt.Errorf("could not update IDs for checking protocol sessions: %w", err)
}
protocolNodes, err = checkUp(ctx, ix, protocolNodes, &protocolRsp{}, maxRetriesProtocols)
if err != nil {
return nil, err
}
for _, n := range protocolNodes {
// Restart any still down protocols individually.
var op string
switch cn := n.(type) {
case *ixconfig.TopologyEthernet:
op = "topology/deviceGroup/ethernet/operations/restartdown"
case *ixconfig.TopologyIpv4:
op = "topology/deviceGroup/ethernet/ipv4/operations/restartdown"
case *ixconfig.TopologyIpv6:
op = "topology/deviceGroup/ethernet/ipv6/operations/restartdown"
default:
return nil, fmt.Errorf("tried to restart invalid config node type %T", cn)
}
nodeID, err := ix.c.NodeID(n)
if err != nil {
return nil, err
}
if err := ix.runOp(ctx, op, ixweb.OpArgs{[]string{nodeID}}, nil); err != nil {
return nil, fmt.Errorf("could not restart down protocol at %q", nodeID)
}
}
protocolNodes, err = checkUp(ctx, ix, protocolNodes, &protocolRsp{}, maxRetriesProtocols)
if err != nil {
return nil, err
}
if ports, err := failedNodesWithPorts(ix, "some protocol instances did not start", protocolNodes, nodeToLink); err != nil {
return ports, err
}
// Validate ingress LSP state
ingressLSPNodes, err = checkUp(ctx, ix, ingressLSPNodes, &lspRsp{}, maxRetriesLSPs)
if err != nil {
return nil, err
}
return failedNodesWithPorts(ix, "some ingress LSP instances did not start", ingressLSPNodes, nodeToLink)
}
func (ix *ixATE) checkPortsUp(ctx context.Context) error {
const upState = "connectedLinkUp"
var vports []ixconfig.IxiaCfgNode
for _, vport := range ix.ports {
vports = append(vports, vport)
}
if err := ix.c.UpdateIDs(ctx, ix.cfg, vports...); err != nil {
return err
}
for port, vport := range ix.ports {
vpid, err := ix.c.NodeID(vport)
if err != nil {
return err
}
var data struct {
ConnectionState string `json:"connectionState"`
}
if err := ix.c.Session().Get(ctx, vpid, &data); err != nil {
return err
}
if data.ConnectionState != upState {
return fmt.Errorf("port %q in state %q, not %q", port, data.ConnectionState, upState)
}
}
return nil
}
func (ix *ixATE) startProtocols(ctx context.Context) error {
if err := ix.checkPortsUp(ctx); err != nil {
return err
}
errStart := ix.runOp(ctx, "operations/startallprotocols", syncedOpArgs, nil)
if errStart != nil {
log.Warningf("First attempted startallprotocols op failed: %v", errStart)
if errStart = ix.runOp(ctx, "operations/startallprotocols", syncedOpArgs, nil); errStart != nil {
log.Warningf("Second attempted startallprotocols op failed: %v", errStart)