11 #include<netinet/in.h>
12 #include <sys/types.h>
16 #define LISTEN_PORT 2156
17 #define MACHINE_IP "127.0.0.1"
18 #define RECEIVE_BUFFER_SIZE 2048
20 extern int classsize[];
21 objstr_t *mainobjstore;
22 plistnode_t *createPiles(transrecord_t *);
23 //int checkPrefetchTuples(int **, int *, short);
25 inline int arrayLength(int *array) {
27 for(i=0 ;array[i] != -1; i++)
32 /* This functions inserts randowm wait delays in the order of msec */
33 void randomdelay(void)
35 struct timespec req, rem;
40 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
41 nanosleep(&req, &rem);
45 transrecord_t *transStart()
47 transrecord_t *tmp = malloc(sizeof(transrecord_t));
48 tmp->cache = objstrCreate(1048576);
49 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
53 /* This function finds the location of the objects involved in a transaction
54 * and returns the pointer to the object if found in a remote location */
55 objheader_t *transRead(transrecord_t *record, unsigned int oid)
57 unsigned int machinenumber;
58 objheader_t *tmp, *objheader;
62 /* Search local cache */
63 if((objheader =(objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
65 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
66 /* Look up in machine lookup table and copy into cache*/
67 // tmp = mhashSearch(oid);
68 size = sizeof(objheader_t)+classsize[tmp->type];
69 objcopy = objstrAlloc(record->cache, size);
70 memcpy(objcopy, (void *)objheader, size);
71 /* Insert into cache's lookup table */
72 chashInsert(record->lookupTable, objheader->oid, objcopy);
74 } else { /* If not found in machine look up */
75 /* Get the object from the remote location */
76 machinenumber = lhashSearch(oid);
77 objcopy = getRemoteObj(record, machinenumber, oid);
79 //If object is not found in Remote location
80 //printf("Object oid = %d not found in Machine %d\n", oid, machinenumber);
84 //printf("Object oid = %d found in Machine %d\n", oid, machinenumber);
89 /* This function creates objects in the transaction record */
90 objheader_t *transCreateObj(transrecord_t *record, unsigned short type)
92 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + classsize[type]));
93 tmp->oid = getNewOID();
96 tmp->rcount = 0; //? not sure how to handle this yet
99 chashInsert(record->lookupTable, tmp->oid, tmp);
102 /* This function creates machine piles based on all machines involved in a
103 * transaction commit request */
104 plistnode_t *createPiles(transrecord_t *record) {
106 unsigned int size;/* Represents number of bins in the chash table */
107 chashlistnode_t *curr, *ptr, *next;
108 plistnode_t *pile = NULL;
109 unsigned int machinenum;
110 void *localmachinenum;
111 objheader_t *headeraddr;
113 ptr = record->lookupTable->table;
114 size = record->lookupTable->size;
116 for(i = 0; i < size ; i++) {
118 /* Inner loop to traverse the linked list of the cache lookupTable */
119 while(curr != NULL) {
120 //if the first bin in hash table is empty
125 //Get machine location for object id
127 if ((machinenum = lhashSearch(curr->key)) == 0) {
128 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
132 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
133 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
136 //Make machine groups
137 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
138 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
142 /* Check if local or not */
143 if((localmachinenum = mhashSearch(curr->key)) != NULL) {
144 pile->local = 1; //True i.e. local
153 /* This function initiates the transaction commit process
154 * Spawns threads for each of the new connections with Participants
155 * and creates new piles by calling the createPiles(),
156 * Fills the piles with necesaary information and
157 * Sends a transrequest() to each pile*/
158 int transCommit(transrecord_t *record) {
159 unsigned int tot_bytes_mod, *listmid;
162 int pilecount = 0, offset, threadnum = 0, trecvcount = 0, tmachcount = 0;
163 char buffer[RECEIVE_BUFFER_SIZE],control;
164 char transid[TID_LEN];
165 trans_req_data_t *tosend;
166 trans_commit_data_t transinfo;
167 static int newtid = 0;
168 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
171 /* Look through all the objects in the transaction record and make piles
172 * for each machine involved in the transaction*/
173 pile = createPiles(record);
175 /* Create the packet to be sent in TRANS_REQUEST */
177 /* Count the number of participants */
178 pilecount = pCount(pile);
180 /* Create a list of machine ids(Participants) involved in transaction */
181 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
182 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
185 pListMid(pile, listmid);
188 /* Initialize thread variables,
189 * Spawn a thread for each Participant involved in a transaction */
190 pthread_t thread[pilecount];
192 pthread_cond_t tcond;
193 pthread_mutex_t tlock;
194 pthread_mutex_t tlshrd;
196 thread_data_array_t *thread_data_array;
197 thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount);
198 local_thread_data_array_t *ltdata;
199 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
200 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
204 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
206 /* Initialize and set thread detach attribute */
207 pthread_attr_init(&attr);
208 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
209 pthread_mutex_init(&tlock, NULL);
210 pthread_cond_init(&tcond, NULL);
212 /* Process each machine pile */
213 while(pile != NULL) {
214 //Create transaction id
216 //trans_req_data_t *tosend;
217 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
218 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
221 tosend->f.control = TRANS_REQUEST;
222 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
223 tosend->f.mcount = pilecount;
224 tosend->f.numread = pile->numread;
225 tosend->f.nummod = pile->nummod;
226 tosend->f.sum_bytes = pile->sum_bytes;
227 tosend->listmid = listmid;
228 tosend->objread = pile->objread;
229 tosend->oidmod = pile->oidmod;
230 thread_data_array[threadnum].thread_id = threadnum;
231 thread_data_array[threadnum].mid = pile->mid;
232 thread_data_array[threadnum].pilecount = pilecount;
233 thread_data_array[threadnum].buffer = tosend;
234 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
235 thread_data_array[threadnum].threshold = &tcond;
236 thread_data_array[threadnum].lock = &tlock;
237 thread_data_array[threadnum].count = &trecvcount;
238 thread_data_array[threadnum].replyctrl = &treplyctrl;
239 thread_data_array[threadnum].replyretry = &treplyretry;
240 thread_data_array[threadnum].rec = record;
241 /* If local do not create any extra connection */
242 if(pile->local != 1) {
243 rc = pthread_create(&thread[threadnum], NULL, transRequest, (void *) &thread_data_array[threadnum]);
245 perror("Error in pthread create\n");
249 /*Unset the pile->local flag*/
251 /*Set flag to identify that Local machine is involved*/
252 ltdata->tdata = &thread_data_array[threadnum];
253 ltdata->transinfo = &transinfo;
254 val = pthread_create(&thread[threadnum], NULL, handleLocalReq, (void *) ltdata);
256 perror("Error in pthread create\n");
264 /* Free attribute and wait for the other threads */
265 pthread_attr_destroy(&attr);
266 for (i = 0 ;i < pilecount ; i++) {
267 rc = pthread_join(thread[i], NULL);
270 printf("ERROR return code from pthread_join() is %d\n", rc);
276 pthread_cond_destroy(&tcond);
277 pthread_mutex_destroy(&tlock);
281 free(thread_data_array);
284 /* Retry trans commit procedure if not sucessful in the first try */
285 if(treplyretry == 1) {
286 /* wait a random amount of time */
289 /* Retry the commiting transaction again */
296 /* This function sends information involved in the transaction request and
297 * accepts a response from particpants.
298 * It calls decideresponse() to decide on what control message
299 * to send next and sends the message using sendResponse()*/
300 void *transRequest(void *threadarg) {
302 struct sockaddr_in serv_addr;
303 struct hostent *server;
304 thread_data_array_t *tdata;
305 objheader_t *headeraddr;
306 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
307 char machineip[16], retval;
309 tdata = (thread_data_array_t *) threadarg;
311 /* Send Trans Request */
312 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
313 perror("Error in socket for TRANS_REQUEST\n");
316 bzero((char*) &serv_addr, sizeof(serv_addr));
317 serv_addr.sin_family = AF_INET;
318 serv_addr.sin_port = htons(LISTEN_PORT);
319 midtoIP(tdata->mid,machineip);
320 machineip[15] = '\0';
321 serv_addr.sin_addr.s_addr = inet_addr(machineip);
322 /* Open Connection */
323 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
324 perror("Error in connect for TRANS_REQUEST\n");
328 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
329 /* Send bytes of data with TRANS_REQUEST control message */
330 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
331 perror("Error sending fixed bytes for thread\n");
334 /* Send list of machines involved in the transaction */
336 int size=sizeof(unsigned int)*tdata->pilecount;
337 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
338 perror("Error sending list of machines for thread\n");
342 /* Send oids and version number tuples for objects that are read */
344 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
345 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
346 perror("Error sending tuples for thread\n");
350 /* Send objects that are modified */
351 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
353 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
354 size=sizeof(objheader_t)+classsize[headeraddr->type];
355 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
356 perror("Error sending obj modified for thread\n");
361 /* Read control message from Participant */
362 if((n = read(sd, &control, sizeof(char))) <= 0) {
363 perror("Error in reading control message from Participant\n");
366 recvcontrol = control;
368 /* Update common data structure and increment count */
369 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
371 /* Lock and update count */
372 //Thread sleeps until all messages from pariticipants are received by coordinator
373 pthread_mutex_lock(tdata->lock);
375 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
377 /* Wake up the threads and invoke decideResponse (once) */
378 if(*(tdata->count) == tdata->pilecount) {
379 if (decideResponse(tdata) != 0) {
380 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
381 pthread_mutex_unlock(tdata->lock);
385 pthread_cond_broadcast(tdata->threshold);
387 pthread_cond_wait(tdata->threshold, tdata->lock);
389 pthread_mutex_unlock(tdata->lock);
391 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
392 * to all participants in their respective socket */
393 if (sendResponse(tdata, sd) == 0) {
394 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
395 pthread_mutex_unlock(tdata->lock);
400 /* Close connection */
405 /* This function decides the reponse that needs to be sent to
406 * all Participant machines involved in the transaction commit */
407 int decideResponse(thread_data_array_t *tdata) {
409 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
412 //Check common data structure
413 for (i = 0 ; i < tdata->pilecount ; i++) {
414 /*Switch on response from Participant */
415 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
416 written onto the shared array */
419 printf("DEBUG-> trans.c Recv TRANS_DISAGREE\n");
424 printf("DEBUG-> trans.c Recv TRANS_AGREE\n");
428 case TRANS_SOFT_ABORT:
429 printf("DEBUG-> trans.c Recv TRANS_SOFT_ABORT\n");
433 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
438 /* Decide what control message to send to Participant */
439 if(transdisagree > 0) {
441 *(tdata->replyctrl) = TRANS_ABORT;
442 printf("DEBUG-> trans.c Sending TRANS_ABORT\n");
443 objstrDelete(tdata->rec->cache);
444 chashDelete(tdata->rec->lookupTable);
446 } else if(transagree == tdata->pilecount){
448 *(tdata->replyctrl) = TRANS_COMMIT;
449 printf("DEBUG-> trans.c Sending TRANS_COMMIT\n");
450 objstrDelete(tdata->rec->cache);
451 chashDelete(tdata->rec->lookupTable);
453 } else if(transsoftabort > 0 && transdisagree == 0) {
454 /* Send Abort in soft abort case followed by retry commiting transaction again*/
455 *(tdata->replyctrl) = TRANS_ABORT;
456 *(tdata->replyretry) = 1;
457 printf("DEBUG-> trans.c Sending TRANS_ABORT\n");
459 printf("DEBUG -> %s, %d: Error: undecided response\n", __FILE__, __LINE__);
465 /* This function sends the final response to all threads in their respective socket id */
466 char sendResponse(thread_data_array_t *tdata, int sd) {
467 int n, N, sum, oidcount = 0;
468 char *ptr, retval = 0;
469 unsigned int *oidnotfound;
471 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
472 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
473 /* Read list of objects missing */
474 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
475 N = oidcount * sizeof(unsigned int);
476 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
477 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
479 ptr = (char *) oidnotfound;
481 n = read(sd, ptr+sum, N-sum);
483 } while(sum < N && n !=0);
485 retval = TRANS_SOFT_ABORT;
487 /* If the decided response is TRANS_ABORT */
488 if(*(tdata->replyctrl) == TRANS_ABORT) {
489 retval = TRANS_ABORT;
490 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
491 retval = TRANS_COMMIT;
493 /* Send response to the Participant */
494 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
495 perror("Error sending ctrl message for participant\n");
501 /* This function opens a connection, places an object read request to the
502 * remote machine, reads the control message and object if available and
503 * copies the object and its header to the local cache.
504 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
506 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
508 struct sockaddr_in serv_addr;
509 struct hostent *server;
515 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
516 perror("Error in socket\n");
519 bzero((char*) &serv_addr, sizeof(serv_addr));
520 serv_addr.sin_family = AF_INET;
521 serv_addr.sin_port = htons(LISTEN_PORT);
522 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
523 midtoIP(mnum,machineip);
524 machineip[15] = '\0';
525 serv_addr.sin_addr.s_addr = inet_addr(machineip);
526 /* Open connection */
527 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
528 perror("Error in connect\n");
531 char readrequest[sizeof(char)+sizeof(unsigned int)];
532 readrequest[0] = READ_REQUEST;
533 *((unsigned int *)(&readrequest[1])) = oid;
534 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
535 perror("Error sending message\n");
540 printf("DEBUG -> ready to rcv ...\n");
542 /* Read response from the Participant */
543 if((val = read(sd, &control, sizeof(char))) <= 0) {
544 perror("No control response for getRemoteObj sent\n");
548 case OBJECT_NOT_FOUND:
549 printf("DEBUG -> Control OBJECT_NOT_FOUND received\n");
552 /* Read object if found into local cache */
553 if((val = read(sd, &size, sizeof(int))) <= 0) {
554 perror("No size is read from the participant\n");
557 objcopy = objstrAlloc(record->cache, size);
558 if((val = read(sd, objcopy, size)) <= 0) {
559 perror("No objects are read from the remote participant\n");
562 /* Insert into cache's lookup table */
563 chashInsert(record->lookupTable, oid, objcopy);
566 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
569 /* Close connection */
574 /*This function handles the local trans requests involved in a transaction commiting process
575 * makes a decision if the local machine sends AGREE or DISAGREE or SOFT_ABORT
576 * Activates the other nonlocal threads that are waiting for the decision and the
577 * based on common decision by all groups involved in the transaction it
578 * either commits or aborts the transaction.
579 * It also frees the calloced memory resources
582 void *handleLocalReq(void *threadarg) {
585 char control = 0, *ptr;
587 unsigned int *oidnotfound = NULL, *oidlocked = NULL, *oidmod = NULL;
589 objheader_t *headptr;
590 local_thread_data_array_t *localtdata;
592 localtdata = (local_thread_data_array_t *) threadarg;
594 /* Counters and arrays to formulate decision on control message to be sent */
595 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
596 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
597 oidmod = (unsigned int *) calloc(localtdata->tdata->buffer->f.nummod, sizeof(unsigned int));
598 int objnotfound = 0, objlocked = 0, objmod =0, v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
599 int objmodnotfound = 0, nummodfound = 0;
601 /* modptr points to the beginning of the object store
602 * created at the Pariticipant */
603 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
604 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
610 /* Process each oid in the machine pile/ group per thread */
611 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
612 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
613 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
615 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
616 incr += sizeof(unsigned int);
617 version = *((short *)(localtdata->tdata->buffer->objread + incr));
618 } else {//Objs modified
619 headptr = (objheader_t *) ptr;
621 oidmod[objmod] = oid;//Array containing modified oids
623 version = headptr->version;
624 ptr += sizeof(objheader_t) + classsize[headptr->type];
627 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
629 /* Save the oids not found and number of oids not found for later use */
630 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
631 /* Save the oids not found and number of oids not found for later use */
633 oidnotfound[objnotfound] = ((objheader_t *)mobj)->oid;
635 } else { /* If Obj found in machine (i.e. has not moved) */
636 /* Check if Obj is locked by any previous transaction */
637 if ((((objheader_t *)mobj)->status & LOCK) == LOCK) {
638 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
640 } else {/* If versions don't match ...HARD ABORT */
642 /* Send TRANS_DISAGREE to Coordinator */
643 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
644 printf("DEBUG -> Sending TRANS_DISAGREE\n");
645 //return tdata->recvmsg[tdata->thread_id].rcv_status;
647 } else {/* If Obj is not locked then lock object */
648 ((objheader_t *)mobj)->status |= LOCK;
649 //TODO Remove this for Testing
652 /* Save all object oids that are locked on this machine during this transaction request call */
653 oidlocked[objlocked] = ((objheader_t *)mobj)->oid;
655 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
657 } else { /* If versions don't match ...HARD ABORT */
659 /* Send TRANS_DISAGREE to Coordinator */
660 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
661 printf("DEBUG -> Sending TRANS_DISAGREE\n");
662 // return tdata->recvmsg[tdata->thread_id].rcv_status;
668 /*Decide the response to be sent to the Coordinator( the local machine in this case)*/
670 /* Condition to send TRANS_AGREE */
671 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
672 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
673 printf("DEBUG -> Sending TRANS_AGREE\n");
675 /* Condition to send TRANS_SOFT_ABORT */
676 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
677 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
678 printf("DEBUG -> Sending TRANS_SOFT_ABORT\n");
679 /* Send number of oids not found and the missing oids if objects are missing in the machine */
680 /* TODO Remember to store the oidnotfound for later use
681 if(objnotfound != 0) {
682 int size = sizeof(unsigned int)* objnotfound;
687 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
688 * if Participant receives a TRANS_COMMIT */
689 localtdata->transinfo->objmod = oidmod;
690 localtdata->transinfo->objlocked = oidlocked;
691 localtdata->transinfo->objnotfound = oidnotfound;
692 localtdata->transinfo->modptr = modptr;
693 localtdata->transinfo->nummod = localtdata->tdata->buffer->f.nummod;
694 localtdata->transinfo->numlocked = objlocked;
695 localtdata->transinfo->numnotfound = objnotfound;
697 /*Set flag to show that common data structure for this individual thread has been written to */
698 //*(tdata->localstatus) |= LM_UPDATED;
700 /* Lock and update count */
701 //Thread sleeps until all messages from pariticipants are received by coordinator
702 pthread_mutex_lock(localtdata->tdata->lock);
703 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
705 /* Wake up the threads and invoke decideResponse (once) */
706 if(*(localtdata->tdata->count) == localtdata->tdata->pilecount) {
707 if (decideResponse(localtdata->tdata) != 0) {
708 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
709 pthread_mutex_unlock(localtdata->tdata->lock);
712 pthread_cond_broadcast(localtdata->tdata->threshold);
714 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
716 pthread_mutex_unlock(localtdata->tdata->lock);
718 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
719 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
720 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->transinfo->nummod, localtdata->tdata->buffer->f.numread) != 0) {
721 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
724 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
725 if(transComProcess(localtdata->transinfo) != 0) {
726 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
732 printf("DEBUG -> Freeing...\n");
734 if (localtdata->transinfo->objmod != NULL) {
735 free(localtdata->transinfo->objmod);
736 localtdata->transinfo->objmod = NULL;
738 if (localtdata->transinfo->objlocked != NULL) {
739 free(localtdata->transinfo->objlocked);
740 localtdata->transinfo->objlocked = NULL;
742 if (localtdata->transinfo->objnotfound != NULL) {
743 free(localtdata->transinfo->objnotfound);
744 localtdata->transinfo->objnotfound = NULL;
749 /* This function completes the ABORT process if the transaction is aborting
751 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod, int numread) {
754 objheader_t *tmp_header;
757 printf("DEBUG -> Recv TRANS_ABORT\n");
758 /* Set all ref counts as 1 and do garbage collection */
760 for(i = 0; i< nummod; i++) {
761 tmp_header = (objheader_t *)ptr;
762 tmp_header->rcount = 1;
763 ptr += sizeof(objheader_t) + classsize[tmp_header->type];
765 /* Unlock objects that was locked due to this transaction */
766 for(i = 0; i< numlocked; i++) {
767 header = mhashSearch(objlocked[i]);// find the header address
768 ((objheader_t *)header)->status &= ~(LOCK);
770 //TODO/* Unset the bit for local objects */
772 /* Send ack to Coordinator */
773 printf("DEBUG-> TRANS_SUCCESSFUL\n");
775 /*Free the pointer */
780 /*This function completes the COMMIT process is the transaction is commiting
782 int transComProcess(trans_commit_data_t *transinfo) {
784 int i = 0, offset = 0;
787 printf("DEBUG -> Recv TRANS_COMMIT\n");
788 /* Process each modified object saved in the mainobject store */
789 for(i=0; i<transinfo->nummod; i++) {
790 if((header = (objheader_t *) mhashSearch(transinfo->objmod[i])) == NULL) {
791 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
793 /* Change reference count of older address and free space in objstr ?? */
794 header->rcount = 1; //TODO Not sure what would be the val
796 /* Change ptr address in mhash table */
797 mhashRemove(transinfo->objmod[i]);
798 mhashInsert(transinfo->objmod[i], (transinfo->modptr + offset));
799 offset += sizeof(objheader_t) + classsize[header->type];
801 /* Update object version number */
802 header = (objheader_t *) mhashSearch(transinfo->objmod[i]);
803 header->version += 1;
806 /* Unlock locked objects */
807 for(i=0; i<transinfo->numlocked; i++) {
808 header = (objheader_t *) mhashSearch(transinfo->objlocked[i]);
809 header->status &= ~(LOCK);
812 //TODO Update location lookup table
813 //TODO/* Unset the bit for local objects */
815 /* Send ack to Coordinator */
816 printf("DEBUG-> TRANS_SUCESSFUL\n");
820 /*This function makes piles to prefetch records and prefetches the oids from remote machines */
821 int transPrefetch(transrecord_t *record, int *arrayofoffset[], short numoids){
823 int arraylength[numoids];
824 unsigned int machinenumber;
825 objheader_t *tmp, *objheader;
830 /* Given tuple find length of tuple*/
831 for(i = 0; i < numoids ; i++) {
832 arraylength[i] = arrayLength(arrayofoffset[i]);
834 /* Check for similar tuples or other special case tuples that can be combined to a
836 if(checkPrefetchTuples(arrayofoffset, arraylength, numoids) != 0) {
837 printf("Error on checkPrefetchTuples at %s, %d\n", __FILE__, __LINE__);
841 /* Check if part of prefetch request available locally */
842 for(i = 0; i < numoids ; i++) {
843 if(arrayofoffset[i][0] != -1) {
844 if((objheader = (objheader_t *) mhashSearch(arrayofoffset[i][k])) != NULL) {
845 /* Look up in machine lookup table and copy into cache*/
846 //tmp = mhashSearch(oid);
847 size = sizeof(objheader_t)+classsize[tmp->type];
848 objcopy = objstrAlloc(record->cache, size);
849 memcpy(objcopy, (void *)objheader, size);
850 /* Insert into cache's lookup table */
851 chashInsert(record->lookupTable, objheader->oid, objcopy);
852 /* Find the offset field*/
853 if(foundLocal(arrayofoffset, record, arrayofoffset[i], tmp, arrayofoffset[i][k+1], i) != 0 ) {
854 printf("Error in foundLocal() %s, %d\n", __FILE__, __LINE__);
863 /* Initialize and set thread attributes
864 * Spawn a thread for each prefetch request sent*/
865 pthread_t thread[numoids];
866 pthread_attr_init(&attr);
867 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
869 /* Create Machine Piles to send prefetch requests use threads*/
870 for( i = 0 ; i< numoids ; i++) {
871 if(arrayofoffset[i][0] == -1)
874 /* For each Pile in the machine send TRANS_PREFETCH */
875 //makePiles(arrayofoffset, numoids);
876 /* Fill thread data structure */
877 rc = pthread_create(&thread[i] , &attr, sendPrefetchReq, (void *) arrayofoffset[i]);
879 perror("Error in pthread create at transPrefetch()\n");
886 /* Free attribute and wait to join other threads */
887 for (i = 0 ;i < numoids ; i++) {
888 rc = pthread_join(thread[i], NULL);
890 perror("Error pthread_join() in transPrefetch()\n");
894 pthread_attr_destroy(&attr);
900 int checkPrefetchTuples(int *arrayofoffset[], int *arraylength, short numoids) {
901 int i, j, k, matchfound = 0, count = 0, slength, length;
902 int *sarray, *larray;
904 /* Check if the prefetch oids are same and have same offsets
905 * for case x.a.b and y.a.b where x and y have same oid's
906 * or if a.b.c is a subset of x.b.c.d*/
907 /* check for case where the generated request a.y.z or x.y.z.g then
908 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
909 for(i = 0; i < numoids -1 ; i++) {
910 if(arrayofoffset[i][0] == -1)
912 for( j = 0; j < (numoids - (i+1)); j++) {
913 if(arrayofoffset[j][0] == -1)
915 /* If the oids of the tuples match */
916 if((arrayofoffset[i][0] == arrayofoffset[j][0]) && (i != j )) {
917 /*Find the smallest length of two arrays, find ptrs to smallest and long array */
918 if(arraylength[i] > arraylength[j]) {
919 slength = arraylength[j];
920 sarray = arrayofoffset[j];
921 larray = arrayofoffset[i];
923 slength = arraylength[i];
924 sarray = arrayofoffset[i];
925 larray = arrayofoffset[j];
927 /* From first offset until end of tuple compare all offsets of sarray and larray
928 * if not a match then break */
929 for(k = 1 ; k < slength -1 ; k++) {
930 if(sarray[k] != larray[k]) {
934 /* If number of same offsets encountered is same as
935 * no of offsets in small array then common tuples found*/
936 if(k == (slength -1))
945 /* This function goes through an array and finds out until what offets
946 * * can it make a new pile
947 * * -1 indicates a special character to mark end of oid, offset tuple*/
948 int foundLocal(int *arrayofoffset[], transrecord_t *record, int *array, objheader_t *header, int offset, int index) {
949 int i, j, counter, len;
952 objheader_t *tmp, *objheader;
955 /* The oid corresponding to the first offset */
956 oid = (int) (header + sizeof(objheader_t) + offset);
957 /* Repeat for all offset values in the array */
958 for(i = 1; array[i] != -1 ; ) {
959 /* If oid is found locally then insert into cache and continue
960 * with next offset to find the corresponding oid */
961 if((objheader = (objheader_t*) mhashSearch(oid)) != NULL) {
962 tmp = mhashSearch(oid);
963 size = sizeof(objheader_t)+classsize[tmp->type];
964 objcopy = objstrAlloc(record->cache, size);
965 memcpy(objcopy, (void *)tmp, size);
966 /* Insert into cache's lookup table */
967 chashInsert(record->lookupTable, objheader->oid, objcopy);
968 oid = (int) (tmp + sizeof(objheader_t) + array[i+1]);
970 /*If oid not found locally then
971 *assign the latest oid found as the first element
972 *of array and copy left over offsets as other
973 *array elements to build the new prefetch array*/
975 arrayofoffset[index][0] = (int) oid;
977 len = arrayLength((int *)array[index]);
978 for( j = 1 ; counter <= len; j++,counter++) {
979 arrayofoffset[index][j] = array[counter + 1];
986 /* If all offsets are found locally, then do not treat this as valid prefetch tuple */
987 if(i == arrayLength((int *)array[index]) - 1) {
988 arrayofoffset[index][0] = -1; //Mark beginning of array as -1
994 void *sendPrefetchReq(void *prefetchtuple) {
996 struct sockaddr_in serv_addr;
997 struct hostent *server;
998 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
999 char machineip[16], retval;
1002 /* Send Trans Prefetch Request */
1003 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1004 perror("Error in socket for TRANS_REQUEST\n");
1007 bzero((char*) &serv_addr, sizeof(serv_addr));
1008 serv_addr.sin_family = AF_INET;
1009 serv_addr.sin_port = htons(LISTEN_PORT);
1010 //midtoIP(tdata->mid,machineip);
1011 // machineip[15] = '\0';
1012 // serv_addr.sin_addr.s_addr = inet_addr(machineip);
1014 /* Open Connection */
1015 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1016 perror("Error in connect for TRANS_REQUEST\n");