-
Notifications
You must be signed in to change notification settings - Fork 390
/
ksync_sock.cc
1051 lines (901 loc) · 33.6 KB
/
ksync_sock.cc
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 (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <string>
#include "base/os.h"
#if defined(__linux__)
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/genetlink.h>
#include <linux/sockios.h>
#elif defined(__FreeBSD__)
#include "vr_os.h"
#endif
#include <sys/socket.h>
#include <boost/bind.hpp>
#include <base/logging.h>
#include <db/db.h>
#include <db/db_entry.h>
#include <db/db_table.h>
#include <db/db_table_partition.h>
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include "ksync_index.h"
#include "ksync_entry.h"
#include "ksync_object.h"
#include "ksync_sock.h"
#include "ksync_sock_user.h"
#include "ksync_types.h"
#include "nl_util.h"
#include "udp_util.h"
#include "vr_genetlink.h"
#include "vr_types.h"
using namespace boost::asio;
/* Note SO_RCVBUFFORCE is supported only for linux version 2.6.14 and above */
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET,
SO_RCVBUFFORCE> ReceiveBuffForceSize;
int KSyncSock::vnsw_netlink_family_id_;
AgentSandeshContext *KSyncSock::agent_sandesh_ctx_;
std::vector<KSyncSock *> KSyncSock::sock_table_;
pid_t KSyncSock::pid_;
tbb::atomic<bool> KSyncSock::shutdown_;
const char* IoContext::io_wq_names[IoContext::MAX_WORK_QUEUES] =
{"Agent::KSync", "Agent::Uve"};
// Copy data from io-vector to a buffer
static uint32_t IoVectorToData(char *data, KSyncBufferList *iovec) {
KSyncBufferList::iterator it = iovec->begin();
int offset = 0;
while (it != iovec->end()) {
unsigned char *buf = boost::asio::buffer_cast<unsigned char *>(*it);
memcpy(data + offset, buf, boost::asio::buffer_size(*it));
offset += boost::asio::buffer_size(*it);
it++;
}
return offset;
}
/////////////////////////////////////////////////////////////////////////////
// Netlink utilities
/////////////////////////////////////////////////////////////////////////////
static uint32_t GetNetlinkSeqno(char *data) {
struct nlmsghdr *nlh = (struct nlmsghdr *)data;
return nlh->nlmsg_seq;
}
static bool NetlinkMsgDone(char *data) {
struct nlmsghdr *nlh = (struct nlmsghdr *)data;
return ((nlh->nlmsg_flags & NLM_F_MULTI) != 0);
}
// Common validation for netlink messages
static bool ValidateNetlink(char *data) {
struct nlmsghdr *nlh = (struct nlmsghdr *)data;
if (nlh->nlmsg_type == NLMSG_ERROR) {
LOG(ERROR, "Netlink error for seqno " << nlh->nlmsg_seq << " len "
<< nlh->nlmsg_len);
assert(0);
return false;
}
if (nlh->nlmsg_len > KSyncSock::kBufLen) {
LOG(ERROR, "Length of " << nlh->nlmsg_len << " is more than expected "
"length of " << KSyncSock::kBufLen);
assert(0);
return false;
}
if (nlh->nlmsg_type == NLMSG_DONE) {
return true;
}
// Sanity checks for generic-netlink message
if (nlh->nlmsg_type != KSyncSock::GetNetlinkFamilyId()) {
LOG(ERROR, "Netlink unknown message type : " << nlh->nlmsg_type);
assert(0);
return false;
}
struct genlmsghdr *genlh = (struct genlmsghdr *) (data + NLMSG_HDRLEN);
if (genlh->cmd != SANDESH_REQUEST) {
LOG(ERROR, "Unknown generic netlink cmd : " << genlh->cmd);
assert(0);
return false;
}
struct nlattr * attr = (struct nlattr *)(data + NLMSG_HDRLEN
+ GENL_HDRLEN);
if (attr->nla_type != NL_ATTR_VR_MESSAGE_PROTOCOL) {
LOG(ERROR, "Unknown generic netlink TLV type : " << attr->nla_type);
assert(0);
return false;
}
return true;
}
static void GetNetlinkPayload(char *data, char **buf, uint32_t *buf_len) {
struct nlmsghdr *nlh = (struct nlmsghdr *)data;
int len = 0;
if (nlh->nlmsg_type == NLMSG_DONE) {
len = NLMSG_HDRLEN;
} else {
len = NLMSG_HDRLEN + GENL_HDRLEN + NLA_HDRLEN;
}
*buf = data + len;
*buf_len = nlh->nlmsg_len - len;
}
static void InitNetlink(nl_client *client) {
nl_init_generic_client_req(client, KSyncSock::GetNetlinkFamilyId());
unsigned char *nl_buf;
uint32_t nl_buf_len;
assert(nl_build_header(client, &nl_buf, &nl_buf_len) >= 0);
}
static void ResetNetlink(nl_client *client) {
unsigned char *nl_buf;
uint32_t nl_buf_len;
client->cl_buf_offset = 0;
nl_build_header(client, &nl_buf, &nl_buf_len);
}
static void UpdateNetlink(nl_client *client, uint32_t len, uint32_t seq_no) {
nl_update_header(client, len);
struct nlmsghdr *nlh = (struct nlmsghdr *)client->cl_buf;
nlh->nlmsg_pid = KSyncSock::GetPid();
nlh->nlmsg_seq = seq_no;
}
static void DecodeSandeshMessages(char *buf, uint32_t buf_len,
SandeshContext *sandesh_context,
uint32_t alignment) {
while (buf_len > (alignment - 1)) {
int error;
int decode_len = Sandesh::ReceiveBinaryMsgOne((uint8_t *)buf, buf_len,
&error, sandesh_context);
if (decode_len < 0) {
LOG(DEBUG, "Incorrect decode len " << decode_len);
break;
}
buf += decode_len;
buf_len -= decode_len;
}
}
/////////////////////////////////////////////////////////////////////////////
// KSyncSock routines
/////////////////////////////////////////////////////////////////////////////
KSyncSock::KSyncSock() :
max_bulk_msg_count_(kMaxBulkMsgCount), max_bulk_buf_size_(kMaxBulkMsgSize),
bulk_seq_no_(-1), tx_count_(0), err_count_(0), read_inline_(true) {
TaskScheduler *scheduler = TaskScheduler::GetInstance();
uint32_t task_id = 0;
for(int i = 0; i < IoContext::MAX_WORK_QUEUES; i++) {
task_id = scheduler->GetTaskId(IoContext::io_wq_names[i]);
receive_work_queue[i] =
new WorkQueue<char *>(task_id, 0,
boost::bind(&KSyncSock::ProcessKernelData,
this, _1));
}
task_id = scheduler->GetTaskId("Ksync::AsyncSend");
async_send_queue_ =
new WorkQueue<IoContext *>(task_id, 0,
boost::bind(&KSyncSock::SendAsyncImpl, this,
_1));
async_send_queue_->SetExitCallback
(boost::bind(&KSyncSock::SendTaskExit, this, _1));
nl_client_ = (nl_client *)malloc(sizeof(nl_client));
bzero(nl_client_, sizeof(nl_client));
rx_buff_ = NULL;
seqno_ = 0;
uve_seqno_ = 0;
}
KSyncSock::~KSyncSock() {
assert(wait_tree_.size() == 0);
if (rx_buff_) {
delete [] rx_buff_;
rx_buff_ = NULL;
}
assert(async_send_queue_->Length() == 0);
async_send_queue_->Shutdown();
delete async_send_queue_;
for(int i = 0; i < IoContext::MAX_WORK_QUEUES; i++) {
receive_work_queue[i]->Shutdown();
delete receive_work_queue[i];
}
if (nl_client_->cl_buf) {
free(nl_client_->cl_buf);
}
free(nl_client_);
}
void KSyncSock::Shutdown() {
shutdown_ = true;
STLDeleteValues(&sock_table_);
}
void KSyncSock::Init(int count) {
sock_table_.resize(count);
pid_ = getpid();
shutdown_ = false;
}
void KSyncSock::Start(bool read_inline) {
for (std::vector<KSyncSock *>::iterator it = sock_table_.begin();
it != sock_table_.end(); ++it) {
(*it)->read_inline_ = read_inline;
if ((*it)->read_inline_) {
continue;
}
(*it)->async_send_queue_->SetStartRunnerFunc(
boost::bind(&KSyncSock::SendAsyncStart, *it));
(*it)->rx_buff_ = new char[kBufLen];
(*it)->AsyncReceive(boost::asio::buffer((*it)->rx_buff_, kBufLen),
boost::bind(&KSyncSock::ReadHandler, *it,
placeholders::error,
placeholders::bytes_transferred));
}
}
void KSyncSock::SetSockTableEntry(int i, KSyncSock *sock) {
sock_table_[i] = sock;
}
void KSyncSock::SetNetlinkFamilyId(int id) {
vnsw_netlink_family_id_ = id;
for (std::vector<KSyncSock *>::iterator it = sock_table_.begin();
it != sock_table_.end(); it++) {
KSyncSock *sock = dynamic_cast<KSyncSock *>(*it);
if (sock) {
InitNetlink(sock->nl_client_);
}
}
}
int KSyncSock::AllocSeqNo(bool is_uve) {
int seq;
if (is_uve) {
seq = uve_seqno_.fetch_and_add(2);
} else {
seq = seqno_.fetch_and_add(2);
seq |= KSYNC_DEFAULT_Q_ID_SEQ;
}
return seq;
}
KSyncSock *KSyncSock::Get(DBTablePartBase *partition) {
int idx = partition->index();
return sock_table_[idx];
}
KSyncSock *KSyncSock::Get(int idx) {
return sock_table_[idx];
}
bool KSyncSock::ValidateAndEnqueue(char *data) {
Validate(data);
IoContext::IoContextWorkQId q_id;
if ((GetSeqno(data) & KSYNC_DEFAULT_Q_ID_SEQ) ==
KSYNC_DEFAULT_Q_ID_SEQ) {
q_id = IoContext::DEFAULT_Q_ID;
} else {
q_id = IoContext::UVE_Q_ID;
}
receive_work_queue[q_id]->Enqueue(data);
return true;
}
// Read handler registered with boost::asio. Demux done based on seqno_
void KSyncSock::ReadHandler(const boost::system::error_code& error,
size_t bytes_transferred) {
if (error) {
LOG(ERROR, "Error reading from Ksync sock. Error : " <<
boost::system::system_error(error).what());
if (shutdown_ == false) {
assert(0);
}
return;
}
ValidateAndEnqueue(rx_buff_);
rx_buff_ = new char[kBufLen];
AsyncReceive(boost::asio::buffer(rx_buff_, kBufLen),
boost::bind(&KSyncSock::ReadHandler, this,
placeholders::error,
placeholders::bytes_transferred));
}
// Process kernel data - executes in the task specified by IoContext
// Currently only Agent::KSync and Agent::Uve are possibilities
bool KSyncSock::ProcessKernelData(char *data) {
uint32_t seqno = GetSeqno(data);
WaitTree::iterator it;
{
tbb::mutex::scoped_lock lock(mutex_);
it = wait_tree_.find(seqno);
}
if (it == wait_tree_.end()) {
LOG(ERROR, "KSync error in finding for sequence number : " << seqno);
assert(0);
}
KSyncBulkSandeshContext *bulk_context = &(it->second);
BulkDecoder(data, bulk_context);
// Remove the IoContext only on last netlink message
if (IsMoreData(data) == false) {
tbb::mutex::scoped_lock lock(mutex_);
wait_tree_.erase(it);
}
async_send_queue_->MayBeStartRunner();
delete[] data;
return true;
}
bool KSyncSock::BlockingRecv() {
char data[kBufLen];
bool ret = false;
do {
Receive(boost::asio::buffer(data, kBufLen));
AgentSandeshContext *ctxt = KSyncSock::GetAgentSandeshContext();
ctxt->SetErrno(0);
// BlockingRecv used only during Init and doesnt support bulk messages
// Use non-bulk version of decoder
Decoder(data, ctxt);
if (ctxt->GetErrno() != 0) {
KSYNC_ERROR(VRouterError, "VRouter operation failed. Error <",
ctxt->GetErrno(), ":", strerror(ctxt->GetErrno()),
">. Object <", "N/A", ">. State <", "N/A",
">. Message number :", 0);
ret = true;
}
} while (IsMoreData(data));
return ret;
}
// BlockingSend does not support bulk messages.
size_t KSyncSock::BlockingSend(char *msg, int msg_len) {
KSyncBufferList iovec;
iovec.push_back(buffer(msg, msg_len));
bulk_buf_size_ = msg_len;
return SendTo(&iovec, 0);
}
void KSyncSock::GenericSend(IoContext *ioc) {
async_send_queue_->Enqueue(ioc);
}
void KSyncSock::SendAsync(KSyncEntry *entry, int msg_len, char *msg,
KSyncEntry::KSyncEvent event) {
uint32_t seq = AllocSeqNo(false);
KSyncIoContext *ioc = new KSyncIoContext(entry, msg_len, msg, seq, event);
async_send_queue_->Enqueue(ioc);
}
// Write handler registered with boost::asio
void KSyncSock::WriteHandler(const boost::system::error_code& error,
size_t bytes_transferred) {
if (error) {
LOG(ERROR, "Ksync sock write error : " <<
boost::system::system_error(error).what());
if (shutdown_ == false) {
assert(0);
}
}
}
// End of messages in the work-queue. Send messages pending in bulk context
void KSyncSock::SendTaskExit(bool done) {
WaitTree::iterator it = wait_tree_.find(bulk_seq_no_);
assert(it != wait_tree_.end());
KSyncBulkSandeshContext *bulk_context = &it->second;
SendBulkMessage(bulk_context, bulk_seq_no_);
}
// Send messages accumilated in bulk context
int KSyncSock::SendBulkMessage(KSyncBulkSandeshContext *bulk_context,
uint32_t seqno) {
KSyncBufferList iovec;
// Get all buffers to send into single io-vector
bulk_context->Data(&iovec);
if (!read_inline_) {
AsyncSendTo(&iovec, seqno,
boost::bind(&KSyncSock::WriteHandler, this,
placeholders::error,
placeholders::bytes_transferred));
} else {
SendTo(&iovec, seqno);
bool more_data = false;
do {
int len = kBufLen;
char *rxbuf = new char[len];
Receive(boost::asio::buffer(rxbuf, kBufLen));
more_data = IsMoreData(rxbuf);
ValidateAndEnqueue(rxbuf);
} while(more_data);
}
bulk_seq_no_ = -1;
return true;
}
// Get the bulk-context for sequence-number
KSyncBulkSandeshContext *KSyncSock::LocateBulkContext(uint32_t seqno) {
tbb::mutex::scoped_lock lock(mutex_);
if (bulk_seq_no_ == -1) {
bulk_seq_no_ = seqno;
bulk_buf_size_ = 0;
bulk_msg_count_ = 0;
wait_tree_.insert(WaitTreePair(seqno, KSyncBulkSandeshContext()));
}
WaitTree::iterator it = wait_tree_.find(bulk_seq_no_);
assert(it != wait_tree_.end());
return &it->second;
}
// Try adding an io-context to bulk context. Returns
// - true : if message can be added to bulk context
// - false : if message cannot be added to bulk context
bool KSyncSock::TryAddToBulk(KSyncBulkSandeshContext *bulk_context,
IoContext *ioc) {
if ((bulk_buf_size_ + ioc->GetMsgLen()) > max_bulk_buf_size_)
return false;
if (bulk_msg_count_ >= max_bulk_msg_count_)
return false;
bulk_buf_size_ += ioc->GetMsgLen();
bulk_msg_count_++;
bulk_context->Insert(ioc);
return true;
}
bool KSyncSock::SendAsyncImpl(IoContext *ioc) {
KSyncBulkSandeshContext *bulk_context = LocateBulkContext(ioc->GetSeqno());
// Try adding message to bulk-message list
if (TryAddToBulk(bulk_context, ioc)) {
// Message added to bulk-list. Nothing more to do
return true;
}
// Message cannot be added to bulk-list. Send the current list
SendBulkMessage(bulk_context, bulk_seq_no_);
// Allocate a new context and add message to it
bulk_context = LocateBulkContext(ioc->GetSeqno());
assert(TryAddToBulk(bulk_context, ioc));
return true;
}
/////////////////////////////////////////////////////////////////////////////
// KSyncSockNetlink routines
/////////////////////////////////////////////////////////////////////////////
KSyncSockNetlink::KSyncSockNetlink(boost::asio::io_service &ios, int protocol)
: sock_(ios, protocol) {
ReceiveBuffForceSize set_rcv_buf;
set_rcv_buf = KSYNC_SOCK_RECV_BUFF_SIZE;
boost::system::error_code ec;
sock_.set_option(set_rcv_buf, ec);
if (ec.value() != 0) {
LOG(ERROR, "Error Changing netlink receive sock buffer size to " <<
set_rcv_buf.value() << " error = " <<
boost::system::system_error(ec).what());
}
boost::asio::socket_base::receive_buffer_size rcv_buf_size;
boost::system::error_code ec1;
sock_.get_option(rcv_buf_size, ec);
LOG(INFO, "Current receive sock buffer size is " << rcv_buf_size.value());
}
KSyncSockNetlink::~KSyncSockNetlink() {
}
void KSyncSockNetlink::Init(io_service &ios, int count, int protocol) {
KSyncSock::Init(count);
for (int i = 0; i < count; i++) {
KSyncSock::SetSockTableEntry(i, new KSyncSockNetlink(ios, protocol));
}
}
uint32_t KSyncSockNetlink::GetSeqno(char *data) {
return GetNetlinkSeqno(data);
}
bool KSyncSockNetlink::IsMoreData(char *data) {
return NetlinkMsgDone(data);
}
bool KSyncSockNetlink::Validate(char *data) {
return ValidateNetlink(data);
}
//netlink socket class for interacting with kernel
void KSyncSockNetlink::AsyncSendTo(KSyncBufferList *iovec, uint32_t seq_no,
HandlerCb cb) {
ResetNetlink(nl_client_);
KSyncBufferList::iterator it = iovec->begin();
iovec->insert(it, buffer((char *)nl_client_->cl_buf,
nl_client_->cl_buf_offset));
UpdateNetlink(nl_client_, bulk_buf_size_, seq_no);
boost::asio::netlink::raw::endpoint ep;
sock_.async_send_to(*iovec, ep, cb);
}
size_t KSyncSockNetlink::SendTo(KSyncBufferList *iovec, uint32_t seq_no) {
ResetNetlink(nl_client_);
KSyncBufferList::iterator it = iovec->begin();
iovec->insert(it, buffer((char *)nl_client_->cl_buf,
nl_client_->cl_buf_offset));
UpdateNetlink(nl_client_, bulk_buf_size_, seq_no);
boost::asio::netlink::raw::endpoint ep;
return sock_.send_to(*iovec, ep);
}
// Static method to decode non-bulk message
void KSyncSockNetlink::NetlinkDecoder(char *data, SandeshContext *ctxt) {
assert(ValidateNetlink(data));
char *buf = NULL;
uint32_t buf_len = 0;
GetNetlinkPayload(data, &buf, &buf_len);
DecodeSandeshMessages(buf, buf_len, ctxt, NLA_ALIGNTO);
}
bool KSyncSockNetlink::Decoder(char *data, AgentSandeshContext *context) {
NetlinkDecoder(data, context);
return true;
}
// Static method used in ksync_sock_user only
void KSyncSockNetlink::NetlinkBulkDecoder(char *data, SandeshContext *ctxt,
bool more) {
assert(ValidateNetlink(data));
char *buf = NULL;
uint32_t buf_len = 0;
GetNetlinkPayload(data, &buf, &buf_len);
KSyncBulkSandeshContext *bulk_context =
dynamic_cast<KSyncBulkSandeshContext *>(ctxt);
bulk_context->Decoder(buf, buf_len, NLA_ALIGNTO, more);
}
bool KSyncSockNetlink::BulkDecoder(char *data,
KSyncBulkSandeshContext *bulk_context) {
// Get sandesh buffer and buffer-length
uint32_t buf_len = 0;
char *buf = NULL;
GetNetlinkPayload(data, &buf, &buf_len);
return bulk_context->Decoder(buf, buf_len, NLA_ALIGNTO, IsMoreData(data));
}
void KSyncSockNetlink::AsyncReceive(mutable_buffers_1 buf, HandlerCb cb) {
sock_.async_receive(buf, cb);
}
void KSyncSockNetlink::Receive(mutable_buffers_1 buf) {
sock_.receive(buf);
struct nlmsghdr *nlh = buffer_cast<struct nlmsghdr *>(buf);
if (nlh->nlmsg_type == NLMSG_ERROR) {
LOG(ERROR, "Netlink error for seqno " << nlh->nlmsg_seq
<< " len " << nlh->nlmsg_len);
assert(0);
}
}
/////////////////////////////////////////////////////////////////////////////
// KSyncSockUdp routines
/////////////////////////////////////////////////////////////////////////////
//Udp socket class for interacting with kernel
KSyncSockUdp::KSyncSockUdp(boost::asio::io_service &ios, int port) :
sock_(ios, ip::udp::endpoint(ip::udp::v4(), 0)),
server_ep_(ip::address::from_string("127.0.0.1"), port) {
}
void KSyncSockUdp::Init(io_service &ios, int count, int port) {
KSyncSock::Init(count);
for (int i = 0; i < count; i++) {
KSyncSock::SetSockTableEntry(i, new KSyncSockUdp(ios, port));
}
}
uint32_t KSyncSockUdp::GetSeqno(char *data) {
struct uvr_msg_hdr *hdr = (struct uvr_msg_hdr *)data;
return hdr->seq_no;
}
bool KSyncSockUdp::IsMoreData(char *data) {
struct uvr_msg_hdr *hdr = (struct uvr_msg_hdr *)data;
return ((hdr->flags & UVR_MORE) == UVR_MORE);
}
// We dont expect any non-bulk operation on UDP
bool KSyncSockUdp::Decoder(char *data, AgentSandeshContext *context) {
assert(0);
}
bool KSyncSockUdp::BulkDecoder(char *data,
KSyncBulkSandeshContext *bulk_context) {
struct uvr_msg_hdr *hdr = (struct uvr_msg_hdr *)data;
uint32_t buf_len = hdr->msg_len;
char *buf = data + sizeof(struct uvr_msg_hdr);
return bulk_context->Decoder(buf, buf_len, 1, IsMoreData(data));
}
void KSyncSockUdp::AsyncSendTo(KSyncBufferList *iovec, uint32_t seq_no,
HandlerCb cb) {
struct uvr_msg_hdr hdr;
hdr.seq_no = seq_no;
hdr.flags = 0;
hdr.msg_len = bulk_buf_size_;
KSyncBufferList::iterator it = iovec->begin();
iovec->insert(it, buffer((char *)(&hdr), sizeof(hdr)));
sock_.async_send_to(*iovec, server_ep_, cb);
}
size_t KSyncSockUdp::SendTo(KSyncBufferList *iovec, uint32_t seq_no) {
struct uvr_msg_hdr hdr;
hdr.seq_no = seq_no;
hdr.flags = 0;
hdr.msg_len = bulk_buf_size_;
KSyncBufferList::iterator it = iovec->begin();
iovec->insert(it, buffer((char *)(&hdr), sizeof(hdr)));
return sock_.send_to(*iovec, server_ep_, MSG_DONTWAIT);
}
bool KSyncSockUdp::Validate(char *data) {
return true;
}
void KSyncSockUdp::AsyncReceive(mutable_buffers_1 buf, HandlerCb cb) {
ip::udp::endpoint ep;
sock_.async_receive_from(buf, ep, cb);
}
void KSyncSockUdp::Receive(mutable_buffers_1 buf) {
ip::udp::endpoint ep;
sock_.receive_from(buf, ep);
}
/////////////////////////////////////////////////////////////////////////////
// KSyncSockTcp routines
/////////////////////////////////////////////////////////////////////////////
//TCP socket class for interacting with vrouter
KSyncSockTcp::KSyncSockTcp(EventManager *evm,
ip::address ip_address, int port) : TcpServer(evm), evm_(evm),
session_(NULL), server_ep_(ip_address, port), connect_complete_(false) {
session_ = CreateSession();
Connect(session_, server_ep_);
}
void KSyncSockTcp::Init(EventManager *evm, int count, ip::address ip_addr,
int port) {
KSyncSock::Init(count);
SetNetlinkFamilyId(10);
for (int i = 0; i < count; i++) {
KSyncSock::SetSockTableEntry(i, new KSyncSockTcp(evm, ip_addr, port));
}
}
TcpSession* KSyncSockTcp::AllocSession(Socket *socket) {
TcpSession *session = new KSyncSockTcpSession(this, socket, false);
session->set_observer(boost::bind(&KSyncSockTcp::OnSessionEvent,
this, _1, _2));
return session;
}
uint32_t KSyncSockTcp::GetSeqno(char *data) {
return GetNetlinkSeqno(data);
}
bool KSyncSockTcp::IsMoreData(char *data) {
return NetlinkMsgDone(data);
}
size_t KSyncSockTcp::SendTo(KSyncBufferList *iovec, uint32_t seq_no) {
char msg[4096];
ResetNetlink(nl_client_);
int offset = nl_client_->cl_buf_offset;
UpdateNetlink(nl_client_, bulk_buf_size_, seq_no);
KSyncBufferList::iterator it = iovec->begin();
iovec->insert(it, buffer((char *)nl_client_->cl_buf, offset));
uint32_t len = IoVectorToData(msg, iovec);
session_->Send((const uint8_t *)msg, len, NULL);
return nl_client_->cl_buf_offset;
}
void KSyncSockTcp::AsyncSendTo(KSyncBufferList *iovec, uint32_t seq_no,
HandlerCb cb) {
SendTo(iovec, seq_no);
return;
}
bool KSyncSockTcp::Validate(char *data) {
return ValidateNetlink(data);
}
bool KSyncSockTcp::Decoder(char *data, AgentSandeshContext *context) {
KSyncSockNetlink::NetlinkDecoder(data, context);
return true;
}
bool KSyncSockTcp::BulkDecoder(char *data,
KSyncBulkSandeshContext *bulk_context) {
// Get sandesh buffer and buffer-length
uint32_t buf_len = 0;
char *buf = NULL;
GetNetlinkPayload(data, &buf, &buf_len);
return bulk_context->Decoder(buf, buf_len, NLA_ALIGNTO, IsMoreData(data));
}
void KSyncSockTcp::AsyncReceive(mutable_buffers_1 buf, HandlerCb cb) {
//Data would be read from ksync tcp session
//hence no socket operation would be required
}
void KSyncSockTcp::Receive(mutable_buffers_1 buf) {
uint32_t bytes_read = 0;
boost::system::error_code ec;
const struct nlmsghdr *nlh = NULL;
//Create a buffer to read netlink header first
mutable_buffers_1 netlink_header(buffer_cast<void *>(buf),
sizeof(struct nlmsghdr));
bool blocking_socket = session_->socket()->non_blocking();
session_->socket()->non_blocking(false, ec);
while (bytes_read < sizeof(struct nlmsghdr)) {
mutable_buffers_1 buffer =
static_cast<mutable_buffers_1>(netlink_header + bytes_read);
bytes_read += session_->socket()->receive(buffer, 0, ec);
if (ec != 0) {
assert(0);
}
//Data read is lesser than netlink header
//continue reading
if (bytes_read == sizeof(struct nlmsghdr)) {
nlh = buffer_cast<struct nlmsghdr *>(buf);
}
}
if (nlh->nlmsg_type == NLMSG_ERROR) {
LOG(ERROR, "Netlink error for seqno " << nlh->nlmsg_seq
<< " len " << nlh->nlmsg_len);
assert(0);
}
bytes_read = 0;
uint32_t payload_size = nlh->nlmsg_len - sizeof(struct nlmsghdr);
//Read data
mutable_buffers_1 data(buffer_cast<void *>(buf + sizeof(struct nlmsghdr)),
payload_size);
while (bytes_read < payload_size) {
mutable_buffers_1 buffer =
static_cast<mutable_buffers_1>(data + bytes_read);
bytes_read += session_->socket()->receive(buffer, 0, ec);
if (ec != 0) {
assert(0);
}
}
session_->socket()->non_blocking(blocking_socket, ec);
}
bool KSyncSockTcp::ReceiveMsg(const u_int8_t *msg, size_t size) {
char *rx_buff = new char[kBufLen];
memcpy(rx_buff, msg, size);
ValidateAndEnqueue(rx_buff);
return true;
}
void KSyncSockTcp::AsyncReadStart() {
session_->AsyncReadStart();
}
void KSyncSockTcp::OnSessionEvent(TcpSession *session,
TcpSession::Event event) {
switch (event) {
case TcpSession::CONNECT_FAILED:
//Retry
Connect(session_, server_ep_);
break;
case TcpSession::CLOSE:
LOG(ERROR, "Connection to dpdk-vrouter lost.");
sleep(1);
exit(EXIT_FAILURE);
break;
case TcpSession::CONNECT_COMPLETE:
connect_complete_ = true;
default:
break;
}
}
/////////////////////////////////////////////////////////////////////////////
// KSyncSockTcpSession routines
/////////////////////////////////////////////////////////////////////////////
KSyncSockTcpSession::KSyncSockTcpSession(TcpServer *server, Socket *sock,
bool async_ready) : TcpSession(server, sock, async_ready) {
KSyncSockTcp *tcp_ptr = static_cast<KSyncSockTcp *>(server);
reader_ = new KSyncSockTcpSessionReader(this,
boost::bind(&KSyncSockTcp::ReceiveMsg, tcp_ptr, _1, _2));
}
void KSyncSockTcpSession::OnRead(Buffer buffer) {
reader_->OnRead(buffer);
}
KSyncSockTcpSessionReader::KSyncSockTcpSessionReader(
TcpSession *session, ReceiveCallback callback) :
TcpMessageReader(session, callback) {
}
int KSyncSockTcpSessionReader::MsgLength(Buffer buffer, int offset) {
size_t size = TcpSession::BufferSize(buffer);
int remain = size - offset;
if (remain < GetHeaderLenSize()) {
return -1;
}
//Byte ordering?
const struct nlmsghdr *nlh =
(const struct nlmsghdr *)(TcpSession::BufferData(buffer) + offset);
return nlh->nlmsg_len;
}
/////////////////////////////////////////////////////////////////////////////
// KSyncIoContext routines
/////////////////////////////////////////////////////////////////////////////
KSyncIoContext::KSyncIoContext(KSyncEntry *sync_entry, int msg_len, char *msg,
uint32_t seqno, KSyncEntry::KSyncEvent event) :
IoContext(msg, msg_len, seqno, KSyncSock::GetAgentSandeshContext(),
IoContext::DEFAULT_Q_ID), entry_(sync_entry), event_(event) {
}
void KSyncIoContext::Handler() {
if (KSyncObject *obj = entry_->GetObject()) {
obj->NetlinkAck(entry_, event_);
}
}
void KSyncIoContext::ErrorHandler(int err) {
entry_->ErrorHandler(err, GetSeqno());
}
/////////////////////////////////////////////////////////////////////////////
// Routines for KSyncBulkSandeshContext
/////////////////////////////////////////////////////////////////////////////
KSyncBulkSandeshContext::KSyncBulkSandeshContext() :
AgentSandeshContext(), vr_response_count_(0), io_context_list_it_(),
io_context_list_() {
}
KSyncBulkSandeshContext::KSyncBulkSandeshContext
(const KSyncBulkSandeshContext &rhs) :
AgentSandeshContext(), vr_response_count_(0), io_context_list_it_(),
io_context_list_() {
}
struct IoContextDisposer {
void operator() (IoContext *io_context) { delete io_context; }
};
KSyncBulkSandeshContext::~KSyncBulkSandeshContext() {
assert(vr_response_count_ == io_context_list_.size());
io_context_list_.clear_and_dispose(IoContextDisposer());
}
void KSyncBulkSandeshContext::Insert(IoContext *ioc) {
io_context_list_.push_back(*ioc);
return;
}
void KSyncBulkSandeshContext::Data(KSyncBufferList *iovec) {
IoContextList::iterator it = io_context_list_.begin();
while (it != io_context_list_.end()) {
iovec->push_back(buffer(it->GetMsg(), it->GetMsgLen()));
it++;
}
}
// Sandesh responses for old context are done. Check for any errors
void KSyncBulkSandeshContext::IoContextDone() {
IoContext *io_context = &(*io_context_list_it_);
AgentSandeshContext *sandesh_context = io_context->GetSandeshContext();
sandesh_context->set_ksync_io_ctx(NULL);
if (sandesh_context->GetErrno() != 0) {
io_context->ErrorHandler(sandesh_context->GetErrno());
}
io_context->Handler();
}
void KSyncBulkSandeshContext::IoContextStart() {
vr_response_count_++;
IoContext &io_context = *io_context_list_it_;
AgentSandeshContext *sandesh_context = io_context.GetSandeshContext();
sandesh_context->set_ksync_io_ctx
(static_cast<KSyncIoContext *>(&io_context));
}
// Process the sandesh messages
// There can be more then one sandesh messages in the netlink buffer.
// Iterate and process all of them
bool KSyncBulkSandeshContext::Decoder(char *data, uint32_t len,
uint32_t alignment, bool more) {
DecodeSandeshMessages(data, len, this, alignment);
assert(io_context_list_it_ != io_context_list_.end());
if (more == true)
return false;
IoContextDone();
// No more netlink messages. Validate that iterator points to last element
// in IoContextList
io_context_list_it_++;
assert(io_context_list_it_ == io_context_list_.end());
return true;
}
void KSyncBulkSandeshContext::SetErrno(int err) {
AgentSandeshContext *context = GetSandeshContext();
context->SetErrno(err);
}
AgentSandeshContext *KSyncBulkSandeshContext::GetSandeshContext() {
assert(vr_response_count_);
return io_context_list_it_->GetSandeshContext();
}
void KSyncBulkSandeshContext::IfMsgHandler(vr_interface_req *req) {
AgentSandeshContext *context = GetSandeshContext();
context->IfMsgHandler(req);
}
void KSyncBulkSandeshContext::NHMsgHandler(vr_nexthop_req *req) {
AgentSandeshContext *context = GetSandeshContext();
context->NHMsgHandler(req);
}
void KSyncBulkSandeshContext::RouteMsgHandler(vr_route_req *req) {
AgentSandeshContext *context = GetSandeshContext();
context->RouteMsgHandler(req);
}
void KSyncBulkSandeshContext::MplsMsgHandler(vr_mpls_req *req) {
AgentSandeshContext *context = GetSandeshContext();
context->MplsMsgHandler(req);
}
// vr_response message is treated as delimiter in a bulk-context. So, move to
// next io-context within bulk-message context.
int KSyncBulkSandeshContext::VrResponseMsgHandler(vr_response *resp) {
AgentSandeshContext *sandesh_context = NULL;
// If this is first vr_reponse received, move io-context to first entry in
// bulk context