4 #include "machinepile.h"
11 #include <sys/types.h>
12 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <sys/types.h>
22 #define LISTEN_PORT 2156
23 #define RECEIVE_BUFFER_SIZE 2048
24 #define NUM_THREADS 10
25 #define PREFETCH_CACHE_SIZE 1048576 //1MB
26 #define CONFIG_FILENAME "dstm.conf"
28 /* Global Variables */
29 extern int classsize[];
30 extern primarypfq_t pqueue; //Shared prefetch queue
31 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
32 objstr_t *prefetchcache; //Global Prefetch cache
33 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
34 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
35 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
36 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
37 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
38 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
39 extern objstr_t *mainobjstore;
40 unsigned int myIpAddr;
41 unsigned int *hostIpAddrs;
44 int myIndexInHostArray;
45 unsigned int oidsPerBlock;
49 void printhex(unsigned char *, int);
50 plistnode_t *createPiles(transrecord_t *);
52 void printhex(unsigned char *ptr, int numBytes)
55 for (i = 0; i < numBytes; i++)
58 printf("0%x ", ptr[i]);
60 printf("%x ", ptr[i]);
66 inline int arrayLength(int *array) {
68 for(i=0 ;array[i] != -1; i++)
72 inline int findmax(int *array, int arraylength) {
75 for(i = 0; i < arraylength; i++){
82 /* This function is a prefetch call generated by the compiler that
83 * populates the shared primary prefetch queue*/
84 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
88 /* Allocate for the queue node*/
91 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
92 if((node = calloc(1, qnodesize)) == NULL) {
93 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
96 /* Set queue node values */
97 len = sizeof(prefetchqelem_t);
98 memcpy(node + len, &ntuples, sizeof(int));
100 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
101 len += ntuples * sizeof(unsigned int);
102 memcpy(node + len, endoffsets, ntuples*sizeof(short));
103 len += ntuples * sizeof(short);
104 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(short));
105 /* Lock and insert into primary prefetch queue */
106 pthread_mutex_lock(&pqueue.qlock);
107 pre_enqueue((prefetchqelem_t *)node);
108 pthread_cond_signal(&pqueue.qcond);
109 pthread_mutex_unlock(&pqueue.qlock);
113 /* This function starts up the transaction runtime. */
114 int dstmStartup(const char * option) {
115 pthread_t thread_Listen;
117 int master=option!=NULL && strcmp(option, "master")==0;
119 if (processConfigFile() != 0)
120 return 0; //TODO: return error value, cause main program to exit
126 pthread_attr_init(&attr);
127 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
128 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
137 //TODO Use this later
138 void *pCacheAlloc(objstr_t *store, unsigned int size) {
144 while(ptr->next != NULL) {
145 /* check if store is empty */
146 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
157 printf("DEBUG-> Unable to insert object in Prefetch cache\n");
162 /* This function initiates the prefetch thread
163 * A queue is shared between the main thread of execution
164 * and the prefetch thread to process the prefetch call
165 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
166 * processes the prefetch requests */
170 //Create and initialize prefetch cache structure
171 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
172 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
173 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
175 /* Initialize attributes for mutex */
176 pthread_mutexattr_init(&prefetchcache_mutex_attr);
177 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
179 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
181 //Create prefetch cache lookup table
182 if(prehashCreate(HASH_SIZE, LOADFACTOR))
184 //Initialize primary shared queue
186 //Initialize machine pile w/prefetch oids and offsets shared queue
188 //Create the primary prefetch thread
191 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
193 pthread_detach(tPrefetch);
195 //Create and Initialize a pool of threads
196 /* Threads are active for the entire period runtime is running */
197 for(t = 0; t< NUM_THREADS; t++) {
199 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
201 pthread_detach(wthreads[t]);
205 /* This function stops the threads spawned */
208 pthread_cancel(tPrefetch);
209 for(t = 0; t < NUM_THREADS; t++)
210 pthread_cancel(wthreads[t]);
215 /* This functions inserts randowm wait delays in the order of msec
216 * Mostly used when transaction commits retry*/
217 void randomdelay(void)
219 struct timespec req, rem;
224 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
225 //nanosleep(&req, &rem);
226 nanosleep(&req, NULL);
230 /* This function initializes things required in the transaction start*/
231 transrecord_t *transStart()
233 transrecord_t *tmp = malloc(sizeof(transrecord_t));
234 tmp->cache = objstrCreate(1048576);
235 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
237 tmp->revertlist=NULL;
242 /* This function finds the location of the objects involved in a transaction
243 * and returns the pointer to the object if found in a remote location */
244 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
245 unsigned int machinenumber;
246 objheader_t *tmp, *objheader;
247 objheader_t *objcopy;
248 int size, rc, found = 0;
253 rc = gettimeofday(&tp, NULL);
257 if (tp.tv_usec >= 1000000)
259 tp.tv_usec -= 1000000;
262 /* Convert from timeval to timespec */
263 ts.tv_sec = tp.tv_sec;
264 ts.tv_nsec = tp.tv_usec * 1000;
266 /* Search local transaction cache */
267 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
269 return &objheader[1];
273 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
274 /* Look up in machine lookup table and copy into cache*/
275 GETSIZE(size, objheader);
276 size += sizeof(objheader_t);
277 objcopy = objstrAlloc(record->cache, size);
278 memcpy(objcopy, (void *)objheader, size);
279 /* Insert into cache's lookup table */
280 chashInsert(record->lookupTable, OID(objheader), objcopy);
286 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
288 size+=sizeof(objheader_t);
289 objcopy = objstrAlloc(record->cache, size);
290 memcpy(objcopy, (void *)tmp, size);
291 /* Insert into cache's lookup table */
292 chashInsert(record->lookupTable, OID(tmp), objcopy);
299 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
300 pthread_mutex_lock(&pflookup.lock);
302 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
303 /* Check Prefetch cache again */
304 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
307 size+=sizeof(objheader_t);
308 objcopy = objstrAlloc(record->cache, size);
309 memcpy(objcopy, (void *)tmp, size);
310 chashInsert(record->lookupTable, OID(tmp), objcopy);
311 pthread_mutex_unlock(&pflookup.lock);
317 } else if (rc == ETIMEDOUT) {
318 // printf("Wait timed out\n");
319 pthread_mutex_unlock(&pflookup.lock);
324 /* Get the object from the remote location */
325 machinenumber = lhashSearch(oid);
326 objcopy = getRemoteObj(record, machinenumber, oid);
327 if(objcopy == NULL) {
328 printf("Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
340 /* This function creates objects in the transaction record */
341 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
343 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
344 OID(tmp) = getNewOID();
348 chashInsert(record->lookupTable, OID(tmp), tmp);
350 return &tmp[1]; //want space after object header
356 /* This function creates machine piles based on all machines involved in a
357 * transaction commit request */
358 plistnode_t *createPiles(transrecord_t *record) {
360 unsigned int size;/* Represents number of bins in the chash table */
361 chashlistnode_t *curr, *ptr, *next;
362 plistnode_t *pile = NULL;
363 unsigned int machinenum;
364 void *localmachinenum;
365 objheader_t *headeraddr;
367 ptr = record->lookupTable->table;
368 size = record->lookupTable->size;
370 for(i = 0; i < size ; i++) {
372 /* Inner loop to traverse the linked list of the cache lookupTable */
373 while(curr != NULL) {
374 //if the first bin in hash table is empty
380 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
381 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
385 //Get machine location for object id (and whether local or not)
386 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
387 machinenum = myIpAddr;
388 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
389 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
393 //Make machine groups
394 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
395 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
405 /* This function initiates the transaction commit process
406 * Spawns threads for each of the new connections with Participants
407 * and creates new piles by calling the createPiles(),
408 * Sends a transrequest() to each remote machines for objects found remotely
409 * and calls handleLocalReq() to process objects found locally */
410 int transCommit(transrecord_t *record) {
411 unsigned int tot_bytes_mod, *listmid;
412 plistnode_t *pile, *pile_ptr;
414 int pilecount, offset, threadnum, trecvcount;
415 char buffer[RECEIVE_BUFFER_SIZE],control;
416 char transid[TID_LEN];
417 trans_req_data_t *tosend;
418 trans_commit_data_t transinfo;
419 static int newtid = 0;
420 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
427 /* Look through all the objects in the transaction record and make piles
428 * for each machine involved in the transaction*/
429 pile_ptr = pile = createPiles(record);
431 /* Create the packet to be sent in TRANS_REQUEST */
433 /* Count the number of participants */
434 pilecount = pCount(pile);
436 /* Create a list of machine ids(Participants) involved in transaction */
437 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
438 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
442 pListMid(pile, listmid);
445 /* Initialize thread variables,
446 * Spawn a thread for each Participant involved in a transaction */
447 pthread_t thread[pilecount];
449 pthread_cond_t tcond;
450 pthread_mutex_t tlock;
451 pthread_mutex_t tlshrd;
453 thread_data_array_t *thread_data_array;
454 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
455 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
456 pthread_cond_destroy(&tcond);
457 pthread_mutex_destroy(&tlock);
464 local_thread_data_array_t *ltdata;
465 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
466 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
467 pthread_cond_destroy(&tcond);
468 pthread_mutex_destroy(&tlock);
471 free(thread_data_array);
476 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
478 /* Initialize and set thread detach attribute */
479 pthread_attr_init(&attr);
480 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
481 pthread_mutex_init(&tlock, NULL);
482 pthread_cond_init(&tcond, NULL);
484 /* Process each machine pile */
485 while(pile != NULL) {
486 //Create transaction id
488 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
489 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
490 pthread_cond_destroy(&tcond);
491 pthread_mutex_destroy(&tlock);
494 free(thread_data_array);
499 tosend->f.control = TRANS_REQUEST;
500 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
501 tosend->f.mcount = pilecount;
502 tosend->f.numread = pile->numread;
503 tosend->f.nummod = pile->nummod;
504 tosend->f.numcreated = pile->numcreated;
505 tosend->f.sum_bytes = pile->sum_bytes;
506 tosend->listmid = listmid;
507 tosend->objread = pile->objread;
508 tosend->oidmod = pile->oidmod;
509 tosend->oidcreated = pile->oidcreated;
510 thread_data_array[threadnum].thread_id = threadnum;
511 thread_data_array[threadnum].mid = pile->mid;
512 thread_data_array[threadnum].buffer = tosend;
513 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
514 thread_data_array[threadnum].threshold = &tcond;
515 thread_data_array[threadnum].lock = &tlock;
516 thread_data_array[threadnum].count = &trecvcount;
517 thread_data_array[threadnum].replyctrl = &treplyctrl;
518 thread_data_array[threadnum].replyretry = &treplyretry;
519 thread_data_array[threadnum].rec = record;
520 /* If local do not create any extra connection */
521 if(pile->mid != myIpAddr) { /* Not local */
523 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
526 perror("Error in pthread create\n");
527 pthread_cond_destroy(&tcond);
528 pthread_mutex_destroy(&tlock);
531 for (i = 0; i < threadnum; i++)
532 free(thread_data_array[i].buffer);
533 free(thread_data_array);
539 ltdata->tdata = &thread_data_array[threadnum];
540 ltdata->transinfo = &transinfo;
542 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
545 perror("Error in pthread create\n");
546 pthread_cond_destroy(&tcond);
547 pthread_mutex_destroy(&tlock);
550 for (i = 0; i < threadnum; i++)
551 free(thread_data_array[i].buffer);
552 free(thread_data_array);
563 /* Free attribute and wait for the other threads */
564 pthread_attr_destroy(&attr);
566 for (i = 0; i < pilecount; i++) {
567 rc = pthread_join(thread[i], NULL);
570 printf("ERROR return code from pthread_join() is %d\n", rc);
571 pthread_cond_destroy(&tcond);
572 pthread_mutex_destroy(&tlock);
575 for (j = i; j < pilecount; j++)
576 free(thread_data_array[j].buffer);
577 free(thread_data_array);
582 free(thread_data_array[i].buffer);
587 pthread_cond_destroy(&tcond);
588 pthread_mutex_destroy(&tlock);
591 free(thread_data_array);
594 /* wait a random amount of time */
595 if (treplyretry == 1) {
599 /* Retry trans commit procedure if not sucessful in the first try */
600 } while (treplyretry == 1);
603 objstrDelete(record->cache);
604 chashDelete(record->lookupTable);
609 /* This function sends information involved in the transaction request
610 * to participants and accepts a response from particpants.
611 * It calls decideresponse() to decide on what control message
612 * to send next to participants and sends the message using sendResponse()*/
613 void *transRequest(void *threadarg) {
615 struct sockaddr_in serv_addr;
616 struct hostent *server;
617 thread_data_array_t *tdata;
618 objheader_t *headeraddr;
619 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
620 char machineip[16], retval;
622 tdata = (thread_data_array_t *) threadarg;
624 /* Send Trans Request */
625 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
626 perror("Error in socket for TRANS_REQUEST\n");
629 bzero((char*) &serv_addr, sizeof(serv_addr));
630 serv_addr.sin_family = AF_INET;
631 serv_addr.sin_port = htons(LISTEN_PORT);
632 midtoIP(tdata->mid,machineip);
633 machineip[15] = '\0';
634 serv_addr.sin_addr.s_addr = inet_addr(machineip);
635 /* Open Connection */
636 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
637 perror("Error in connect for TRANS_REQUEST\n");
642 /* Send bytes of data with TRANS_REQUEST control message */
643 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
644 perror("Error sending fixed bytes for thread\n");
648 /* Send list of machines involved in the transaction */
650 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
651 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
652 perror("Error sending list of machines for thread\n");
657 /* Send oids and version number tuples for objects that are read */
659 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
660 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
661 perror("Error sending tuples for thread\n");
666 /* Send objects that are modified */
667 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
669 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
670 GETSIZE(size,headeraddr);
671 size+=sizeof(objheader_t);
672 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
673 perror("Error sending obj modified for thread\n");
679 /* Read control message from Participant */
680 if((n = read(sd, &control, sizeof(char))) <= 0) {
681 perror("Error in reading control message from Participant\n");
685 recvcontrol = control;
687 /* Update common data structure and increment count */
688 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
690 /* Lock and update count */
691 /* Thread sleeps until all messages from pariticipants are received by coordinator */
692 pthread_mutex_lock(tdata->lock);
694 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
696 /* Wake up the threads and invoke decideResponse (once) */
697 if(*(tdata->count) == tdata->buffer->f.mcount) {
698 decideResponse(tdata);
699 pthread_cond_broadcast(tdata->threshold);
701 pthread_cond_wait(tdata->threshold, tdata->lock);
703 pthread_mutex_unlock(tdata->lock);
705 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
706 * to all participants in their respective socket */
707 if (sendResponse(tdata, sd) == 0) {
708 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
713 /* Close connection */
718 /* This function decides the reponse that needs to be sent to
719 * all Participant machines after the TRANS_REQUEST protocol */
720 void decideResponse(thread_data_array_t *tdata) {
722 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
725 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
726 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
727 written onto the shared array */
730 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
731 /* treat as disagree, pass thru */
740 case TRANS_SOFT_ABORT:
746 if(transdisagree > 0) {
748 *(tdata->replyctrl) = TRANS_ABORT;
749 *(tdata->replyretry) = 0;
750 /* clear objects from prefetch cache */
751 for (i = 0; i < tdata->buffer->f.numread; i++)
752 prehashRemove(*(unsigned int *)(tdata->buffer->objread + (sizeof(unsigned int) + sizeof(unsigned short))*i));
753 for (i = 0; i < tdata->buffer->f.nummod; i++)
754 prehashRemove(tdata->buffer->oidmod[i]);
755 } else if(transagree == tdata->buffer->f.mcount){
757 *(tdata->replyctrl) = TRANS_COMMIT;
758 *(tdata->replyretry) = 0;
760 /* Send Abort in soft abort case followed by retry commiting transaction again*/
761 *(tdata->replyctrl) = TRANS_ABORT;
762 *(tdata->replyretry) = 1;
767 /* This function sends the final response to remote machines per thread in their respective socket id
768 * It returns a char that is only needed to check the correctness of execution of this function inside
770 char sendResponse(thread_data_array_t *tdata, int sd) {
771 int n, N, sum, oidcount = 0;
772 char *ptr, retval = 0;
773 unsigned int *oidnotfound;
775 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
776 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
777 /* Read list of objects missing */
778 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
779 N = oidcount * sizeof(unsigned int);
780 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
781 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
784 ptr = (char *) oidnotfound;
786 n = read(sd, ptr+sum, N-sum);
788 } while(sum < N && n !=0);
790 retval = TRANS_SOFT_ABORT;
792 /* If the decided response is TRANS_ABORT */
793 if(*(tdata->replyctrl) == TRANS_ABORT) {
794 retval = TRANS_ABORT;
795 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
796 retval = TRANS_COMMIT;
799 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
800 perror("Error sending ctrl message for participant\n");
806 /* This function opens a connection, places an object read request to the
807 * remote machine, reads the control message and object if available and
808 * copies the object and its header to the local cache.
809 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
811 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
813 struct sockaddr_in serv_addr;
814 struct hostent *server;
820 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
821 perror("Error in socket\n");
824 bzero((char*) &serv_addr, sizeof(serv_addr));
825 serv_addr.sin_family = AF_INET;
826 serv_addr.sin_port = htons(LISTEN_PORT);
827 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
828 midtoIP(mnum,machineip);
829 machineip[15] = '\0';
830 serv_addr.sin_addr.s_addr = inet_addr(machineip);
831 /* Open connection */
832 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
833 perror("Error in connect\n");
836 char readrequest[sizeof(char)+sizeof(unsigned int)];
837 readrequest[0] = READ_REQUEST;
838 *((unsigned int *)(&readrequest[1])) = oid;
839 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
840 perror("Error sending message\n");
844 /* Read response from the Participant */
845 if((val = read(sd, &control, sizeof(char))) <= 0) {
846 perror("No control response for getRemoteObj sent\n");
850 case OBJECT_NOT_FOUND:
853 /* Read object if found into local cache */
854 if((val = read(sd, &size, sizeof(int))) <= 0) {
855 perror("No size is read from the participant\n");
858 objcopy = objstrAlloc(record->cache, size);
859 if((val = read(sd, objcopy, size)) <= 0) {
860 perror("No objects are read from the remote participant\n");
863 /* Insert into cache's lookup table */
864 chashInsert(record->lookupTable, oid, objcopy);
867 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
870 /* Close connection */
875 /* This function handles the local objects involved in a transaction commiting process.
876 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
877 * Note Coordinator = local machine
878 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
879 * based on common agreement it either commits or aborts the transaction.
880 * It also frees the memory resources */
881 void *handleLocalReq(void *threadarg) {
882 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
883 local_thread_data_array_t *localtdata;
884 int objnotfound = 0, objlocked = 0;
885 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
888 unsigned short version;
890 objheader_t *headptr;
892 localtdata = (local_thread_data_array_t *) threadarg;
894 /* Counters and arrays to formulate decision on control message to be sent */
895 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
896 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
898 numread = localtdata->tdata->buffer->f.numread;
899 /* Process each oid in the machine pile/ group per thread */
900 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
901 if (i < localtdata->tdata->buffer->f.numread) {
902 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
904 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
905 version = *((short *)(localtdata->tdata->buffer->objread + incr + sizeof(unsigned int)));
906 } else { // Objects Modified
908 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
909 if (headptr == NULL) {
910 printf("Error: handleLocalReq() returning NULL\n");
914 version = headptr->version;
916 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
918 /* Save the oids not found and number of oids not found for later use */
919 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
920 /* Save the oids not found and number of oids not found for later use */
921 oidnotfound[objnotfound] = oid;
923 } else { /* If Obj found in machine (i.e. has not moved) */
924 /* Check if Obj is locked by any previous transaction */
925 if ((STATUS(((objheader_t *)mobj)) & LOCK) == LOCK) {
926 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
928 } else {/* If versions don't match ...HARD ABORT */
930 /* Send TRANS_DISAGREE to Coordinator */
931 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
933 } else {/* If Obj is not locked then lock object */
934 STATUS(((objheader_t *)mobj)) |= LOCK;
935 /* Save all object oids that are locked on this machine during this transaction request call */
936 oidlocked[objlocked] = OID(((objheader_t *)mobj));
938 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
940 } else { /* If versions don't match ...HARD ABORT */
942 /* Send TRANS_DISAGREE to Coordinator */
943 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
948 /* Condition to send TRANS_AGREE */
949 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
950 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
952 /* Condition to send TRANS_SOFT_ABORT */
953 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
954 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
957 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
958 * if Participant receives a TRANS_COMMIT */
959 localtdata->transinfo->objlocked = oidlocked;
960 localtdata->transinfo->objnotfound = oidnotfound;
961 localtdata->transinfo->modptr = NULL;
962 localtdata->transinfo->numlocked = objlocked;
963 localtdata->transinfo->numnotfound = objnotfound;
964 /* Lock and update count */
965 //Thread sleeps until all messages from pariticipants are received by coordinator
966 pthread_mutex_lock(localtdata->tdata->lock);
967 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
969 /* Wake up the threads and invoke decideResponse (once) */
970 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
971 decideResponse(localtdata->tdata);
972 pthread_cond_broadcast(localtdata->tdata->threshold);
974 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
976 pthread_mutex_unlock(localtdata->tdata->lock);
977 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
978 if(transAbortProcess(localtdata) != 0) {
979 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
982 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
983 if(transComProcess(localtdata) != 0) {
984 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
989 if (localtdata->transinfo->objlocked != NULL) {
990 free(localtdata->transinfo->objlocked);
992 if (localtdata->transinfo->objnotfound != NULL) {
993 free(localtdata->transinfo->objnotfound);
999 /* This function completes the ABORT process if the transaction is aborting */
1000 int transAbortProcess(local_thread_data_array_t *localtdata) {
1002 unsigned int *objlocked;
1005 numlocked = localtdata->transinfo->numlocked;
1006 objlocked = localtdata->transinfo->objlocked;
1008 for (i = 0; i < numlocked; i++) {
1009 if((header = mhashSearch(objlocked[i])) == NULL) {
1010 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1013 STATUS(((objheader_t *)header)) &= ~(LOCK);
1016 printf("TRANS_ABORTED at Coordinator end\n");
1021 /*This function completes the COMMIT process is the transaction is commiting*/
1022 int transComProcess(local_thread_data_array_t *localtdata) {
1023 objheader_t *header, *tcptr;
1024 int i, nummod, tmpsize, numcreated, numlocked;
1025 unsigned int *oidmod, *oidcreated, *oidlocked;
1028 nummod = localtdata->tdata->buffer->f.nummod;
1029 oidmod = localtdata->tdata->buffer->oidmod;
1030 numcreated = localtdata->tdata->buffer->f.numcreated;
1031 oidcreated = localtdata->tdata->buffer->oidcreated;
1032 numlocked = localtdata->transinfo->numlocked;
1033 oidlocked = localtdata->transinfo->objlocked;
1034 for (i = 0; i < nummod; i++) {
1035 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1036 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1039 /* Copy from transaction cache -> main object store */
1040 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1041 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1044 GETSIZE(tmpsize, header);
1046 pthread_mutex_lock(&mainobjstore_mutex);
1047 memcpy(header, tcptr, tmpsize + sizeof(objheader_t));
1048 header->version += 1;
1049 pthread_mutex_unlock(&mainobjstore_mutex);
1051 /* If object is newly created inside transaction then commit it */
1052 for (i = 0; i < numcreated; i++) {
1053 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1054 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1057 GETSIZE(tmpsize, header);
1058 pthread_mutex_lock(&mainobjstore_mutex);
1059 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1060 printf("Error: transComProcess() failed objstrAlloc\n");
1061 pthread_mutex_unlock(&mainobjstore_mutex);
1064 pthread_mutex_unlock(&mainobjstore_mutex);
1065 memcpy(ptrcreate, header, tmpsize + sizeof(objheader_t));
1067 mhashInsert(oidcreated[i], ptrcreate);
1068 lhashInsert(oidcreated[i], myIpAddr);
1070 /* Unlock locked objects */
1071 for(i = 0; i < numlocked; i++) {
1072 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1073 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1076 STATUS(header) &= ~(LOCK);
1081 /* This function checks if the prefetch oids are same and have same offsets
1082 * for case x.a.b and y.a.b where x and y have same oid's
1083 * or if a.b.c is a subset of x.b.c.d*/
1084 /* check for case where the generated request a.y.z or x.y.z.g then
1085 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1086 void checkPrefetchTuples(prefetchqelem_t *node) {
1087 int i,j, count,k, sindex, index;
1089 int ntuples, slength;
1091 short *endoffsets, *arryfields;
1093 /* Check for the case x.y.z and a.b.c are same oids */
1094 ptr = (char *) node;
1095 ntuples = *(GET_NTUPLES(ptr));
1096 oid = GET_PTR_OID(ptr);
1097 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1098 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1099 /* Find offset length for each tuple */
1100 int numoffset[ntuples];
1101 numoffset[0] = endoffsets[0];
1102 for(i = 1; i<ntuples; i++) {
1103 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1105 /* Check for redundant tuples by comparing oids of each tuple */
1106 for(i = 0; i < ntuples; i++) {
1109 for(j = i+1 ; j < ntuples; j++) {
1112 /*If oids of tuples match */
1113 if (oid[i] == oid[j]) {
1114 /* Find the smallest offset length of two tuples*/
1115 if(numoffset[i] > numoffset[j]){
1116 slength = numoffset[j];
1120 slength = numoffset[i];
1124 /* Compare the offset values based on the current indices
1125 * break if they do not match
1126 * if all offset values match then pick the largest tuple*/
1130 index = endoffsets[j -1];
1131 for(count = 0; count < slength; count ++) {
1132 if (arryfields[k] != arryfields[index]) {
1139 k = endoffsets[i-1];
1140 index = endoffsets[j-1];
1141 for(count = 0; count < slength; count++) {
1142 if(arryfields[k] != arryfields[index]) {
1150 if(slength == count) {
1158 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1160 int ntuples, i, k, flag;
1162 short *endoffsets, *arryfields;
1163 objheader_t *header;
1165 ptr = (char *) node;
1166 ntuples = *(GET_NTUPLES(ptr));
1167 oid = GET_PTR_OID(ptr);
1168 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1169 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1171 if(oidnfound == 1) {
1172 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1174 } else { //Found in Prefetch Cache
1175 //TODO Decide if object is too old, if old remove from cache
1176 tmp = (char *) header;
1177 /* Check if any of the offset oid is available in the Prefetch cache */
1178 for(i = counter; i < loopcount; i++) {
1179 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1180 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1189 for(i = counter; i<loopcount; i++) {
1190 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1191 tmp = (char *) header;
1192 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1202 /* If oid not found locally or in prefetch cache then
1203 * assign the latest oid found as the new oid
1204 * and copy left over offsets into the arrayoffsetfieldarray*/
1206 numoffset[iter] = numoffset[iter] - (i+1);
1207 for(k = 0; k < numoffset[iter] ; k++) {
1208 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1213 numoffset[iter] = 0;
1217 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1218 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1220 int ntuples, slength, i, machinenum;
1223 short *endoffsets, *arryfields, *offset;
1224 prefetchpile_t *head = NULL;
1226 /* Check for the case x.y.z and a.b.c are same oids */
1227 ptr = (char *) node;
1228 ntuples = *(GET_NTUPLES(ptr));
1229 oid = GET_PTR_OID(ptr);
1230 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1231 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1233 /* Check for redundant tuples by comparing oids of each tuple */
1234 for(i = 0; i < ntuples; i++) {
1237 /* For each tuple make piles */
1238 if ((machinenum = lhashSearch(oid[i])) == 0) {
1239 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1242 /* Insert into machine pile */
1243 offset = &arryfields[endoffsets[i-1]];
1244 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1250 /* This function checks if the oids within the prefetch tuples are available locally.
1251 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1252 * the prefetchqelem_t node to represent a new prefetch tuple */
1253 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1254 int ntuples,i, j, k, oidnfound = 0, index, flag;
1256 unsigned int objoid;
1258 objheader_t *objheader;
1259 short *endoffsets, *arryfields;
1260 prefetchpile_t *head = NULL;
1262 ptr = (char *) node;
1263 ntuples = *(GET_NTUPLES(ptr));
1264 oid = GET_PTR_OID(ptr);
1265 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1266 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1267 /* Find offset length for each tuple */
1268 int numoffset[ntuples];//Number of offsets for each tuple
1269 numoffset[0] = endoffsets[0];
1270 for(i = 1; i<ntuples; i++) {
1271 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1273 for(i = 0; i < ntuples; i++) {
1276 /* If object found locally */
1277 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1279 tmp = (char *) objheader;
1280 /* Find the oid of its offset value */
1284 index = endoffsets[i - 1];
1285 for(j = 0 ; j < numoffset[i] ; j++) {
1286 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1287 /*If oid found locally then
1288 *assign the latest oid found as the new oid
1289 *and copy left over offsets into the arrayoffsetfieldarray*/
1291 numoffset[i] = numoffset[i] - (j+1);
1292 for(k = 0; k < numoffset[i]; k++)
1293 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1295 /*New offset oid not found */
1296 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1298 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1304 /*If all offset oids are found locally,make the prefetch tuple invalid */
1311 /* Look in Prefetch cache */
1312 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1316 /* Make machine groups */
1317 head = makePreGroups(node, numoffset);
1321 /* This function is called by the thread calling transPrefetch */
1322 void *transPrefetch(void *t) {
1323 prefetchqelem_t *qnode;
1324 prefetchpile_t *pilehead = NULL;
1327 /* lock mutex of primary prefetch queue */
1328 pthread_mutex_lock(&pqueue.qlock);
1329 /* while primary queue is empty, then wait */
1330 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1331 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1334 /* dequeue node to create a machine piles and finally unlock mutex */
1335 if((qnode = pre_dequeue()) == NULL) {
1336 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1337 pthread_mutex_unlock(&pqueue.qlock);
1340 pthread_mutex_unlock(&pqueue.qlock);
1341 /* Reduce redundant prefetch requests */
1342 checkPrefetchTuples(qnode);
1343 /* Check if the tuples are found locally, if yes then reduce them further*/
1344 /* and group requests by remote machine ids by calling the makePreGroups() */
1345 pilehead = foundLocal(qnode);
1347 /* Lock mutex of pool queue */
1348 pthread_mutex_lock(&mcqueue.qlock);
1349 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1350 mcpileenqueue(pilehead);
1351 /* Broadcast signal on machine pile queue */
1352 pthread_cond_broadcast(&mcqueue.qcond);
1353 /* Unlock mutex of machine pile queue */
1354 pthread_mutex_unlock(&mcqueue.qlock);
1355 /* Deallocate the prefetch queue pile node */
1361 /* Each thread in the pool of threads calls this function to establish connection with
1362 * remote machines, send the prefetch requests and process the reponses from
1363 * the remote machines .
1364 * The thread is active throughout the period of runtime */
1366 void *mcqProcess(void *threadid) {
1368 prefetchpile_t *mcpilenode;
1370 tid = (int) threadid;
1372 /* Lock mutex of mc pile queue */
1373 pthread_mutex_lock(&mcqueue.qlock);
1374 /* When mc pile queue is empty, wait */
1375 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1376 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1378 /* Dequeue node to send remote machine connections*/
1379 if((mcpilenode = mcpiledequeue()) == NULL) {
1380 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1381 pthread_mutex_unlock(&mcqueue.qlock);
1385 pthread_mutex_unlock(&mcqueue.qlock);
1387 /*Initiate connection to remote host and send request */
1388 /* Process Request */
1389 sendPrefetchReq(mcpilenode, tid);
1391 /* Deallocate the machine queue pile node */
1392 mcdealloc(mcpilenode);
1396 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1397 int sd, i, offset, off, len, endpair, count = 0;
1398 struct sockaddr_in serv_addr;
1399 struct hostent *server;
1400 char machineip[16], control;
1404 /* Send Trans Prefetch Request */
1405 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1406 perror("Error in socket for TRANS_REQUEST\n");
1409 bzero((char*) &serv_addr, sizeof(serv_addr));
1410 serv_addr.sin_family = AF_INET;
1411 serv_addr.sin_port = htons(LISTEN_PORT);
1412 midtoIP(mcpilenode->mid ,machineip);
1413 machineip[15] = '\0';
1414 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1416 /* Open Connection */
1417 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1418 perror("Error in connect for TRANS_REQUEST\n");
1423 /* Send TRANS_PREFETCH control message */
1424 control = TRANS_PREFETCH;
1425 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1426 perror("Error in sending prefetch control\n");
1431 /* Send Oids and offsets in pairs */
1432 tmp = mcpilenode->objpiles;
1433 while(tmp != NULL) {
1435 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1436 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1437 char oidnoffset[len];
1438 memcpy(oidnoffset, &len, sizeof(int));
1440 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1441 off += sizeof(unsigned int);
1442 for(i = 0; i < tmp->numoffset; i++) {
1443 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1446 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1447 perror("Error sending fixed bytes for thread\n");
1454 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1456 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1457 perror("Error sending fixed bytes for thread\n");
1462 /* Get Response from the remote machine */
1463 getPrefetchResponse(count,sd);
1468 void getPrefetchResponse(int count, int sd) {
1469 int i = 0, val, n, N, sum, index, objsize;
1470 unsigned int bufsize,oid;
1471 char buffer[RECEIVE_BUFFER_SIZE], control;
1473 void *modptr, *oldptr;
1475 /* Read prefetch response from the Remote machine */
1476 if((val = read(sd, &control, sizeof(char))) <= 0) {
1477 perror("No control response for Prefetch request sent\n");
1481 if(control == TRANS_PREFETCH_RESPONSE) {
1482 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1486 /* Read the size of buffer to be received */
1487 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1488 perror("Size of buffer not recv\n");
1491 memcpy(&bufsize, buffer, sizeof(unsigned int));
1492 ptr = buffer + sizeof(unsigned int);
1493 /* Keep receiving the buffer containing oid info */
1495 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1497 } while(sum < bufsize && n != 0);
1498 /* Decode the contents of the buffer */
1499 index = sizeof(unsigned int);
1500 while(index < (bufsize - sizeof(unsigned int))) {
1501 if(buffer[index] == OBJECT_FOUND) {
1502 /* Increment it to get the object */
1503 index += sizeof(char);
1504 memcpy(&oid, buffer + index, sizeof(unsigned int));
1505 index += sizeof(unsigned int);
1506 /* For each object found add to Prefetch Cache */
1507 memcpy(&objsize, buffer + index, sizeof(int));
1509 pthread_mutex_lock(&prefetchcache_mutex);
1510 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1511 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1512 pthread_mutex_unlock(&prefetchcache_mutex);
1515 pthread_mutex_unlock(&prefetchcache_mutex);
1516 memcpy(modptr, buffer+index, objsize);
1518 /* Insert the oid and its address into the prefetch hash lookup table */
1519 /* Do a version comparison if the oid exists */
1520 if((oldptr = prehashSearch(oid)) != NULL) {
1521 /* If older version then update with new object ptr */
1522 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1524 prehashInsert(oid, modptr);
1525 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1526 /* Add the new object ptr to hash table */
1528 prehashInsert(oid, modptr);
1529 } else { /* Do nothing: TODO modptr should be reference counted */
1532 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1533 prehashInsert(oid, modptr);
1535 /* Lock the Prefetch Cache look up table*/
1536 pthread_mutex_lock(&pflookup.lock);
1537 /* Broadcast signal on prefetch cache condition variable */
1538 pthread_cond_broadcast(&pflookup.cond);
1539 /* Unlock the Prefetch Cache look up table*/
1540 pthread_mutex_unlock(&pflookup.lock);
1541 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1542 /* Increment it to get the object */
1543 /* TODO: For each object not found query DHT for new location and retrieve the object */
1544 index += sizeof(char);
1545 memcpy(&oid, buffer + index, sizeof(unsigned int));
1546 index += sizeof(unsigned int);
1547 /* Throw an error */
1548 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1551 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1559 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1563 unsigned short getObjType(unsigned int oid)
1565 objheader_t *objheader;
1566 unsigned short numoffset[] ={0};
1567 short fieldoffset[] ={};
1569 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1571 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1573 //prefetch(1, &oid, &numoffsets, NULL);
1574 prefetch(1, &oid, numoffset, fieldoffset);
1575 pthread_mutex_lock(&pflookup.lock);
1576 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1578 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1580 pthread_mutex_unlock(&pflookup.lock);
1584 return TYPE(objheader);
1587 int startRemoteThread(unsigned int oid, unsigned int mid)
1590 struct sockaddr_in remoteAddr;
1591 char msg[1 + sizeof(unsigned int)];
1595 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1597 perror("startRemoteThread():socket()");
1601 bzero(&remoteAddr, sizeof(remoteAddr));
1602 remoteAddr.sin_family = AF_INET;
1603 remoteAddr.sin_port = htons(LISTEN_PORT);
1604 remoteAddr.sin_addr.s_addr = htonl(mid);
1606 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1608 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1609 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1614 msg[0] = START_REMOTE_THREAD;
1615 memcpy(&msg[1], &oid, sizeof(unsigned int));
1617 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1620 perror("startRemoteThread():send()");
1623 else if (bytesSent != 1 + sizeof(unsigned int))
1625 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1638 //TODO: when reusing oids, make sure they are not already in use!
1639 unsigned int getNewOID(void) {
1640 static unsigned int id = 0xFFFFFFFF;
1643 if (id > oidMax || id < oidMin)
1650 int processConfigFile()
1653 const int maxLineLength = 200;
1654 char lineBuffer[maxLineLength];
1656 const char *delimiters = " \t\n";
1660 configFile = fopen(CONFIG_FILENAME, "r");
1661 if (configFile == NULL)
1663 printf("error opening %s:\n", CONFIG_FILENAME);
1668 numHostsInSystem = 0;
1669 sizeOfHostArray = 8;
1670 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1672 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1674 commentBegin = strchr(lineBuffer, '#');
1675 if (commentBegin != NULL)
1676 *commentBegin = '\0';
1677 token = strtok(lineBuffer, delimiters);
1678 while (token != NULL)
1680 tmpAddr = inet_addr(token);
1681 if ((int)tmpAddr == -1)
1683 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1688 addHost(htonl(tmpAddr));
1689 token = strtok(NULL, delimiters);
1695 if (numHostsInSystem < 1)
1697 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1701 myIpAddr = getMyIpAddr("en1");
1703 myIpAddr = getMyIpAddr("eth0");
1705 myIndexInHostArray = findHost(myIpAddr);
1706 if (myIndexInHostArray == -1)
1708 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1711 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1712 oidMin = oidsPerBlock * myIndexInHostArray;
1713 if (myIndexInHostArray == numHostsInSystem - 1)
1714 oidMax = 0xFFFFFFFF;
1716 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1721 void addHost(unsigned int hostIp)
1723 unsigned int *tmpArray;
1725 if (findHost(hostIp) != -1)
1728 if (numHostsInSystem == sizeOfHostArray)
1730 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1731 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1733 hostIpAddrs = tmpArray;
1736 hostIpAddrs[numHostsInSystem++] = hostIp;
1741 int findHost(unsigned int hostIp)
1744 for (i = 0; i < numHostsInSystem; i++)
1745 if (hostIpAddrs[i] == hostIp)