7b5bd7345982fa5f47c78ed18148dc2e751a024e
[IRC.git] / Robust / src / Runtime / DSTM / interface / dstmserver.c
1 /* Coordinator => Machine that initiates the transaction request call for commiting a transaction
2  * Participant => Machines that host the objects involved in a transaction commit */
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <pthread.h>
8 #include <netdb.h>
9 #include <fcntl.h>
10 #include "dstm.h"
11 #include "mlookup.h"
12 #include "llookup.h"
13
14 #define LISTEN_PORT 2156
15 #define BACKLOG 10 //max pending connections
16 #define RECEIVE_BUFFER_SIZE 2048
17
18 extern int classsize[];
19
20 objstr_t *mainobjstore;
21
22 int dstmInit(void)
23 {
24         /* Initialize main object store */
25         mainobjstore = objstrCreate(DEFAULT_OBJ_STORE_SIZE);    
26         /* Create machine lookup table and location lookup table */
27         if (mhashCreate(HASH_SIZE, LOADFACTOR))
28                 return 1; //failure
29         
30         if (lhashCreate(HASH_SIZE, LOADFACTOR))
31                 return 1; //failure
32         
33         return 0;
34 }
35
36 void *dstmListen()
37 {
38         int listenfd, acceptfd;
39         struct sockaddr_in my_addr;
40         struct sockaddr_in client_addr;
41         socklen_t addrlength = sizeof(struct sockaddr);
42         pthread_t thread_dstm_accept;
43         int i;
44         int setsockflag=1;
45
46         listenfd = socket(AF_INET, SOCK_STREAM, 0);
47         if (listenfd == -1)
48         {
49                 perror("socket");
50                 exit(1);
51         }
52
53         if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof (setsockflag)) < 0) {
54           perror("socket");
55           exit(1);
56         }
57 #ifdef MAC
58         if (setsockopt(listenfd, SOL_SOCKET, SO_NOSIGPIPE, &setsockflag, sizeof (setsockflag)) < 0) {
59           perror("socket");
60           exit(1);
61         }
62 #endif
63
64         my_addr.sin_family = AF_INET;
65         my_addr.sin_port = htons(LISTEN_PORT);
66         my_addr.sin_addr.s_addr = INADDR_ANY;
67         memset(&(my_addr.sin_zero), '\0', 8);
68
69         if (bind(listenfd, (struct sockaddr *)&my_addr, addrlength) == -1)
70         {
71                 perror("bind");
72                 exit(1);
73         }
74         
75         if (listen(listenfd, BACKLOG) == -1)
76         {
77                 perror("listen");
78                 exit(1);
79         }
80
81         printf("Listening on port %d, fd = %d\n", LISTEN_PORT, listenfd);
82         while(1)
83         {
84                 acceptfd = accept(listenfd, (struct sockaddr *)&client_addr, &addrlength);
85                 pthread_create(&thread_dstm_accept, NULL, dstmAccept, (void *)acceptfd);
86         }
87         pthread_exit(NULL);
88 }
89 /* This function accepts a new connection request, decodes the control message in the connection 
90  * and accordingly calls other functions to process new requests */
91 void *dstmAccept(void *acceptfd)
92 {
93         int numbytes,i, val, retval;
94         unsigned int oid;
95         char buffer[RECEIVE_BUFFER_SIZE], control,ctrl;
96         char *ptr;
97         void *srcObj;
98         objheader_t *h;
99         trans_commit_data_t transinfo;
100         
101         int fd_flags = fcntl((int)acceptfd, F_GETFD), size;
102
103         printf("Recieved connection: fd = %d\n", (int)acceptfd);
104         /* Receive control messages from other machines */
105         if((retval = recv((int)acceptfd, &control, sizeof(char), 0)) <= 0) {
106                 if (retval == 0) {
107                         return; // Testing connection
108                 }
109                 perror("Error in receiving control from coordinator\n");
110                 return;
111         }
112         
113         switch(control) {
114                 case READ_REQUEST:
115                         /* Read oid requested and search if available */
116                         if((retval = recv((int)acceptfd, &oid, sizeof(unsigned int), 0)) <= 0) {
117                                 perror("Error receiving object from cooridnator\n");
118                                 return NULL;
119                         }
120                         srcObj = mhashSearch(oid);
121                         h = (objheader_t *) srcObj;
122                         size = sizeof(objheader_t) + sizeof(classsize[h->type]);
123                         if (h == NULL) {
124                                 ctrl = OBJECT_NOT_FOUND;
125                                 if(send((int)acceptfd, &ctrl, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
126                                         perror("Error sending control msg to coordinator\n");
127                                         return NULL;
128                                 }
129                         } else {
130                                 /* Type */
131                           char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
132                           *((int *)&msg[1])=size;
133                           if(send((int)acceptfd, &msg, sizeof(msg), MSG_NOSIGNAL) < sizeof(msg)) {
134                                   perror("Error sending size of object to coordinator\n");
135                                   return NULL;
136                           }
137                           if(send((int)acceptfd, h, size, MSG_NOSIGNAL) < size) {
138                                   perror("Error in sending object\n");
139                                   return NULL;
140                           }
141                         }
142                         break;
143                 
144                 case READ_MULT_REQUEST:
145                         printf("DEBUG-> READ_MULT_REQUEST\n");
146                         break;
147         
148                 case MOVE_REQUEST:
149                         printf("DEBUG -> MOVE_REQUEST\n");
150                         break;
151
152                 case MOVE_MULT_REQUEST:
153                         printf("DEBUG -> MOVE_MULT_REQUEST\n");
154                         break;
155
156                 case TRANS_REQUEST:
157                         /* Read transaction request */
158                         printf("DEBUG -> Recv TRANS_REQUEST\n");
159                         if((val = readClientReq(&transinfo, (int)acceptfd)) != 0) {
160                                 printf("Error in readClientReq\n");
161                                 return;
162                         }
163                         break;
164                 case TRANS_PREFETCH:
165                         printf("DEBUG -> Recv TRANS_PREFETCH\n");
166                         if((val = prefetchReq((int)acceptfd)) != 0) {
167                                 printf("Error in readClientReq\n");
168                                 return;
169                         }
170                         break;
171
172                 default:
173                         printf("DEBUG -> dstmAccept: Error Unknown opcode %d\n", control);
174         }
175
176         /* Close connection */
177         if (close((int)acceptfd) == -1)
178                 perror("close");
179         else 
180                 printf("Closed connection: fd = %d\n", (int)acceptfd);
181         
182         pthread_exit(NULL);
183 }
184
185 /* This function reads the information available in a transaction request
186  * and makes a function call to process the request */
187 int readClientReq(trans_commit_data_t *transinfo, int acceptfd) {
188         char *ptr;
189         void *modptr;
190         fixed_data_t fixed;
191         int sum = 0, i, N, n, val;
192
193         /* Read fixed_data_t data structure */ 
194         N = sizeof(fixed) - 1;
195         ptr = (char *)&fixed;;
196         fixed.control = TRANS_REQUEST;
197         do {
198                 n = recv((int)acceptfd, (void *) ptr+1+sum, N-sum, 0);
199                 sum += n;
200         } while(sum < N && n != 0); 
201
202         /* Read list of mids */
203         int mcount = fixed.mcount;
204         N = mcount * sizeof(unsigned int);
205         unsigned int listmid[mcount];
206         ptr = (char *) listmid;
207         sum = 0;
208         do {
209                 n = recv((int)acceptfd, (void *) ptr+sum, N-sum, 0);
210                 sum += n;
211         } while(sum < N && n != 0);
212
213         /* Read oid and version tuples for those objects that are not modified in the transaction */
214         int numread = fixed.numread;
215         N = numread * (sizeof(unsigned int) + sizeof(short));
216         char objread[N];
217         if(numread != 0) { //If pile contains more than one object to be read, 
218                           // keep reading all objects
219                 sum = 0;
220                 do {
221                         n = recv((int)acceptfd, (void *) objread, N, 0);
222                         sum += n;
223                 } while(sum < N && n != 0);
224         }
225         
226         /* Read modified objects */
227         if(fixed.nummod != 0) { // If pile contains more than one modified object,
228                                 // allocate new object store and recv all modified objects
229                                 // TODO deallocate this space
230                 if ((modptr = objstrAlloc(mainobjstore, fixed.sum_bytes)) == NULL) {
231                         printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
232                         return 1;
233                 }
234                 sum = 0;
235                 do { // Recv the objs that are modified by the Coordinator
236                         n = recv((int)acceptfd, modptr+sum, fixed.sum_bytes-sum, 0);
237                         sum += n;
238                 } while (sum < fixed.sum_bytes && n != 0);
239         }
240
241         /*Process the information read */
242         if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, acceptfd)) != 0) {
243                 printf("Error in processClientReq %s, %d\n", __FILE__, __LINE__);
244                 return 1;
245         }
246
247         return 0;
248 }
249
250 /* This function processes the Coordinator's transaction request using "handleTransReq" 
251  * function and sends a reply to the co-ordinator.
252  * Following this it also receives a new control message from the co-ordinator and processes this message*/
253 int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo,
254                 unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
255         char *ptr, control, sendctrl;
256         objheader_t *tmp_header;
257         void *header;
258         int  i = 0, val, retval;
259
260         /* Send reply to the Coordinator */
261         if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) {
262                 printf("Handle Trans Req error %s, %d\n", __FILE__, __LINE__);
263                 return 1;
264         }
265         /* Read new control message from Coordiator */
266         if((retval = recv((int)acceptfd, &control, sizeof(char), 0)) <= 0 ) {
267                 perror("Error in receiving control message\n");
268                 return 1;
269         }
270
271         /* Process the new control message */
272         switch(control) {
273                 case TRANS_ABORT:
274                         /* Set all ref counts as 1 and do garbage collection */
275                         ptr = modptr;
276                         for(i = 0; i< fixed->nummod; i++) {
277                                 tmp_header = (objheader_t *)ptr;
278                                 tmp_header->rcount = 1;
279                                 ptr += sizeof(objheader_t) + classsize[tmp_header->type];
280                         }
281                         /* Unlock objects that was locked due to this transaction */
282                         for(i = 0; i< transinfo->numlocked; i++) {
283                                 header = mhashSearch(transinfo->objlocked[i]);// find the header address
284                                 ((objheader_t *)header)->status &= ~(LOCK);             
285                         }
286                 
287                         /* Send ack to Coordinator */
288                         printf("DEBUG -> Recv TRANS_ABORT\n");
289                         sendctrl = TRANS_SUCESSFUL;
290                         if(send((int)acceptfd, &sendctrl, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
291                                 perror("Error sending ACK to coordinator\n");
292                                 return 1;
293                         }
294                         ptr = NULL;
295         //              return 0;
296                         break;
297
298                 case TRANS_COMMIT:
299                         /* Invoke the transCommit process() */
300                         printf("DEBUG -> Recv TRANS_COMMIT \n");
301                         if((val = transCommitProcess(transinfo, (int)acceptfd)) != 0) {
302                                 printf("Error in transCommitProcess %s, %d\n", __FILE__, __LINE__);
303                                 return 1;
304                         }
305                         break;
306
307                 case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
308                         //TODO expect another transrequest from client
309                         printf("DEBUG -> Recv TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING\n");
310                         break;
311                 default:
312                         printf("No response to TRANS_AGREE OR DISAGREE protocol\n");
313                         //TODO Use fixed.trans_id  TID since Client may have died
314                         break;
315         }
316         /* Free memory */
317         printf("DEBUG -> Freeing...\n");
318         fflush(stdout);
319         if (transinfo->objmod != NULL) {
320                 free(transinfo->objmod);
321                 transinfo->objmod = NULL;
322         }
323         if (transinfo->objlocked != NULL) {
324                 free(transinfo->objlocked);
325                 transinfo->objlocked = NULL;
326         }
327         if (transinfo->objnotfound != NULL) {
328                 free(transinfo->objnotfound);
329                 transinfo->objnotfound = NULL;
330         }
331         return 0;
332 }
333
334 /* This function increments counters while running a voting decision on all objects involved 
335  * in TRANS_REQUEST */
336
337 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
338         int val, i = 0;
339         short version;
340         char control = 0, *ptr;
341         unsigned int oid;
342         unsigned int *oidnotfound, *oidlocked, *oidmod;
343         void *mobj;
344         objheader_t *headptr;
345
346         /* Counters and arrays to formulate decision on control message to be sent */
347         oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
348         oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
349         oidmod = (unsigned int *) calloc(fixed->nummod, sizeof(unsigned int));
350         int objnotfound = 0, objlocked = 0, objmod =0, v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
351         int objmodnotfound = 0, nummodfound = 0;
352
353         /* modptr points to the beginning of the object store 
354          * created at the Pariticipant. 
355          * Object store holds the modified objects involved in the transaction request */ 
356         ptr = modptr;
357         
358         /* Process each oid in the machine pile/ group per thread */
359         for (i = 0; i < fixed->numread + fixed->nummod; i++) {
360                 if (i < fixed->numread) {//Objs only read and not modified
361                         int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
362                         incr *= i;
363                         oid = *((unsigned int *)(objread + incr));
364                         incr += sizeof(unsigned int);
365                         version = *((short *)(objread + incr));
366                 } else {//Objs modified
367                         headptr = (objheader_t *) ptr;
368                         oid = headptr->oid;
369                         oidmod[objmod] = oid;//Array containing modified oids
370                         objmod++;
371                         version = headptr->version;
372                         ptr += sizeof(objheader_t) + classsize[headptr->type];
373                 }
374                 
375                 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
376
377                 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
378                         /* Save the oids not found and number of oids not found for later use */
379                         oidnotfound[objnotfound] = ((objheader_t *)mobj)->oid;
380                         objnotfound++;
381                 } else { /* If Obj found in machine (i.e. has not moved) */
382                         /* Check if Obj is locked by any previous transaction */
383                         if ((((objheader_t *)mobj)->status & LOCK) == LOCK) {           
384                                 if (version == ((objheader_t *)mobj)->version) {      /* If not locked then match versions */
385                                         v_matchlock++;
386                                 } else {/* If versions don't match ...HARD ABORT */
387                                         v_nomatch++;
388                                         /* Send TRANS_DISAGREE to Coordinator */
389                                         control = TRANS_DISAGREE;
390                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
391                                                 perror("Error in sending control to the Coordinator\n");
392                                                 return 0;
393                                         }
394                                         printf("DEBUG -> Sending TRANS_DISAGREE\n");
395                                         return control;
396                                 }
397                         } else {/* If Obj is not locked then lock object */
398                                 ((objheader_t *)mobj)->status |= LOCK;
399                                
400                                 /*TESTING Add random wait to make transactions run for a long time such that
401                                  * we can test for soft abort case */
402                         
403                                 randomdelay();
404
405                                 /* Save all object oids that are locked on this machine during this transaction request call */
406                                 oidlocked[objlocked] = ((objheader_t *)mobj)->oid;
407                                 objlocked++;
408                                 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
409                                         v_matchnolock++;
410                                 } else { /* If versions don't match ...HARD ABORT */
411                                         v_nomatch++;
412                                         control = TRANS_DISAGREE;
413                                         /* Send TRANS_DISAGREE to Coordinator */
414                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
415                                                 perror("Error in sending control to the Coordinator\n");
416                                                 return 0;
417                                         }
418                                         printf("DEBUG -> Sending TRANS_DISAGREE\n");
419                                         return control;
420                                 }
421                         }
422                 }
423         }
424         
425         /* Decide what control message to send to Coordinator */
426         if ((val = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked,
427                                         modptr, oidnotfound, oidlocked, oidmod, acceptfd)) == 0) {
428                 printf("Error in decideCtrlMessage %s, %d\n", __FILE__, __LINE__);
429                 return 0;
430         }
431         
432         return val;
433
434 }
435 /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT
436  * to send to Coordinator based on the votes of oids involved in the transaction */
437 int decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, 
438                 int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, 
439                 unsigned int *oidnotfound, unsigned int *oidlocked, unsigned int *oidmod,
440                 int acceptfd) {
441         int val;
442         char control = 0;
443         /* Condition to send TRANS_AGREE */
444         if(*(v_matchnolock) == fixed->numread + fixed->nummod) {
445                 control = TRANS_AGREE;
446                 if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
447                         perror("Error in sending control to Coordinator\n");
448                         return 0;
449                 }
450                 printf("DEBUG -> Sending TRANS_AGREE\n");
451         }
452         /* Condition to send TRANS_SOFT_ABORT */
453         if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) {
454                 control = TRANS_SOFT_ABORT;
455                 char msg[]={TRANS_SOFT_ABORT, 0,0,0,0};
456                 *((int*)&msg[1])= *(objnotfound);
457
458                 printf("DEBUG -> Sending TRANS_SOFT_ABORT\n");
459                 /* Send control message */
460                 if((val = send(acceptfd, &msg, sizeof(msg),MSG_NOSIGNAL)) < sizeof(msg)) {
461                         perror("Error in sending no of objects that are not found\n");
462                         return 0;
463                 }
464                 /* Send number of oids not found and the missing oids if objects are missing in the machine */
465                 if(*(objnotfound) != 0) { 
466                         int size = sizeof(unsigned int)* *(objnotfound);
467                         if((val = send(acceptfd, oidnotfound, size ,MSG_NOSIGNAL)) < size) {
468                                 perror("Error in sending objects that are not found\n");
469                                 return 0;
470                         }
471                 }
472         }
473
474         /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
475          * if Participant receives a TRANS_COMMIT */
476         transinfo->objmod = oidmod;
477         transinfo->objlocked = oidlocked;
478         transinfo->objnotfound = oidnotfound;
479         transinfo->modptr = modptr;
480         transinfo->nummod = fixed->nummod;
481         transinfo->numlocked = *(objlocked);
482         transinfo->numnotfound = *(objnotfound);
483         
484         return control;
485 }
486
487 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer 
488  * addresses in lookup table and also changes version number
489  * Sends an ACK back to Coordinator */
490 int transCommitProcess(trans_commit_data_t *transinfo, int acceptfd) {
491         objheader_t *header;
492         int i = 0, offset = 0;
493         char control;
494         /* Process each modified object saved in the mainobject store */
495         for(i=0; i<transinfo->nummod; i++) {
496                 if((header = (objheader_t *) mhashSearch(transinfo->objmod[i])) == NULL) {
497                         printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
498                 }
499                 /* Change reference count of older address and free space in objstr ?? */
500                 header->rcount = 1; //Not sure what would be the val
501
502                 /* Change ptr address in mhash table */
503                 printf("DEBUG -> removing object oid = %d\n", transinfo->objmod[i]);
504                 mhashRemove(transinfo->objmod[i]);
505                 mhashInsert(transinfo->objmod[i], (transinfo->modptr + offset));
506                 offset += sizeof(objheader_t) + classsize[header->type];
507
508                 /* Update object version number */
509                 header = (objheader_t *) mhashSearch(transinfo->objmod[i]);
510                 header->version += 1; 
511         }
512         /* Unlock locked objects */
513         for(i=0; i<transinfo->numlocked; i++) {
514                 header = (objheader_t *) mhashSearch(transinfo->objlocked[i]);
515                 header->status &= ~(LOCK);
516         }
517
518         //TODO Update location lookup table
519
520         /* Send ack to coordinator */
521         control = TRANS_SUCESSFUL;
522         printf("DEBUG-> TRANS_SUCESSFUL\n");
523         if(send((int)acceptfd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
524                 perror("Error sending ACK to coordinator\n");
525         }
526         
527         return 0;
528 }
529
530
531 int prefetchReq(int acceptfd) {
532
533         return 0;
534 }