Repository navigation
Expand file tree
/
Copy pathcp_node.cc
More file actions
3765 lines (3453 loc) · 106 KB
/
Copy pathcp_node.cc
File metadata and controls
3765 lines (3453 loc) · 106 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
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) 2019-2023 Homa Developers
* SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0+
*/
/* This file contains a program that runs on one node, as part of
* the cluster_perf test.
*/
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <algorithm>
#include <atomic>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <optional>
#include <random>
#include <thread>
#include <vector>
#include "dist.h"
extern "C" {
#include "homa.h"
}
#include "homa_receiver.h"
#include "test_utils.h"
#include "time_trace.h"
using std::string;
/* Command-line parameter values (note: changes to default values must
* also be reflected in client and server constructors): */
uint32_t client_max = 1;
uint32_t client_port_max = 1;
int client_ports = 0;
int first_port = -1;
bool is_server = false;
int node_id = -1;
double net_gbps = 0.0;
bool tcp_trunc = true;
bool one_way = false;
int port_receivers = 1;
int port_threads = 1;
std::string protocol_string;
const char *protocol = "homa";
int server_ports = 1;
bool verbose = false;
std::string workload_string;
const char *workload = "100";
int unloaded = 0;
bool client_iovec = false;
bool server_iovec = false;
int inet_family = AF_INET;
int server_core = -1;
int buf_bpages = 1000;
/* Node ids for client to send requests to. */
std::vector<int> server_ids;
/** @rand_gen: random number generator. */
static std::mt19937 rand_gen(
std::chrono::system_clock::now().time_since_epoch().count());
/**
* struct conn_id - A 32-bit value that encodes a unique connection
* between a TCP client and server.
*/
struct conn_id {
/**
* @client_port: the index (starting at 0) of the port within
* the client (corresponds to a particular sending thread).
* This will be the low byte returned by int().
*/
uint8_t client_port;
/** @client: the node index for the client (starts from zero). */
uint8_t client;
/**
* @server_port: the index (starting at 0) of a particular port
* within the server.
*/
uint8_t server_port;
/** @server: the node index for the server (starts from 0). */
uint8_t server;
conn_id(uint8_t server, uint8_t server_port, uint8_t client,
uint8_t client_port)
: client_port(client_port), client(client),
server_port(server_port), server(server)
{}
conn_id()
: client_port(0), client(0), server_port(0), server(0)
{}
inline operator int()
{
return *(reinterpret_cast<int *>(this));
}
};
/** @message_id: used to generate unique identifiers for outgoing messages.*/
std::atomic<uint32_t> message_id;
/**
* @experiments: names of all known experiments (may include some that are
* no longer in use)
*/
std::vector<std::string> experiments;
/**
* @last_stats_time: time (in rdtsc cycles) when we last printed
* statistics. Zero means that none of the statistics below are valid.
*/
uint64_t last_stats_time = 0;
/**
* @last_client_rpcs: entries correspond to @experiments; total number of
* client RPCs completed by that experiment as of the last time we printed
* statistics.
*/
std::vector<uint64_t> last_client_rpcs;
/**
* @last_client_bytes_out: entries correspond to @experiments; total amount
* of data sent in request messages by client RPCs in that experiment as
* of the last time we printed statistics.
*/
std::vector<uint64_t> last_client_bytes_out;
/**
* @last_client_bytes_in: entries correspond to @experiments; total
* amount of data received in response messages for client RPCs in that
* experiment as of the last time we printed statistics.
*/
std::vector<uint64_t> last_client_bytes_in;
/**
* @last_total_rtt: entries correspond to @experiments; total amount of
* elapsed time for all client RPCs in that experiment (units of rdtsc cycles)
* as of the last time we printed statistics.
*/
std::vector<uint64_t> last_total_rtt;
/**
* @last_lag: entries correspond to @experiments; total lag (measured in rdtsc
* cycles) for all clients in that experiment, as of the last time we printed
* statistics.
*/
std::vector<uint64_t> last_lag;
/**
* @last_backups: entries correspond to @experiments; total # of backed-up
* sends for client RPCs issued by that experiment as of the last time we
* printed statistics.
*/
std::vector<uint64_t> last_backups;
/**
* @last_server_rpcs: entries correspond to @experiments; total # of server
* RPCs handled by that experiment as of the last time we printed statistics.
*/
std::vector<uint64_t> last_server_rpcs;
/**
* @last_server_bytes_in: entries correspond to @experiments; total amount
* of data in incoming requests handled by that experiment as of the last
* time we printed statistics.
*/
std::vector<uint64_t> last_server_bytes_in;
/**
* @last_server_bytes_out: entries correspond to @experiments; total amount
* of data in responses sent by that experiment as of the last time we printed
* statistics.
*/
std::vector<uint64_t> last_server_bytes_out;
/**
* @last_per_server_rpcs: server->requests for each individual server,
* as of the last time we printed statistics.
*/
std::vector<uint64_t> last_per_server_rpcs;
/** @log_file: where log messages get printed. */
FILE* log_file = stdout;
enum Msg_Type {NORMAL, VERBOSE};
/** @log_level: only print log messages if they have a level <= this value. */
Msg_Type log_level = NORMAL;
extern void log(Msg_Type type, const char *format, ...)
__attribute__((format(printf, 2, 3)));
/**
* @cmd_lock: held whenever a command is executing. Used to ensure that
* operations such as statistics printing don't run when commands such
* as "stop" are changing the client or server structure.
*/
std::mutex cmd_lock;
/**
* @fd_locks: used to synchronize concurrent accesses to the same fd
* (indexed by fd).
*/
#define MAX_FDS 100000
std::atomic_bool fd_locks[MAX_FDS];
/**
* @kfreeze_count: number of times that kfreeze has been evoked since
* the last time a client was created; used to eliminate redundant
* freezes that waste time.
*/
int kfreeze_count = 0;
/**
* @debug: values set with the "debug" command; typically used to
* trigger various debugging behaviors.
*/
int64_t debug[5];
/**
* fatal() - Invoked when fatal errors occur: exits the application.
*/
void fatal()
{
fflush(stdout);
fflush(stderr);
_exit(1);
}
/**
* print_help() - Print out usage information for this program.
* @name: Name of the program (argv[0])
*/
void print_help(const char *name)
{
printf("Usage: cp_node [command]\n\n"
"If there are command-line options, they constitute a single command\n"
"to execute, after which cp_node will print statistics every second.\n\n"
"If there are no command-line options, then cp_node enters a loop reading\n"
"lines from standard input and executing them as commands. The following\n"
"commands are supported, each followed by a list of options supported\n"
"by that command:\n\n"
"client [options] Start one or more client threads\n");
printf(" --buf-bpages Number of bpages to allocate in the buffer poool for\n"
" incoming messages (default: %d)\n",
buf_bpages);
printf(" --client-max Maximum number of outstanding requests from a single\n"
" client machine (divided equally among client ports)\n"
" (default: %d)\n", client_max);
printf(" --exp Name of the experiment in which these client threads\n");
printf(" will be participating; used to label measurement data\n");
printf(" (defaults to <protocol>_<workload>)\n");
printf(" --first-port Lowest port number to use for each server (default: \n");
printf(" 4000 for Homa, 5000 for TCP)\n");
printf(" --first-server Id of first server node (default: 1, meaning node1)\n");
printf(" --gbps Target network utilization, including only message data,\n"
" Gbps; 0 means send continuously (default: %.1f)\n",
net_gbps);
printf(" --id Id of this node; a value of I >= 0 means requests will\n"
" not be sent to nodeI (default: -1)\n");
printf(" --ipv6 Use IPv6 instead of IPv4\n");
printf(" --no-trunc For TCP, allow messages longer than Homa's limit\n");
printf(" --one-way Make all response messages 100 B, instead of the same\n"\
" size as request messages\n");
printf(" --ports Number of ports on which to send requests (one\n"
" sending thread per port (default: %d)\n",
client_ports);
printf(" --port-receivers Number of threads to listen for responses on each\n"
" port (default: %d). Zero means senders wait for their\n"
" own requests synchronously\n",
port_receivers);
printf(" --protocol Transport protocol to use: homa or tcp (default: %s)\n",
protocol);
printf(" --server-nodes Number of nodes running server threads (default: 1)\n");
printf(" --server-ports Number of server ports on each server node\n"
" (default: %d)\n",
server_ports);
printf(" --servers Comma-separated list of integer ids to use as server\n");
printf(" nodes; if specified, overrides --first-server and\n"
" --server-nodes\n");
printf(" --unloaded Nonzero means run test in special mode for collecting\n"
" baseline data, with the given number of measurements\n"
" per length in the distribution (Homa only, default: 0)\n");
printf(" --workload Name of distribution for request lengths (e.g., 'w1')\n"
" or integer for fixed length (default: %s)\n\n",
workload);
printf("debug value value ... Set one or more int64_t values that may be used for\n"
" various debugging purposes\n\n");
printf("dump_times file [exp] Log RTT times (and lengths) for clients running\n");
printf(" experiment exp to file; if exp is omitted, dump\n");
printf(" all RTTs\n\n");
printf("exit Exit the application\n\n");
printf("log [options] [msg] Configure logging as determined by the options. If\n"
" there is an \"option\" that doesn't start with \"--\",\n"
" then it and all of the remaining words are printed to\n"
" the log as a message.\n");
printf(" --file Name of log file where messages should be appended in the\n"
" future (\"-\" means use standard output)");
printf(" --level Log level: either normal or verbose\n\n");
printf("server [options] Start serving requests on one or more ports\n");
printf(" --buf-bpages Number of bpages to allocate in the buffer poool for\n"
" incoming messages (default: %d)\n",
buf_bpages);
printf(" --exp Name of the experiment in which these server ports\n");
printf(" will be participating; used to label measurement data\n");
printf(" (defaults to <protocol>_<workload>)\n");
printf(" --first-port Lowest port number to use (default: 4000 for Homa,\n");
printf(" 5000 for TCP)\n");
printf(" --iovec Use iovecs for reply instead of a single buffer\n");
printf(" --ipv6 Use IPv6 instead of IPv4\n");
printf(" --pin All server threads will be restricted to run only\n"
" on the givevn core\n");
printf(" --protocol Transport protocol to use: homa or tcp (default: %s)\n",
protocol);
printf(" --port-threads Number of server threads to service each port\n"
" (default: %d)\n",
port_threads);
printf(" --ports Number of ports to listen on (default: %d)\n\n",
server_ports);
printf("stop [options] Stop existing client and/or server threads; each\n"
" option must be either 'clients' or 'servers'\n\n");
printf(" tt [options] Manage time tracing:\n");
printf(" freeze Stop recording time trace information until\n"
" print has been invoked\n");
printf(" kfreeze Freeze the kernel's internal timetrace\n");
printf(" print file Dump timetrace information to file\n");
}
/**
* log() - Print a message to the current log file
* @type: Kind of message (NORMAL or VERBOSE); used to control degree of
* log verbosity
* @format: printf-style format string, followed by printf-style arguments.
*/
void log(Msg_Type type, const char *format, ...)
{
char buffer[1000];
struct timespec now;
va_list args;
if (type > log_level)
return;
va_start(args, format);
clock_gettime(CLOCK_REALTIME, &now);
vsnprintf(buffer, sizeof(buffer), format, args);
fprintf(log_file, "%010lu.%09lu %s", now.tv_sec, now.tv_nsec, buffer);
}
inline void parse_type(const char *s, char **end, int *value)
{
*value = strtol(s, end, 0);
}
inline void parse_type(const char *s, char **end, int64_t *value)
{
*value = strtoll(s, end, 0);
}
inline void parse_type(const char *s, char **end, double *value)
{
*value = strtod(s, end);
}
/**
* parse() - Parse a value of a particular type from an argument word.
* @words: Words of a command being parsed.
* @i: Index within words of a word expected to contain an integer
* value (may be outside the range of words, in which case an
* error message is printed).
* @value: The parsed value corresponding to @words[i] is stored here,
* if the function completes successfully.
* @format: Name of option being parsed (for use in error messages).
* @type_name: Human-readable name for ValueType (for use in error messages).
* Return: Nonzero means success, zero means an error occurred (and a
* message was printed).
*/
template<typename ValueType>
int parse(std::vector<string> &words, unsigned i, ValueType *value,
const char *option, const char *type_name)
{
ValueType num;
char *end;
if (i >= words.size()) {
printf("No value provided for %s\n", option);
return 0;
}
parse_type(words[i].c_str(), &end, &num);
if (*end != 0) {
printf("Bad value '%s' for %s; must be %s\n",
words[i].c_str(), option, type_name);
return 0;
}
*value = num;
return 1;
}
/**
* log_affinity() - Log a message listing the core affinity for the
* current thread.
*/
void log_affinity()
{
cpu_set_t cores;
if (sched_getaffinity(0, sizeof(cores), &cores) != 0) {
log(NORMAL, "ERROR: couldn't read core affinities: %s",
strerror(errno));
return;
}
int total = CPU_COUNT(&cores);
std::string list = "";
for (int i = 0; total > 0; i++) {
if (!CPU_ISSET(i, &cores))
continue;
total--;
if (!list.empty())
list.append(" ");
list.append(std::to_string(i));
}
log(NORMAL, "Core affinities: %s\n", list.c_str());
}
/**
* kfreeze() - Freeze the kernel-level timetrace.
*/
void kfreeze()
{
#ifndef __STRIP__ /* See strip.py */
kfreeze_count++;
if (kfreeze_count > 1)
return;
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_HOMA);
if (fd < 0) {
log(NORMAL, "ERROR: kfreeze couldn't open Homa socket: %s\n",
strerror(errno));
return;
}
if (ioctl(fd, HOMAIOCFREEZE, NULL) != 0)
log(NORMAL, "ERROR: HOMAIOCFREEZE ioctl failed: %s\n",
strerror(errno));
close(fd);
#endif /* See strip.py */
}
/**
* get_homa_error() - Return a string describing the most recent error
* detected by Homa for a socket (extracted with HOMAIOCINFO).
* @fd: File descriptor for a Homa socket.
* Return: The error string.
*/
std::string get_homa_error(int fd) {
struct homa_info hinfo;
std::string result;
int status;
hinfo.rpc_info = 0;
hinfo.rpc_info_length = 0;
status = ioctl(fd, HOMAIOCINFO, &hinfo);
if (status != 0) {
log(NORMAL, "HOMAIOCINFO failed for fd %d (%p): %s\n", fd,
&hinfo, strerror(errno));
result = "couldn't read Homa error message: HOMAIOCINFO failed";
} else {
result = hinfo.error_msg;
}
return result;
}
/**
* struct message_header - The first few bytes of each message (request or
* response) have the structure defined here. The client initially specifies
* this information in the request, and the server returns the information
* in the response.
*/
struct message_header {
/**
* @length: total number of bytes in the message, including this
* header.
*/
int32_t length;
/**
* @cid: uniquely identifies the connection between a client
* and a server.
*/
conn_id cid;
/**
* @msg_id: created by client, returned by server so client can
* match responses to requests; distinguishes among concurrent
* outstanding requests from a client. Not unique across all time.
*/
uint16_t msg_id;
/** @freeze: true means the recipient should freeze its time trace. */
unsigned int freeze:1;
/**
* @short_response: true means responses should only be 100 bytes,
* regardless of the request length.
*/
unsigned int short_response:1;
/**
* @response: nonzero means this is a response messages, zero means
* request
*/
unsigned int response:1;
unsigned int reserved:13;
};
/**
* class spin_lock - Implements simple spin lock guards: lock is acquired by
* constructor, released by destructor.
*/
class spin_lock {
public:
spin_lock(std::atomic_bool *mutex)
: mutex(mutex)
{
do {
/* mutex.exchange() always invalidates the cache line
* mutex resides in, regardless of whether it succeeded
* in updating the value. To reduce cache invalidation
* traffic, wait until we observe the lock to be free.
*/
while (mutex->load(std::memory_order_relaxed)) {
/* Do nothing */
}
} while (mutex->exchange(1, std::memory_order_acquire));
}
~spin_lock()
{
mutex->store(0, std::memory_order_release);
}
protected:
std::atomic_bool *mutex;
};
/**
* class tcp_connection - Handles the reading and writing of TCP messages
* from/to a given peer. Incoming messages may arrive in several chunks
* spaced out in time, and outgoing messages may have to be sent in
* multiple chunks because the stream backed up. This class keeps track
* of the state of partial messages.
*/
class tcp_connection {
public:
tcp_connection(int fd, uint32_t epoll_id, int port,
sockaddr_in_union peer);
size_t pending();
int read(bool loop, std::function<void (message_header *header)> func);
bool send_message(message_header *header);
void set_epoll_events(int epoll_fd, uint32_t events);
bool xmit();
/** @fd: File descriptor to use for reading and writing data. */
int fd;
/**
* @epoll_id: identifier for this connection, which will be stored
* in the u32 field of the data for epoll events for this
* connection. */
uint32_t epoll_id;
/**
* @port: Port number associated with this connection (listen port
* for servers, outgoing port for clients). Used for error messages.
*/
int port;
/**
* @peer: Address of the machine on the other end of this connection.
*/
sockaddr_in_union peer;
/**
* @bytes_received: nonzero means we have read part of an incoming
* request; the value indicates how many bytes have been received
* so far.
*/
int bytes_received;
/**
* @header: will eventually hold the first bytes of an incoming
* message. If @bytes_received is less than the size of this value,
* then it has not yet been fully read.
*/
message_header header;
/**
* @outgoing: queue of headers for messages waiting to be
* transmitted. The first entry may have been partially transmitted.
*/
std::deque<message_header> outgoing;
/*
* @bytes_sent: Nonzero means we have sent part of the first message
* in outgoing; the value indicates how many bytes have been
* successfully transmitted.
*/
int bytes_sent;
/**
* @epoll_events: OR-ed combination of epoll events such as EPOLLIN
* currently enabled for this connection.
*/
uint32_t epoll_events;
/**
* @error_message: holds human-readable error information after
* an error.
*/
char error_message[200];
};
/**
* tcp_connection:: tcp_connection() - Constructor for tcp_connection objects.
* @fd: File descriptor from which to read data.
* @epoll_id: Identifier to store in the u32 data field of epoll events
* for this connection.
* @port: Port number associated with this connection; used for messages.
* @peer: Address of the machine we're reading from; used for messages.
*/
tcp_connection::tcp_connection(int fd, uint32_t epoll_id, int port,
sockaddr_in_union peer)
: fd(fd)
, epoll_id(epoll_id)
, port(port)
, peer(peer)
, bytes_received(0)
, header()
, outgoing()
, bytes_sent(0)
, epoll_events(0)
{
}
/**
* pending() - Return a count of the number of messages currently
* waiting to be transmitted (nonzero means the connection is backed up).
*/
inline size_t tcp_connection::pending()
{
return outgoing.size();
}
/**
* tcp_connection::read() - Reads more data from a TCP connection and calls
* a function to handle complete messages, if any.
* @loop: If true, this function will read repeatedly from the
* socket, stopping only when there is no more data to read
* (the socket must be in nonblocking mode). If false, only
* one read call will be issued.
* @func: Function to call when there is a complete message; the argument
* to the function is a pointer to the standard header from the
* message. Func may be called multiple times in a single
* invocation of this method.
* Return: Zero means success; nonzero means the socket was closed
* by the peer, or there was an error; a human-readable message
* will be left in @error_message.
*/
int tcp_connection::read(bool loop,
std::function<void (message_header *header)> func)
{
char buffer[100000];
char *next;
while (1) {
int count = ::read(fd, buffer, sizeof(buffer));
if (count <= 0) {
if ((count < 0) && ((errno == EAGAIN)
|| (errno == EWOULDBLOCK)))
return 0;
if ((count == 0) || ((count < 0)
&& (errno == ECONNRESET))) {
/* Connection was closed by the client. */
snprintf(error_message, sizeof(error_message),
"TCP connection on port %d (fd %d) closed by peer %s",
port, fd, print_address(&peer));
return 1;
}
/* At this point count < 0. */
if (errno == EFAULT) {
/* As of 6/2020, the system call above
* sometimes returns EFAULT for no apparent
* reason (particularly under high load).
* Retrying seems to work...
*/
log(NORMAL, "WARNING: tcp_connect::read "
"retrying after EFAULT\n");
continue;
}
log(NORMAL, "ERROR: read failed for TCP connection on "
"port %d (fd %d) to %s: %s (%d)\n",
port, fd, print_address(&peer),
strerror(errno), errno);
snprintf(error_message, sizeof(error_message),
"Error reading from TCP connection on "
"port %d (fd %d) to %s: %s", port, fd,
print_address(&peer), strerror(errno));
return 1;
}
if ((count >= 4) && (strncmp(buffer, "GET ", 4) == 0)) {
/* It looks like someone is trying to make an HTTP
* connection to us; that's bogus.
*/
log(NORMAL, "ERROR: unexpected data received from "
"%s: %.*s\n", print_address(&peer),
count, buffer);
snprintf(error_message, sizeof(error_message),
"Unexpected data received from %s",
print_address(&peer));
return 1;
}
/*
* Process incoming bytes (could contains parts of multiple
* requests). The first 4 bytes of each request give its
* length.
*/
next = buffer;
while (count > 0) {
/* First, fill in the message header with incoming data
* (there's no guarantee that a single read will return
* all of the bytes needed for these).
*/
int header_bytes = sizeof32(message_header)
- bytes_received;
if (header_bytes > 0) {
if (count < header_bytes)
header_bytes = count;
char *dst = reinterpret_cast<char *>(&header);
memcpy(dst + bytes_received, next, header_bytes);
bytes_received += header_bytes;
next += header_bytes;
count -= header_bytes;
if (bytes_received < sizeof32(message_header)) {
tt("Received %d header bytes; need %d "
"more for complete "
"header", count,
sizeof32(message_header)
- bytes_received);
break;
}
}
if ((header.length > HOMA_MAX_MESSAGE_LENGTH)
|| (header.length < 0)) {
log(NORMAL, "ERROR: invalid message length %d "
"from %s, closing connection\n",
header.length,
print_address(&peer));
snprintf(error_message, sizeof(error_message),
"Invalid message length %d "
"from %s",
header.length,
print_address(&peer));
return 1;
}
/* At this point we know the request length, so read
* until we've got a full request.
*/
int needed = header.length - bytes_received;
if (count < needed) {
tt("Received %d bytes for cid 0x%08x, id %d; "
"need %d more for complete "
"message", count, header.cid,
header.msg_id, needed-count);
bytes_received += count;
break;
}
/* We now have a full message. */
count -= needed;
next += needed;
func(&header);
bytes_received = 0;
}
if (!loop)
return 0;
}
}
/**
* tcp_connection::set_epoll_events() - Convenience method to set events
* for epolling on this connection.
* @epoll_fd: File descriptor on which epoll events are collected and
* waited for.
* @event: OR-ed combination of EPOLLIN, EPOLLOUT, etc.
*/
void tcp_connection::set_epoll_events(int epoll_fd, uint32_t events)
{
struct epoll_event ev;
if (events == epoll_events)
return;
ev.events = events;
ev.data.u32 = epoll_id;
if (epoll_ctl(epoll_fd, (epoll_events == 0) ? EPOLL_CTL_ADD
: EPOLL_CTL_MOD, fd, &ev) < 0) {
log(NORMAL, "FATAL: couldn't add/modify epoll event: %s\n",
strerror(errno));
fatal();
}
epoll_events = events;
}
/**
* tcp_connection::send_message() - Begin the process of sending a message
* to a peer; the message may not be completely transmitted at the time this
* method returns.
* @header: Transmitted as the first bytes of the message.
* If the size isn't at least as large as the header,
* we'll round it up.
* Return: true means the message was completely transmitted; false means
* it has not been fully transmitted (xmit will need to be called later to
* finish the job).
*/
bool tcp_connection::send_message(message_header *header)
{
if (header->length < sizeof32(*header))
header->length = sizeof32(*header);
outgoing.emplace_back(*header);
if (outgoing.size() > 1)
return false;
return xmit();
}
/**
* tcp_connection::xmit() - Transmit as much data as possible on this
* connection.
* Return: true means all available data has been sent; false means
* there is data that couldn't be sent because the stream
* backed up.
*/
bool tcp_connection::xmit()
{
char buffer[100000];
struct message_header *header;
int start;
int send_length;
ssize_t result;
while (true) {
if (outgoing.size() == 0)
return true;
header = &outgoing[0];
if (bytes_sent < sizeof32(*header)) {
*(reinterpret_cast<message_header *>(buffer))
= *header;
start = bytes_sent;
} else
start = 0;
send_length = header->length - bytes_sent;
if (send_length > (sizeof32(buffer) - start))
send_length = sizeof32(buffer) - start;
result = send(fd, buffer + start, send_length,
MSG_NOSIGNAL|MSG_DONTWAIT);
if (result >= 0)
bytes_sent += result;
else {
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
return false;
if ((errno == EPIPE) || (errno == ECONNRESET))
bytes_sent = header->length;
else {
log(NORMAL, "FATAL: error sending TCP message "
"to %s: %s (port %d)\n",
print_address(&peer),
strerror(errno), port);
fatal();
}
}
if (bytes_sent < header->length) {
tt("Sent %d bytes (out of %d) on cid 0x%08x",
result, header->length, header->cid);
continue;
}
bytes_sent = 0;
tt("Finished sending TCP message, cid 0x%08x, id %d, length %d, "
"%u messages queued", header->cid,
header->msg_id, header->length,
outgoing.size() - 1);
outgoing.pop_front();
}
}
/**
* class server_metrics - Keeps statistics for a single server thread
* (i.e. all the requests arriving via one Homa port or one TCP listen
* socket).
*/
class server_metrics {
public:
/** @experiment: Name of experiment for this server thread */
std::string experiment;
/** @requests: Total number of requests handled so far. */
uint64_t requests;
/**
* @bytes_in: Total number of bytes of message data received by this
* server in requests.
*/
uint64_t bytes_in;
/**
* @bytes_out: Total number of bytes of message data sent by this
* server in responses.
*/
uint64_t bytes_out;
server_metrics(std::string& experiment) : experiment(experiment),
requests(0), bytes_in(0), bytes_out(0) {}
};
/**
* @metrics: keeps track of metrics for all servers (whether Homa or TCP).
* These are malloc-ed and must be freed eventually. This is a pointer so
* that it doesn't get destructed
*/
std::vector<server_metrics *> metrics;
/**
* class homa_server - Holds information about a single port used
* to receive incoming requests, including one or more threads that
* handle requests arriving via the port.
*/
class homa_server {
public:
homa_server(int port, int id, int inet_family, int num_threads,
std::string& experiment);
~homa_server();
void server(int thread_id, server_metrics *metrics);
/** @id: Unique identifier for this server among all Homa servers. */
int id;
/** @fd: File descriptor for a Homa socket. */
int fd;
/** @port: Homa port number managed by this object. */
int port;
/** @experiment: name of the experiment this server is running. */
string experiment;
/**
* @buf_region: mmapped region of memory in which receive buffers
* are alloocated.
*/
char *buf_region;
/** @buf_size: number of bytes available at @buf_region. */
size_t buf_size;
/** @threads: One or more threads that service incoming requests*/
std::vector<std::thread> threads;
};
/** @homa_servers: keeps track of all existing Homa servers. */
std::vector<homa_server *> homa_servers;