4 #include "machinepile.h"
9 #include "threadnotify.h"
12 #include <sys/types.h>
13 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <sys/types.h>
25 #define LISTEN_PORT 2156
27 #define PREFETCH_CACHE_SIZE 1048576 //1MB
28 #define CONFIG_FILENAME "dstm.conf"
30 /* Global Variables */
31 extern int classsize[];
32 extern primarypfq_t pqueue; //Shared prefetch queue
33 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
34 objstr_t *prefetchcache; //Global Prefetch cache
35 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
36 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
37 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
38 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
39 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
40 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
41 extern objstr_t *mainobjstore;
42 unsigned int myIpAddr;
43 unsigned int *hostIpAddrs;
46 int myIndexInHostArray;
47 unsigned int oidsPerBlock;
51 /************************************************************
52 * Global variables to map socketid and remote mid to
54 ***********************************************************/
55 midSocketInfo_t midSocketArray[NUM_MACHINES];
56 int sockCount; //number of connections with all remote machines(one socket per mc)
57 int sockIdFound; //track if socket file descriptor is already established
59 void printhex(unsigned char *, int);
60 plistnode_t *createPiles(transrecord_t *);
62 /*******************************
63 * Send and Recv function calls
64 *******************************/
65 void send_data(int fd , void *buf, int buflen) {
66 char *buffer = (char *)(buf);
70 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
73 printf("error: at %s, %d\n", __FILE__, __LINE__);
81 void recv_data(int fd , void *buf, int buflen) {
82 char *buffer = (char *)(buf);
86 numbytes = recv(fd, buffer, size, 0);
89 printf("error: at %s, %d\n", __FILE__, __LINE__);
97 void printhex(unsigned char *ptr, int numBytes)
100 for (i = 0; i < numBytes; i++)
103 printf("0%x ", ptr[i]);
105 printf("%x ", ptr[i]);
111 inline int arrayLength(int *array) {
113 for(i=0 ;array[i] != -1; i++)
117 inline int findmax(int *array, int arraylength) {
120 for(i = 0; i < arraylength; i++){
127 /* This function is a prefetch call generated by the compiler that
128 * populates the shared primary prefetch queue*/
129 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
130 /* Allocate for the queue node*/
132 int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
135 if((node = calloc(1, qnodesize)) == NULL) {
136 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
139 /* Set queue node values */
140 int len = sizeof(prefetchqelem_t);
142 unsigned int *narray;
143 unsigned short *narray2;
145 int top=endoffsets[ntuples-1];
146 *((int *)(node+len))=ntuples;
148 narray=(unsigned int *)(node+len);
149 narray2=(unsigned short *)(narray+ntuples);
150 narray3=(short *)(narray2+ntuples);
152 for(i=0;i<ntuples;i++) {
154 narray2[i]=endoffsets[i];
157 narray3[i]=arrayfields[i];
159 /* Lock and insert into primary prefetch queue */
160 pthread_mutex_lock(&pqueue.qlock);
161 pre_enqueue((prefetchqelem_t *)node);
162 pthread_cond_signal(&pqueue.qcond);
163 pthread_mutex_unlock(&pqueue.qlock);
168 /* This function starts up the transaction runtime. */
169 int dstmStartup(const char * option) {
170 pthread_t thread_Listen;
172 int master=option!=NULL && strcmp(option, "master")==0;
174 if (processConfigFile() != 0)
175 return 0; //TODO: return error value, cause main program to exit
187 pthread_attr_init(&attr);
188 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
189 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
198 //TODO Use this later
199 void *pCacheAlloc(objstr_t *store, unsigned int size) {
205 while(ptr->next != NULL) {
206 /* check if store is empty */
207 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
222 /* This function initiates the prefetch thread
223 * A queue is shared between the main thread of execution
224 * and the prefetch thread to process the prefetch call
225 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
226 * processes the prefetch requests */
230 //Create and initialize prefetch cache structure
231 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
232 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
233 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
235 /* Initialize attributes for mutex */
236 pthread_mutexattr_init(&prefetchcache_mutex_attr);
237 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
239 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
241 //Create prefetch cache lookup table
242 if(prehashCreate(HASH_SIZE, LOADFACTOR))
245 //Initialize primary shared queue
247 //Initialize machine pile w/prefetch oids and offsets shared queue
250 //Create the primary prefetch thread
252 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
254 pthread_detach(tPrefetch);
256 //Initialize mid to socketid mapping array
258 for(t = 0; t < NUM_MACHINES; t++) {
259 midSocketArray[t].mid = 0;
260 midSocketArray[t].sockid = 0;
263 //Create and Initialize a pool of threads
264 /* Threads are active for the entire period runtime is running */
265 for(t = 0; t< NUM_THREADS; t++) {
267 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
269 pthread_detach(wthreads[t]);
273 /* This function stops the threads spawned */
276 pthread_cancel(tPrefetch);
277 for(t = 0; t < NUM_THREADS; t++)
278 pthread_cancel(wthreads[t]);
283 /* This functions inserts randowm wait delays in the order of msec
284 * Mostly used when transaction commits retry*/
292 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
293 nanosleep(&req, NULL);
297 /* This function initializes things required in the transaction start*/
298 transrecord_t *transStart()
300 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
301 tmp->cache = objstrCreate(1048576);
302 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
304 tmp->revertlist=NULL;
309 /* This function finds the location of the objects involved in a transaction
310 * and returns the pointer to the object if found in a remote location */
311 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
312 unsigned int machinenumber;
313 objheader_t *tmp, *objheader;
314 objheader_t *objcopy;
319 printf("Error: %s, %d oid is NULL \n", __FILE__, __LINE__);
323 /* Search local transaction cache */
324 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
326 return &objheader[1];
330 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
331 /* Look up in machine lookup table and copy into cache*/
332 GETSIZE(size, objheader);
333 size += sizeof(objheader_t);
334 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
335 memcpy(objcopy, objheader, size);
336 /* Insert into cache's lookup table */
337 chashInsert(record->lookupTable, OID(objheader), objcopy);
343 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
345 size+=sizeof(objheader_t);
346 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
347 memcpy(objcopy, tmp, size);
348 /* Insert into cache's lookup table */
349 chashInsert(record->lookupTable, OID(tmp), objcopy);
356 /* Get the object from the remote location */
357 if((machinenumber = lhashSearch(oid)) == 0) {
358 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
361 objcopy = getRemoteObj(record, machinenumber, oid);
363 if(objcopy == NULL) {
364 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
377 /* This function creates objects in the transaction record */
378 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
380 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
381 tmp->notifylist = NULL;
382 OID(tmp) = getNewOID();
386 chashInsert(record->lookupTable, OID(tmp), tmp);
389 return &tmp[1]; //want space after object header
395 /* This function creates machine piles based on all machines involved in a
396 * transaction commit request */
397 plistnode_t *createPiles(transrecord_t *record) {
399 unsigned int size;/* Represents number of bins in the chash table */
400 chashlistnode_t *curr, *ptr, *next;
401 plistnode_t *pile = NULL;
402 unsigned int machinenum;
403 void *localmachinenum;
404 objheader_t *headeraddr;
406 ptr = record->lookupTable->table;
407 size = record->lookupTable->size;
409 for(i = 0; i < size ; i++) {
411 /* Inner loop to traverse the linked list of the cache lookupTable */
412 while(curr != NULL) {
413 //if the first bin in hash table is empty
419 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
420 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
424 //Get machine location for object id (and whether local or not)
425 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
426 machinenum = myIpAddr;
427 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
428 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
432 //Make machine groups
433 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
434 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
444 /* This function initiates the transaction commit process
445 * Spawns threads for each of the new connections with Participants
446 * and creates new piles by calling the createPiles(),
447 * Sends a transrequest() to each remote machines for objects found remotely
448 * and calls handleLocalReq() to process objects found locally */
449 int transCommit(transrecord_t *record) {
450 unsigned int tot_bytes_mod, *listmid;
451 plistnode_t *pile, *pile_ptr;
453 int pilecount, offset, threadnum = 0, trecvcount = 0;
455 char transid[TID_LEN];
456 trans_req_data_t *tosend;
457 trans_commit_data_t transinfo;
458 static int newtid = 0;
459 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
461 thread_data_array_t *thread_data_array;
462 local_thread_data_array_t *ltdata;
468 thread_data_array = NULL;
471 /* Look through all the objects in the transaction record and make piles
472 * for each machine involved in the transaction*/
473 pile_ptr = pile = createPiles(record);
475 /* Create the packet to be sent in TRANS_REQUEST */
477 /* Count the number of participants */
478 pilecount = pCount(pile);
480 /* Create a list of machine ids(Participants) involved in transaction */
481 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
482 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
485 pListMid(pile, listmid);
488 /* Initialize thread variables,
489 * Spawn a thread for each Participant involved in a transaction */
490 pthread_t thread[pilecount];
492 pthread_cond_t tcond;
493 pthread_mutex_t tlock;
494 pthread_mutex_t tlshrd;
496 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
497 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
498 pthread_cond_destroy(&tcond);
499 pthread_mutex_destroy(&tlock);
505 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
506 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
507 pthread_cond_destroy(&tcond);
508 pthread_mutex_destroy(&tlock);
511 free(thread_data_array);
515 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
517 /* Initialize and set thread detach attribute */
518 pthread_attr_init(&attr);
519 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
520 pthread_mutex_init(&tlock, NULL);
521 pthread_cond_init(&tcond, NULL);
523 /* Process each machine pile */
524 while(pile != NULL) {
525 //Create transaction id
527 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
528 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
529 pthread_cond_destroy(&tcond);
530 pthread_mutex_destroy(&tlock);
533 free(thread_data_array);
537 tosend->f.control = TRANS_REQUEST;
538 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
539 tosend->f.mcount = pilecount;
540 tosend->f.numread = pile->numread;
541 tosend->f.nummod = pile->nummod;
542 tosend->f.numcreated = pile->numcreated;
543 tosend->f.sum_bytes = pile->sum_bytes;
544 tosend->listmid = listmid;
545 tosend->objread = pile->objread;
546 tosend->oidmod = pile->oidmod;
547 tosend->oidcreated = pile->oidcreated;
548 thread_data_array[threadnum].thread_id = threadnum;
549 thread_data_array[threadnum].mid = pile->mid;
550 thread_data_array[threadnum].buffer = tosend;
551 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
552 thread_data_array[threadnum].threshold = &tcond;
553 thread_data_array[threadnum].lock = &tlock;
554 thread_data_array[threadnum].count = &trecvcount;
555 thread_data_array[threadnum].replyctrl = &treplyctrl;
556 thread_data_array[threadnum].replyretry = &treplyretry;
557 thread_data_array[threadnum].rec = record;
558 /* If local do not create any extra connection */
559 if(pile->mid != myIpAddr) { /* Not local */
561 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
564 perror("Error in pthread create\n");
565 pthread_cond_destroy(&tcond);
566 pthread_mutex_destroy(&tlock);
569 for (i = 0; i < threadnum; i++)
570 free(thread_data_array[i].buffer);
571 free(thread_data_array);
576 ltdata->tdata = &thread_data_array[threadnum];
577 ltdata->transinfo = &transinfo;
579 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
582 perror("Error in pthread create\n");
583 pthread_cond_destroy(&tcond);
584 pthread_mutex_destroy(&tlock);
587 for (i = 0; i < threadnum; i++)
588 free(thread_data_array[i].buffer);
589 free(thread_data_array);
598 /* Free attribute and wait for the other threads */
599 pthread_attr_destroy(&attr);
601 for (i = 0; i < threadnum; i++) {
602 rc = pthread_join(thread[i], NULL);
605 printf("Error: return code from pthread_join() is %d\n", rc);
606 pthread_cond_destroy(&tcond);
607 pthread_mutex_destroy(&tlock);
610 for (j = i; j < threadnum; j++) {
611 free(thread_data_array[j].buffer);
615 free(thread_data_array[i].buffer);
619 pthread_cond_destroy(&tcond);
620 pthread_mutex_destroy(&tlock);
624 /* wait a random amount of time before retrying to commit transaction*/
625 if(treplyretry == 1) {
626 free(thread_data_array);
631 /* Retry trans commit procedure during soft_abort case */
632 } while (treplyretry == 1);
635 if(treplyctrl == TRANS_ABORT) {
637 objstrDelete(record->cache);
638 chashDelete(record->lookupTable);
640 free(thread_data_array);
643 } else if(treplyctrl == TRANS_COMMIT) {
645 objstrDelete(record->cache);
646 chashDelete(record->lookupTable);
648 free(thread_data_array);
652 //TODO Add other cases
653 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
660 /* This function sends information involved in the transaction request
661 * to participants and accepts a response from particpants.
662 * It calls decideresponse() to decide on what control message
663 * to send next to participants and sends the message using sendResponse()*/
664 void *transRequest(void *threadarg) {
666 struct sockaddr_in serv_addr;
667 thread_data_array_t *tdata;
668 objheader_t *headeraddr;
669 char control, recvcontrol;
670 char machineip[16], retval;
672 tdata = (thread_data_array_t *) threadarg;
674 /* Send Trans Request */
675 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
676 perror("Error in socket for TRANS_REQUEST\n");
679 bzero((char*) &serv_addr, sizeof(serv_addr));
680 serv_addr.sin_family = AF_INET;
681 serv_addr.sin_port = htons(LISTEN_PORT);
682 midtoIP(tdata->mid,machineip);
683 machineip[15] = '\0';
684 serv_addr.sin_addr.s_addr = inet_addr(machineip);
685 /* Open Connection */
686 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
687 perror("Error in connect for TRANS_REQUEST\n");
692 /* Send bytes of data with TRANS_REQUEST control message */
693 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
695 /* Send list of machines involved in the transaction */
697 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
698 send_data(sd, tdata->buffer->listmid, size);
701 /* Send oids and version number tuples for objects that are read */
703 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
704 send_data(sd, tdata->buffer->objread, size);
707 /* Send objects that are modified */
708 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
710 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
711 GETSIZE(size,headeraddr);
712 size+=sizeof(objheader_t);
713 send_data(sd, headeraddr, size);
716 /* Read control message from Participant */
717 recv_data(sd, &control, sizeof(char));
718 recvcontrol = control;
720 /* Update common data structure and increment count */
721 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
723 /* Lock and update count */
724 /* Thread sleeps until all messages from pariticipants are received by coordinator */
725 pthread_mutex_lock(tdata->lock);
727 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
729 /* Wake up the threads and invoke decideResponse (once) */
730 if(*(tdata->count) == tdata->buffer->f.mcount) {
731 decideResponse(tdata);
732 pthread_cond_broadcast(tdata->threshold);
734 pthread_cond_wait(tdata->threshold, tdata->lock);
736 pthread_mutex_unlock(tdata->lock);
738 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
739 * to all participants in their respective socket */
740 if (sendResponse(tdata, sd) == 0) {
741 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
746 recv_data((int)sd, &control, sizeof(char));
748 if(control == TRANS_UNSUCESSFUL) {
749 //printf("DEBUG-> TRANS_ABORTED\n");
750 } else if(control == TRANS_SUCESSFUL) {
751 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
753 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
756 /* Close connection */
761 /* This function decides the reponse that needs to be sent to
762 * all Participant machines after the TRANS_REQUEST protocol */
763 void decideResponse(thread_data_array_t *tdata) {
765 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
768 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
769 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
770 written onto the shared array */
773 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
774 /* treat as disagree, pass thru */
783 case TRANS_SOFT_ABORT:
789 if(transdisagree > 0) {
791 *(tdata->replyctrl) = TRANS_ABORT;
792 *(tdata->replyretry) = 0;
793 /* clear objects from prefetch cache */
794 for (i = 0; i < tdata->buffer->f.numread; i++)
795 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
796 for (i = 0; i < tdata->buffer->f.nummod; i++)
797 prehashRemove(tdata->buffer->oidmod[i]);
798 } else if(transagree == tdata->buffer->f.mcount){
800 *(tdata->replyctrl) = TRANS_COMMIT;
801 *(tdata->replyretry) = 0;
803 /* Send Abort in soft abort case followed by retry commiting transaction again*/
804 *(tdata->replyctrl) = TRANS_ABORT;
805 *(tdata->replyretry) = 1;
810 /* This function sends the final response to remote machines per thread in their respective socket id
811 * It returns a char that is only needed to check the correctness of execution of this function inside
813 char sendResponse(thread_data_array_t *tdata, int sd) {
814 int n, size, sum, oidcount = 0, control;
815 char *ptr, retval = 0;
816 unsigned int *oidnotfound;
818 control = *(tdata->replyctrl);
819 send_data(sd, &control, sizeof(char));
821 //TODO read missing objects to be used during object migration
822 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
824 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
825 // Read list of objects missing
826 recv_data(sd, &oidcount, sizeof(int));
827 //if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
829 size = oidcount * sizeof(unsigned int);
830 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
831 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
834 ptr = (char *) oidnotfound;
835 recv_data(sd, ptr, size);
837 retval = TRANS_SOFT_ABORT;
841 /* If the decided response is TRANS_ABORT */
842 if(*(tdata->replyctrl) == TRANS_ABORT) {
843 retval = TRANS_ABORT;
844 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
845 retval = TRANS_COMMIT;
851 /* This function opens a connection, places an object read request to the
852 * remote machine, reads the control message and object if available and
853 * copies the object and its header to the local cache.
856 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
858 struct sockaddr_in serv_addr;
864 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
865 perror("Error in socket\n");
869 bzero((char*) &serv_addr, sizeof(serv_addr));
870 serv_addr.sin_family = AF_INET;
871 serv_addr.sin_port = htons(LISTEN_PORT);
872 midtoIP(mnum,machineip);
873 machineip[15] = '\0';
874 serv_addr.sin_addr.s_addr = inet_addr(machineip);
877 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
878 perror("getRemoteObj() Error in connect\n");
882 char readrequest[sizeof(char)+sizeof(unsigned int)];
883 readrequest[0] = READ_REQUEST;
884 *((unsigned int *)(&readrequest[1])) = oid;
885 send_data(sd, readrequest, sizeof(readrequest));
887 /* Read response from the Participant */
888 recv_data(sd, &control, sizeof(char));
891 case OBJECT_NOT_FOUND:
894 /* Read object if found into local cache */
895 recv_data(sd, &size, sizeof(int));
896 objcopy = objstrAlloc(record->cache, size);
897 recv_data(sd, objcopy, size);
899 /* Insert into cache's lookup table */
900 chashInsert(record->lookupTable, oid, objcopy);
903 printf("Error: in recv response from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
912 /* This function handles the local objects involved in a transaction commiting process.
913 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
914 * Note Coordinator = local machine
915 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
916 * based on common agreement it either commits or aborts the transaction.
917 * It also frees the memory resources */
918 void *handleLocalReq(void *threadarg) {
919 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
920 local_thread_data_array_t *localtdata;
921 int objnotfound = 0, objlocked = 0;
922 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
925 unsigned short version;
927 objheader_t *headptr;
929 localtdata = (local_thread_data_array_t *) threadarg;
931 /* Counters and arrays to formulate decision on control message to be sent */
932 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
933 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
935 numread = localtdata->tdata->buffer->f.numread;
936 /* Process each oid in the machine pile/ group per thread */
937 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
938 if (i < localtdata->tdata->buffer->f.numread) {
939 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
941 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
942 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
943 } else { // Objects Modified
945 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
946 if (headptr == NULL) {
947 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
951 version = headptr->version;
953 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
955 /* Save the oids not found and number of oids not found for later use */
956 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
957 /* Save the oids not found and number of oids not found for later use */
958 oidnotfound[objnotfound] = oid;
960 } else { /* If Obj found in machine (i.e. has not moved) */
961 /* Check if Obj is locked by any previous transaction */
962 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
963 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
965 } else {/* If versions don't match ...HARD ABORT */
967 /* Send TRANS_DISAGREE to Coordinator */
968 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
970 } else {/* If Obj is not locked then lock object */
971 STATUS(((objheader_t *)mobj)) |= LOCK;
972 /* Save all object oids that are locked on this machine during this transaction request call */
973 oidlocked[objlocked] = OID(((objheader_t *)mobj));
975 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
977 } else { /* If versions don't match ...HARD ABORT */
979 /* Send TRANS_DISAGREE to Coordinator */
980 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
985 /* Condition to send TRANS_AGREE */
986 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
987 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
989 /* Condition to send TRANS_SOFT_ABORT */
990 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
991 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
994 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
995 * if Participant receives a TRANS_COMMIT */
996 localtdata->transinfo->objlocked = oidlocked;
997 localtdata->transinfo->objnotfound = oidnotfound;
998 localtdata->transinfo->modptr = NULL;
999 localtdata->transinfo->numlocked = objlocked;
1000 localtdata->transinfo->numnotfound = objnotfound;
1001 /* Lock and update count */
1002 //Thread sleeps until all messages from pariticipants are received by coordinator
1003 pthread_mutex_lock(localtdata->tdata->lock);
1004 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1006 /* Wake up the threads and invoke decideResponse (once) */
1007 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1008 decideResponse(localtdata->tdata);
1009 pthread_cond_broadcast(localtdata->tdata->threshold);
1011 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1013 pthread_mutex_unlock(localtdata->tdata->lock);
1014 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1015 if(transAbortProcess(localtdata) != 0) {
1016 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1019 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1020 if(transComProcess(localtdata) != 0) {
1021 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1026 if (localtdata->transinfo->objlocked != NULL) {
1027 free(localtdata->transinfo->objlocked);
1029 if (localtdata->transinfo->objnotfound != NULL) {
1030 free(localtdata->transinfo->objnotfound);
1036 /* This function completes the ABORT process if the transaction is aborting */
1037 int transAbortProcess(local_thread_data_array_t *localtdata) {
1039 unsigned int *objlocked;
1042 numlocked = localtdata->transinfo->numlocked;
1043 objlocked = localtdata->transinfo->objlocked;
1045 for (i = 0; i < numlocked; i++) {
1046 if((header = mhashSearch(objlocked[i])) == NULL) {
1047 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1050 STATUS(((objheader_t *)header)) &= ~(LOCK);
1056 /*This function completes the COMMIT process is the transaction is commiting*/
1057 int transComProcess(local_thread_data_array_t *localtdata) {
1058 objheader_t *header, *tcptr;
1059 int i, nummod, tmpsize, numcreated, numlocked;
1060 unsigned int *oidmod, *oidcreated, *oidlocked;
1063 nummod = localtdata->tdata->buffer->f.nummod;
1064 oidmod = localtdata->tdata->buffer->oidmod;
1065 numcreated = localtdata->tdata->buffer->f.numcreated;
1066 oidcreated = localtdata->tdata->buffer->oidcreated;
1067 numlocked = localtdata->transinfo->numlocked;
1068 oidlocked = localtdata->transinfo->objlocked;
1070 for (i = 0; i < nummod; i++) {
1071 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1072 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1075 /* Copy from transaction cache -> main object store */
1076 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1077 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1080 GETSIZE(tmpsize, header);
1081 pthread_mutex_lock(&mainobjstore_mutex);
1082 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1083 header->version += 1;
1084 if(header->notifylist != NULL) {
1085 notifyAll(&header->notifylist, OID(header), header->version);
1087 pthread_mutex_unlock(&mainobjstore_mutex);
1089 /* If object is newly created inside transaction then commit it */
1090 for (i = 0; i < numcreated; i++) {
1091 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1092 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1095 GETSIZE(tmpsize, header);
1096 tmpsize += sizeof(objheader_t);
1097 pthread_mutex_lock(&mainobjstore_mutex);
1098 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1099 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1100 pthread_mutex_unlock(&mainobjstore_mutex);
1103 pthread_mutex_unlock(&mainobjstore_mutex);
1104 memcpy(ptrcreate, header, tmpsize);
1105 mhashInsert(oidcreated[i], ptrcreate);
1106 lhashInsert(oidcreated[i], myIpAddr);
1108 /* Unlock locked objects */
1109 for(i = 0; i < numlocked; i++) {
1110 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1111 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1114 STATUS(header) &= ~(LOCK);
1120 /* This function checks if the prefetch oids are same and have same offsets
1121 * for case x.a.b and y.a.b where x and y have same oid's
1122 * or if a.b.c is a subset of x.b.c.d*/
1123 /* check for case where the generated request a.y.z or x.y.z.g then
1124 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1125 void checkPrefetchTuples(prefetchqelem_t *node) {
1126 int i,j, count,k, sindex, index;
1128 int ntuples, slength;
1130 unsigned short *endoffsets;
1133 /* Check for the case x.y.z and a.b.c are same oids */
1134 ptr = (char *) node;
1135 ntuples = *(GET_NTUPLES(ptr));
1136 oid = GET_PTR_OID(ptr);
1137 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1138 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1140 /* Find offset length for each tuple */
1141 int numoffset[ntuples];
1142 numoffset[0] = endoffsets[0];
1143 for(i = 1; i<ntuples; i++) {
1144 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1146 /* Check for redundant tuples by comparing oids of each tuple */
1147 for(i = 0; i < ntuples; i++) {
1150 for(j = i+1 ; j < ntuples; j++) {
1153 /*If oids of tuples match */
1154 if (oid[i] == oid[j]) {
1155 /* Find the smallest offset length of two tuples*/
1156 if(numoffset[i] > numoffset[j]){
1157 slength = numoffset[j];
1161 slength = numoffset[i];
1165 /* Compare the offset values based on the current indices
1166 * break if they do not match
1167 * if all offset values match then pick the largest tuple*/
1172 k = endoffsets[i-1];
1174 index = endoffsets[j -1];
1175 for(count = 0; count < slength; count ++) {
1176 if (arryfields[k] != arryfields[index]) {
1182 if(slength == count) {
1189 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1190 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1192 int ntuples, i, machinenum, count=0;
1194 unsigned short *endoffsets;
1195 short *arryfields, *offset;
1196 prefetchpile_t *head = NULL, *tmp = NULL;
1198 /* Check for the case x.y.z and a.b.c are same oids */
1199 ptr = (char *) node;
1200 ntuples = *(GET_NTUPLES(ptr));
1201 oid = GET_PTR_OID(ptr);
1202 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1203 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1205 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1206 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1210 /* Check for redundant tuples by comparing oids of each tuple */
1211 for(i = 0; i < ntuples; i++) {
1213 if(head->next != NULL) {
1214 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1215 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1218 tmp->mid = myIpAddr;
1222 head->mid = myIpAddr;
1226 /* For each tuple make piles */
1227 if ((machinenum = lhashSearch(oid[i])) == 0) {
1228 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1231 /* Insert into machine pile */
1233 offset = &arryfields[0];
1235 offset = &arryfields[endoffsets[i-1]];
1238 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1239 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1247 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1248 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1252 objheader_t *objheader;
1253 unsigned short *endoffsets;
1255 prefetchpile_t *head = NULL;
1257 ptr = (char *) node;
1258 ntuples = *(GET_NTUPLES(ptr));
1259 oid = GET_PTR_OID(ptr);
1260 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1261 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1263 /* Find offset length for each tuple */
1264 int numoffset[ntuples];//Number of offsets for each tuple
1265 numoffset[0] = endoffsets[0];
1266 for(i = 1; i<ntuples; i++) {
1267 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1270 for(i = 0; i < ntuples; i++) {
1274 nextarryfieldindex = endoffsets[0];
1276 arryfieldindex = endoffsets[i-1];
1277 nextarryfieldindex = endoffsets[i];
1280 endoffsets[0] = val = numoffset[0];
1281 for(k = 1; k < ntuples; k++) {
1282 val = val + numoffset[k];
1283 endoffsets[k] = val;
1286 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1287 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1292 /* If object found locally */
1293 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1295 tmp = (char *) objheader;
1296 int orgnumoffset = numoffset[i];
1300 arryfieldindex = endoffsets[i-1];
1303 for(j = 0; j<orgnumoffset; j++) {
1304 unsigned int objoid = 0;
1305 /* Check for arrays */
1306 if(TYPE(objheader) > NUMCLASSES) {
1310 int elementsize = classsize[TYPE(objheader)];
1311 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1312 int length = ao->___length___;
1313 /* Check if array out of bounds */
1314 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1315 break; //if yes then treat the object as found
1317 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1319 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1321 //Update numoffset array
1322 numoffset[i] = numoffset[i] - 1;
1325 //Update endoffset array
1326 endoffsets[0] = val = numoffset[0];
1327 for(k = 1; k < ntuples; k++) {
1328 val = val + numoffset[k];
1329 endoffsets[k] = val;
1331 //Update arrayfields array
1332 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1333 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1335 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1337 checkPreCache(node, numoffset, oid[i], i);
1340 tmp = (char *) objheader;
1343 /*If all offset oids are found locally,make the prefetch tuple invalid */
1348 /* Look in Prefetch cache */
1349 checkPreCache(node, numoffset, oid[i],i);
1354 /* Make machine groups */
1355 if((head = makePreGroups(node, numoffset)) == NULL) {
1356 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1363 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1365 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1367 unsigned short *endoffsets;
1369 objheader_t *header;
1371 ptr = (char *) node;
1372 ntuples = *(GET_NTUPLES(ptr));
1373 oid = GET_PTR_OID(ptr);
1374 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1375 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1377 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1379 } else { //Found in Prefetch Cache
1380 //TODO Decide if object is too old, if old remove from cache
1381 tmp = (char *) header;
1382 int loopcount = numoffset[index];
1386 arryfieldindex = endoffsets[(index - 1)];
1387 // Check if any of the offset oid is available in the Prefetch cache
1388 for(i = 0; i < loopcount; i++) {
1389 /* Check for arrays */
1390 if(TYPE(header) > NUMCLASSES) {
1395 int elementsize = classsize[TYPE(header)];
1396 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1397 int length = ao->___length___;
1398 /* Check if array out of bounds */
1399 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1400 break; //if yes treat the object as found
1402 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1404 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1406 //Update numoffset array
1407 numoffset[index] = numoffset[index] - 1;
1409 oid[index] = objoid;
1410 //Update endoffset array
1411 endoffsets[0] = val = numoffset[0];
1412 for(k = 1; k < ntuples; k++) {
1413 val = val + numoffset[k];
1414 endoffsets[k] = val;
1416 //Update arrayfields array
1417 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1418 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1420 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1421 tmp = (char *) header;
1429 //Found in the prefetch cache
1430 if(flag == 0 && (numoffset[index] == 0)) {
1437 /* This function is called by the thread calling transPrefetch */
1438 void *transPrefetch(void *t) {
1439 prefetchqelem_t *qnode;
1440 prefetchpile_t *pilehead = NULL;
1441 prefetchpile_t *ptr = NULL, *piletail = NULL;
1444 /* lock mutex of primary prefetch queue */
1445 pthread_mutex_lock(&pqueue.qlock);
1446 /* while primary queue is empty, then wait */
1447 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1448 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1451 /* dequeue node to create a machine piles and finally unlock mutex */
1452 if((qnode = pre_dequeue()) == NULL) {
1453 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1454 pthread_mutex_unlock(&pqueue.qlock);
1457 pthread_mutex_unlock(&pqueue.qlock);
1459 /* Reduce redundant prefetch requests */
1460 checkPrefetchTuples(qnode);
1461 /* Check if the tuples are found locally, if yes then reduce them further*/
1462 /* and group requests by remote machine ids by calling the makePreGroups() */
1463 if((pilehead = foundLocal(qnode)) == NULL) {
1464 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1470 while(ptr != NULL) {
1471 if(ptr->next == NULL) {
1477 /* Lock mutex of pool queue */
1478 pthread_mutex_lock(&mcqueue.qlock);
1479 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1480 mcpileenqueue(pilehead, piletail);
1481 /* Broadcast signal on machine pile queue */
1482 pthread_cond_broadcast(&mcqueue.qcond);
1483 /* Unlock mutex of machine pile queue */
1484 pthread_mutex_unlock(&mcqueue.qlock);
1485 /* Deallocate the prefetch queue pile node */
1490 /* Each thread in the pool of threads calls this function to establish connection with
1491 * remote machines, send the prefetch requests and process the reponses from
1492 * the remote machines .
1493 * The thread is active throughout the period of runtime */
1495 void *mcqProcess(void *threadid) {
1497 prefetchpile_t *mcpilenode;
1498 struct sockaddr_in remoteAddr;
1501 tid = (int) threadid;
1505 /* Lock mutex of mc pile queue */
1506 pthread_mutex_lock(&mcqueue.qlock);
1507 /* When mc pile queue is empty, wait */
1508 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1509 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1511 /* Dequeue node to send remote machine connections*/
1512 if((mcpilenode = mcpiledequeue()) == NULL) {
1513 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1514 pthread_mutex_unlock(&mcqueue.qlock);
1518 pthread_mutex_unlock(&mcqueue.qlock);
1520 /*Initiate connection to remote host and send prefetch request */
1521 if(mcpilenode->mid != myIpAddr) {
1522 /* Check to see if socket exists */
1523 for(i = 0; i < NUM_MACHINES; i++) {
1524 if(midSocketArray[i].mid == mcpilenode->mid) {
1525 sendPrefetchReq(mcpilenode, midSocketArray[i].sockid);
1531 if(sockIdFound == 0) {
1532 if(sockCount < NUM_MACHINES) {
1534 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1535 printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
1539 bzero(&remoteAddr, sizeof(remoteAddr));
1540 remoteAddr.sin_family = AF_INET;
1541 remoteAddr.sin_port = htons(LISTEN_PORT);
1542 remoteAddr.sin_addr.s_addr = htonl(mcpilenode->mid);
1544 /* Open Connection */
1545 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1546 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1547 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1552 midSocketArray[sockCount].mid = mcpilenode->mid;
1553 midSocketArray[sockCount].sockid = sd;
1554 sendPrefetchReq(mcpilenode, midSocketArray[sockCount].sockid);
1557 //TODO Fix for connecting to more than 2 machines && close socket
1558 printf("%s(): Error: Currently works for only 2 machines\n", __func__);
1564 /* Deallocate the machine queue pile node */
1565 mcdealloc(mcpilenode);
1569 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1570 int i, off, len, endpair, count = 0;
1571 char machineip[16], control;
1574 /* Send TRANS_PREFETCH control message */
1575 control = TRANS_PREFETCH;
1576 send_data(sd, &control, sizeof(char));
1578 /* Send Oids and offsets in pairs */
1579 tmp = mcpilenode->objpiles;
1580 while(tmp != NULL) {
1582 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1583 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1584 char oidnoffset[len];
1585 bzero(oidnoffset, len);
1586 *((int*)oidnoffset) = len;
1588 *((unsigned int *)(oidnoffset + off)) = tmp->oid;
1589 off += sizeof(unsigned int);
1590 *((unsigned int *)(oidnoffset + off)) = myIpAddr;
1591 off += sizeof(unsigned int);
1592 for(i = 0; i < tmp->numoffset; i++) {
1593 *((short*)(oidnoffset + off)) = tmp->offset[i];
1596 send_data(sd, oidnoffset, len);
1600 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1602 send_data(sd, &endpair, sizeof(int));
1607 int getPrefetchResponse(int sd) {
1608 int numbytes = 0, length = 0, size = 0;
1609 char *recvbuffer, control;
1611 void *modptr, *oldptr;
1613 recv_data((int)sd, &length, sizeof(int));
1614 size = length - sizeof(int);
1615 if((recvbuffer = calloc(1, size)) == NULL) {
1616 printf("%s() Calloc error at %s,%d\n", __func__, __FILE__, __LINE__);
1620 recv_data((int)sd, recvbuffer, size);
1622 control = *((char *) recvbuffer);
1623 if(control == OBJECT_FOUND) {
1625 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1626 size = size - (sizeof(char) + sizeof(unsigned int));
1627 pthread_mutex_lock(&prefetchcache_mutex);
1628 if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1629 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1630 pthread_mutex_unlock(&prefetchcache_mutex);
1634 pthread_mutex_unlock(&prefetchcache_mutex);
1635 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1637 /* Insert the oid and its address into the prefetch hash lookup table */
1638 /* Do a version comparison if the oid exists */
1639 if((oldptr = prehashSearch(oid)) != NULL) {
1640 /* If older version then update with new object ptr */
1641 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1643 prehashInsert(oid, modptr);
1645 /* TODO modptr should be reference counted */
1647 } else {/* Else add the object ptr to hash table*/
1648 prehashInsert(oid, modptr);
1650 /* Lock the Prefetch Cache look up table*/
1651 pthread_mutex_lock(&pflookup.lock);
1652 /* Broadcast signal on prefetch cache condition variable */
1653 pthread_cond_broadcast(&pflookup.cond);
1654 /* Unlock the Prefetch Cache look up table*/
1655 pthread_mutex_unlock(&pflookup.lock);
1656 } else if(control == OBJECT_NOT_FOUND) {
1657 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1658 /* TODO: For each object not found query DHT for new location and retrieve the object */
1659 /* Throw an error */
1660 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1664 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1672 unsigned short getObjType(unsigned int oid)
1674 objheader_t *objheader;
1675 unsigned short numoffset[] ={0};
1676 short fieldoffset[] ={};
1678 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1680 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1682 prefetch(1, &oid, numoffset, fieldoffset);
1683 pthread_mutex_lock(&pflookup.lock);
1684 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1686 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1688 pthread_mutex_unlock(&pflookup.lock);
1692 return TYPE(objheader);
1695 int startRemoteThread(unsigned int oid, unsigned int mid)
1698 struct sockaddr_in remoteAddr;
1699 char msg[1 + sizeof(unsigned int)];
1703 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1705 perror("startRemoteThread():socket()");
1709 bzero(&remoteAddr, sizeof(remoteAddr));
1710 remoteAddr.sin_family = AF_INET;
1711 remoteAddr.sin_port = htons(LISTEN_PORT);
1712 remoteAddr.sin_addr.s_addr = htonl(mid);
1714 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1716 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1717 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1722 msg[0] = START_REMOTE_THREAD;
1723 memcpy(&msg[1], &oid, sizeof(unsigned int));
1724 send_data(sock, msg, 1 + sizeof(unsigned int));
1731 //TODO: when reusing oids, make sure they are not already in use!
1732 unsigned int getNewOID(void) {
1733 static unsigned int id = 0xFFFFFFFF;
1736 if (id > oidMax || id < oidMin)
1743 int processConfigFile()
1746 const int maxLineLength = 200;
1747 char lineBuffer[maxLineLength];
1749 const char *delimiters = " \t\n";
1753 configFile = fopen(CONFIG_FILENAME, "r");
1754 if (configFile == NULL)
1756 printf("error opening %s:\n", CONFIG_FILENAME);
1761 numHostsInSystem = 0;
1762 sizeOfHostArray = 8;
1763 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1765 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1767 commentBegin = strchr(lineBuffer, '#');
1768 if (commentBegin != NULL)
1769 *commentBegin = '\0';
1770 token = strtok(lineBuffer, delimiters);
1771 while (token != NULL)
1773 tmpAddr = inet_addr(token);
1774 if ((int)tmpAddr == -1)
1776 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1781 addHost(htonl(tmpAddr));
1782 token = strtok(NULL, delimiters);
1788 if (numHostsInSystem < 1)
1790 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1794 myIpAddr = getMyIpAddr("en1");
1796 myIpAddr = getMyIpAddr("eth0");
1798 myIndexInHostArray = findHost(myIpAddr);
1799 if (myIndexInHostArray == -1)
1801 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1804 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1805 oidMin = oidsPerBlock * myIndexInHostArray;
1806 if (myIndexInHostArray == numHostsInSystem - 1)
1807 oidMax = 0xFFFFFFFF;
1809 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1814 void addHost(unsigned int hostIp)
1816 unsigned int *tmpArray;
1818 if (findHost(hostIp) != -1)
1821 if (numHostsInSystem == sizeOfHostArray)
1823 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1824 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1826 hostIpAddrs = tmpArray;
1829 hostIpAddrs[numHostsInSystem++] = hostIp;
1834 int findHost(unsigned int hostIp)
1837 for (i = 0; i < numHostsInSystem; i++)
1838 if (hostIpAddrs[i] == hostIp)
1845 /* This function sends notification request per thread waiting on object(s) whose version
1847 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1849 objheader_t *objheader;
1850 struct sockaddr_in remoteAddr;
1851 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1855 unsigned short version;
1856 unsigned int oid,mid;
1857 static unsigned int threadid = 0;
1858 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1859 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1860 notifydata_t *ndata;
1862 //FIXME currently all oids belong to one machine
1864 if((mid = lhashSearch(oid)) == 0) {
1865 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1869 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1870 perror("reqNotify():socket()");
1874 bzero(&remoteAddr, sizeof(remoteAddr));
1875 remoteAddr.sin_family = AF_INET;
1876 remoteAddr.sin_port = htons(LISTEN_PORT);
1877 remoteAddr.sin_addr.s_addr = htonl(mid);
1879 /* Generate unique threadid */
1882 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1883 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1884 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1887 ndata->numoid = numoid;
1888 ndata->threadid = threadid;
1889 ndata->oidarry = oidarry;
1890 ndata->versionarry = versionarry;
1891 ndata->threadcond = threadcond;
1892 ndata->threadnotify = threadnotify;
1893 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1894 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1899 /* Send number of oids, oidarry, version array, machine id and threadid */
1900 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1901 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1902 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1906 msg[0] = THREAD_NOTIFY_REQUEST;
1907 *((unsigned int *)(&msg[1])) = numoid;
1908 /* Send array of oids */
1909 size = sizeof(unsigned int);
1914 *((unsigned int *)(&msg[1] + size)) = oid;
1915 size += sizeof(unsigned int);
1920 /* Send array of version */
1924 version = versionarry[i];
1925 *((unsigned short *)(&msg[1] + size)) = version;
1926 size += sizeof(unsigned short);
1931 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1932 size += sizeof(unsigned int);
1933 *((unsigned int *)(&msg[1] + size)) = threadid;
1935 pthread_mutex_lock(&(ndata->threadnotify));
1936 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1937 send_data(sock, msg, size);
1938 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1939 pthread_mutex_unlock(&(ndata->threadnotify));
1942 pthread_cond_destroy(&threadcond);
1943 pthread_mutex_destroy(&threadnotify);
1949 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1950 notifydata_t *ndata;
1951 int i, objIsFound = 0, index;
1954 //Look up the tid and call the corresponding pthread_cond_signal
1955 if((ndata = notifyhashSearch(tid)) == NULL) {
1956 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1959 for(i = 0; i < ndata->numoid; i++) {
1960 if(ndata->oidarry[i] == oid){
1965 if(objIsFound == 0){
1966 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1969 if(version <= ndata->versionarry[index]){
1970 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1973 /* Clear from prefetch cache and free thread related data structure */
1974 if((ptr = prehashSearch(oid)) != NULL) {
1977 pthread_cond_signal(&(ndata->threadcond));
1984 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1987 struct sockaddr_in remoteAddr;
1988 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1989 int sock, status, size, bytesSent;
1991 while(*head != NULL) {
1994 //create a socket connection to that machine
1995 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1996 perror("notifyAll():socket()");
2000 bzero(&remoteAddr, sizeof(remoteAddr));
2001 remoteAddr.sin_family = AF_INET;
2002 remoteAddr.sin_port = htons(LISTEN_PORT);
2003 remoteAddr.sin_addr.s_addr = htonl(mid);
2004 //send Thread Notify response and threadid to that machine
2005 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2006 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2007 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2010 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2011 msg[0] = THREAD_NOTIFY_RESPONSE;
2012 *((unsigned int *)&msg[1]) = oid;
2013 size = sizeof(unsigned int);
2014 *((unsigned short *)(&msg[1]+ size)) = version;
2015 size+= sizeof(unsigned short);
2016 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2018 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2019 send_data(sock, msg, size);
2030 void transAbort(transrecord_t *trans) {
2031 objstrDelete(trans->cache);
2032 chashDelete(trans->lookupTable);