Clean up code
[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
165                 default:
166                         printf("DEBUG -> dstmAccept: Error Unknown opcode %d\n", control);
167         }
168
169         /* Close connection */
170         if (close((int)acceptfd) == -1)
171                 perror("close");
172         else 
173                 printf("Closed connection: fd = %d\n", (int)acceptfd);
174         
175         pthread_exit(NULL);
176 }
177
178 /* This function reads the information available in a transaction request
179  * and makes a function call to process the request */
180 int readClientReq(trans_commit_data_t *transinfo, int acceptfd) {
181         char *ptr;
182         void *modptr;
183         fixed_data_t fixed;
184         int sum = 0, i, N, n, val;
185
186         /* Read fixed_data_t data structure */ 
187         N = sizeof(fixed) - 1;
188         ptr = (char *)&fixed;;
189         fixed.control = TRANS_REQUEST;
190         do {
191                 n = recv((int)acceptfd, (void *) ptr+1+sum, N-sum, 0);
192                 sum += n;
193         } while(sum < N && n != 0); 
194
195         /* Read list of mids */
196         int mcount = fixed.mcount;
197         N = mcount * sizeof(unsigned int);
198         unsigned int listmid[mcount];
199         ptr = (char *) listmid;
200         sum = 0;
201         do {
202                 n = recv((int)acceptfd, (void *) ptr+sum, N-sum, 0);
203                 sum += n;
204         } while(sum < N && n != 0);
205
206         /* Read oid and version tuples for those objects that are not modified in the transaction */
207         int numread = fixed.numread;
208         N = numread * (sizeof(unsigned int) + sizeof(short));
209         char objread[N];
210         if(numread != 0) { //If pile contains more than one object to be read, 
211                           // keep reading all objects
212                 sum = 0;
213                 do {
214                         n = recv((int)acceptfd, (void *) objread, N, 0);
215                         sum += n;
216                 } while(sum < N && n != 0);
217         }
218         
219         /* Read modified objects */
220         if(fixed.nummod != 0) { // If pile contains more than one modified object,
221                                 // allocate new object store and recv all modified objects
222                                 // TODO deallocate this space
223                 if ((modptr = objstrAlloc(mainobjstore, fixed.sum_bytes)) == NULL) {
224                         printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
225                         return 1;
226                 }
227                 sum = 0;
228                 do { // Recv the objs that are modified by the Coordinator
229                         n = recv((int)acceptfd, modptr+sum, fixed.sum_bytes-sum, 0);
230                         sum += n;
231                 } while (sum < fixed.sum_bytes && n != 0);
232         }
233
234         /*Process the information read */
235         if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, acceptfd)) != 0) {
236                 printf("Error in processClientReq %s, %d\n", __FILE__, __LINE__);
237                 return 1;
238         }
239
240         return 0;
241 }
242
243 /* This function processes the Coordinator's transaction request using "handleTransReq" 
244  * function and sends a reply to the co-ordinator.
245  * Following this it also receives a new control message from the co-ordinator and processes this message*/
246 int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo,
247                 unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
248         char *ptr, control, sendctrl;
249         objheader_t *tmp_header;
250         void *header;
251         int  i = 0, val, retval;
252
253         /* Send reply to the Coordinator */
254         if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) {
255                 printf("Handle Trans Req error %s, %d\n", __FILE__, __LINE__);
256                 return 1;
257         }
258         /* Read new control message from Coordiator */
259         if((retval = recv((int)acceptfd, &control, sizeof(char), 0)) <= 0 ) {
260                 perror("Error in receiving control message\n");
261                 return 1;
262         }
263
264         /* Process the new control message */
265         switch(control) {
266                 case TRANS_ABORT:
267                         /* Set all ref counts as 1 and do garbage collection */
268                         ptr = modptr;
269                         for(i = 0; i< fixed->nummod; i++) {
270                                 tmp_header = (objheader_t *)ptr;
271                                 tmp_header->rcount = 1;
272                                 ptr += sizeof(objheader_t) + classsize[tmp_header->type];
273                         }
274                         /* Unlock objects that was locked due to this transaction */
275                         for(i = 0; i< transinfo->numlocked; i++) {
276                                 header = mhashSearch(transinfo->objlocked[i]);// find the header address
277                                 ((objheader_t *)header)->status &= ~(LOCK);             
278                         }
279                 
280                         /* Send ack to Coordinator */
281                         printf("DEBUG -> Recv TRANS_ABORT\n");
282                         sendctrl = TRANS_SUCESSFUL;
283                         if(send((int)acceptfd, &sendctrl, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
284                                 perror("Error sending ACK to coordinator\n");
285                                 return 1;
286                         }
287                         ptr = NULL;
288         //              return 0;
289                         break;
290
291                 case TRANS_COMMIT:
292                         /* Invoke the transCommit process() */
293                         printf("DEBUG -> Recv TRANS_COMMIT \n");
294                         if((val = transCommitProcess(transinfo, (int)acceptfd)) != 0) {
295                                 printf("Error in transCommitProcess %s, %d\n", __FILE__, __LINE__);
296                                 return 1;
297                         }
298                         break;
299
300                 case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
301                         //TODO expect another transrequest from client
302                         printf("DEBUG -> Recv TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING\n");
303                         break;
304                 default:
305                         printf("No response to TRANS_AGREE OR DISAGREE protocol\n");
306                         //TODO Use fixed.trans_id  TID since Client may have died
307                         break;
308         }
309         /* Free memory */
310         printf("DEBUG -> Freeing...\n");
311         fflush(stdout);
312         if (transinfo->objmod != NULL) {
313                 free(transinfo->objmod);
314                 transinfo->objmod = NULL;
315         }
316         if (transinfo->objlocked != NULL) {
317                 free(transinfo->objlocked);
318                 transinfo->objlocked = NULL;
319         }
320         if (transinfo->objnotfound != NULL) {
321                 free(transinfo->objnotfound);
322                 transinfo->objnotfound = NULL;
323         }
324         return 0;
325 }
326
327 /* This function increments counters while running a voting decision on all objects involved 
328  * in TRANS_REQUEST */
329
330 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
331         int val, i = 0;
332         short version;
333         char control = 0, *ptr;
334         unsigned int oid;
335         unsigned int *oidnotfound, *oidlocked, *oidmod;
336         void *mobj;
337         objheader_t *headptr;
338
339         /* Counters and arrays to formulate decision on control message to be sent */
340         oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
341         oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
342         oidmod = (unsigned int *) calloc(fixed->nummod, sizeof(unsigned int));
343         int objnotfound = 0, objlocked = 0, objmod =0, v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
344         int objmodnotfound = 0, nummodfound = 0;
345
346         /* modptr points to the beginning of the object store 
347          * created at the Pariticipant. 
348          * Object store holds the modified objects involved in the transaction request */ 
349         ptr = modptr;
350         
351         /* Process each oid in the machine pile/ group per thread */
352         for (i = 0; i < fixed->numread + fixed->nummod; i++) {
353                 if (i < fixed->numread) {//Objs only read and not modified
354                         int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
355                         incr *= i;
356                         oid = *((unsigned int *)(objread + incr));
357                         incr += sizeof(unsigned int);
358                         version = *((short *)(objread + incr));
359                 } else {//Objs modified
360                         headptr = (objheader_t *) ptr;
361                         oid = headptr->oid;
362                         oidmod[objmod] = oid;//Array containing modified oids
363                         objmod++;
364                         version = headptr->version;
365                         ptr += sizeof(objheader_t) + classsize[headptr->type];
366                 }
367                 
368                 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
369
370                 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
371                         /* Save the oids not found and number of oids not found for later use */
372                         oidnotfound[objnotfound] = ((objheader_t *)mobj)->oid;
373                         objnotfound++;
374                 } else { /* If Obj found in machine (i.e. has not moved) */
375                         /* Check if Obj is locked by any previous transaction */
376                         if ((((objheader_t *)mobj)->status & LOCK) == LOCK) {           
377                                 if (version == ((objheader_t *)mobj)->version) {      /* If not locked then match versions */
378                                         v_matchlock++;
379                                 } else {/* If versions don't match ...HARD ABORT */
380                                         v_nomatch++;
381                                         /* Send TRANS_DISAGREE to Coordinator */
382                                         control = TRANS_DISAGREE;
383                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
384                                                 perror("Error in sending control to the Coordinator\n");
385                                                 return 0;
386                                         }
387                                         printf("DEBUG -> Sending TRANS_DISAGREE\n");
388                                         return control;
389                                 }
390                         } else {/* If Obj is not locked then lock object */
391                                 ((objheader_t *)mobj)->status |= LOCK;
392                                
393                                 /*TESTING Add random wait to make transactions run for a long time such that
394                                  * we can test for soft abort case */
395                         
396                                 randomdelay();
397
398                                 /* Save all object oids that are locked on this machine during this transaction request call */
399                                 oidlocked[objlocked] = ((objheader_t *)mobj)->oid;
400                                 objlocked++;
401                                 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
402                                         v_matchnolock++;
403                                 } else { /* If versions don't match ...HARD ABORT */
404                                         v_nomatch++;
405                                         control = TRANS_DISAGREE;
406                                         /* Send TRANS_DISAGREE to Coordinator */
407                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
408                                                 perror("Error in sending control to the Coordinator\n");
409                                                 return 0;
410                                         }
411                                         printf("DEBUG -> Sending TRANS_DISAGREE\n");
412                                         return control;
413                                 }
414                         }
415                 }
416         }
417         
418         /* Decide what control message to send to Coordinator */
419         if ((val = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked,
420                                         modptr, oidnotfound, oidlocked, oidmod, acceptfd)) == 0) {
421                 printf("Error in decideCtrlMessage %s, %d\n", __FILE__, __LINE__);
422                 return 0;
423         }
424         
425         return val;
426
427 }
428 /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT
429  * to send to Coordinator based on the votes of oids involved in the transaction */
430 int decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, 
431                 int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, 
432                 unsigned int *oidnotfound, unsigned int *oidlocked, unsigned int *oidmod,
433                 int acceptfd) {
434         int val;
435         char control = 0;
436         /* Condition to send TRANS_AGREE */
437         if(*(v_matchnolock) == fixed->numread + fixed->nummod) {
438                 control = TRANS_AGREE;
439                 if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
440                         perror("Error in sending control to Coordinator\n");
441                         return 0;
442                 }
443                 printf("DEBUG -> Sending TRANS_AGREE\n");
444         }
445         /* Condition to send TRANS_SOFT_ABORT */
446         if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) {
447                 control = TRANS_SOFT_ABORT;
448                 char msg[]={TRANS_SOFT_ABORT, 0,0,0,0};
449                 *((int*)&msg[1])= *(objnotfound);
450
451                 printf("DEBUG -> Sending TRANS_SOFT_ABORT\n");
452                 /* Send control message */
453                 if((val = send(acceptfd, &msg, sizeof(msg),MSG_NOSIGNAL)) < sizeof(msg)) {
454                         perror("Error in sending no of objects that are not found\n");
455                         return 0;
456                 }
457                 /* Send number of oids not found and the missing oids if objects are missing in the machine */
458                 if(*(objnotfound) != 0) { 
459                         int size = sizeof(unsigned int)* *(objnotfound);
460                         if((val = send(acceptfd, oidnotfound, size ,MSG_NOSIGNAL)) < size) {
461                                 perror("Error in sending objects that are not found\n");
462                                 return 0;
463                         }
464                 }
465         }
466
467         /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
468          * if Participant receives a TRANS_COMMIT */
469         transinfo->objmod = oidmod;
470         transinfo->objlocked = oidlocked;
471         transinfo->objnotfound = oidnotfound;
472         transinfo->modptr = modptr;
473         transinfo->nummod = fixed->nummod;
474         transinfo->numlocked = *(objlocked);
475         transinfo->numnotfound = *(objnotfound);
476         
477         return control;
478 }
479
480 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer 
481  * addresses in lookup table and also changes version number
482  * Sends an ACK back to Coordinator */
483 int transCommitProcess(trans_commit_data_t *transinfo, int acceptfd) {
484         objheader_t *header;
485         int i = 0, offset = 0;
486         char control;
487         /* Process each modified object saved in the mainobject store */
488         for(i=0; i<transinfo->nummod; i++) {
489                 if((header = (objheader_t *) mhashSearch(transinfo->objmod[i])) == NULL) {
490                         printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
491                 }
492                 /* Change reference count of older address and free space in objstr ?? */
493                 header->rcount = 1; //Not sure what would be the val
494
495                 /* Change ptr address in mhash table */
496                 printf("DEBUG -> removing object oid = %d\n", transinfo->objmod[i]);
497                 mhashRemove(transinfo->objmod[i]);
498                 mhashInsert(transinfo->objmod[i], (transinfo->modptr + offset));
499                 offset += sizeof(objheader_t) + classsize[header->type];
500
501                 /* Update object version number */
502                 header = (objheader_t *) mhashSearch(transinfo->objmod[i]);
503                 header->version += 1; 
504         }
505         /* Unlock locked objects */
506         for(i=0; i<transinfo->numlocked; i++) {
507                 header = (objheader_t *) mhashSearch(transinfo->objlocked[i]);
508                 header->status &= ~(LOCK);
509         }
510
511         //TODO Update location lookup table
512
513         /* Send ack to coordinator */
514         control = TRANS_SUCESSFUL;
515         printf("DEBUG-> TRANS_SUCESSFUL\n");
516         if(send((int)acceptfd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
517                 perror("Error sending ACK to coordinator\n");
518         }
519         
520         return 0;
521 }
522