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>
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) {
161 /* This function initiates the prefetch thread
162 * A queue is shared between the main thread of execution
163 * and the prefetch thread to process the prefetch call
164 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
165 * processes the prefetch requests */
169 //Create and initialize prefetch cache structure
170 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
171 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
172 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
174 /* Initialize attributes for mutex */
175 pthread_mutexattr_init(&prefetchcache_mutex_attr);
176 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
178 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
180 //Create prefetch cache lookup table
181 if(prehashCreate(HASH_SIZE, LOADFACTOR))
183 //Initialize primary shared queue
185 //Initialize machine pile w/prefetch oids and offsets shared queue
187 //Create the primary prefetch thread
190 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
192 pthread_detach(tPrefetch);
194 //Create and Initialize a pool of threads
195 /* Threads are active for the entire period runtime is running */
196 for(t = 0; t< NUM_THREADS; t++) {
198 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
200 pthread_detach(wthreads[t]);
204 /* This function stops the threads spawned */
207 pthread_cancel(tPrefetch);
208 for(t = 0; t < NUM_THREADS; t++)
209 pthread_cancel(wthreads[t]);
214 /* This functions inserts randowm wait delays in the order of msec
215 * Mostly used when transaction commits retry*/
223 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
224 nanosleep(&req, NULL);
228 /* This function initializes things required in the transaction start*/
229 transrecord_t *transStart()
231 transrecord_t *tmp = malloc(sizeof(transrecord_t));
232 tmp->cache = objstrCreate(1048576);
233 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
235 tmp->revertlist=NULL;
240 /* This function finds the location of the objects involved in a transaction
241 * and returns the pointer to the object if found in a remote location */
242 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
243 unsigned int machinenumber;
244 objheader_t *tmp, *objheader;
245 objheader_t *objcopy;
246 int size, rc, found = 0;
255 rc = gettimeofday(&tp, NULL);
259 if (tp.tv_usec >= 1000000)
261 tp.tv_usec -= 1000000;
264 /* Convert from timeval to timespec */
265 ts.tv_sec = tp.tv_sec;
266 ts.tv_nsec = tp.tv_usec * 1000;
268 /* Search local transaction cache */
269 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
271 return &objheader[1];
275 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
276 /* Look up in machine lookup table and copy into cache*/
277 GETSIZE(size, objheader);
278 size += sizeof(objheader_t);
279 objcopy = objstrAlloc(record->cache, size);
280 memcpy(objcopy, (void *)objheader, size);
281 /* Insert into cache's lookup table */
282 chashInsert(record->lookupTable, OID(objheader), objcopy);
288 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
290 size+=sizeof(objheader_t);
291 objcopy = objstrAlloc(record->cache, size);
292 memcpy(objcopy, (void *)tmp, size);
293 /* Insert into cache's lookup table */
294 chashInsert(record->lookupTable, OID(tmp), objcopy);
301 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
302 pthread_mutex_lock(&pflookup.lock);
304 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
305 /* Check Prefetch cache again */
306 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
309 size+=sizeof(objheader_t);
310 objcopy = objstrAlloc(record->cache, size);
311 memcpy(objcopy, (void *)tmp, size);
312 chashInsert(record->lookupTable, OID(tmp), objcopy);
313 pthread_mutex_unlock(&pflookup.lock);
319 } else if (rc == ETIMEDOUT) {
320 printf("Wait timed out\n");
321 pthread_mutex_unlock(&pflookup.lock);
326 /* Get the object from the remote location */
327 machinenumber = lhashSearch(oid);
329 midtoIP(machinenumber, ipaddr);
330 objcopy = getRemoteObj(record, machinenumber, oid);
331 if(objcopy == NULL) {
332 printf("Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
344 /* This function creates objects in the transaction record */
345 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
347 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
348 tmp->notifylist = NULL;
349 OID(tmp) = getNewOID();
353 chashInsert(record->lookupTable, OID(tmp), tmp);
356 return &tmp[1]; //want space after object header
362 /* This function creates machine piles based on all machines involved in a
363 * transaction commit request */
364 plistnode_t *createPiles(transrecord_t *record) {
366 unsigned int size;/* Represents number of bins in the chash table */
367 chashlistnode_t *curr, *ptr, *next;
368 plistnode_t *pile = NULL;
369 unsigned int machinenum;
370 void *localmachinenum;
371 objheader_t *headeraddr;
373 ptr = record->lookupTable->table;
374 size = record->lookupTable->size;
376 for(i = 0; i < size ; i++) {
378 /* Inner loop to traverse the linked list of the cache lookupTable */
379 while(curr != NULL) {
380 //if the first bin in hash table is empty
386 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
387 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
391 //Get machine location for object id (and whether local or not)
392 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
393 machinenum = myIpAddr;
394 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
395 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
399 //Make machine groups
400 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
401 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
411 /* This function initiates the transaction commit process
412 * Spawns threads for each of the new connections with Participants
413 * and creates new piles by calling the createPiles(),
414 * Sends a transrequest() to each remote machines for objects found remotely
415 * and calls handleLocalReq() to process objects found locally */
416 int transCommit(transrecord_t *record) {
417 unsigned int tot_bytes_mod, *listmid;
418 plistnode_t *pile, *pile_ptr;
420 int pilecount, offset, threadnum, trecvcount;
421 char buffer[RECEIVE_BUFFER_SIZE],control;
422 char transid[TID_LEN];
423 trans_req_data_t *tosend;
424 trans_commit_data_t transinfo;
425 static int newtid = 0;
426 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
434 /* Look through all the objects in the transaction record and make piles
435 * for each machine involved in the transaction*/
436 pile_ptr = pile = createPiles(record);
438 /* Create the packet to be sent in TRANS_REQUEST */
440 /* Count the number of participants */
441 pilecount = pCount(pile);
443 /* Create a list of machine ids(Participants) involved in transaction */
444 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
445 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
449 pListMid(pile, listmid);
452 /* Initialize thread variables,
453 * Spawn a thread for each Participant involved in a transaction */
454 pthread_t thread[pilecount];
456 pthread_cond_t tcond;
457 pthread_mutex_t tlock;
458 pthread_mutex_t tlshrd;
460 thread_data_array_t *thread_data_array;
461 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
462 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
463 pthread_cond_destroy(&tcond);
464 pthread_mutex_destroy(&tlock);
471 local_thread_data_array_t *ltdata;
472 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
473 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
474 pthread_cond_destroy(&tcond);
475 pthread_mutex_destroy(&tlock);
478 free(thread_data_array);
483 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
485 /* Initialize and set thread detach attribute */
486 pthread_attr_init(&attr);
487 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
488 pthread_mutex_init(&tlock, NULL);
489 pthread_cond_init(&tcond, NULL);
491 /* Process each machine pile */
492 while(pile != NULL) {
493 //Create transaction id
495 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
496 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
497 pthread_cond_destroy(&tcond);
498 pthread_mutex_destroy(&tlock);
501 free(thread_data_array);
506 tosend->f.control = TRANS_REQUEST;
507 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
508 tosend->f.mcount = pilecount;
509 tosend->f.numread = pile->numread;
510 tosend->f.nummod = pile->nummod;
511 tosend->f.numcreated = pile->numcreated;
512 tosend->f.sum_bytes = pile->sum_bytes;
513 tosend->listmid = listmid;
514 tosend->objread = pile->objread;
515 tosend->oidmod = pile->oidmod;
516 tosend->oidcreated = pile->oidcreated;
517 thread_data_array[threadnum].thread_id = threadnum;
518 thread_data_array[threadnum].mid = pile->mid;
519 thread_data_array[threadnum].buffer = tosend;
520 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
521 thread_data_array[threadnum].threshold = &tcond;
522 thread_data_array[threadnum].lock = &tlock;
523 thread_data_array[threadnum].count = &trecvcount;
524 thread_data_array[threadnum].replyctrl = &treplyctrl;
525 thread_data_array[threadnum].replyretry = &treplyretry;
526 thread_data_array[threadnum].rec = record;
527 /* If local do not create any extra connection */
528 if(pile->mid != myIpAddr) { /* Not local */
530 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
533 perror("Error in pthread create\n");
534 pthread_cond_destroy(&tcond);
535 pthread_mutex_destroy(&tlock);
538 for (i = 0; i < threadnum; i++)
539 free(thread_data_array[i].buffer);
540 free(thread_data_array);
546 ltdata->tdata = &thread_data_array[threadnum];
547 ltdata->transinfo = &transinfo;
549 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
552 perror("Error in pthread create\n");
553 pthread_cond_destroy(&tcond);
554 pthread_mutex_destroy(&tlock);
557 for (i = 0; i < threadnum; i++)
558 free(thread_data_array[i].buffer);
559 free(thread_data_array);
570 /* Free attribute and wait for the other threads */
571 pthread_attr_destroy(&attr);
573 for (i = 0; i < pilecount; i++) {
574 rc = pthread_join(thread[i], NULL);
577 printf("ERROR return code from pthread_join() is %d\n", rc);
578 pthread_cond_destroy(&tcond);
579 pthread_mutex_destroy(&tlock);
582 for (j = i; j < pilecount; j++)
583 free(thread_data_array[j].buffer);
584 free(thread_data_array);
589 free(thread_data_array[i].buffer);
593 pthread_cond_destroy(&tcond);
594 pthread_mutex_destroy(&tlock);
597 free(thread_data_array);
600 /* wait a random amount of time before retrying to commit transaction*/
601 if(treplyretry == 1) {
605 /* Retry trans commit procedure if not sucessful in the first try */
606 } while (treplyretry == 1);
609 objstrDelete(record->cache);
610 chashDelete(record->lookupTable);
615 /* This function sends information involved in the transaction request
616 * to participants and accepts a response from particpants.
617 * It calls decideresponse() to decide on what control message
618 * to send next to participants and sends the message using sendResponse()*/
619 void *transRequest(void *threadarg) {
621 struct sockaddr_in serv_addr;
622 struct hostent *server;
623 thread_data_array_t *tdata;
624 objheader_t *headeraddr;
625 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
626 char machineip[16], retval;
628 tdata = (thread_data_array_t *) threadarg;
630 /* Send Trans Request */
631 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
632 perror("Error in socket for TRANS_REQUEST\n");
635 bzero((char*) &serv_addr, sizeof(serv_addr));
636 serv_addr.sin_family = AF_INET;
637 serv_addr.sin_port = htons(LISTEN_PORT);
638 midtoIP(tdata->mid,machineip);
639 machineip[15] = '\0';
640 serv_addr.sin_addr.s_addr = inet_addr(machineip);
641 /* Open Connection */
642 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
643 perror("Error in connect for TRANS_REQUEST\n");
648 /* Send bytes of data with TRANS_REQUEST control message */
649 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
650 perror("Error sending fixed bytes for thread\n");
654 /* Send list of machines involved in the transaction */
656 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
657 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
658 perror("Error sending list of machines for thread\n");
663 /* Send oids and version number tuples for objects that are read */
665 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
666 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
667 perror("Error sending tuples for thread\n");
672 /* Send objects that are modified */
673 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
675 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
676 GETSIZE(size,headeraddr);
677 size+=sizeof(objheader_t);
678 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
679 perror("Error sending obj modified for thread\n");
685 /* Read control message from Participant */
686 if((n = read(sd, &control, sizeof(char))) <= 0) {
687 perror("Error in reading control message from Participant\n");
691 recvcontrol = control;
693 /* Update common data structure and increment count */
694 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
696 /* Lock and update count */
697 /* Thread sleeps until all messages from pariticipants are received by coordinator */
698 pthread_mutex_lock(tdata->lock);
700 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
702 /* Wake up the threads and invoke decideResponse (once) */
703 if(*(tdata->count) == tdata->buffer->f.mcount) {
704 decideResponse(tdata);
705 pthread_cond_broadcast(tdata->threshold);
707 pthread_cond_wait(tdata->threshold, tdata->lock);
709 pthread_mutex_unlock(tdata->lock);
711 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
712 * to all participants in their respective socket */
713 if (sendResponse(tdata, sd) == 0) {
714 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
719 /* Close connection */
721 //pthread_exit(NULL);
724 /* This function decides the reponse that needs to be sent to
725 * all Participant machines after the TRANS_REQUEST protocol */
726 void decideResponse(thread_data_array_t *tdata) {
728 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
731 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
732 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
733 written onto the shared array */
736 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
737 /* treat as disagree, pass thru */
746 case TRANS_SOFT_ABORT:
752 if(transdisagree > 0) {
754 *(tdata->replyctrl) = TRANS_ABORT;
755 *(tdata->replyretry) = 0;
756 /* clear objects from prefetch cache */
757 for (i = 0; i < tdata->buffer->f.numread; i++)
758 prehashRemove(*(unsigned int *)(tdata->buffer->objread + (sizeof(unsigned int) + sizeof(unsigned short))*i));
759 for (i = 0; i < tdata->buffer->f.nummod; i++)
760 prehashRemove(tdata->buffer->oidmod[i]);
761 } else if(transagree == tdata->buffer->f.mcount){
763 *(tdata->replyctrl) = TRANS_COMMIT;
764 *(tdata->replyretry) = 0;
766 /* Send Abort in soft abort case followed by retry commiting transaction again*/
767 *(tdata->replyctrl) = TRANS_ABORT;
768 *(tdata->replyretry) = 1;
773 /* This function sends the final response to remote machines per thread in their respective socket id
774 * It returns a char that is only needed to check the correctness of execution of this function inside
776 char sendResponse(thread_data_array_t *tdata, int sd) {
777 int n, N, sum, oidcount = 0;
778 char *ptr, retval = 0;
779 unsigned int *oidnotfound;
781 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
782 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
783 /* Read list of objects missing */
784 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
785 N = oidcount * sizeof(unsigned int);
786 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
787 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
790 ptr = (char *) oidnotfound;
792 n = read(sd, ptr+sum, N-sum);
794 } while(sum < N && n !=0);
796 retval = TRANS_SOFT_ABORT;
798 /* If the decided response is TRANS_ABORT */
799 if(*(tdata->replyctrl) == TRANS_ABORT) {
800 retval = TRANS_ABORT;
801 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
802 retval = TRANS_COMMIT;
805 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
806 perror("Error sending ctrl message for participant\n");
812 /* This function opens a connection, places an object read request to the
813 * remote machine, reads the control message and object if available and
814 * copies the object and its header to the local cache.
815 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
817 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
819 struct sockaddr_in serv_addr;
820 struct hostent *server;
826 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
827 perror("Error in socket\n");
830 bzero((char*) &serv_addr, sizeof(serv_addr));
831 serv_addr.sin_family = AF_INET;
832 serv_addr.sin_port = htons(LISTEN_PORT);
833 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
834 midtoIP(mnum,machineip);
835 machineip[15] = '\0';
836 serv_addr.sin_addr.s_addr = inet_addr(machineip);
837 /* Open connection */
838 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
839 perror("Error in connect\n");
842 char readrequest[sizeof(char)+sizeof(unsigned int)];
843 readrequest[0] = READ_REQUEST;
844 *((unsigned int *)(&readrequest[1])) = oid;
845 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
846 perror("Error sending message\n");
850 /* Read response from the Participant */
851 if((val = read(sd, &control, sizeof(char))) <= 0) {
852 perror("No control response for getRemoteObj sent\n");
856 case OBJECT_NOT_FOUND:
859 /* Read object if found into local cache */
860 if((val = read(sd, &size, sizeof(int))) <= 0) {
861 perror("No size is read from the participant\n");
864 objcopy = objstrAlloc(record->cache, size);
865 if((val = read(sd, objcopy, size)) <= 0) {
866 perror("No objects are read from the remote participant\n");
869 /* Insert into cache's lookup table */
870 chashInsert(record->lookupTable, oid, objcopy);
873 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
876 /* Close connection */
881 /* This function handles the local objects involved in a transaction commiting process.
882 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
883 * Note Coordinator = local machine
884 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
885 * based on common agreement it either commits or aborts the transaction.
886 * It also frees the memory resources */
887 void *handleLocalReq(void *threadarg) {
888 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
889 local_thread_data_array_t *localtdata;
890 int objnotfound = 0, objlocked = 0;
891 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
894 unsigned short version;
896 objheader_t *headptr;
898 localtdata = (local_thread_data_array_t *) threadarg;
900 /* Counters and arrays to formulate decision on control message to be sent */
901 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
902 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
904 numread = localtdata->tdata->buffer->f.numread;
905 /* Process each oid in the machine pile/ group per thread */
906 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
907 if (i < localtdata->tdata->buffer->f.numread) {
908 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
910 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
911 version = *((short *)(localtdata->tdata->buffer->objread + incr + sizeof(unsigned int)));
912 } else { // Objects Modified
914 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
915 if (headptr == NULL) {
916 printf("Error: handleLocalReq() returning NULL\n");
920 version = headptr->version;
922 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
924 /* Save the oids not found and number of oids not found for later use */
925 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
926 /* Save the oids not found and number of oids not found for later use */
927 oidnotfound[objnotfound] = oid;
929 } else { /* If Obj found in machine (i.e. has not moved) */
930 /* Check if Obj is locked by any previous transaction */
931 if ((STATUS(((objheader_t *)mobj)) & LOCK) == LOCK) {
932 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
934 } else {/* If versions don't match ...HARD ABORT */
936 /* Send TRANS_DISAGREE to Coordinator */
937 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
939 } else {/* If Obj is not locked then lock object */
940 STATUS(((objheader_t *)mobj)) |= LOCK;
941 /* Save all object oids that are locked on this machine during this transaction request call */
942 oidlocked[objlocked] = OID(((objheader_t *)mobj));
944 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
946 } else { /* If versions don't match ...HARD ABORT */
948 /* Send TRANS_DISAGREE to Coordinator */
949 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
954 /* Condition to send TRANS_AGREE */
955 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
956 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
958 /* Condition to send TRANS_SOFT_ABORT */
959 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
960 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
963 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
964 * if Participant receives a TRANS_COMMIT */
965 localtdata->transinfo->objlocked = oidlocked;
966 localtdata->transinfo->objnotfound = oidnotfound;
967 localtdata->transinfo->modptr = NULL;
968 localtdata->transinfo->numlocked = objlocked;
969 localtdata->transinfo->numnotfound = objnotfound;
970 /* Lock and update count */
971 //Thread sleeps until all messages from pariticipants are received by coordinator
972 pthread_mutex_lock(localtdata->tdata->lock);
973 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
975 /* Wake up the threads and invoke decideResponse (once) */
976 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
977 decideResponse(localtdata->tdata);
978 pthread_cond_broadcast(localtdata->tdata->threshold);
980 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
982 pthread_mutex_unlock(localtdata->tdata->lock);
983 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
984 if(transAbortProcess(localtdata) != 0) {
985 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
988 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
989 if(transComProcess(localtdata) != 0) {
990 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
995 if (localtdata->transinfo->objlocked != NULL) {
996 free(localtdata->transinfo->objlocked);
998 if (localtdata->transinfo->objnotfound != NULL) {
999 free(localtdata->transinfo->objnotfound);
1002 //pthread_exit(NULL);
1005 /* This function completes the ABORT process if the transaction is aborting */
1006 int transAbortProcess(local_thread_data_array_t *localtdata) {
1008 unsigned int *objlocked;
1011 numlocked = localtdata->transinfo->numlocked;
1012 objlocked = localtdata->transinfo->objlocked;
1014 for (i = 0; i < numlocked; i++) {
1015 if((header = mhashSearch(objlocked[i])) == NULL) {
1016 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1019 STATUS(((objheader_t *)header)) &= ~(LOCK);
1022 printf("TRANS_ABORTED at Coordinator end\n");
1027 /*This function completes the COMMIT process is the transaction is commiting*/
1028 int transComProcess(local_thread_data_array_t *localtdata) {
1029 objheader_t *header, *tcptr;
1030 int i, nummod, tmpsize, numcreated, numlocked;
1031 unsigned int *oidmod, *oidcreated, *oidlocked;
1034 nummod = localtdata->tdata->buffer->f.nummod;
1035 oidmod = localtdata->tdata->buffer->oidmod;
1036 numcreated = localtdata->tdata->buffer->f.numcreated;
1037 oidcreated = localtdata->tdata->buffer->oidcreated;
1038 numlocked = localtdata->transinfo->numlocked;
1039 oidlocked = localtdata->transinfo->objlocked;
1040 for (i = 0; i < nummod; i++) {
1041 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1042 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1045 /* Copy from transaction cache -> main object store */
1046 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1047 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1050 GETSIZE(tmpsize, header);
1052 pthread_mutex_lock(&mainobjstore_mutex);
1053 memcpy(header, tcptr, tmpsize + sizeof(objheader_t));
1054 header->version += 1;
1055 /* If threads are waiting on this object to be updated, notify them */
1056 if(header->notifylist != NULL) {
1057 notifyAll(&header->notifylist, OID(header), header->version);
1060 pthread_mutex_unlock(&mainobjstore_mutex);
1062 /* If object is newly created inside transaction then commit it */
1063 for (i = 0; i < numcreated; i++) {
1064 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1065 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1068 GETSIZE(tmpsize, header);
1069 tmpsize += sizeof(objheader_t);
1070 pthread_mutex_lock(&mainobjstore_mutex);
1071 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1072 printf("Error: transComProcess() failed objstrAlloc\n");
1073 pthread_mutex_unlock(&mainobjstore_mutex);
1076 pthread_mutex_unlock(&mainobjstore_mutex);
1077 memcpy(ptrcreate, header, tmpsize + sizeof(objheader_t));
1078 mhashInsert(oidcreated[i], ptrcreate);
1079 lhashInsert(oidcreated[i], myIpAddr);
1081 /* Unlock locked objects */
1082 for(i = 0; i < numlocked; i++) {
1083 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1084 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1087 STATUS(header) &= ~(LOCK);
1092 /* This function checks if the prefetch oids are same and have same offsets
1093 * for case x.a.b and y.a.b where x and y have same oid's
1094 * or if a.b.c is a subset of x.b.c.d*/
1095 /* check for case where the generated request a.y.z or x.y.z.g then
1096 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1097 void checkPrefetchTuples(prefetchqelem_t *node) {
1098 int i,j, count,k, sindex, index;
1100 int ntuples, slength;
1102 short *endoffsets, *arryfields;
1104 /* Check for the case x.y.z and a.b.c are same oids */
1105 ptr = (char *) node;
1106 ntuples = *(GET_NTUPLES(ptr));
1107 oid = GET_PTR_OID(ptr);
1108 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1109 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1111 /* Find offset length for each tuple */
1112 int numoffset[ntuples];
1113 numoffset[0] = endoffsets[0];
1114 for(i = 1; i<ntuples; i++) {
1115 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1117 /* Check for redundant tuples by comparing oids of each tuple */
1118 for(i = 0; i < ntuples; i++) {
1121 for(j = i+1 ; j < ntuples; j++) {
1124 /*If oids of tuples match */
1125 if (oid[i] == oid[j]) {
1126 /* Find the smallest offset length of two tuples*/
1127 if(numoffset[i] > numoffset[j]){
1128 slength = numoffset[j];
1132 slength = numoffset[i];
1136 /* Compare the offset values based on the current indices
1137 * break if they do not match
1138 * if all offset values match then pick the largest tuple*/
1143 k = endoffsets[i-1];
1145 index = endoffsets[j -1];
1146 for(count = 0; count < slength; count ++) {
1147 if (arryfields[k] != arryfields[index]) {
1153 if(slength == count) {
1160 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1161 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1163 int ntuples, slength, i, machinenum;
1166 short *endoffsets, *arryfields, *offset;
1167 prefetchpile_t *head = NULL;
1169 /* Check for the case x.y.z and a.b.c are same oids */
1170 ptr = (char *) node;
1171 ntuples = *(GET_NTUPLES(ptr));
1172 oid = GET_PTR_OID(ptr);
1173 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1174 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1176 /* Check for redundant tuples by comparing oids of each tuple */
1177 for(i = 0; i < ntuples; i++) {
1180 /* For each tuple make piles */
1181 if ((machinenum = lhashSearch(oid[i])) == 0) {
1182 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1185 /* Insert into machine pile */
1186 offset = &arryfields[endoffsets[i-1]];
1187 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1192 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1193 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1195 unsigned int objoid;
1198 objheader_t *objheader;
1199 short *endoffsets, *arryfields;
1200 prefetchpile_t *head = NULL;
1202 ptr = (char *) node;
1203 ntuples = *(GET_NTUPLES(ptr));
1204 oid = GET_PTR_OID(ptr);
1205 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1206 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1207 /* Find offset length for each tuple */
1208 int numoffset[ntuples];//Number of offsets for each tuple
1209 numoffset[0] = endoffsets[0];
1210 for(i = 1; i<ntuples; i++) {
1211 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1213 for(i = 0; i < ntuples; i++) {
1217 nextarryfieldindex = endoffsets[0];
1219 arryfieldindex = endoffsets[i-1];
1220 nextarryfieldindex = endoffsets[i];
1223 endoffsets[0] = val = numoffset[0];
1224 for(k = 1; k < ntuples; k++) {
1225 val = val + numoffset[k];
1226 endoffsets[k] = val;
1229 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1230 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1234 /* If object found locally */
1235 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1236 tmp = (char *) objheader;
1237 int orgnumoffset = numoffset[i];
1241 arryfieldindex = endoffsets[i-1];
1244 for(j = 0; j<orgnumoffset; j++) {
1245 /* Check for arrays */
1246 if(TYPE(objheader) > NUMCLASSES) {
1250 int elementsize = classsize[TYPE(objheader)];
1251 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1253 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1255 //Update numoffset array
1256 numoffset[i] = numoffset[i] - 1;
1259 //Update endoffset array
1260 endoffsets[0] = val = numoffset[0];
1261 for(k = 1; k < ntuples; k++) {
1262 val = val + numoffset[k];
1263 endoffsets[k] = val;
1265 //Update arrayfields array
1266 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1267 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1269 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1271 checkPreCache(node, numoffset, oid[i], i);
1274 tmp = (char *) objheader;
1277 /*If all offset oids are found locally,make the prefetch tuple invalid */
1282 /* Look in Prefetch cache */
1283 checkPreCache(node, numoffset, oid[i],i);
1287 /* Make machine groups */
1288 head = makePreGroups(node, numoffset);
1292 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1294 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1296 short *endoffsets, *arryfields;
1297 objheader_t *header;
1299 ptr = (char *) node;
1300 ntuples = *(GET_NTUPLES(ptr));
1301 oid = GET_PTR_OID(ptr);
1302 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1303 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1305 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1307 } else { //Found in Prefetch Cache
1308 //TODO Decide if object is too old, if old remove from cache
1309 tmp = (char *) header;
1310 int loopcount = numoffset[index];
1314 arryfieldindex = endoffsets[(index - 1)];
1315 // Check if any of the offset oid is available in the Prefetch cache
1316 for(i = 0; i < loopcount; i++) {
1317 /* Check for arrays */
1318 if(TYPE(header) > NUMCLASSES) {
1322 int elementsize = classsize[TYPE(header)];
1323 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1325 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1327 //Update numoffset array
1328 numoffset[index] = numoffset[index] - 1;
1330 oid[index] = objoid;
1331 //Update endoffset array
1332 endoffsets[0] = val = numoffset[0];
1333 for(k = 1; k < ntuples; k++) {
1334 val = val + numoffset[k];
1335 endoffsets[k] = val;
1337 //Update arrayfields array
1338 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1339 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1341 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1342 tmp = (char *) header;
1350 //Found in the prefetch cache
1351 if(flag == 0 && (numoffset[index] == 0)) {
1358 /* This function is called by the thread calling transPrefetch */
1359 void *transPrefetch(void *t) {
1360 prefetchqelem_t *qnode;
1361 prefetchpile_t *pilehead = NULL;
1364 /* lock mutex of primary prefetch queue */
1365 pthread_mutex_lock(&pqueue.qlock);
1366 /* while primary queue is empty, then wait */
1367 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1368 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1371 /* dequeue node to create a machine piles and finally unlock mutex */
1372 if((qnode = pre_dequeue()) == NULL) {
1373 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1374 pthread_mutex_unlock(&pqueue.qlock);
1377 pthread_mutex_unlock(&pqueue.qlock);
1378 /* Reduce redundant prefetch requests */
1379 checkPrefetchTuples(qnode);
1380 /* Check if the tuples are found locally, if yes then reduce them further*/
1381 /* and group requests by remote machine ids by calling the makePreGroups() */
1382 pilehead = foundLocal(qnode);
1384 /* Lock mutex of pool queue */
1385 pthread_mutex_lock(&mcqueue.qlock);
1386 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1387 mcpileenqueue(pilehead);
1388 /* Broadcast signal on machine pile queue */
1389 pthread_cond_broadcast(&mcqueue.qcond);
1390 /* Unlock mutex of machine pile queue */
1391 pthread_mutex_unlock(&mcqueue.qlock);
1392 /* Deallocate the prefetch queue pile node */
1398 /* Each thread in the pool of threads calls this function to establish connection with
1399 * remote machines, send the prefetch requests and process the reponses from
1400 * the remote machines .
1401 * The thread is active throughout the period of runtime */
1403 void *mcqProcess(void *threadid) {
1405 prefetchpile_t *mcpilenode;
1407 tid = (int) threadid;
1409 /* Lock mutex of mc pile queue */
1410 pthread_mutex_lock(&mcqueue.qlock);
1411 /* When mc pile queue is empty, wait */
1412 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1413 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1415 /* Dequeue node to send remote machine connections*/
1416 if((mcpilenode = mcpiledequeue()) == NULL) {
1417 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1418 pthread_mutex_unlock(&mcqueue.qlock);
1422 pthread_mutex_unlock(&mcqueue.qlock);
1424 /*Initiate connection to remote host and send request */
1425 /* Process Request */
1426 sendPrefetchReq(mcpilenode, tid);
1428 /* Deallocate the machine queue pile node */
1429 mcdealloc(mcpilenode);
1433 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1434 int sd, i, offset, off, len, endpair, count = 0;
1435 struct sockaddr_in serv_addr;
1436 struct hostent *server;
1437 char machineip[16], control;
1441 /* Send Trans Prefetch Request */
1442 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1443 perror("Error in socket for TRANS_REQUEST\n");
1446 bzero((char*) &serv_addr, sizeof(serv_addr));
1447 serv_addr.sin_family = AF_INET;
1448 serv_addr.sin_port = htons(LISTEN_PORT);
1449 midtoIP(mcpilenode->mid ,machineip);
1450 machineip[15] = '\0';
1451 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1453 /* Open Connection */
1454 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1455 perror("Error in connect for TRANS_REQUEST\n");
1460 /* Send TRANS_PREFETCH control message */
1461 control = TRANS_PREFETCH;
1462 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1463 perror("Error in sending prefetch control\n");
1468 /* Send Oids and offsets in pairs */
1469 tmp = mcpilenode->objpiles;
1470 while(tmp != NULL) {
1472 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1473 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1474 char oidnoffset[len];
1475 memcpy(oidnoffset, &len, sizeof(int));
1477 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1478 off += sizeof(unsigned int);
1479 for(i = 0; i < tmp->numoffset; i++) {
1480 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1483 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1484 perror("Error sending fixed bytes for thread\n");
1491 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1493 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1494 perror("Error sending fixed bytes for thread\n");
1499 /* Get Response from the remote machine */
1500 getPrefetchResponse(count,sd);
1505 void getPrefetchResponse(int count, int sd) {
1506 int i = 0, val, n, N, sum, index, objsize;
1507 unsigned int bufsize,oid;
1508 char buffer[RECEIVE_BUFFER_SIZE], control;
1510 void *modptr, *oldptr;
1512 /* Read prefetch response from the Remote machine */
1513 if((val = read(sd, &control, sizeof(char))) <= 0) {
1514 perror("No control response for Prefetch request sent\n");
1518 if(control == TRANS_PREFETCH_RESPONSE) {
1519 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1523 /* Read the size of buffer to be received */
1524 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1525 perror("Size of buffer not recv\n");
1528 memcpy(&bufsize, buffer, sizeof(unsigned int));
1529 ptr = buffer + sizeof(unsigned int);
1530 /* Keep receiving the buffer containing oid info */
1532 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1534 } while(sum < bufsize && n != 0);
1535 /* Decode the contents of the buffer */
1536 index = sizeof(unsigned int);
1537 while(index < (bufsize - sizeof(unsigned int))) {
1538 if(buffer[index] == OBJECT_FOUND) {
1539 /* Increment it to get the object */
1540 index += sizeof(char);
1541 memcpy(&oid, buffer + index, sizeof(unsigned int));
1542 index += sizeof(unsigned int);
1543 /* For each object found add to Prefetch Cache */
1544 memcpy(&objsize, buffer + index, sizeof(int));
1546 pthread_mutex_lock(&prefetchcache_mutex);
1547 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1548 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1549 pthread_mutex_unlock(&prefetchcache_mutex);
1552 pthread_mutex_unlock(&prefetchcache_mutex);
1553 memcpy(modptr, buffer+index, objsize);
1555 /* Insert the oid and its address into the prefetch hash lookup table */
1556 /* Do a version comparison if the oid exists */
1557 if((oldptr = prehashSearch(oid)) != NULL) {
1558 /* If older version then update with new object ptr */
1559 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1561 prehashInsert(oid, modptr);
1562 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1563 /* Add the new object ptr to hash table */
1565 prehashInsert(oid, modptr);
1566 } else { /* Do nothing: TODO modptr should be reference counted */
1569 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1570 prehashInsert(oid, modptr);
1572 /* Lock the Prefetch Cache look up table*/
1573 pthread_mutex_lock(&pflookup.lock);
1574 /* Broadcast signal on prefetch cache condition variable */
1575 pthread_cond_broadcast(&pflookup.cond);
1576 /* Unlock the Prefetch Cache look up table*/
1577 pthread_mutex_unlock(&pflookup.lock);
1578 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1579 /* Increment it to get the object */
1580 /* TODO: For each object not found query DHT for new location and retrieve the object */
1581 index += sizeof(char);
1582 //memcpy(&oid, buffer + index, sizeof(unsigned int));
1583 oid = *((unsigned int *)(buffer + index));
1584 index += sizeof(unsigned int);
1585 /* Throw an error */
1586 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1589 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1597 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1601 unsigned short getObjType(unsigned int oid)
1603 objheader_t *objheader;
1604 unsigned short numoffset[] ={0};
1605 short fieldoffset[] ={};
1607 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1609 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1611 prefetch(1, &oid, numoffset, fieldoffset);
1612 pthread_mutex_lock(&pflookup.lock);
1613 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1615 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1617 pthread_mutex_unlock(&pflookup.lock);
1621 return TYPE(objheader);
1624 int startRemoteThread(unsigned int oid, unsigned int mid)
1627 struct sockaddr_in remoteAddr;
1628 char msg[1 + sizeof(unsigned int)];
1632 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1634 perror("startRemoteThread():socket()");
1638 bzero(&remoteAddr, sizeof(remoteAddr));
1639 remoteAddr.sin_family = AF_INET;
1640 remoteAddr.sin_port = htons(LISTEN_PORT);
1641 remoteAddr.sin_addr.s_addr = htonl(mid);
1643 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1645 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1646 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1651 msg[0] = START_REMOTE_THREAD;
1652 memcpy(&msg[1], &oid, sizeof(unsigned int));
1654 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1657 perror("startRemoteThread():send()");
1660 else if (bytesSent != 1 + sizeof(unsigned int))
1662 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1675 //TODO: when reusing oids, make sure they are not already in use!
1676 unsigned int getNewOID(void) {
1677 static unsigned int id = 0xFFFFFFFF;
1680 if (id > oidMax || id < oidMin)
1687 int processConfigFile()
1690 const int maxLineLength = 200;
1691 char lineBuffer[maxLineLength];
1693 const char *delimiters = " \t\n";
1697 configFile = fopen(CONFIG_FILENAME, "r");
1698 if (configFile == NULL)
1700 printf("error opening %s:\n", CONFIG_FILENAME);
1705 numHostsInSystem = 0;
1706 sizeOfHostArray = 8;
1707 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1709 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1711 commentBegin = strchr(lineBuffer, '#');
1712 if (commentBegin != NULL)
1713 *commentBegin = '\0';
1714 token = strtok(lineBuffer, delimiters);
1715 while (token != NULL)
1717 tmpAddr = inet_addr(token);
1718 if ((int)tmpAddr == -1)
1720 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1725 addHost(htonl(tmpAddr));
1726 token = strtok(NULL, delimiters);
1732 if (numHostsInSystem < 1)
1734 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1738 myIpAddr = getMyIpAddr("en1");
1740 myIpAddr = getMyIpAddr("eth0");
1742 myIndexInHostArray = findHost(myIpAddr);
1743 if (myIndexInHostArray == -1)
1745 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1748 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1749 oidMin = oidsPerBlock * myIndexInHostArray;
1750 if (myIndexInHostArray == numHostsInSystem - 1)
1751 oidMax = 0xFFFFFFFF;
1753 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1758 void addHost(unsigned int hostIp)
1760 unsigned int *tmpArray;
1762 if (findHost(hostIp) != -1)
1765 if (numHostsInSystem == sizeOfHostArray)
1767 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1768 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1770 hostIpAddrs = tmpArray;
1773 hostIpAddrs[numHostsInSystem++] = hostIp;
1778 int findHost(unsigned int hostIp)
1781 for (i = 0; i < numHostsInSystem; i++)
1782 if (hostIpAddrs[i] == hostIp)
1789 /* This function sends notification request per thread waiting on object(s) whose version
1791 void reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int numoid) {
1793 objheader_t *objheader;
1794 struct sockaddr_in remoteAddr;
1795 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + sizeof(unsigned int) * 3];
1799 unsigned short version;
1800 unsigned int oid, threadid;
1801 pthread_mutex_t threadnotify; //Lock and condition var for threadjoin and notification
1802 pthread_cond_t threadcond;
1804 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1805 perror("reqNotify():socket()");
1809 bzero(&remoteAddr, sizeof(remoteAddr));
1810 remoteAddr.sin_family = AF_INET;
1811 remoteAddr.sin_port = htons(LISTEN_PORT);
1812 remoteAddr.sin_addr.s_addr = htonl(mid);
1814 /* Generate unique threadid */
1815 threadid = (unsigned int) pthread_self();
1816 if((status = notifyhashInsert(threadid, threadcond)) != 0) {
1817 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1821 /* Save data that is sent for later processing */
1822 //Save threadid, numoid, oidarray, versionarray, also the pthread_cond_variable in a linked list
1825 /* Send oidarry, version array, threadid and machine id */
1826 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1827 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1828 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1831 msg[0] = THREAD_NOTIFY_REQUEST;
1833 /* Send array of oids */
1834 size = sizeof(unsigned int);
1839 *((unsigned int *)(&msg[1] + size)) = oid;
1840 size += sizeof(unsigned int);
1845 /* Send array of version */
1849 version = versionarry[i];
1850 *((unsigned short *)(&msg[1] + size)) = oid;
1851 size += sizeof(unsigned short);
1856 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1857 size += sizeof(unsigned int);
1858 *((unsigned int *)(&msg[1] + size)) = threadid;
1860 pthread_mutex_lock(&threadnotify);
1861 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 2 * sizeof(unsigned int) , 0);
1863 perror("reqNotify():send()");
1865 } else if (bytesSent != 1 + 5*sizeof(unsigned int)){
1866 printf("reNotify(): error, sent %d bytes\n", bytesSent);
1871 pthread_cond_wait(&threadcond, &threadnotify);
1872 pthread_mutex_unlock(&threadnotify);
1878 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1880 //Look up the tid and call the corresponding pthread_cond_signal
1881 ret = notifyhashSearch(tid);
1882 pthread_cond_signal(&ret);
1883 //TODO process oid and version
1886 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1889 struct sockaddr_in remoteAddr;
1890 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1891 int sock, status, size, bytesSent;
1892 while(*head != NULL) {
1895 //create a socket connection to that machine
1896 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1897 perror("notifyAll():socket()");
1901 bzero(&remoteAddr, sizeof(remoteAddr));
1902 remoteAddr.sin_family = AF_INET;
1903 remoteAddr.sin_port = htons(LISTEN_PORT);
1904 remoteAddr.sin_addr.s_addr = htonl(mid);
1905 //send Thread Notify response and threadid to that machine
1906 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1907 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1908 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1911 msg[0] = THREAD_NOTIFY_RESPONSE;
1913 size = sizeof(unsigned int);
1914 *(&msg[1]+ size) = version;
1915 size+= sizeof(unsigned short);
1916 *(&msg[1]+ size) = ptr->threadid;
1918 bytesSent = send(sock, msg, 1 + 2*sizeof(unsigned int) + sizeof(unsigned short), 0);
1920 perror("notifyAll():send()");
1922 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
1923 printf("notifyAll(): error, sent %d bytes\n", bytesSent);
1937 void transAbort(transrecord_t *trans) {
1938 objstrDelete(trans->cache);
1939 chashDelete(trans->lookupTable);