-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
2496 lines (2156 loc) · 84.8 KB
/
net.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 mrnes
// nets.go contains code and data structures supporting the
// simulation of traffic through the communication network.
// mrnes supports passage of discrete packets. These pass
// through the interfaces of devices (routers and switch) on the
// shortest path route between endpoints, accumulating delay through the interfaces
// and across the networks, as a function of overall traffic load (most particularly
// including the background flows)
import (
"fmt"
"github.com/iti/evt/evtm"
"github.com/iti/evt/vrtime"
"github.com/iti/rngstream"
"golang.org/x/exp/slices"
"gopkg.in/yaml.v3"
"math"
"strconv"
"strings"
)
// The mrnsbit network simulator is built around two strong assumptions that
// simplify implementation, but which may have to be addressed if mrnsbit
// is to be used when fine-grained networking details are thought to be important.
//
// The first assumption is that routing is static, that the complete route for
// a message from specified source to specified destination can be computed at
// the time the message enters the network. It happens that this implementation
// uses minimum hop count as the metric for choosing routes, but this is not so rigourously
// embedded in the design as is static routes.
//
// The second assumption is related to the reality that messages do not traverse a link or
// pass through an interface instaneously, they 'connect' across links, through networks, and through devices.
// Flows have bandwidth, and every interface, link, device, and network has its own bandwidth
// limit. From the point of view of the receiving endpt, the effective bandwidth (assuming the bandwidths
// all along the path don't change) is the minimum bandwidth among all the things on the path.
// In the path before the hop that induces the least bandwidth message may scoot through connections
// at higher bandwidth, but the progress of that connection is ultimately limited by the smallest bandwidth.
// The simplifying assumption then is that the connection of the message's bits _everywhere_ along the path
// is at that minimum bandwidth. More detail in tracking and changing bandwidths along sections of the message
// are possible, but at this point it is more complicated and time-consuming to do that than it seems to be worth
// for anticipated use-cases.
//
// intPair, intrfcIDPair, intrfcRate and floatPair are
// structs introduced to add more than basic elements to lists and maps
type intPair struct {
i, j int
}
type intrfcIDPair struct {
prevID, nextID int
rate float64
}
type intrfcRate struct {
intrfcID int
rate float64
}
type floatPair struct {
x, y float64
}
// classQueue holds information about a given
// class of packets and/or flows
type classQueue struct {
classID int
ingressLambda float64 // sum of rates of flows in this class on the ingress side
egressLambda float64 // sum of rates of flows in this class on the egress side
inQueue []*NetworkMsg // number of enqueued packets
waiting float64 // waiting time of class flow (from priority queue formula)
}
// append the given NetworkMsg to the classQueue, to await service
func (cQ *classQueue) addNetworkMsg(nm *NetworkMsg) {
cQ.inQueue = append(cQ.inQueue, nm)
}
// represent the queue state of the classQueue in a string, for traces
func (cQ *classQueue) Str() string {
rtnVec := []string{strconv.Itoa(cQ.classID), strconv.Itoa(len(cQ.inQueue))}
return strings.Join(rtnVec, " % ")
}
// ClassQueue holds multi-level priority queue structures for
// an interface
type ClassQueue struct {
ingressID2Q map[int]int // classID to index in ordered priority list
egressID2Q map[int]int // classID to index in ordered priority list
ingressQs []*classQueue // messages waiting for service on the ingress side, earlier indices mean higher priority
egressQs []*classQueue // messages waiting for service on the egress side, earlier indices mean higher priority
}
// createClassQueue is a constructor
func createClassQueue() *ClassQueue {
CQ := new(ClassQueue)
CQ.ingressID2Q = make(map[int]int)
CQ.egressID2Q = make(map[int]int)
CQ.ingressQs = []*classQueue{}
CQ.egressQs = []*classQueue{}
return CQ
}
// Str represents the state of the ClassQueue queues as a string, for traces
func (CQ *ClassQueue) Str() string {
rtn := []string{}
for idx := 0; idx < len(CQ.ingressQs); idx++ {
rtn = append(rtn, "ingress_"+CQ.ingressQs[idx].Str())
}
for idx := 0; idx < len(CQ.egressQs); idx++ {
rtn = append(rtn, "egress_"+CQ.egressQs[idx].Str())
}
return strings.Join(rtn, ",")
}
// append a classID to the ClassQueue if not already present
// maintain decreasing order of classID (higher classID is higher priority)
// in the insertion
func (CQ *ClassQueue) addClassID(classID int, ingress bool) {
var Qs []*classQueue
var id2Q map[int]int
// do processing on queues and id2A
if ingress {
Qs = CQ.ingressQs
id2Q = CQ.ingressID2Q
} else {
Qs = CQ.egressQs
id2Q = CQ.egressID2Q
}
// if we have it already we're done
_, present := id2Q[classID]
if present {
return
}
// starting with highest priority, find first instance of lower priority.
// That's the insertion point
here := 0
for idx := 0; idx < len(Qs); idx++ {
thisClassID := Qs[idx].classID
if thisClassID < classID {
break
}
here += 1
}
// create and initialize the new classQueue structure
newcq := new(classQueue)
newcq.classID = classID
newcq.inQueue = []*NetworkMsg{}
// create newQs to be the modified slice
newQs := Qs[:here]
newQs = append(newQs, newcq)
Qs = append(newQs, Qs[here:]...)
// redo the id2Q map after the insert
id2Q = make(map[int]int)
for idx := 0; idx < len(Qs); idx++ {
cq := Qs[idx]
id2Q[cq.classID] = idx
}
// save the modified data structures
if ingress {
CQ.ingressQs = Qs
CQ.ingressID2Q = id2Q
} else {
CQ.egressQs = Qs
CQ.egressID2Q = id2Q
}
}
// transferBW computes how long it taks a message with the given msgLen to traverse the interface, once in motion
func (CQ *ClassQueue) transferBW(classID int, msgLen float64, intrfc *intrfcStruct, ingress bool) float64 {
bndwdth := intrfc.useableBW()
// subtract off bandwidth of higher priority flows
var qIdx int
if ingress {
qIdx = CQ.ingressID2Q[classID]
} else {
qIdx = CQ.egressID2Q[classID]
}
// subtract off bandwidth of all classIDs with higher priority
for idx := 0; idx < qIdx; idx++ {
if ingress {
bndwdth -= CQ.ingressQs[idx].ingressLambda
} else {
bndwdth -= CQ.egressQs[idx].egressLambda
}
}
return bndwdth
}
// addNetworkMsg appends the network message argument to the correct
// inQueue
func (CQ *ClassQueue) addNetworkMsg(nm *NetworkMsg, ingress bool) {
classID := nm.ClassID
if ingress {
CQ.ingressQs[CQ.ingressID2Q[classID]].inQueue = append(CQ.ingressQs[CQ.ingressID2Q[classID]].inQueue, nm)
} else {
CQ.egressQs[CQ.egressID2Q[classID]].inQueue = append(CQ.egressQs[CQ.egressID2Q[classID]].inQueue, nm)
}
}
// nxtNetworkMsg is called to extract first message with highest priority classID
// from its inQueue and compute its delay through the interface
func (CQ *ClassQueue) nxtNetworkMsg(intrfc *intrfcStruct, ingress bool) *NetworkMsg {
// find the highest priority message to move
var nm *NetworkMsg
var Qs []*classQueue
if ingress {
Qs = CQ.ingressQs
} else {
Qs = CQ.egressQs
}
// look for the highest priority queue that is not empty
for idx := 0; idx < len(Qs); idx++ {
cg := Qs[idx]
if len(cg.inQueue) > 0 {
// found it. Extract it, modify its queue
nm, cg.inQueue = cg.inQueue[0], cg.inQueue[1:]
break
}
}
return nm
}
// getClassQueue returns the classQueue associated with the given classID
func (CQ *ClassQueue) getClassQueue(classID int, ingress bool) *classQueue {
if ingress {
_, present := CQ.ingressID2Q[classID]
if !present {
panic(fmt.Errorf("classID %d not found in ClassQueue", classID))
}
return CQ.ingressQs[CQ.ingressID2Q[classID]]
} else {
_, present := CQ.egressID2Q[classID]
if !present {
panic(fmt.Errorf("classID %d not found in ClassQueue", classID))
}
return CQ.egressQs[CQ.egressID2Q[classID]]
}
}
// putClassQueue replaces the classQueue element
func (CQ *ClassQueue) putClassQueue(cQ *classQueue, ingress bool) {
if ingress {
_, present := CQ.ingressID2Q[cQ.classID]
if !present {
panic(fmt.Errorf("classID %d not found in ClassQueue", cQ.classID))
}
CQ.ingressQs[CQ.ingressID2Q[cQ.classID]] = cQ
} else {
_, present := CQ.egressID2Q[cQ.classID]
if !present {
panic(fmt.Errorf("classID %d not found in ClassQueue", cQ.classID))
}
CQ.egressQs[CQ.egressID2Q[cQ.classID]] = cQ
}
}
// NetworkMsgType give enumeration for message types that may be given to the network
// to carry. packet is a discrete packet, handled differently from flows.
// srtFlow tags a message that introduces a new flow, endFlow tags one that terminates it,
// and chgFlow tags a message that alters the flow rate on a given flow.
type NetworkMsgType int
const (
PacketType NetworkMsgType = iota
FlowType
)
// FlowAction describes the reason for the flow message, that it is starting, ending, or changing the request rate
type FlowAction int
const (
None FlowAction = iota
Srt
Chg
End
)
// nmtToStr is a translation table for creating strings from more complex
// data types
var nmtToStr map[NetworkMsgType]string = map[NetworkMsgType]string{PacketType: "packet",
FlowType: "flow"}
// routeStepIntrfcs maps a pair of device IDs to a pair of interface IDs
// that connect them
var routeStepIntrfcs map[intPair]intPair
// getRouteStepIntrfcs looks up the identity of the interfaces involved in connecting
// the named source and the named destination. These were previously built into a table
func getRouteStepIntrfcs(srcID, dstID int) (int, int) {
ip := intPair{i: srcID, j: dstID}
intrfcs, present := routeStepIntrfcs[ip]
if !present {
intrfcs, present = routeStepIntrfcs[intPair{j: srcID, i: dstID}]
if !present {
panic(fmt.Errorf("no step between %s and %s", TopoDevByID[srcID].DevName(), TopoDevByID[dstID].DevName()))
}
return intrfcs.j, intrfcs.i
}
return intrfcs.i, intrfcs.j
}
// NetworkPortal implements the pces interface used to pass
// traffic between the application layer and the network sim
type NetworkPortal struct {
QkNetSim bool
ReturnTo map[int]*rtnRecord // indexed by connectID
LossRtn map[int]*rtnRecord // indexed by connectID
ReportRtnSrc map[int]*rtnRecord // indexed by connectID
ReportRtnDst map[int]*rtnRecord // indexed by connectID
RequestRate map[int]float64 // indexed by flowID to get requested arrival rate
AcceptedRate map[int]float64 // indexed by flowID to get accepted arrival rate
Class map[int]int // indexed by flowID to get priority class
Elastic map[int]bool // indexed by flowID to record whether flow is elastic
Connections map[int]int // indexed by connectID to get flowID
InvConnection map[int]int // indexed by flowID to get connectID
LatencyConsts map[int]float64 // indexex by flowID to get latency constants on flow's route
}
// ActivePortal remembers the most recent NetworkPortal created
// (there should be only one call to CreateNetworkPortal...)
var ActivePortal *NetworkPortal
type ActiveRec struct {
Number int
Rate float64
}
// CreateNetworkPortal is a constructor, passed a flag indicating which
// of two network simulation modes to use, passes a flag indicating whether
// packets should be passed whole, and writes the NetworkPortal pointer into a global variable
func CreateNetworkPortal() *NetworkPortal {
if ActivePortal != nil {
return ActivePortal
}
np := new(NetworkPortal)
// set default settings
np.QkNetSim = false
np.ReturnTo = make(map[int]*rtnRecord)
np.LossRtn = make(map[int]*rtnRecord)
np.ReportRtnSrc = make(map[int]*rtnRecord)
np.ReportRtnDst = make(map[int]*rtnRecord)
np.RequestRate = make(map[int]float64)
np.AcceptedRate = make(map[int]float64)
np.Class = make(map[int]int)
np.Elastic = make(map[int]bool)
np.Connections = make(map[int]int)
np.InvConnection = make(map[int]int)
np.LatencyConsts = make(map[int]float64)
// save the mrnes memory space version
ActivePortal = np
connections = 0
return np
}
// SetQkNetSim saves the argument as indicating whether latencies
// should be computed as 'Placed', meaning constant, given the state of the network at the time of
// computation
func (np *NetworkPortal) SetQkNetSim(quick bool) {
np.QkNetSim = quick
}
// ClearRmFlow removes entries from maps indexed
// by flowID and associated connectID, to help clean up space
func (np *NetworkPortal) ClearRmFlow(flowID int) {
connectID := np.InvConnection[flowID]
delete(np.ReturnTo, connectID)
delete(np.LossRtn, connectID)
delete(np.ReportRtnSrc, connectID)
delete(np.ReportRtnDst, connectID)
delete(np.Connections, connectID)
delete(np.RequestRate, flowID)
delete(np.AcceptedRate, flowID)
delete(np.Class, flowID)
delete(np.LatencyConsts, flowID)
}
// EndptDevModel helps NetworkPortal implement the pces NetworkPortal interface,
// returning the CPU model associated with a named endpt. Present because the
// application layer does not otherwise have visibility into the network topology
func (np *NetworkPortal) EndptDevModel(devName string, accelName string) string {
endpt, present := EndptDevByName[devName]
if !present {
return ""
}
if len(accelName) == 0 {
return endpt.EndptModel
}
accelModel, present := endpt.EndptAccelModel[accelName]
if !present {
return ""
}
return accelModel
}
// Depart is called to return an application message being carried through
// the network back to the application layer
func (np *NetworkPortal) Depart(evtMgr *evtm.EventManager, nm NetworkMsg) {
connectID := nm.ConnectID
// may not require knowledge that delivery made it
rtnRec, present := np.ReturnTo[connectID]
if !present || rtnRec == nil || rtnRec.rtnCxt == nil {
return
}
rtnRec.prArrvl *= nm.PrArrvl
rtnRec.pckts -= 1
// if rtnRec.pckts is not zero there are more packets coming associated
// with connectID and so we exit
if rtnRec.pckts > 0 {
return
}
prArrvl := rtnRec.prArrvl
// so we can return now
rtnMsg := new(RtnMsgStruct)
rtnMsg.Latency = evtMgr.CurrentSeconds() - nm.StartTime
if nm.carriesPckt() {
rtnMsg.Rate = nm.PcktRate
rtnMsg.PrLoss = (1.0 - prArrvl)
} else {
rtnMsg.Rate = np.AcceptedRate[nm.FlowID]
}
rtnMsg.Msg = nm.Msg
rtnCxt := rtnRec.rtnCxt
rtnFunc := rtnRec.rtnFunc
// schedule the re-integration into the application simulator
evtMgr.Schedule(rtnCxt, rtnMsg, rtnFunc, vrtime.SecondsToTime(0.0))
delete(np.ReturnTo, connectID)
delete(np.LossRtn, connectID)
delete(np.ReportRtnSrc, connectID)
delete(np.ReportRtnDst, connectID)
}
// requestedLoadFracVec computes the relative requested rate for a flow
// among a list of flows. Used to rescale accepted rates
func (np *NetworkPortal) requestedLoadFracVec(vec []int) []float64 {
rtn := make([]float64, len(vec))
var agg float64
// gather up the rates in an array and compute the normalizing sum
for idx, flowID := range vec {
rate := np.RequestRate[flowID]
agg += rate
rtn[idx] = rate
}
// normalize
for idx := range vec {
rtn[idx] /= agg
}
return rtn
}
// RtnMsgStruct formats the report passed from the network to the
// application calling it
type RtnMsgStruct struct {
Latency float64 // span of time (secs) from srcDev to dstDev
Rate float64 // for a flow, its accept rate. For a packet, the minimum non-flow bandwidth at a
// network or interface it encountered
PrLoss float64 // estimated probability of having been dropped somewhere in transit
Msg any // msg introduced at EnterNetwork
}
// Arrive is called at the point an application message is received by the network
// and a new connectID is created (and returned) to track it. It saves information needed to re-integrate
// the application message into the application layer when the message arrives at its destination
func (np *NetworkPortal) Arrive(rtns RtnDescs, frames int) int {
// record how to transition from network to upper layer, through event handler at upper layer
rtnRec := &rtnRecord{rtnCxt: rtns.Rtn.Cxt, rtnFunc: rtns.Rtn.EvtHdlr, prArrvl: 1.0, pckts: frames}
connectID := nxtConnectID()
np.ReturnTo[connectID] = rtnRec
// if requested, record how to notify source end of connection at upper layer through connection
if rtns.Src != nil {
rtnRec = new(rtnRecord)
*rtnRec = rtnRecord{rtnCxt: rtns.Src.Cxt, rtnFunc: rtns.Src.EvtHdlr, prArrvl: 1.0, pckts: 1}
np.ReportRtnSrc[connectID] = rtnRec
}
// if requested, record how to notify destination end of connection at upper layer through event handler
if rtns.Dst != nil {
rtnRec = new(rtnRecord)
*rtnRec = rtnRecord{rtnCxt: rtns.Dst.Cxt, rtnFunc: rtns.Dst.EvtHdlr, prArrvl: 1.0, pckts: 1}
np.ReportRtnDst[connectID] = rtnRec
}
// if requested, record how to notify occurance of loss at upper layer, through event handler
if rtns.Loss != nil {
rtnRec = new(rtnRecord)
*rtnRec = rtnRecord{rtnCxt: rtns.Loss.Cxt, rtnFunc: rtns.Loss.EvtHdlr, prArrvl: 1.0, pckts: 1}
np.LossRtn[connectID] = rtnRec
}
return connectID
}
// lostConnection is called when a connection is lost by the network layer.
// The response is to remove the connection from the portal's table, and
// call the event handler passed in to deal with lost connections
func (np *NetworkPortal) lostConnection(evtMgr *evtm.EventManager, nm *NetworkMsg, connectID int) {
_, present := np.ReturnTo[connectID]
if !present {
return
}
_, present = np.LossRtn[connectID]
if !present {
return
}
lossRec := np.LossRtn[connectID]
lossCxt := lossRec.rtnCxt
lossFunc := lossRec.rtnFunc
// schedule the re-integration into the application simulator
evtMgr.Schedule(lossCxt, nm.Msg, lossFunc, vrtime.SecondsToTime(0.0))
}
// DevCode is the base type for an enumerated type of network devices
type DevCode int
const (
EndptCode DevCode = iota
SwitchCode
RouterCode
UnknownCode
)
// DevCodeFromStr returns the devCode corresponding to an string name for it
func DevCodeFromStr(code string) DevCode {
switch code {
case "Endpt", "endpt":
return EndptCode
case "Switch", "switch":
return SwitchCode
case "Router", "router", "rtr":
return RouterCode
default:
return UnknownCode
}
}
// DevCodeToStr returns a string corresponding to an input devCode for it
func DevCodeToStr(code DevCode) string {
switch code {
case EndptCode:
return "Endpt"
case SwitchCode:
return "Switch"
case RouterCode:
return "Router"
case UnknownCode:
return "Unknown"
}
return "Unknown"
}
// NetworkScale is the base type for an enumerated type of network type descriptions
type NetworkScale int
const (
LAN NetworkScale = iota
WAN
T3
T2
T1
GeneralNet
)
// NetScaleFromStr returns the networkScale corresponding to an string name for it
func NetScaleFromStr(netScale string) NetworkScale {
switch netScale {
case "LAN":
return LAN
case "WAN":
return WAN
case "T3":
return T3
case "T2":
return T2
case "T1":
return T1
default:
return GeneralNet
}
}
// NetScaleToStr returns a string name that corresponds to an input networkScale
func NetScaleToStr(ntype NetworkScale) string {
switch ntype {
case LAN:
return "LAN"
case WAN:
return "WAN"
case T3:
return "T3"
case T2:
return "T2"
case T1:
return "T1"
case GeneralNet:
return "GeneralNet"
default:
return "GeneralNet"
}
}
// NetworkMedia is the base type for an enumerated type of comm network media
type NetworkMedia int
const (
Wired NetworkMedia = iota
Wireless
UnknownMedia
)
// NetMediaFromStr returns the networkMedia type corresponding to the input string name
func NetMediaFromStr(media string) NetworkMedia {
switch media {
case "Wired", "wired":
return Wired
case "wireless", "Wireless":
return Wireless
default:
return UnknownMedia
}
}
// every new network connection is given a unique connectID upon arrival
var connections int
func nxtConnectID() int {
connections += 1
return connections
}
type DFS map[int]intrfcIDPair
// TopoDev interface specifies the functionality different device types provide
type TopoDev interface {
DevName() string // every device has a unique name
DevID() int // every device has a unique integer id
DevType() DevCode // every device is one of the devCode types
DevIntrfcs() []*intrfcStruct // we can get from devices a list of the interfaces they endpt, if any
DevDelay(any, int) float64 // every device can be be queried for the delay it introduces for an operation
DevState() any // every device as a structure of state that can be accessed
DevIsSimple() bool // switches or routers can be 'simple'
DevRng() *rngstream.RngStream // every device has its own RNG stream
DevAddActive(*NetworkMsg) // add the connectID argument to the device's list of active connections
DevRmActive(int) // remove the connectID argument to the device's list of active connections
DevForward() DFS // index by FlowID, yields map of ingress intrfc ID to egress intrfc ID
LogNetEvent(vrtime.Time, *NetworkMsg, string)
}
// paramObj interface is satisfied by every network object that
// can be configured at run-time with performance parameters. These
// are intrfcStruct, networkStruct, switchDev, endptDev, routerDev
type paramObj interface {
matchParam(string, string) bool
setParam(string, valueStruct)
paramObjName() string
LogNetEvent(vrtime.Time, *NetworkMsg, string)
}
// The intrfcStruct holds information about a network interface embedded in a device
type intrfcStruct struct {
Name string // unique name, probably generated automatically
Groups []string // list of groups this interface may belong to
Number int // unique integer id, probably generated automatically
DevType DevCode // device code of the device holding the interface
Media NetworkMedia // media of the network the interface interacts with
Device TopoDev // pointer to the device holding the interface
PrmDev paramObj // pointer to the device holding the interface as a paramObj
Cable *intrfcStruct // For a wired interface, points to the "other" interface in the connection
Carry []*intrfcStruct // points to the "other" interface in a connection
Wireless []*intrfcStruct // For a wired interface, points to the "other" interface in the connection
Faces *networkStruct // pointer to the network the interface interacts with
State *intrfcState // pointer to the interface's block of state information
}
// The intrfcState holds parameters descriptive of the interface's capabilities
type intrfcState struct {
Bndwdth float64 // maximum bandwidth (in Mbytes/sec)
BckgrndBW float64 // deep background load consumes bandwidth
BufferSize float64 // buffer capacity (in Mbytes)
Latency float64 // time the leading bit takes to traverse the wire out of the interface
Delay float64 // time the leading bit takes to traverse the interface
IngressTransit bool
EgressTransit bool
Simple bool // use the pass-through timing model
MTU int // maximum packet size (bytes)
Trace bool // switch for calling add trace
Drop bool // whether to permit packet drops
ToIngress map[int]float64 // sum of flow rates into ingress side of device
ThruIngress map[int]float64 // sum of flow rates out of ingress side of device
ToEgress map[int]float64 // sum of flow rates into egress side of device
ThruEgress map[int]float64 // sum of flow rates out of egress side device
PcktClass float64 // fraction of bandwidth reserved for packets
IngressLambda float64 // sum of rates of flows approach interface from ingress side.
EgressLambda float64
RsrvdFrac float64 // fraction of bandwidth reserved for non-flow traffic
end2endBW float64 // scratch location
priQueue *ClassQueue
}
// useableBW returns the interface bandwidth after background load is removed
func (intrfc *intrfcStruct) useableBW() float64 {
return intrfc.State.Bndwdth - intrfc.State.BckgrndBW
}
// createIntrfcState is a constructor, assumes defaults on unspecified attributes
func createIntrfcState() *intrfcState {
iss := new(intrfcState)
iss.Delay = 1e+6 // in seconds! Set this way so that if not initialized we'll notice
iss.Latency = 1e+6
iss.MTU = 1500 // in bytes Set for Ethernet2 MTU, should change if wireless
iss.ToIngress = make(map[int]float64)
iss.ThruIngress = make(map[int]float64)
iss.ToEgress = make(map[int]float64)
iss.ThruEgress = make(map[int]float64)
iss.EgressLambda = 0.0
iss.IngressLambda = 0.0
iss.RsrvdFrac = 0.0
iss.priQueue = createClassQueue()
iss.end2endBW = iss.Bndwdth-iss.BckgrndBW
return iss
}
// computeFlowWaits estimates the time a flow arrival in classID is in the system,
// for either an ingress or egress interface. Called when an accepted flow rate changes
// Formula for class k waiting time (of flows) is
// k=1 is highest priority
// W_k : mean waiting time of class-k msgs
// S_k : mean service time of class-k msg
// lambda_k : arrival rate class k
// rho_k : load of class-k, rho_k = lambda_k*S_k
//
// R : mean residual of server on arrival : (server util)*D/2
//
// W_k = \frac{R}/((1- \sum_{j=1}^{k-1} rho_j)*(1-\sum_{j=1}^{k} \rho_j))
//
// Note that S_k = D for all k, and that R = (D/2)*\sum_{j=1}^N \rho_j
//
// When a packet arrives we include the waiting time for all packets with equal or higher priority, so
// the waiting time for it is approximated by
//
// W = W_k + \sum{j=1}^k Q_j
//
// where Q_j is the number of packets in class j waiting for service.
//
//
// ComputeFlowWaits computes a model-based estimate of the waiting time
// due to higher priority flows
func (intrfc *intrfcStruct) ComputeFlowWaits(D float64, ingress bool) {
CQ := intrfc.State.priQueue
var Qs []*classQueue
if ingress {
Qs = CQ.ingressQs
} else {
Qs = CQ.egressQs
}
rho := make([]float64, len(Qs))
rhoSum := make([]float64, len(Qs))
var allRho float64
for idx := 0; idx < len(Qs); idx++ {
cg := Qs[idx]
if ingress {
rho[idx] = D * cg.ingressLambda
} else {
rho[idx] = D * cg.egressLambda
}
allRho += rho[idx]
if idx == 0 {
rhoSum[idx] = rho[idx]
} else {
rhoSum[idx] = rho[idx] + rhoSum[idx-1]
}
}
rbar := allRho * D / 2.0
for idx := 0; idx < len(Qs); idx++ {
cg := Qs[idx]
cg.waiting = rbar / ((1 - rhoSum[idx-1]) * (1 - rhoSum[idx]))
}
}
// createIntrfcStruct is a constructor, building an intrfcStruct
// from a desc description of the interface
func createIntrfcStruct(intrfc *IntrfcDesc) *intrfcStruct {
is := new(intrfcStruct)
is.Groups = intrfc.Groups
// name comes from desc description
is.Name = intrfc.Name
// unique id is locally generated
is.Number = nxtID()
// desc representation codes the device type as a string
switch intrfc.DevType {
case "Endpt":
is.DevType = EndptCode
case "Router":
is.DevType = RouterCode
case "Switch":
is.DevType = SwitchCode
}
// The desc description gives the name of the device endpting the interface.
// We can use this to look up the locally constructed representation of the device
// and save a pointer to it
is.Device = TopoDevByName[intrfc.Device]
is.PrmDev = paramObjByName[intrfc.Device]
// desc representation codes the media type as a string
switch intrfc.MediaType {
case "wired", "Wired":
is.Media = Wired
case "wireless", "Wireless":
is.Media = Wireless
default:
is.Media = UnknownMedia
}
is.Wireless = make([]*intrfcStruct, 0)
is.Carry = make([]*intrfcStruct, 0)
is.State = createIntrfcState()
return is
}
// non-preemptive priority
// k=1 is highest priority
// W_k : mean waiting time of class-k msgs
// S_k : mean service time of class-k msg
// lambda_k : arrival rate class k
// rho_k : load of class-k, rho_k = lambda_k*S_k
// R : mean residual of server on arrival : (server util)*D/2
//
// W_k = R/((1-rho_{1}-rho_{2}- ... -rho_{k-1})*(1-rho_1-rho_2- ... -rho_k))
//
// Mean time in system of class-k msg is T_k = W_k+S_k
//
// for our purposes we will use k=0 for least class, and use the formula
// W_0 = R/((1-rho_{1}-rho_{2}- ... -rho_{k-1})*(1-rho_1-rho_2- ... -rho_{k-1}-rho_0))
// ShortIntrfc stores information we serialize for storage in a trace
type ShortIntrfc struct {
DevName string
Faces string
ToIngress float64
ThruIngress float64
ToEgress float64
ThruEgress float64
FlowID int
NetMsgType NetworkMsgType
Rate float64
PrArrvl float64
Time float64
}
// Serialize turns a ShortIntrfc into a string, in yaml format
func (sis *ShortIntrfc) Serialize() string {
var bytes []byte
var merr error
bytes, merr = yaml.Marshal(*sis)
if merr != nil {
panic(merr)
}
return string(bytes[:])
}
// addTrace gathers information about an interface and message
// passing though it, and prints it out
func (intrfc *intrfcStruct) addTrace(label string, nm *NetworkMsg, t float64) {
if true || !intrfc.State.Trace {
return
}
si := new(ShortIntrfc)
si.DevName = intrfc.Device.DevName()
si.Faces = intrfc.Faces.Name
flwID := nm.FlowID
si.FlowID = flwID
si.ToIngress = intrfc.State.ToIngress[flwID]
si.ThruIngress = intrfc.State.ThruIngress[flwID]
si.ToEgress = intrfc.State.ToEgress[flwID]
si.ThruEgress = intrfc.State.ThruEgress[flwID]
si.NetMsgType = nm.NetMsgType
si.PrArrvl = nm.PrArrvl
si.Time = t
siStr := si.Serialize()
siStr = strings.Replace(siStr, "\n", " ", -1)
fmt.Println(label, siStr)
}
// matchParam is used to determine whether a run-time parameter description
// should be applied to the interface. Its definition here helps intrfcStruct satisfy
// paramObj interface. To apply or not to apply depends in part on whether the
// attribute given matchParam as input matches what the interface has. The
// interface attributes that can be tested are the device type of device that endpts it, and the
// media type of the network it interacts with
func (intrfc *intrfcStruct) matchParam(attrbName, attrbValue string) bool {
switch attrbName {
case "name":
return intrfc.Name == attrbValue
case "group":
return slices.Contains(intrfc.Groups, attrbValue)
case "media":
return NetMediaFromStr(attrbValue) == intrfc.Media
case "devtype":
return DevCodeToStr(intrfc.Device.DevType()) == attrbValue
case "devname":
return intrfc.Device.DevName() == attrbValue
}
// an error really, as we should match only the names given in the switch statement above
return false
}
// setParam assigns the parameter named in input with the value given in the input.
// N.B. the valueStruct has fields for integer, float, and string values. Pick the appropriate one.
// setParam's definition here helps intrfcStruct satisfy the paramObj interface.
func (intrfc *intrfcStruct) setParam(paramType string, value valueStruct) {
switch paramType {
// latency, delay, and bandwidth are floats
case "latency":
// units of delay are seconds
intrfc.State.Latency = value.floatValue
case "delay":
// units of delay are seconds
intrfc.State.Delay = value.floatValue
case "bandwidth":
// units of bandwidth are Mbits/sec
intrfc.State.Bndwdth = value.floatValue
case "bckgrndBW":
// units of bandwidth consumed by background traffic (not flows)
intrfc.State.BckgrndBW = value.floatValue
case "buffer":
// units of buffer are Mbytes
intrfc.State.BufferSize = value.floatValue
case "MTU":
// number of bytes in maximally sized packet
intrfc.State.MTU = value.intValue
case "trace":
intrfc.State.Trace = value.boolValue
case "drop":
intrfc.State.Drop = value.boolValue
case "rsrvd":
intrfc.State.RsrvdFrac = value.floatValue
}
}
// LogNetEvent creates and logs a network event from a message passing
// through this interface
func (intrfc *intrfcStruct) LogNetEvent(time vrtime.Time, nm *NetworkMsg, op string) {
if !intrfc.State.Trace {
return
}
AddNetTrace(devTraceMgr, time, nm, intrfc.Number, op)
}
// paramObjName helps intrfcStruct satisfy paramObj interface, returns interface name