-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpfs_api.cpp
1248 lines (995 loc) · 37.1 KB
/
pfs_api.cpp
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 "pfs_config.hpp"
#include "pfs_api.hpp"
#include "pfs_common.hpp"
#include "pfs_client.pb.h"
#include "pfs_client.grpc.pb.h"
#include <grpcpp/grpcpp.h>
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using google::protobuf::Empty;
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
void RunServer();
map<int, string> fileservers;
map <string, fileopeninfo> fileinfos;
map<int, string> fdToFilenameMap;
map<int, vector<struct tokeninterval> > fdToReadTokensList;
map<int, vector<struct tokeninterval> > fdToWriteTokensList;
mutex tokenconsistency;
bool revocation = 1;
int client_id = -1;
int clientAsServer = 0;
int getmode(int fd) {
int mode = -1;
if (fdToFilenameMap.find(fd) != fdToFilenameMap.end()) {
string fname = fdToFilenameMap[fd];
return fileinfos[fname].mode;
}
return mode;
}
class FileClient {
public:
FileClient(std::shared_ptr<Channel> channel) : stub_(FileService::NewStub(channel)) {}
int isConnected() {
ClientContext context;
Empty response;
Dummy request;
Status status = stub_->isConnected(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int deleteFd(int fd) {
ClientContext context;
Empty response;
File request;
request.set_fd(fd);
Status status = stub_->deleteFd(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
string readData(int fd, ll blocknum) {
ClientContext context;
Blockinfo request; request.set_fd(fd); request.set_blocknum(blocknum);
Data response;
Status status = stub_->readData(&context, request, &response);
if (status.ok()) {
return response.data();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return "";
}
}
int writeDataSpecific(int fd, ll blocknum, string out, ll offset, ll size) {
ClientContext context;
DataSpecific request;
request.set_fd(fd); request.set_blocknum(blocknum);
request.set_data(out);
request.set_startoffset(offset);
request.set_size(size);
Empty response;
Status status = stub_->writeDataSpecific(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int writeData(struct CacheBlock cb, char * out) {
ClientContext context;
Data request;
request.set_fd(cb.fd); request.set_blocknum(cb.blocknum);
request.set_data(string(out));
Empty response;
Status status = stub_->writeData(&context, request, &response);
if (status.ok()) {
return 0;
} else {
////std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
private:
std::unique_ptr<FileService::Stub> stub_;
};
FileClient* fileclient[NUM_FILE_SERVERS];
struct Cache {
char* blocks[CLIENT_CACHE_BLOCKS];
map<struct CacheBlock, int> blockToPosMap;
map<int, struct CacheBlock> posToBlockMap;
ll timestamp[CLIENT_CACHE_BLOCKS];
ll timestampCnt = 0;
int serverid[CLIENT_CACHE_BLOCKS];
bool dirty[CLIENT_CACHE_BLOCKS];
mutex mtx;
struct pfs_execstat *exestat;
struct CacheBlock* imp;
Cache() {
exestat = new struct pfs_execstat();
exestat->num_read_hits = 0;
exestat->num_write_hits = 0;
exestat->num_evictions = 0;
exestat->num_writebacks = 0;
exestat->num_invalidations = 0;
exestat->num_close_writebacks = 0;
exestat->num_close_evictions = 0;
for (int i = 0; i < CLIENT_CACHE_BLOCKS; i++) {
timestamp[i] = -1; //empty
blocks[i] = NULL;
dirty[i] = 0;
serverid[i] = -1;
imp = NULL;
}
}
bool isImp(int fd, ll blocknum) {
if (imp != NULL && imp->fd ==fd && imp->blocknum == blocknum) return true;
return false;
}
char * getBlockFromCache(int fd, ll blockNumber) {
struct CacheBlock cb;
cb.fd = fd;
cb.blocknum = blockNumber;
// found
if (blockToPosMap.find(cb) != blockToPosMap.end()) {
int pos = blockToPosMap[cb];
//put recent timestamp
timestampCnt++;
timestamp[pos] = timestampCnt;
return blocks[pos];
}
return NULL; // not found
}
int findBlockposFromCache(int fd, ll blockNumber) {
struct CacheBlock cb;
cb.fd = fd;
cb.blocknum = blockNumber;
// found
if (blockToPosMap.find(cb) != blockToPosMap.end()) {
int pos = blockToPosMap[cb];
return pos;
}
return -1;
}
int getEmptyOrLRUPos() {
ll mn = 10000000000000LL;
int pos;
for (int i = 0; i < CLIENT_CACHE_BLOCKS; i++) {
if (timestamp[i] < mn) {
mn = timestamp[i];
pos = i;
}
}
return pos;
}
void setDirty(int fd, ll blockNumber) {
struct CacheBlock cb;
cb.fd = fd;
cb.blocknum = blockNumber;
// found
if (blockToPosMap.find(cb) != blockToPosMap.end()) {
int pos = blockToPosMap[cb];
dirty[pos] = 1;
}
}
void evictOrInvalidateBlock(int pos, bool evict, bool onclose) {
//cout<<"I am evicted"<<endl;
struct CacheBlock cb = posToBlockMap[pos];
if (dirty[pos]) { //if dirty, needs writeback to FS
struct CacheBlock cb = posToBlockMap[pos];
fileclient[serverid[pos]]->writeData(cb, blocks[pos]);
exestat->num_writebacks++;
//cout<< "WB" <<exestat->num_writebacks<<endl;
if (onclose) {
exestat->num_close_writebacks++;
}
}
blocks[pos] = NULL;
timestamp[pos] = -1;
dirty[pos] = 0;
blockToPosMap.erase(cb);
posToBlockMap.erase(pos);
serverid[pos] = -1;
if (evict) {
exestat->num_evictions++;
if (onclose) exestat->num_close_evictions++;
} else {
exestat->num_invalidations++;
}
}
void invalidatecb(int fd, ll blocknum) {
int pos = findBlockposFromCache(fd, blocknum);
if (pos != -1) {
evictOrInvalidateBlock(pos, false, false);
}
}
void placeBlockIncache(int fd, ll blockNumber, char* blockholder, bool dirt, int sid) {
struct CacheBlock cb;
cb.fd = fd;
cb.blocknum = blockNumber;
int pos = getEmptyOrLRUPos();
if (timestamp[pos] != -1) { //eviction needed
evictOrInvalidateBlock(pos, true, false);
} else {
//empty block
//nothing needds to do
}
blocks[pos] = blockholder;
timestampCnt++;
timestamp[pos] = timestampCnt;
dirty[pos] = dirt;
blockToPosMap[cb] = pos;
posToBlockMap[pos] = cb;
serverid[pos] = sid;
}
void evictBlocksonClose(int fd) {
for (int i = 0; i < CLIENT_CACHE_BLOCKS; i++) {
if (timestamp[i] != -1) {
struct CacheBlock cb = posToBlockMap[i];
if (cb.fd == fd) {
evictOrInvalidateBlock(i, true, true);
}
}
}
}
};
struct Cache* mycache = NULL;
class Client {
public:
Client(std::shared_ptr<Channel> channel) : stub_(MetaService::NewStub(channel)) {
}
ll getfilesize(int fd) {
ClientContext context;
File request, response;
request.set_fd(fd);
Status status = stub_->getfilesize(&context, request, &response);
if (status.ok()) {
return response.filesize();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int setfilesize(int fd, ll filesize) {
ClientContext context;
File request, response;
request.set_fd(fd);
request.set_filesize(filesize);
Status status = stub_->setfilesize(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int getClientId(ClientInfo request) {
ClientContext context;
ClientId response;
Status status = stub_->getClientId(&context, request, &response);
if (status.ok()) {
return response.id();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int startClientService(ClientInfo request) {
ClientContext context;
Empty response;
Status status = stub_->startClientService(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int canCacheBlock(int fd, ll blockNumber, int full, int type) {
ClientContext context;
CacheRequest request;
Blockinfo* blockinfo = request.mutable_block();
blockinfo->set_fd(fd);
blockinfo->set_blocknum(blockNumber);
request.set_type(type);
request.set_full(full);
request.set_clientid(client_id);
ResponseCode response;
Status status = stub_->canCacheBlock(&context, request, &response);
if (status.ok()) {
return response.val();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int createFile(FileCreateRequest request) {
ClientContext context;
ResponseCode response;
Status status = stub_->createFile(&context, request, &response);
if (status.ok()) {
return response.val();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int deleteFile(FileDeleteRequest request) {
ClientContext context;
Sidlist response;
Status status = stub_->deleteFile(&context, request, &response);
if (status.ok()) {
if (response.sids().size() > 0) {
for (int i = 0; i < (int)response.sids().size(); i++) {
fileclient[response.sids(i)]->deleteFd(response.fd());
}
}
return response.res();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int openFile(FileOpenRequest request) {
ClientContext context;
ResponseCode response;
Status status = stub_->openFile(&context, request, &response);
if (status.ok()) {
return response.val();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int closefd(int fd) {
ClientContext context;
CloseRequest request;
request.set_fd(fd);
request.set_clientid(client_id);
Empty response;
Status status = stub_->closefd(&context, request, &response);
if (status.ok()) {
return 0;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int fstat(int fd, struct pfs_metadata* meta_data) {
ClientContext context;
ResponseCode request;
request.set_val(fd);
Metadata response;
Status status = stub_->fstat(&context, request, &response);
if (status.ok()) {
int resp = response.res();
if (resp == 0) {
memcpy(meta_data->filename, response.fname().c_str(), response.fname().size());
meta_data->file_size = response.filesize();
meta_data->ctime = response.ctime();
meta_data->mtime = response.mtime();
}
return resp;
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int requestToken(Token request) {
ClientContext context;
ResponseCode response;
Status status = stub_->requestToken(&context, request, &response);
if (status.ok()) {
return response.val();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
int getServerInfoForBlock(int fd, ll blocknum) {
ClientContext context;
Blockinfo request;
request.set_fd(fd); request.set_blocknum(blocknum);
ResponseCode response;
Status status = stub_->getServerInfoForBlock(&context, request, &response);
if (status.ok()) {
return response.val();
} else {
//std::cerr << "RPC failed: " << status.error_code() << ": " << status.error_message() << std::endl;
return -1;
}
}
private:
std::unique_ptr<MetaService::Stub> stub_;
};
std::shared_ptr<Channel> channel;
Client* client = NULL;
/*
Init the PFS client. Return a positive value client id allocated by the metadata server.
Return -1 on error (e.g., can't communicate with metadata server, file servers (total of NUM_FILE_SERVERS) are not online yet, etc.).
The metadata and file servers' ip address and port can be found in pfs_list.txt.
You may need to allocate a struct pfs_execstat internally. You may need to initialize the client cache.
*/
int pfs_initialize()
{
setpfslist("../pfs_list.txt");
ClientInfo info;
info.set_client_ip(getMyIP());
info.set_client_name(getMyHostname());
if (client == NULL) {
channel = grpc::CreateChannel(getMetaServerAddress(), grpc::InsecureChannelCredentials());
client = new Client(channel);
}
fileservers = getFileServers();
for (int i = 0; i < NUM_FILE_SERVERS; i++) {
if (fileservers.find(i) == fileservers.end()) {
cout<< i << " File server missing" << endl;
return -1;
} else {
fileclient[i] = new FileClient(grpc::CreateChannel(fileservers[i], grpc::InsecureChannelCredentials()));
int ok = fileclient[i]->isConnected();
if (ok == -1) return -1;
//is fS alive? else -1;
}
}
client_id = client->getClientId(info);
if (client_id == -1) return -1;
thread serverthread(RunServer);
serverthread.detach();
info.set_clientid(client_id);
while (!clientAsServer);
//int ok =
client->startClientService(info);
//cout<<"MS started service for clients:" <<ok<<endl;
mycache = new struct Cache(); //cache initialized
return client_id;
}
/*Creates a file with the name filename. The file will be in striped into stripe_width number of servers.
Return 0 on success. Return -1 on error (e.g., duplicate filename, stripe_width larger than
NUM_FILE_SERVERS, etc). This will also create the metadata on the metadata server. Users can
access the metadata via pfs_fstat()
*/
int pfs_create(const char *filename, int stripe_width)
{
if (stripe_width > NUM_FILE_SERVERS) {
return -1;
}
FileCreateRequest request;
request.set_filename(std::string(filename));
request.set_stripe_width(stripe_width);
if (client != NULL) {
int resp = client->createFile(request);
return resp;
}
return -1;
}
/*
Opens a file with name filename. The mode will be either 1 (read) or 2 (read/write).
Return a positive value file descriptor. Return -1 on error (e.g., non-existing file, duplicate open, etc).
*/
int pfs_open(const char *filename, int mode)
{
auto it = fileinfos.find(std::string(filename));
//already opened.
if (it != fileinfos.end()) {
return -1;
}
string fname = std::string(filename);
FileOpenRequest request;
request.set_filename(fname);
request.set_mode(mode); //dont need to send actually....
if (client != NULL) {
int fd = client->openFile(request);
if (fd != -1) { //file exists
struct fileopeninfo info;
info.fd = fd;
info.mode = mode;
fileinfos[fname] = info; // insert this in openfile list
fdToFilenameMap[fd] = fname;
}
return fd;
}
return -1;
}
int getReadToken(int fd, ll startoffset, ll endoffset) {
//cout<<"enter"<<endl;
//tokenconsistency.lock();
struct tokeninterval required;
required.startoffset = startoffset;
required.endoffset = endoffset;
vector<struct tokeninterval> missing;
vector<struct tokeninterval> rdwrall;
auto it = fdToReadTokensList.find(fd);
if (it != fdToReadTokensList.end()) {
rdwrall.insert(rdwrall.end(), fdToReadTokensList[fd].begin(), fdToReadTokensList[fd].end());
} else {
vector<struct tokeninterval> v;
fdToReadTokensList[fd] = v;
}
it = fdToWriteTokensList.find(fd);
if (it != fdToWriteTokensList.end()) {
rdwrall.insert(rdwrall.end(), fdToWriteTokensList[fd].begin(), fdToWriteTokensList[fd].end());
} else {
vector<struct tokeninterval> v;
fdToWriteTokensList[fd] = v;
}
sort(rdwrall.begin(), rdwrall.end());
missing = missingTokenintervals(rdwrall, required);
if (missing.size() == 0) {
//no token request needed
//cout<< "local" << endl;
//after read/write done.
//tokenconsistency.unlock();
} else {
// need tokens from metaserver. if MS cant give us tokens, it will signal that tokenconsistency needs to be unlocked
//as it is blocked for someitme in the metaserver.
//tokenconsistency.unlock(); // because it may take time.
Token t;
t.set_clientid(client_id);
t.set_fd(fd);
t.set_type(1); // read
/*for (int i = 0; i < (int)missing.size(); i++) {
Tokeninterval* ti = t.add_tokenintervals();
ti->set_startoffset(missing[i].startoffset);
ti->set_endoffset(missing[i].endoffset);
}*/
Tokeninterval* ti = t.add_tokenintervals();
ti->set_startoffset(required.startoffset);
ti->set_endoffset(required.endoffset);
//just unblock lock because I am blocked in RPC
tokenconsistency.unlock();
int res = client->requestToken(t);
//cout << "successful"<<endl;
if (res == 0)
{
tokenconsistency.lock(); // pick the lock again after getting back from wait
revocation = 1; //imp
} else {
//cout <<"error while getting bck from RPC write request toekn" <<endl;
}
//add acquired token to own tken list
//fdToWriteTokensList[fd].insert(fdToWriteTokensList[fd].end(), missing.begin(), missing.end());
fdToReadTokensList[fd].push_back(required);
//after read/write done.
//printtokenlist(fdToReadTokensList[fd]);
//tokenconsistency.unlock();
}
//cout<<"end"<<endl;
return 0;
}
int getWriteToken(int fd, ll startoffset, ll endoffset) {
//cout<<"enter"<<endl;
//--moved to actal read/write calltokenconsistency.lock();
struct tokeninterval required;
required.startoffset = startoffset;
required.endoffset = endoffset;
vector<struct tokeninterval> missing;
auto it = fdToWriteTokensList.find(fd);
if (it != fdToWriteTokensList.end()) {
sort(fdToWriteTokensList[fd].begin(), fdToWriteTokensList[fd].end());
missing = missingTokenintervals(fdToWriteTokensList[fd], required);
} else {
vector<struct tokeninterval> v;
fdToWriteTokensList[fd] = v;
missing.push_back(required);
}
if (missing.size() == 0) {
//no token request needed
//cout<< "local" << endl;
//after read/write done.
//--moved to actal read/write calltokenconsistency.lock();
} else {
// need tokens from metaserver. if MS cant give us tokens, it will signal that tokenconsistency needs to be unlocked
//as it is blocked for someitme in the metaserver.
//tokenconsistency.unlock(); // because it may take time.
Token t;
t.set_clientid(client_id);
t.set_fd(fd);
t.set_type(2);
/*for (int i = 0; i < (int)missing.size(); i++) {
Tokeninterval* ti = t.add_tokenintervals();
ti->set_startoffset(missing[i].startoffset);
ti->set_endoffset(missing[i].endoffset);
}*/
Tokeninterval* ti = t.add_tokenintervals();
ti->set_startoffset(required.startoffset);
ti->set_endoffset(required.endoffset);
//just unblock lock because I am blocked in RPC
tokenconsistency.unlock();
int res = client->requestToken(t);
//cout << "successful"<<endl;
if (res == 0)
{
tokenconsistency.lock(); // pick the lock again after getting back from wait
revocation = 1;
} else {
//cout <<"error while getting bck from RPC write request toekn" <<endl;
}
//add acquired token to own tken list
//fdToWriteTokensList[fd].insert(fdToWriteTokensList[fd].end(), missing.begin(), missing.end());
fdToWriteTokensList[fd].push_back(required);
//after read/write done.
//printtokenlist(fdToWriteTokensList[fd]);
//--moved to actal read/write call tokenconsistency.lock();
}
//cout<<"end"<<endl;
return 0;
}
/*
Reads num_bytes bytes from the file fd, reading starts from offset~.
Return the actual number of read bytes (may be smaller than the requested,
if the offset is close to end-of-file). (A return of zero indicates end-of-file.)
Return -1 on error (e.g., offset is larger than the filesize, non-existing file descriptor,
communication with metadata/file server failed, etc.)
*/
int pfs_read(int fd, void *buf, size_t num_bytes, off_t offset)
{
//lock to guard token revocation request from Metaserver
//getToken -can be waited fhere for sometime
//--already acquired? check the missing token locally
//asks metaserver for missing tokens
//getBlocks - from fileservers
//for each block that is not local - CanIcacheblocks(blocknum)
//read/write locally or remotely
//check file size first--whether this valid or not
if (getmode(fd) == -1) return -1;
ll filesize = client->getfilesize(fd);
if (filesize < 0) return -1;
if (offset < 0 || offset > filesize) {
return -1;
}
int size = (int)num_bytes;
if (size == 0) return 0;
ll endoffset = offset + (ll)size - 1; // 0-1023 = 0 + 1024 - 1 = 123;
if (endoffset > (filesize - 1)) endoffset = filesize - 1;
size = endoffset - offset + 1;
if (size <= 0) return 0;
//if pwrite succesful, update filesize and modification time (can before/after..thnk)
tokenconsistency.lock(); // should I move this before acuire tokwn??
////
//1. need to check whether this call itself is valid or not.//client != null, connection is ok
//2.acquire token
getReadToken(fd, offset, endoffset); //can be blocked for sometime here.
//3. get the blocks
ll curoffset = offset;
int bufI = 0;
while (curoffset <= endoffset) {
//fetchBlock with curoffset
ll blockNumber = curoffset / PFS_BLOCK_SIZE;
ll blockstartoffset = blockNumber * PFS_BLOCK_SIZE;
ll blockendoffset = ((blockNumber + 1) * PFS_BLOCK_SIZE) - 1;
int full = (blockstartoffset >= offset) && (blockendoffset <= endoffset);
char * blockholder = NULL;
int canCache = 0;
int sid;
if (CACHE_ENABLED) {
mycache->mtx.lock();
blockholder = mycache->getBlockFromCache(fd, blockNumber);
if (blockholder == NULL) //read-miss
{
struct CacheBlock* cb = new struct CacheBlock();
cb->fd = fd;
cb->blocknum = blockNumber;
mycache->imp = cb;
mycache->mtx.unlock();
canCache = client->canCacheBlock(fd, blockNumber, full, 1);
mycache->mtx.lock();
} else {
mycache->exestat->num_read_hits++;
}
}
if (blockholder == NULL) {
sid = client->getServerInfoForBlock(fd, blockNumber);
if (sid == -1) return -1;
string blockdata = fileclient[sid]->readData(fd, blockNumber);
blockholder = (char*)malloc(PFS_BLOCK_SIZE);
for(int i = 0; i < (int)blockdata.size(); i++) blockholder[i] = blockdata[i]; //get current block data
}
ll internalcuroffset = curoffset - blockstartoffset;
ll sz;
if (endoffset >= blockendoffset) sz = blockendoffset - curoffset + 1;
else {
sz = endoffset - curoffset + 1;
}
//blockplaceholder-for cache
memcpy((char *)buf + bufI, blockholder + internalcuroffset, sz);
if (canCache) {
mycache->placeBlockIncache(fd, blockNumber, blockholder, false, sid);
}
if (CACHE_ENABLED) {
mycache->imp = NULL;
mycache->mtx.unlock();
}
bufI += sz;
curoffset += sz;
}
tokenconsistency.unlock();
return size;
}
/*
Writes num_bytes bytes to the file fd, writing starts from offset~.
Return the number of written bytes. Return -1 on error.
pfs_write() will require offset to be: 0<=offset<=file size.
as the file size increases (due to write), you will distribute the blocks as above.
You can store this information in the file recipe.
*/
int pfs_write(int fd, const void *buf, size_t num_bytes, off_t offset)
{
//check file size first--whether this valid or not
int mode = getmode(fd);
if (mode != 2) return -1;
ll filesize = client->getfilesize(fd);
//cout<<"FSIZE: " << filesize<<endl;
if (filesize < 0) return -1; //non-existent
if (offset < 0 || offset > filesize) {
return -1;
}
int size = (int)num_bytes;
if (size == 0) return 0;
ll endoffset = offset + (ll)size - 1; // 0-1023 = 0 + 1024 - 1 = 123;
//cout<<"W " << offset << " " << endoffset << endl;
//if pwrite succesful, update filesize and modification time (can before/after..thnk)
tokenconsistency.lock(); // should I move this before acuire tokwn??
////
//1. need to check whether this call itself is valid or not.//client != null, connection is ok
//2.acquire token
getWriteToken(fd, offset, endoffset); //can be blocked for sometime here.
if (endoffset + 1 > filesize) filesize = endoffset + 1;
client->setfilesize(fd, filesize); //mtime included
//cout<<ok<<endl;
//3. get the blocks
ll curoffset = offset;
int bufI = 0;
while (curoffset <= endoffset) {
//fetchBlock with curoffset
ll blockNumber = curoffset / PFS_BLOCK_SIZE;
ll blockstartoffset = blockNumber * PFS_BLOCK_SIZE;
ll blockendoffset = ((blockNumber + 1) * PFS_BLOCK_SIZE) - 1;
int full = (blockstartoffset >= offset) && (blockendoffset <= endoffset);
char * blockholder = NULL;
int canCache = 0;
int sid;
if (CACHE_ENABLED) {
mycache->mtx.lock();
blockholder = mycache->getBlockFromCache(fd, blockNumber);
if (blockholder == NULL) //write-miss
{
struct CacheBlock* cb = new struct CacheBlock();
cb->fd = fd;
cb->blocknum = blockNumber;
mycache->imp = cb;
mycache->mtx.unlock();
canCache = client->canCacheBlock(fd, blockNumber, full, 2);
mycache->mtx.lock();
} else {
mycache->exestat->num_write_hits++;
}
}
if (blockholder == NULL) {
sid = client->getServerInfoForBlock(fd, blockNumber);
if (sid == -1) return -1;
string blockdata = fileclient[sid]->readData(fd, blockNumber);
blockholder = (char*)malloc(PFS_BLOCK_SIZE);
for(int i = 0; i < (int)blockdata.size(); i++) blockholder[i] = blockdata[i]; //get current block data
}
ll internalcuroffset = curoffset - blockstartoffset;
ll sz;
if (endoffset >= blockendoffset) sz = blockendoffset - curoffset + 1;
else {
sz = endoffset - curoffset + 1;