forked from sonic-net/sonic-linkmgrd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkProber.cpp
More file actions
824 lines (730 loc) · 24.9 KB
/
LinkProber.cpp
File metadata and controls
824 lines (730 loc) · 24.9 KB
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
/*
* Copyright 2021 (c) Microsoft Corporation.
*
* 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
*
* http://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.
*/
/*
* LinkProber.cpp
*
* Created on: Oct 4, 2020
* Author: tamer
*/
#include <netpacket/packet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <malloc.h>
#include <boost/bind/bind.hpp>
#include "common/MuxLogger.h"
#include "LinkProber.h"
#include "common/MuxException.h"
namespace link_prober
{
//
// Berkeley Packet Filter program that captures incoming ICMP traffic
//
SockFilter LinkProber::mIcmpFilter[] = {
[0] = {.code = 0x28, .jt = 0, .jf = 0, .k = 0x0000000c},
[1] = {.code = 0x15, .jt = 0, .jf = 10, .k = 0x00000800},
[2] = {.code = 0x20, .jt = 0, .jf = 0, .k = 0x0000001a},
[3] = {.code = 0x15, .jt = 0, .jf = 8, .k = 0x00000000},
[4] = {.code = 0x30, .jt = 0, .jf = 0, .k = 0x00000017},
[5] = {.code = 0x15, .jt = 0, .jf = 6, .k = 0x00000001},
[6] = {.code = 0x28, .jt = 0, .jf = 0, .k = 0x00000014},
[7] = {.code = 0x45, .jt = 4, .jf = 0, .k = 0x00001fff},
[8] = {.code = 0xb1, .jt = 0, .jf = 0, .k = 0x0000000e},
[9] = {.code = 0x50, .jt = 0, .jf = 0, .k = 0x0000000e},
[10] = {.code = 0x15, .jt = 0, .jf = 1, .k = 0x00000000},
[11] = {.code = 0x6, .jt = 0, .jf = 0, .k = 0x00040000},
[12] = {.code = 0x6, .jt = 0, .jf = 0, .k = 0x00000000},
};
//
// ---> LinkProber(
// common::MuxPortConfig &muxPortConfig,
// boost::asio::io_service &ioService,
// LinkProberStateMachine &linkProberStateMachine
// );
//
// class constructor
//
LinkProber::LinkProber(
common::MuxPortConfig &muxPortConfig,
boost::asio::io_service &ioService,
LinkProberStateMachine &linkProberStateMachine
) :
mMuxPortConfig(muxPortConfig),
mIoService(ioService),
mLinkProberStateMachine(linkProberStateMachine),
mStrand(mIoService),
mDeadlineTimer(mIoService),
mSuspendTimer(mIoService),
mSwitchoverTimer(mIoService),
mStream(mIoService)
{
try {
mSockFilterPtr = std::shared_ptr<SockFilter> (
new SockFilter[sizeof(mIcmpFilter) / sizeof(*mIcmpFilter)],
std::default_delete<SockFilter[]>()
);
memcpy(mSockFilterPtr.get(), mIcmpFilter, sizeof(mIcmpFilter));
mSockFilterProg.len = sizeof(mIcmpFilter) / sizeof(*mIcmpFilter);
mSockFilterProg.filter = mSockFilterPtr.get();
}
catch (const std::bad_alloc& ex) {
std::ostringstream errMsg;
errMsg << "Failed allocate memory. Exception details: " << ex.what();
throw MUX_ERROR(BadAlloc, errMsg.str());
}
}
//
// ---> initialize();
//
// initialize link prober sockets and builds ICMP packet
//
void LinkProber::initialize()
{
mSocket = socket(AF_PACKET, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_ICMP);
if (mSocket < 0) {
std::ostringstream errMsg;
errMsg << "Failed to open socket with '" << strerror(errno) << "'"
<< std::endl;
throw MUX_ERROR(SocketError, errMsg.str());
}
SockAddrLinkLayer addr;
memset(&addr, 0, sizeof(addr));
addr.sll_ifindex = if_nametoindex(mMuxPortConfig.getPortName().c_str());
addr.sll_family = AF_PACKET;
addr.sll_protocol = htons(ETH_P_ALL);
if (bind(mSocket, (struct sockaddr *) &addr, sizeof(addr))) {
std::ostringstream errMsg;
errMsg << "Failed to bind to interface '" << mMuxPortConfig.getPortName() << "' with '"
<< strerror(errno) << "'" << std::endl;
throw MUX_ERROR(SocketError, errMsg.str());
}
mSockFilterPtr.get()[3].k = mMuxPortConfig.getBladeIpv4Address().to_v4().to_uint();
if (setsockopt(mSocket, SOL_SOCKET, SO_ATTACH_FILTER, &mSockFilterProg, sizeof(mSockFilterProg)) != 0) {
std::ostringstream errMsg;
errMsg << "Failed to attach filter with '" << strerror(errno) << "'"
<< std::endl;
throw MUX_ERROR(SocketError, errMsg.str());
}
mStream.assign(mSocket);
initializeSendBuffer();
startInitRecv();
}
//
// ---> startProbing();
//
// start sending ICMP ECHOREQUEST packets
//
void LinkProber::startProbing()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mStream.cancel();
sendHeartbeat();
startRecv();
startTimer();
}
//
// ---> suspendTxProbes(uint32_t suspendTime_msec);
//
// suspend sending ICMP ECHOREQUEST packets
//
void LinkProber::suspendTxProbes(uint32_t suspendTime_msec)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mSuspendTimer.expires_from_now(boost::posix_time::milliseconds(suspendTime_msec));
mSuspendTimer.async_wait(mStrand.wrap(boost::bind(
&LinkProber::handleSuspendTimeout,
this,
boost::asio::placeholders::error
)));
mSuspendTx = true;
}
//
// ---> resumeTxProbes();
//
// resume sending ICMP ECHOREQUEST packets
//
void LinkProber::resumeTxProbes()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mSuspendTimer.cancel();
}
//
// ---> updateEthernetFrame();
//
// update Ethernet frame of Tx Buffer
//
void LinkProber::updateEthernetFrame()
{
boost::asio::io_service &ioService = mStrand.context();
ioService.post(mStrand.wrap(boost::bind(&LinkProber::handleUpdateEthernetFrame, this)));
}
//
// ---> probePeerTor();
//
// send an early HB to peer ToR
//
void LinkProber::probePeerTor()
{
boost::asio::io_service &ioService = mStrand.context();
ioService.post(mStrand.wrap(boost::bind(&LinkProber::sendHeartbeat, this)));
}
//
// ---> sendPeerSwitchCommand();
//
// send send peer switch command
//
void LinkProber::sendPeerSwitchCommand()
{
boost::asio::io_service &ioService = mStrand.context();
ioService.post(mStrand.wrap(boost::bind(&LinkProber::handleSendSwitchCommand, this)));
}
//
// ---> handleUpdateEthernetFrame();
//
// update Ethernet frame of Tx Buffer
//
void LinkProber::handleUpdateEthernetFrame()
{
initializeSendBuffer();
}
//
// ---> handleSendSwitchCommand();
//
// send switch command to peer ToR
//
void LinkProber::handleSendSwitchCommand()
{
resetTxBufferTlv();
appendTlvCommand(Command::COMMAND_SWITCH_ACTIVE);
appendTlvSentinel();
size_t totalPayloadSize = mTxPacketSize - mPacketHeaderSize;
iphdr *ipHeader = reinterpret_cast<iphdr *> (mTxBuffer.data() + sizeof(ether_header));
icmphdr *icmpHeader = reinterpret_cast<icmphdr *> (mTxBuffer.data() + sizeof(ether_header) + sizeof(iphdr));
computeChecksum(icmpHeader, sizeof(icmphdr) + totalPayloadSize);
ipHeader->tot_len = htons(sizeof(iphdr) + sizeof(icmphdr) + totalPayloadSize);
sendHeartbeat();
resetTxBufferTlv();
appendTlvSentinel();
totalPayloadSize = mTxPacketSize - mPacketHeaderSize;
computeChecksum(icmpHeader, sizeof(icmphdr) + totalPayloadSize);
ipHeader->tot_len = htons(sizeof(iphdr) + sizeof(icmphdr) + totalPayloadSize);
// inform the composite state machine about commend send completion
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
static_cast<void (LinkProberStateMachine::*) (SwitchActiveCommandCompleteEvent&)>
(&LinkProberStateMachine::processEvent),
&mLinkProberStateMachine,
LinkProberStateMachine::getSwitchActiveCommandCompleteEvent()
)));
}
//
// ---> sendHeartbeat()
//
// send ICMP ECHOREQUEST packet
//
void LinkProber::sendHeartbeat()
{
MUXLOGTRACE(mMuxPortConfig.getPortName());
updateIcmpSequenceNo();
// check if suspend timer is running
if ((!mSuspendTx) && (!mShutdownTx)) {
boost::system::error_code errorCode;
mStream.write_some(boost::asio::buffer(mTxBuffer.data(), mTxPacketSize), errorCode);
if (errorCode) {
MUXLOGTRACE(mMuxPortConfig.getPortName() + ": Failed to send heartbeat!");
} else {
MUXLOGTRACE(mMuxPortConfig.getPortName() + ": Done sending data");
}
}
}
//
// ---> handleTlvCommandRecv(Tlv *tlvPtr,, bool isPeer);
//
// handle packet reception
//
void LinkProber::handleTlvCommandRecv(
Tlv *tlvPtr,
bool isPeer
)
{
if (isPeer) {
if (tlvPtr->command == static_cast<uint8_t> (Command::COMMAND_SWITCH_ACTIVE)) {
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
static_cast<void (LinkProberStateMachine::*) (SwitchActiveRequestEvent&)>
(&LinkProberStateMachine::processEvent),
&mLinkProberStateMachine,
LinkProberStateMachine::getSwitchActiveRequestEvent()
)));
}
}
}
//
// ---> handleRecv(const boost::system::error_code& errorCode, size_t bytesTransferred);
//
// handle packet reception
//
void LinkProber::handleRecv(
const boost::system::error_code& errorCode,
size_t bytesTransferred
)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
if (errorCode != boost::asio::error::operation_aborted) {
iphdr *ipHeader = reinterpret_cast<iphdr *> (mRxBuffer.data() + sizeof(ether_header));
icmphdr *icmpHeader = reinterpret_cast<icmphdr *> (
mRxBuffer.data() + sizeof(ether_header) + sizeof(iphdr)
);
MUXLOGTRACE(boost::format("%s: Got data from: %s, size: %d") %
mMuxPortConfig.getPortName() %
boost::asio::ip::address_v4(ntohl(ipHeader->saddr)).to_string() %
(bytesTransferred - sizeof(iphdr) - sizeof(ether_header))
);
IcmpPayload *icmpPayload = reinterpret_cast<IcmpPayload *> (
mRxBuffer.data() + mPacketHeaderSize
);
if (ntohl(icmpPayload->cookie) == IcmpPayload::getCookie() &&
ntohl(icmpPayload->version) <= IcmpPayload::getVersion() &&
ntohs(icmpHeader->un.echo.id) == mMuxPortConfig.getServerId()) {
MUXLOGTRACE(boost::format("%s: Valid ICMP Packet from %s") %
mMuxPortConfig.getPortName() %
mMuxPortConfig.getBladeIpv4Address().to_string()
);
bool isMatch = (memcmp(icmpPayload->uuid, IcmpPayload::getGuidData(), sizeof(icmpPayload->uuid)) == 0);
if (isMatch) {
MUXLOGTRACE(boost::format("%s: Matching Guid") % mMuxPortConfig.getPortName());
// echo reply for an echo request generated by this/active ToR
mRxSelfSeqNo = mTxSeqNo;
mLinkProberStateMachine.postLinkProberStateEvent(LinkProberStateMachine::getIcmpSelfEvent());
} else {
mRxPeerSeqNo = mTxSeqNo;
mLinkProberStateMachine.postLinkProberStateEvent(LinkProberStateMachine::getIcmpPeerEvent());
}
size_t nextTlvOffset = mTlvStartOffset;
size_t nextTlvSize = 0;
bool stopProcessTlv = false;
while ((nextTlvSize = findNextTlv(nextTlvOffset, bytesTransferred)) > 0 && !stopProcessTlv) {
Tlv *nextTlvPtr = reinterpret_cast<Tlv *> (mRxBuffer.data() + nextTlvOffset);
switch (nextTlvPtr->tlvhead.type) {
case TlvType::TLV_COMMAND: {
handleTlvCommandRecv(nextTlvPtr, !isMatch);
break;
}
case TlvType::TLV_SENTINEL: {
// sentinel TLV, stop processing
stopProcessTlv = true;
break;
}
default: {
// try to skip unknown TLV with valid length(>0)
stopProcessTlv = (nextTlvSize == sizeof(Tlv));
break;
}
}
nextTlvOffset += nextTlvSize;
}
if (nextTlvOffset < bytesTransferred) {
size_t BytesNotProcessed = bytesTransferred - nextTlvOffset;
MUXLOGTRACE(boost::format("%s: %d bytes in RxBuffer not processed") %
mMuxPortConfig.getPortName() %
BytesNotProcessed
);
}
} else {
// Unknown ICMP packet, ignore.
}
// start another receive to consume as much as possible of backlog packets if any
startRecv();
}
}
//
// ---> handleInitRecv(const boost::system::error_code& errorCode, size_t bytesTransferred);
//
// handle packet reception
//
void LinkProber::handleInitRecv(
const boost::system::error_code& errorCode,
size_t bytesTransferred
)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
if (errorCode != boost::asio::error::operation_aborted) {
ether_header *ethHeader = reinterpret_cast<ether_header *> (mRxBuffer.data());
std::array<uint8_t, ETHER_ADDR_LEN> macAddress;
memcpy(macAddress.data(), ethHeader->ether_shost, macAddress.size());
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
&LinkProberStateMachine::handleMackAddressUpdate,
&mLinkProberStateMachine,
macAddress
)));
}
}
//
// ---> handleTimeout(boost::system::error_code ec);
//
// handle ICMP packet reception timeout
//
void LinkProber::handleTimeout(boost::system::error_code errorCode)
{
MUXLOGTRACE(boost::format("%s: server: %d, mRxSelfSeqNo: %d, mTxSeqNo: %d") %
mMuxPortConfig.getPortName() %
mMuxPortConfig.getServerId() %
mRxSelfSeqNo %
mTxSeqNo
);
mStream.cancel();
if (mTxSeqNo != mRxSelfSeqNo && mTxSeqNo != mRxPeerSeqNo) {
// post unknown event
mLinkProberStateMachine.postLinkProberStateEvent(LinkProberStateMachine::getIcmpUnknownEvent());
mIcmpUnknownEventCount++;
}
mIcmpPacketCount++;
if (mIcmpPacketCount % mMuxPortConfig.getNegativeStateChangeRetryCount() == 0) {
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
&LinkProberStateMachine::handlePckLossRatioUpdate,
&mLinkProberStateMachine,
mIcmpUnknownEventCount,
mIcmpPacketCount
)));
}
// start another cycle of send/recv
startProbing();
}
//
// ---> handleSuspendTimeout(boost::system::error_code errorCode);
//
// handle suspend timer timeout
//
void LinkProber::handleSuspendTimeout(boost::system::error_code errorCode)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mSuspendTx = false;
if (errorCode == boost::system::errc::success) {
// inform the composite state machine about Suspend timer expiry
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
static_cast<void (LinkProberStateMachine::*) (SuspendTimerExpiredEvent&)>
(&LinkProberStateMachine::processEvent),
&mLinkProberStateMachine,
LinkProberStateMachine::getSuspendTimerExpiredEvent()
)));
}
}
//
// ---> startRecv();
//
// start ICMP ECHOREPLY reception
//
void LinkProber::startRecv()
{
MUXLOGTRACE(mMuxPortConfig.getPortName());
mStream.async_read_some(
boost::asio::buffer(mRxBuffer, MUX_MAX_ICMP_BUFFER_SIZE),
mStrand.wrap(boost::bind(
&LinkProber::handleRecv,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
))
);
}
//
// ---> startInitRecv();
//
// start ICMP ECHOREPLY reception
//
void LinkProber::startInitRecv()
{
MUXLOGTRACE(mMuxPortConfig.getPortName());
mStream.async_read_some(
boost::asio::buffer(mRxBuffer, MUX_MAX_ICMP_BUFFER_SIZE),
mStrand.wrap(boost::bind(
&LinkProber::handleInitRecv,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
))
);
}
//
// ---> startTimer();
//
// start ICMP ECHOREPLY timeout timer
//
void LinkProber::startTimer()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
// time out these heartbeats
mDeadlineTimer.expires_from_now(boost::posix_time::milliseconds(getProbingInterval()));
mDeadlineTimer.async_wait(mStrand.wrap(boost::bind(
&LinkProber::handleTimeout,
this,
boost::asio::placeholders::error
)));
}
//
// ---> calculateChecksum(uint16_t *data, size_t size);
//
// calculate ICMP payload checksum
//
uint32_t LinkProber::calculateChecksum(uint16_t *data, size_t size)
{
uint32_t sum = 0;
while (size > 1) {
sum += ntohs(*data++);
size -= sizeof(uint16_t);
}
if (size) {
sum += ntohs(static_cast<uint16_t> ((*reinterpret_cast<uint8_t *> (data))));
}
return sum;
}
//
// ---> addChecksumCarryover(uint16_t *checksum, uint32_t sum);
//
// add checksum carryover
//
void LinkProber::addChecksumCarryover(uint16_t *checksum, uint32_t sum)
{
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
*checksum = htons(~sum);
}
//
// ---> computeChecksum(icmphdr *icmpHeader, size_t size);
//
// compute ICMP checksum
//
void LinkProber::computeChecksum(icmphdr *icmpHeader, size_t size)
{
icmpHeader->checksum = 0;
mIcmpChecksum = calculateChecksum(
reinterpret_cast<uint16_t *> (icmpHeader), size
);
addChecksumCarryover(&icmpHeader->checksum, mIcmpChecksum);
}
//
// ---> computeChecksum(iphdr *ipHeader, size_t size);
//
// compute IPv4 checksum
//
void LinkProber::computeChecksum(iphdr *ipHeader, size_t size)
{
ipHeader->check = 0;
mIpChecksum = calculateChecksum(
reinterpret_cast<uint16_t *> (ipHeader), size
);
addChecksumCarryover(&ipHeader->check, mIpChecksum);
}
//
// ---> initializeSendBuffer();
//
// initialize ICMP packet once
//
void LinkProber::initializeSendBuffer()
{
ether_header *ethHeader = reinterpret_cast<ether_header *> (mTxBuffer.data());
memcpy(ethHeader->ether_dhost, mMuxPortConfig.getBladeMacAddress().data(), sizeof(ethHeader->ether_dhost));
memcpy(ethHeader->ether_shost, mMuxPortConfig.getTorMacAddress().data(), sizeof(ethHeader->ether_shost));
ethHeader->ether_type = htons(ETHERTYPE_IP);
iphdr *ipHeader = reinterpret_cast<iphdr *> (mTxBuffer.data() + sizeof(ether_header));
icmphdr *icmpHeader = reinterpret_cast<icmphdr *> (mTxBuffer.data() + sizeof(ether_header) + sizeof(iphdr));
new (mTxBuffer.data() + mPacketHeaderSize) IcmpPayload();
resetTxBufferTlv();
appendTlvSentinel();
size_t totalPayloadSize = mTxPacketSize - mPacketHeaderSize;
ipHeader->ihl = sizeof(iphdr) >> 2;
ipHeader->version = IPVERSION;
ipHeader->tos = 0xb8;
ipHeader->tot_len = htons(sizeof(iphdr) + sizeof(icmphdr) + totalPayloadSize);
ipHeader->id = static_cast<uint16_t> (rand());
ipHeader->frag_off = 0;
ipHeader->ttl = 64;
ipHeader->protocol = IPPROTO_ICMP;
ipHeader->check = 0;
ipHeader->saddr = htonl(mMuxPortConfig.getLoopbackIpv4Address().to_v4().to_uint());
ipHeader->daddr = htonl(mMuxPortConfig.getBladeIpv4Address().to_v4().to_uint());
computeChecksum(ipHeader, ipHeader->ihl << 2);
icmpHeader->type = ICMP_ECHO;
icmpHeader->code = 0;
icmpHeader->un.echo.id = htons(mMuxPortConfig.getServerId());
icmpHeader->un.echo.sequence = htons(mTxSeqNo);
computeChecksum(icmpHeader, sizeof(icmphdr) + totalPayloadSize);
}
//
// ---> updateIcmpSequenceNo();
//
// update ICMP packet checksum, used before sending new heartbeat
//
void LinkProber::updateIcmpSequenceNo()
{
// update received sequence to avoid reporting invalid ICMP event when sequence number rolls over
mRxPeerSeqNo = mTxSeqNo;
mRxSelfSeqNo = mTxSeqNo;
icmphdr *icmpHeader = reinterpret_cast<icmphdr *> (mTxBuffer.data() + sizeof(ether_header) + sizeof(iphdr));
icmpHeader->un.echo.sequence = htons(++mTxSeqNo);
mIcmpChecksum += mTxSeqNo ? 1 : 0;
addChecksumCarryover(&icmpHeader->checksum, mIcmpChecksum);
}
//
// ---> findNextTlv
//
// Find next TLV to process in rxBuffer
//
size_t LinkProber::findNextTlv(size_t readOffset, size_t bytesTransferred)
{
size_t tlvSize = 0;
if (readOffset + sizeof(TlvHead) <= bytesTransferred) {
Tlv *tlvPtr = reinterpret_cast<Tlv *> (mRxBuffer.data() + readOffset);
tlvSize = (sizeof(TlvHead) + ntohs(tlvPtr->tlvhead.length));
if (readOffset + tlvSize > bytesTransferred) {
tlvSize = 0;
}
}
return tlvSize;
}
//
// ---> appendTlvCommand
//
// Append TlvCommand to the end of txBuffer
//
size_t LinkProber::appendTlvCommand(Command commandType)
{
size_t tlvSize = sizeof(TlvHead) + sizeof(Command);
assert(mTxPacketSize + tlvSize <= MUX_MAX_ICMP_BUFFER_SIZE);
Tlv *tlvPtr = reinterpret_cast<Tlv *> (mTxBuffer.data() + mTxPacketSize);
tlvPtr->tlvhead.type = TlvType::TLV_COMMAND;
tlvPtr->tlvhead.length = htons(sizeof(Command));
tlvPtr->command = static_cast<uint8_t> (commandType);
mTxPacketSize += tlvSize;
return tlvSize;
}
//
// ---> appendTlvSentinel
//
// Append TlvSentinel to the end of txBuffer
//
size_t LinkProber::appendTlvSentinel()
{
size_t tlvSize = sizeof(TlvHead);
assert(mTxPacketSize + tlvSize <= MUX_MAX_ICMP_BUFFER_SIZE);
Tlv *tlvPtr = reinterpret_cast<Tlv *> (mTxBuffer.data() + mTxPacketSize);
tlvPtr->tlvhead.type = TlvType::TLV_SENTINEL;
tlvPtr->tlvhead.length = 0;
mTxPacketSize += tlvSize;
return tlvSize;
}
//
// ---> appendTlvDummy
//
// Append a dummy TLV, test purpose only
//
size_t LinkProber::appendTlvDummy(size_t paddingSize, int seqNo)
{
size_t tlvSize = sizeof(TlvHead) + paddingSize + sizeof(uint32_t);
assert(mTxPacketSize + tlvSize <= MUX_MAX_ICMP_BUFFER_SIZE);
Tlv *tlvPtr = reinterpret_cast<Tlv *> (mTxBuffer.data() + mTxPacketSize);
tlvPtr->tlvhead.type = TlvType::TLV_DUMMY;
tlvPtr->tlvhead.length = htons(paddingSize + sizeof(uint32_t));
memset(tlvPtr->data, 0, paddingSize);
*(reinterpret_cast<uint32_t *> (tlvPtr->data + paddingSize)) = htonl(seqNo);
mTxPacketSize += tlvSize;
return tlvSize;
}
//
// ---> resetIcmpPacketCounts
//
// reset Icmp packet counts, post a pck loss ratio update immediately
//
void LinkProber::resetIcmpPacketCounts()
{
mIcmpUnknownEventCount = 0;
mIcmpPacketCount = 0;
boost::asio::io_service::strand &strand = mLinkProberStateMachine.getStrand();
boost::asio::io_service &ioService = strand.context();
ioService.post(strand.wrap(boost::bind(
&LinkProberStateMachine::handlePckLossRatioUpdate,
&mLinkProberStateMachine,
mIcmpUnknownEventCount,
mIcmpPacketCount
)));
}
void LinkProber::shutdownTxProbes()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mShutdownTx = true;
}
void LinkProber::restartTxProbes()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mShutdownTx = false;
}
//
// ---> decreaseProbeIntervalAfterSwitch(uint32_t switchTime_msec);
//
// adjust link prober interval to 10 ms after switchover to better measure the switchover overhead.
//
void LinkProber::decreaseProbeIntervalAfterSwitch(uint32_t switchTime_msec)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mSwitchoverTimer.expires_from_now(boost::posix_time::milliseconds(switchTime_msec));
mSwitchoverTimer.async_wait(mStrand.wrap(boost::bind(
&LinkProber::handleSwitchoverTimeout,
this,
boost::asio::placeholders::error
)));
mDecreaseProbingInterval = true;
}
// ---> revertProbeIntervalAfterSwitchComplete();
//
// revert probe interval change after switchover is completed
//
void LinkProber::revertProbeIntervalAfterSwitchComplete()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mSwitchoverTimer.cancel();
mDecreaseProbingInterval = false;
}
//
// ---> handleSwitchoverTimeout(boost::system::error_code errorCode)
//
// handle switchover time out
//
void LinkProber::handleSwitchoverTimeout(boost::system::error_code errorCode)
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
mDecreaseProbingInterval = false;
if (errorCode == boost::system::errc::success) {
MUXLOGWARNING(boost::format("%s: link prober timeout on waiting for expected ICMP event after switchover is triggered ") % mMuxPortConfig.getPortName());
}
}
//
// ---> getProbingInterval
//
// get link prober interval
//
inline uint32_t LinkProber::getProbingInterval()
{
MUXLOGDEBUG(mMuxPortConfig.getPortName());
return mDecreaseProbingInterval? mMuxPortConfig.getDecreasedTimeoutIpv4_msec():mMuxPortConfig.getTimeoutIpv4_msec();
}
} /* namespace link_prober */