-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKVServer.cpp
More file actions
1013 lines (808 loc) · 42.7 KB
/
KVServer.cpp
File metadata and controls
1013 lines (808 loc) · 42.7 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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <vector>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <wait.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <unistd.h>
#include <unordered_map>
#include <string>
#include "storageManager.hpp"
using namespace std;
// States codes for GET, PUT and DEL requests as well as for SUCCESS and ERROR responses
enum STATUS_CODES {GET_STATUS_CODE = 1, PUT_STATUS_CODE = 2, DEL_STATUS_CODE = 3, LRU_CACHE = 4, LFU_CACHE = 5, SUCCESS_STATUS_CODE = 200, ERROR_STATUS_CODE = 240};
// Defining the name of server configuration file
#define SERVER_CONFIG_FILE "server.config"
// Message length (in bytes)
#define MESSAGE_LENGTH 513
// Key/Value maximum length (in bytes)
#define KEY_VALUE_MAX_LENGTH 256
// Key-Value Cache
unordered_map<string, KeyValueEntry> keyValueCache;
// Maintains the cache blocks in least recently used
vector<KeyValueEntry> leastRecentlyUsedTracker;
// This structure defines the information a worker thread needs about a client
typedef struct client_info
{
int connectionFD; // Holds the file descriptor returned by accept call
struct sockaddr_in addr;
struct sockaddr_in client;
socklen_t addrlen;
}ClientInfo;
// This structure will be used to pass the necessary arguments on thread creation
struct worker_args
{
int pendingRequestsQueueIndex;
};
// These values will be replaced by the ones present in the server.config file
int SERVER_LISTENING_PORT = -1; // Port number on which the server is listening
int INITIAL_THREAD_POOL_SIZE = -1; // Initial number of threads in the thread pool
int THREAD_QUEUE_SIZE = -1; // Maximum number of clients a thread can support
int THREAD_POOL_GROWTH_SIZE = -1; // Number of new threads to be added to the thread pool if it becomes full
int NUMBER_OF_ENTRIES_IN_CACHE = -1; // Number of entries that can be present in the cache at a time
int CACHE_REPLACEMENT_POLICY = -1; // Indicates which cache replacement policy to use while replacing an entry in the cache
// This vector holds the pending accepted connections to be handled by each worker thread.
vector<vector<ClientInfo *> > pendingRequestsQueue;
// This vector holds the number of clients each thread is handling
vector<int> liveClientCounter;
// Reader-Writer Lock to protect LRU entries tracker (leastRecentlyUsedTracker vector) from concurrent execution effects
pthread_rwlock_t lockLRUTracker;
// Defining mutexes for files
vector<pthread_mutex_t> fileLock(256);
// Server ready indicator
int isServerReady = 0;
// Each worker thread will execute this function
void *worker_thread(void *workerArgs)
{
struct worker_args *workerThreadArgs = (struct worker_args *) workerArgs;
int positionInQueueVector = workerThreadArgs->pendingRequestsQueueIndex;
char buffer[MESSAGE_LENGTH];
// Setting up epoll context
struct epoll_event events[THREAD_QUEUE_SIZE];
int ePollFD = epoll_create(THREAD_QUEUE_SIZE);
// Continuously adding new connections to the context (if any) and monitoring the epoll context
while (1)
{
if (pendingRequestsQueue[positionInQueueVector].empty() == 0)
{
while (pendingRequestsQueue[positionInQueueVector].empty() == 0)
{
static struct epoll_event ev;
// Reading then connection info from the queue
ClientInfo *tempInfo = pendingRequestsQueue[positionInQueueVector].front();
ev.data.fd = tempInfo->connectionFD;
ev.events = EPOLLIN;
epoll_ctl(ePollFD, EPOLL_CTL_ADD, ev.data.fd, &ev);
// Removing the entry from pending requests queue
pendingRequestsQueue[positionInQueueVector].erase(pendingRequestsQueue[positionInQueueVector].begin());
}
}
int nfds = epoll_wait(ePollFD, events, THREAD_QUEUE_SIZE, NULL);
//cout << "Alright " << ePollFD << endl;
for (int i = 0; i < nfds; i++)
{
memset(buffer, 0, MESSAGE_LENGTH);
int n = read(events[i].data.fd, buffer, MESSAGE_LENGTH);
if (n == 0)
{
// The client has disconnected so we officially close the connection
close(events[i].data.fd);
continue;
}
else
{
char responseMessage[MESSAGE_LENGTH];
// This is done to make the padding process easy
for (int j = 0; j < MESSAGE_LENGTH; j++)
{
responseMessage[j] = '\0';
}
// Fetching the status code from the request message
int statusCode = buffer[0] & 255;
if (statusCode == GET_STATUS_CODE)
{
// This means that the request is a 'GET' request
char key[KEY_VALUE_MAX_LENGTH + 1];
key[KEY_VALUE_MAX_LENGTH] = '\0';
// Fetching key from the request message stored in the buffer
for (int j = 0; j < KEY_VALUE_MAX_LENGTH; j++)
{
key[j] = buffer[j + 1];
}
string keyString(key);
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Checking whether the key exists in the cache or not
if (keyValueCache.count(keyString) > 0)
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// This means that the key exists in the cache, so we send the corresponding value
responseMessage[0] = SUCCESS_STATUS_CODE;
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Fetching the entry corresponding to the key from the cache
KeyValueEntry keyValueEntry = keyValueCache[keyString];
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
for (int j = 0; j < strlen(keyValueEntry.value); j++)
{
responseMessage[KEY_VALUE_MAX_LENGTH + 1 + j] = keyValueEntry.value[j];
}
// Adjusting the least recently used vector
int j;
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Finding the key-value entry and incrementing its reference count
for (int k = 0; k < leastRecentlyUsedTracker.size(); k++)
{
string tempString(leastRecentlyUsedTracker[k].key);
if (tempString == keyString)
{
j = k;
leastRecentlyUsedTracker[k].frequency += 1;
break;
}
}
// Based on the reference count, adjusting it's position in the vector
for (; j < leastRecentlyUsedTracker.size() - 1; j++)
{
KeyValueEntry temp = leastRecentlyUsedTracker[j + 1];
leastRecentlyUsedTracker[j + 1] = leastRecentlyUsedTracker[j];
leastRecentlyUsedTracker[j] = temp;
}
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// If the key doesn't exist in the cache, then we search for it in the persistent storage
int fileNameInt = keyString.at(0);
// Acquiring the file lock
pthread_mutex_lock(&fileLock[fileNameInt]);
// Searching for the key-value entry on the persistent storage
KeyValueEntry *entryFromStorage = search_on_storage(keyString);
// Releasing the file lock
pthread_mutex_unlock(&fileLock[fileNameInt]);
if (entryFromStorage == NULL)
{
// The key doesn't exist on the persistent storage as well, so we send an error message
responseMessage[0] = ERROR_STATUS_CODE;
// Sending the response to the client indicating that an error has occurred
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else
{
responseMessage[0] = SUCCESS_STATUS_CODE;
// The key exists in the persistent storage, we now insert it into the cache
if (leastRecentlyUsedTracker.size() == NUMBER_OF_ENTRIES_IN_CACHE)
{
// Need to replace a key-value entry in the cache
if (CACHE_REPLACEMENT_POLICY == LFU_CACHE)
{
// Follow the LFU Replacement Policy (if required)
int minFreqIndex = 0;
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Checking for the key-value entry which is referenced least number of times
for (int j = 1; j < leastRecentlyUsedTracker.size(); j++)
{
if (leastRecentlyUsedTracker[j].frequency < leastRecentlyUsedTracker[minFreqIndex].frequency)
{
minFreqIndex = j;
}
}
string minFreqStr(leastRecentlyUsedTracker[minFreqIndex].key);
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Removing the entry from the cache
keyValueCache.erase(minFreqStr);
leastRecentlyUsedTracker.erase(leastRecentlyUsedTracker.begin() + minFreqIndex);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = entryFromStorage->key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = entryFromStorage->value[j];
}
delete entryFromStorage;
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Adding the key-value entry to the cache
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting the value corresponding to the key in the response message
for (int j = 0; j < strlen(newEntry.value); j++)
{
responseMessage[KEY_VALUE_MAX_LENGTH + 1 + j] = newEntry.value[j];
}
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else
{
// Follow the LRU Replacement Policy
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// The first entry is the least recently used
KeyValueEntry entryToBeRemoved = leastRecentlyUsedTracker[0];
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
string entryToBeRemovedStr(entryToBeRemoved.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Removing the key-value entry from the cache
keyValueCache.erase(entryToBeRemovedStr);
leastRecentlyUsedTracker.erase(leastRecentlyUsedTracker.begin());
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = entryFromStorage->key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = entryFromStorage->value[j];
}
delete entryFromStorage;
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Inserting the key-value entry into the cache
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting the value corresponding to the key in the response message
for (int j = 0; j < strlen(newEntry.value); j++)
{
responseMessage[KEY_VALUE_MAX_LENGTH + 1 + j] = newEntry.value[j];
}
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
}
else
{
// No need to replace a key-value entry in the cache
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = entryFromStorage->key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = entryFromStorage->value[j];
}
delete entryFromStorage;
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Inserting the key-value entry into the cache
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting the value corresponding to the key in the response message
for (int j = 0; j < strlen(newEntry.value); j++)
{
responseMessage[KEY_VALUE_MAX_LENGTH + 1 + j] = newEntry.value[j];
}
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
}
}
}
else if (statusCode == PUT_STATUS_CODE)
{
// This means that the request is a 'PUT' request
char key[KEY_VALUE_MAX_LENGTH + 1];
char value[KEY_VALUE_MAX_LENGTH + 1];
key[KEY_VALUE_MAX_LENGTH] = '\0';
value[KEY_VALUE_MAX_LENGTH] = '\0';
// Fetching key from the request message stored in the buffer
for (int j = 0; j < KEY_VALUE_MAX_LENGTH; j++)
{
key[j] = buffer[j + 1];
}
// Fetching value from the request message stored in the buffer
for (int j = 0; j < KEY_VALUE_MAX_LENGTH; j++)
{
value[j] = buffer[KEY_VALUE_MAX_LENGTH + 1 + j];
}
string keyString(key);
string valueString(value);
int fileNameInt = keyString.at(0);
//Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Checking whether the key already exists in the storage or not
if (keyValueCache.count(keyString) > 0)
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Key exists in the cache, so update its corresponding value
for (int j = 0; j < 257; j++)
{
keyValueCache[keyString].value[j] = value[j];
}
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// Updating the value in the persistent storage as well
KeyValueEntry *newEntry = new KeyValueEntry;
newEntry->frequency = 0;
newEntry->isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry->key[j] = key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry->value[j] = value[j];
}
// Acquiring the file lock
pthread_mutex_lock(&fileLock[fileNameInt]);
// Updating the key-value entry on the persistent storage
insert_on_storage(newEntry);
// Releasing the file lock
pthread_mutex_unlock(&fileLock[fileNameInt]);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Incrementing the key-value entry reference count
for (int k = 0; k < leastRecentlyUsedTracker.size(); k++)
{
string tempString(leastRecentlyUsedTracker[k].key);
if (tempString == keyString)
{
leastRecentlyUsedTracker[k].frequency += 1;
break;
}
}
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
delete newEntry;
}
else
{
// Key doesn't exist in the cache, so we insert/update the key in persistent storage first
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
KeyValueEntry *newEntryToBeInserted = new KeyValueEntry;
newEntryToBeInserted->frequency = 0;
newEntryToBeInserted->isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntryToBeInserted->key[j] = key[j];
}
for (int j = 0; j < 257; j++)
{
newEntryToBeInserted->value[j] = value[j];
}
// Acquiring the file lock
pthread_mutex_lock(&fileLock[fileNameInt]);
// Inserting the key-value entry into the persistent storage
insert_on_storage(newEntryToBeInserted);
// Releasing the file lock
pthread_mutex_unlock(&fileLock[fileNameInt]);
delete newEntryToBeInserted;
if (leastRecentlyUsedTracker.size() == NUMBER_OF_ENTRIES_IN_CACHE)
{
// Need to replace a key-value entry in the cache
if (CACHE_REPLACEMENT_POLICY == LFU_CACHE)
{
// Follow the LFU Replacement Policy
int minFreqIndex = 0;
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Checking the key-value entry which has been referenced least number of times
for (int j = 1; j < leastRecentlyUsedTracker.size(); j++)
{
if (leastRecentlyUsedTracker[j].frequency < leastRecentlyUsedTracker[minFreqIndex].frequency)
{
minFreqIndex = j;
}
}
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
string minFreqStr(leastRecentlyUsedTracker[minFreqIndex].key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Removing the least referenced entry from the cache
keyValueCache.erase(minFreqStr);
leastRecentlyUsedTracker.erase(leastRecentlyUsedTracker.begin() + minFreqIndex);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = value[j];
}
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Inserting the key-value pair into the cache
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
}
else
{
// Follow the LRU Replacement Policy
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// The first entry is the least recently used
KeyValueEntry entryToBeRemoved = leastRecentlyUsedTracker[0];
string entryToBeRemovedStr(entryToBeRemoved.key);
// Removing from the cache
keyValueCache.erase(entryToBeRemovedStr);
// Removing from the vector
leastRecentlyUsedTracker.erase(leastRecentlyUsedTracker.begin());
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = value[j];
}
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Inserting the key-value entry into the cache
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
}
}
else
{
// No need to replace a key-value entry in the cache
// Inserting new entry into the cache and vector
KeyValueEntry newEntry;
newEntry.frequency = 1;
newEntry.isValid = 1;
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = '\0';
newEntry.value[j] = '\0';
}
for (int j = 0; j < 257; j++)
{
newEntry.key[j] = key[j];
}
for (int j = 0; j < 257; j++)
{
newEntry.value[j] = value[j];
}
string newEntryStr(newEntry.key);
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
keyValueCache.insert({newEntryStr, newEntry});
leastRecentlyUsedTracker.push_back(newEntry);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
}
}
// Indicating successful insertion/updation in our response message
responseMessage[0] = SUCCESS_STATUS_CODE;
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else if (statusCode == DEL_STATUS_CODE)
{
// This means that the request is a 'DEL' request
char key[KEY_VALUE_MAX_LENGTH + 1];
key[KEY_VALUE_MAX_LENGTH] = '\0';
// Fetching key from the request message stored in the buffer
for (int j = 0; j < KEY_VALUE_MAX_LENGTH; j++)
{
key[j] = buffer[j + 1];
}
string keyString(key);
int fileNameInt = keyString.at(0);
// Acquiring the file lock
pthread_mutex_lock(&fileLock[fileNameInt]);
// Deleting the key-value entry from the persistent storage (if it exists)
int deletionStatus = delete_from_storage(keyString);
// Releasing the file lock
pthread_mutex_unlock(&fileLock[fileNameInt]);
// Acquiring the reader lock
pthread_rwlock_rdlock(&lockLRUTracker);
// Checking whether the key exists in the cache or not
if (keyValueCache.count(keyString) > 0)
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
int delIndex;
// Acquiring the writer lock
pthread_rwlock_wrlock(&lockLRUTracker);
// Removing the key-value pair from the vector
for (int k = 0; k < leastRecentlyUsedTracker.size(); k++)
{
string tempString(leastRecentlyUsedTracker[k].key);
if (tempString == keyString)
{
delIndex = k;
break;
}
}
leastRecentlyUsedTracker.erase(leastRecentlyUsedTracker.begin() + delIndex);
// Removing the key-value pair from the cache
keyValueCache.erase(keyString);
// Releasing the writer lock
pthread_rwlock_unlock(&lockLRUTracker);
// Indicates that the deletion is successful in response message
responseMessage[0] = SUCCESS_STATUS_CODE;
// Sending the response to the client
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else if (deletionStatus == 0)
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
// If the key doesn't exist, then send a response indicating error
responseMessage[0] = ERROR_STATUS_CODE;
// Sending the response to the client indicating that an error has occurred
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
else
{
// Releasing the reader lock
pthread_rwlock_unlock(&lockLRUTracker);
responseMessage[0] = ERROR_STATUS_CODE;
// Sending the response to the client indicating that an error has occurred
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
//pthread_mutex_unlock(&lockLRUTracker);
}
else
{
// Invalid request
responseMessage[0] = ERROR_STATUS_CODE;
// Sending the response to the client indicating that an error has occurred
int m = write(events[i].data.fd, responseMessage, MESSAGE_LENGTH);
}
}
}
}
}
/* Used for performance analysis
struct timespec start,finish;
double elapsed;
void print_throughput(int sig)
{
clock_gettime(CLOCK_MONOTONIC, &finish);
// Calculating the total time and throughput
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
double throughput = (double) (120000/elapsed);
printf("\n\nTotal time to process 60000 requests is %f and throughput is %f\n", elapsed, throughput);
exit(1);
}
*/
int main(int argc, char *argv[])
{
//signal(SIGINT, print_throughput);
// Initializing the reader-writer lock for LRU entries tracker (leastRecentlyUsedTracker vector)
pthread_rwlock_init(&lockLRUTracker, NULL);
// Initializing the file locks
for (int i = 0; i < 256; i++)
{
pthread_mutex_init(&fileLock[i], NULL);
}
// Reading initial parameters from server configuration file
FILE *serverConfigFile = fopen(SERVER_CONFIG_FILE, "r");
char *temp = NULL;
size_t len = 0;
ssize_t numberOfLinesRead;
while ((numberOfLinesRead = getline(&temp, &len, serverConfigFile)) != -1)
{
char *configParameter = strtok(temp, "=");
char *parameterValue = strtok(NULL, "=");
if (strcmp(configParameter, "PORT_NUMBER") == 0)
{
SERVER_LISTENING_PORT = atoi(parameterValue);
}
else if (strcmp(configParameter, "INITIAL_THREAD_POOL_SIZE") == 0)
{
INITIAL_THREAD_POOL_SIZE = atoi(parameterValue);
}
else if (strcmp(configParameter, "THREAD_QUEUE_SIZE") == 0)
{
THREAD_QUEUE_SIZE = atoi(parameterValue);
}
else if (strcmp(configParameter, "THREAD_POOL_GROWTH_SIZE") == 0)
{
THREAD_POOL_GROWTH_SIZE = atoi(parameterValue);
}
else if (strcmp(configParameter, "NUMBER_OF_ENTRIES_IN_CACHE") == 0)
{
NUMBER_OF_ENTRIES_IN_CACHE = atoi(parameterValue);
cout << "Number of entries: " << NUMBER_OF_ENTRIES_IN_CACHE << endl;
}
else if (strcmp(configParameter, "CACHE_REPLACEMENT_POLICY") == 0)
{
if (strcmp(parameterValue, "LFU\n") == 0)
{
CACHE_REPLACEMENT_POLICY = LFU_CACHE;
cout << "LFU " << endl;
}
else
{
CACHE_REPLACEMENT_POLICY = LRU_CACHE;
cout << "LRU " << endl;
}
}
}
// Setting up server socket and connection handling
struct sockaddr_in addr;
int sockFD;
int y = 1;
sockFD = socket(AF_INET, SOCK_STREAM, 0);
if (sockFD < 0)
{
printf("\nError opening socket!\n");
exit(1);
}
if (setsockopt(sockFD, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int)) == -1)
{
printf("\nError: Setsockopt error. Please restart the server!\n");
exit(1);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(SERVER_LISTENING_PORT);
addr.sin_addr.s_addr = INADDR_ANY;
/*
* ------------------------------Setting up the thread pool------------------------------
* This step involves creating the initial number of threads specified in the config file.
*/
vector<pthread_t> threadPool(INITIAL_THREAD_POOL_SIZE);
for (int i = 0; i < INITIAL_THREAD_POOL_SIZE; i++)
{
vector<ClientInfo *> temp;
pendingRequestsQueue.push_back(temp);
pendingRequestsQueue[pendingRequestsQueue.size() - 1].clear();
liveClientCounter.push_back(0);
struct worker_args *workerArgs = (struct worker_args *) malloc(sizeof(struct worker_args));
workerArgs->pendingRequestsQueueIndex = i;
int threadCreateStatus = pthread_create(&threadPool[i], NULL, worker_thread, (void *) workerArgs);
if (threadCreateStatus != 0)
{
printf("ERROR. Unable to create the thread!\n");
exit(-1);
}
}
bind(sockFD, (struct sockaddr *) &addr, sizeof(addr));
listen(sockFD, INITIAL_THREAD_POOL_SIZE*THREAD_QUEUE_SIZE);
// Used to decide which thread will handle a particular connnection request.
int WORKER_THREAD_TURN = 0;
//int firstTime = 0;
while (1)
{
ClientInfo *newClient = (ClientInfo *) malloc(sizeof(ClientInfo));
newClient->addr = addr;
memset(&newClient->client, 0, sizeof(newClient->client));
newClient->addrlen = sizeof(newClient->client);
newClient->connectionFD = accept(sockFD, (struct sockaddr *) &newClient->client, &newClient->addrlen);
if (newClient->connectionFD < 0)
{
printf("\nServer accept error. Please restart the server!\n");
exit(1);
}
pendingRequestsQueue[WORKER_THREAD_TURN].push_back(newClient);
liveClientCounter[WORKER_THREAD_TURN] += 1;
/*
if (!firstTime)
{
clock_gettime(CLOCK_MONOTONIC, &start);
firstTime = 1;
}
*/
/* Incrementing it since we have to assign connection requests to threads in round-robin
* manner. */
WORKER_THREAD_TURN = (WORKER_THREAD_TURN + 1) % pendingRequestsQueue.size();
// Checking whether the queue of all threads has become full or not
int threadPoolFull = 1;
for (int i = 0; i < liveClientCounter.size(); i++)
{
if (liveClientCounter[i] < THREAD_QUEUE_SIZE)
{
threadPoolFull = 0;
break;
}
}
// If thread pool has reached its maximum capacity, we add more threads into the pool
if (threadPoolFull)
{
int oldSize = threadPool.size();
threadPool.resize(oldSize + THREAD_POOL_GROWTH_SIZE);
for (int i = 0; i < THREAD_POOL_GROWTH_SIZE; i++)
{
int positionIndex = oldSize + i;
vector<ClientInfo *> temp;
pendingRequestsQueue.push_back(temp);
liveClientCounter.push_back(0);