Debian Codegraph @

hmmer/src/hmmdmstr_shard.c

raw symbols SCIP
1 /* master side of the hmmpgmd daemon
2 * MSF, Thu Aug 12, 2010 [Janelia]
3 */
4 #include <p7_config.h>
5
6 #ifdef HMMER_THREADS
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <unistd.h>
13 #include <signal.h>
14 #include <pthread.h>
15 #include <setjmp.h>
16 #include <sys/socket.h>
17 #ifdef HAVE_NETINET_IN_H
18 #include <netinet/in.h> /* On FreeBSD, you need netinet/in.h for struct sockaddr_in */
19 #endif /* On OpenBSD, netinet/in.h is required for (must precede) arpa/inet.h */
20 #include <arpa/inet.h>
21 #include <syslog.h>
22 #include <assert.h>
23 #include <time.h>
24
25 #ifndef HMMER_THREADS
26 #error "Program requires pthreads be enabled."
27 #endif /*HMMER_THREADS*/
28 #include "easel.h"
29 #include "esl_alphabet.h"
30 #include "esl_getopts.h"
31 #include "esl_sq.h"
32 #include "esl_sqio.h"
33 #include "esl_stack.h"
34 #include "esl_stopwatch.h"
35 #include "esl_threads.h"
36
37 #include "hmmer.h"
38 #include "hmmpgmd.h"
39 #include "hmmpgmd_shard.h"
40 #include "cachedb.h"
41 #include "cachedb_shard.h"
42 #include "p7_hmmcache.h"
43
44 #define MAX_WORKERS 64
45 #define MAX_BUFFER 4096
46
47 #define CONF_FILE "/etc/hmmpgmd.conf"
48 #define INVALID_IP 0xfefefefe // 254.254.254.254 is supposed to be in the "reserved for future use" range of IPs, so we
49 // should never see one
50
51 typedef struct {
52 HMMD_SEARCH_STATS stats;
53 HMMD_SEARCH_STATUS status;
54 P7_HIT **hits;
55 int nhits;
56 int db_inx;
57 int db_cnt;
58 int errors;
59 } SEARCH_RESULTS;
60
61 typedef struct {
62 int sock_fd;
63 char ip_addr[64];
64
65 ESL_STACK *cmdstack; /* stack of commands that clients want done */
66 } CLIENTSIDE_ARGS;
67
68 typedef struct {
69 int sock_fd;
70
71 pthread_mutex_t work_mutex;
72 pthread_cond_t start_cond;
73 pthread_cond_t complete_cond;
74
75 int db_version;
76 P7_SEQCACHE *seq_db;
77 P7_HMMCACHE *hmm_db;
78
79 int ready;
80 int failed;
81 struct worker_s *head;
82 struct worker_s *tail;
83
84 int pend_cnt;
85 struct worker_s *pending;
86
87 int idle_cnt;
88 struct worker_s *idling;
89
90 RANGE_LIST *range_list; /* (optional) list of ranges searched within the seqdb */
91
92 int completed;
93 uint32_t num_shards; // new for sharding
94 uint32_t *worker_ips; // IP addresses of the workers we've connected to
95
96 } WORKERSIDE_ARGS;
97
98 typedef struct worker_s {
99 int sock_fd;
100 char ip_addr[64];
101
102 int completed;
103 int terminated;
104 HMMD_COMMAND_SHARD *cmd;
105
106 uint32_t srch_inx;
107 uint32_t srch_cnt;
108
109 HMMD_SEARCH_STATS stats;
110 HMMD_SEARCH_STATUS status;
111 char *err_buf;
112 P7_HIT **hits;
113 uint32_t allocated_hits;
114 int total;
115
116 WORKERSIDE_ARGS *parent;
117
118 struct worker_s *next;
119 struct worker_s *prev;
120 uint32_t num_shards; // New for sharding
121 uint32_t my_shard; // New for sharding
122 } WORKER_DATA;
123
124 static void
125 free_QueueData_shard(QUEUE_DATA_SHARD *data)
126 {
127 /* free the query data */
128 esl_getopts_Destroy(data->opts);
129
130 if (data->abc != NULL) esl_alphabet_Destroy(data->abc);
131 if (data->hmm != NULL) p7_hmm_Destroy(data->hmm);
132 if (data->seq != NULL) esl_sq_Destroy(data->seq);
133 if (data->cmd != NULL) free(data->cmd);
134 memset(data, 0, sizeof(*data));
135 free(data);
136 }
137
138 static void setup_clientside_comm(ESL_GETOPTS *opts, CLIENTSIDE_ARGS *args);
139 static void setup_workerside_comm(ESL_GETOPTS *opts, WORKERSIDE_ARGS *args);
140
141 static void destroy_worker(WORKER_DATA *worker);
142
143 static void init_results(SEARCH_RESULTS *results);
144 static void clear_results(WORKERSIDE_ARGS *comm, SEARCH_RESULTS *results);
145 static void gather_results(QUEUE_DATA_SHARD *query, WORKERSIDE_ARGS *comm, SEARCH_RESULTS *results);
146 static void forward_results(QUEUE_DATA_SHARD *query, SEARCH_RESULTS *results);
147
148 static void print_client_msg(int fd, int status, char *format, va_list ap)
149 {
150 uint32_t nalloc =0;
151 uint32_t buf_offset = 0;
152 uint8_t *buf = NULL;
153 char ebuf[512];
154
155 HMMD_SEARCH_STATUS s;
156
157 memset(&s, 0, sizeof(HMMD_SEARCH_STATUS));
158
159 s.status = status;
160 s.msg_size = vsnprintf(ebuf, sizeof(ebuf), format, ap) +1; /* +1 because we send the \0 */
161
162 p7_syslog(LOG_ERR, ebuf);
163
164 if(hmmd_search_status_Serialize(&s, &buf, &buf_offset, &nalloc) != eslOK){
165 LOG_FATAL_MSG("Serializing HMMD_SEARCH_STATUS failed", errno);
166 }
167 /* send back an unsuccessful status message */
168
169 if (writen(fd, buf, buf_offset) != buf_offset) {
170 p7_syslog(LOG_ERR,"[%s:%d] - writing (%d) error %d - %s\n", __FILE__, __LINE__, fd, errno, strerror(errno));
171 return;
172 }
173 if (writen(fd, ebuf, s.msg_size) != s.msg_size) {
174 p7_syslog(LOG_ERR,"[%s:%d] - writing (%d) error %d - %s\n", __FILE__, __LINE__, fd, errno, strerror(errno));
175 return;
176 }
177
178 free(buf);
179 }
180
181 static void
182 client_msg(int fd, int status, char *format, ...)
183 {
184 va_list ap;
185
186 va_start(ap, format);
187 print_client_msg(fd, status, format, ap);
188 va_end(ap);
189 }
190
191 static void
192 client_msg_longjmp(int fd, int status, jmp_buf *env, char *format, ...)
193 {
194 va_list ap;
195
196 va_start(ap, format);
197 print_client_msg(fd, status, format, ap);
198 va_end(ap);
199
200 longjmp(*env, 1);
201 }
202
203 static int
204 validate_workers(WORKERSIDE_ARGS *args)
205 {
206 int ready = 0;
207 int failed = 0;
208 int pending = 0;
209 int idling = 0;
210
211 WORKER_DATA *worker = NULL;
212 WORKER_DATA *tail = NULL;
213
214 /* count the idling workers */
215 worker = args->idling;
216 while (worker != NULL) {
217 ++idling;
218 if (worker->terminated) ++failed;
219 worker = worker->next;
220 }
221 assert(idling == args->idle_cnt);
222
223 /* count the pending workers */
224 worker = args->pending;
225 while (worker != NULL) {
226 ++pending;
227 if (worker->terminated) ++failed;
228 worker = worker->next;
229 }
230 assert(pending == args->pend_cnt);
231
232 if (args->head == NULL && args->tail == NULL) {
233 assert(failed == args->failed);
234 assert(ready == 0);
235 return 1;
236 }
237
238 assert(args->head != NULL && args->tail != NULL);
239 assert(args->head->prev == NULL);
240 assert(args->tail->next == NULL);
241
242 /* count the ready workers */
243 worker = args->head;
244 while (worker != NULL) {
245 ++ready;
246 assert(worker->prev == tail);
247 assert(ready <= args->ready);
248 tail = worker;
249 if (worker->terminated) ++failed;
250 worker = worker->next;
251 }
252 assert(ready == args->ready);
253 assert(failed == args->failed);
254 assert(tail == args->tail);
255
256 return 1;
257 }
258
259 static void
260 update_workers(WORKERSIDE_ARGS *args)
261 {
262 WORKER_DATA *worker = NULL;
263
264 assert(validate_workers(args));
265
266 /* if there are any workers waiting to join, add them */
267 while (args->pending != NULL) {
268 worker = args->pending;
269 args->pending = worker->next;
270
271 worker->next = NULL;
272 if (args->head == NULL) {
273 args->head = worker;
274 worker->prev = NULL;
275 } else {
276 args->tail->next = worker;
277 worker->prev = args->tail;
278 }
279 args->tail = worker;
280
281 args->pend_cnt--;
282 args->ready++;
283 }
284
285 /* remove any workers who have failed */
286 worker = args->head;
287 while (args->failed > 0 && worker != NULL) {
288 WORKER_DATA *next = worker->next;
289 if (worker->terminated) {
290 --args->failed;
291 --args->ready;
292 args->worker_ips[worker->my_shard] = INVALID_IP; // This worker is no longer responsible for a shard
293 if (args->head == worker && args->tail == worker) {
294 args->head = NULL;
295 args->tail = NULL;
296 } else if (args->head == worker) {
297 args->head = worker->next;
298 worker->next->prev = NULL;
299 } else if (args->tail == worker) {
300 args->tail = worker->prev;
301 worker->prev->next = NULL;
302 } else {
303 worker->next->prev = worker->prev;
304 worker->prev->next = worker->next;
305 }
306 destroy_worker(worker);
307 }
308 worker = next;
309 }
310
311 assert(validate_workers(args));
312 }
313
314 static void
315 process_search(WORKERSIDE_ARGS *args, QUEUE_DATA_SHARD *query)
316 {
317 ESL_STOPWATCH *w = NULL; /* timer used for profiling statistics */
318 WORKER_DATA *worker = NULL;
319 SEARCH_RESULTS results;
320 int n;
321 int cnt;
322 int inx;
323 int ready_workers; /* counter variable used to track the number of workers currently available to receive work; short for "remaining", I imagine */
324 int tries;
325
326 memset(&results, 0, sizeof(SEARCH_RESULTS)); /* avoid valgrind bitching about uninit bytes; remove, if we ever serialize structs properly */
327
328 /* figure out the size of the database we are searching */
329 if (query->cmd_type == HMMD_CMD_SEARCH) {
330 if((args->seq_db == NULL)||(args->seq_db->db == NULL)|| (query->dbx >= args->seq_db->db_cnt) || (query->dbx < 0)){
331 // Client is attempting to search a database that does not exist, complain and abort search
332 client_msg(query->sock, eslFAIL, "Specified sequence database has not been loaded into the daemon. \n");
333 return;
334 }
335 else{
336 cnt = args->seq_db->db[query->dbx].count;
337 }
338 } else {
339 if(args->hmm_db == NULL){
340 // Client is attempting to search a database that does not exist, complain and abort search
341 client_msg(query->sock, eslFAIL, "No HMM database has been loaded into the daemon. \n");
342 return;
343 }
344 else{
345 cnt = args->hmm_db->n;
346 }
347 }
348
349 // Start stopwatch after we've determined that the search can proceed to simplify cleanup when it can't
350 w = esl_stopwatch_Create();
351 esl_stopwatch_Start(w);
352
353 init_results(&results);
354
355 //if range(s) are given, count how many of the seqdb's sequences are within supplied range(s)
356 /* if (args->range_list) { // can only happen in HMMD_CMD_SEARCH case
357 int range_cnt = 0; // this will now count how many of the seqs in the db are within the range
358 for (i=0; i<cnt; i++) {
359 if ( hmmpgmd_IsWithinRanges(args->seq_db->list[i].idx, args->range_list ) )
360 range_cnt++;
361 }
362 cnt = range_cnt;
363 }
364 */
365
366
367 inx = 0;
368 tries = 0;
369 do {
370 /* process any changes to the available workers */
371 if ((n = pthread_mutex_lock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
372
373 /* build a list of the currently available workers */
374 update_workers(args);
375
376 /* if there aren't enough workers ready, report an error */
377 if (args->ready == args->num_shards) {
378 ready_workers = args->ready;
379
380 /* update the workers search information */
381 worker = args->head;
382
383 while (worker != NULL) {
384 worker->cmd = query->cmd;
385 worker->completed = 0;
386 worker->total = 0;
387
388 /* assign each worker a portion of the database */
389 worker->srch_inx = inx;
390 if (args->range_list) {
391 /* old code for non-sharded database. For sharded database, each worker should be told to search the entire range of the
392 search, because a worker only has 1/nth of the database
393 // if ranges are given, need to split the db list based on which elements in the list are within the given range(s)
394 int goal = cnt / ready_workers; //how many within-range sequences do I want to ask this worker to handle
395 int curr = 0; //how many within-range sequences have I seen since the start of this full-db range
396 worker->srch_cnt = 0;
397 while (curr < goal) {
398 if ( hmmpgmd_IsWithinRanges (args->seq_db->list[inx].idx, args->range_list ) )
399 curr++;
400 worker->srch_cnt++;
401 inx++;
402 }
403 cnt -= curr;
404 */
405 worker->srch_cnt = cnt;
406 } else {
407 if(query->cmd_type == HMMD_CMD_SEARCH){
408 // This is a sharded hmmsearch, so each worker should be told to search the entire db range, which
409 // will cause them to search their entire shard
410 worker->srch_cnt = cnt;
411 }
412 else{
413 // This is a hmmscan, so the database is not sharded and each worker should be told to search a fraction of it
414 worker->srch_cnt = cnt / ready_workers;
415 inx += worker->srch_cnt;
416 cnt -= worker->srch_cnt;
417 }
418 }
419
420 --ready_workers;
421 worker = worker->next;
422 }
423
424 args->completed = 0;
425
426 /* notify all the worker threads of the new query */
427 if ((n = pthread_cond_broadcast(&args->start_cond)) != 0) LOG_FATAL_MSG("cond broadcast", n);
428 }
429
430 if ((n = pthread_mutex_unlock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
431
432 if (args->ready > 0) {
433 /* Wait for all the workers to complete */
434 if ((n = pthread_mutex_lock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
435
436 while (args->completed < args->ready) {
437 if ((n = pthread_cond_wait (&args->complete_cond, &args->work_mutex)) != 0) LOG_FATAL_MSG("cond wait", n);
438 }
439
440 if ((n = pthread_mutex_unlock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
441 }
442
443 /* gather up the results from all the workers */
444 gather_results(query, args, &results);
445
446 /* we can recover from one worker crashing. get the block that worker ran on
447 * and redistribute its load to all the remaining workers.
448 */
449 inx = results.db_inx;
450 cnt = results.db_cnt;
451 ++tries;
452
453 } while (args->ready > 0 && results.errors == 1 && tries < 2);
454
455
456 esl_stopwatch_Stop(w);
457
458 /* copy the search stats */
459 results.stats.elapsed = w->elapsed;
460 results.stats.user = w->user;
461 results.stats.sys = w->sys;
462 results.stats.hit_offsets = NULL; // set this to make sure we allocate memory later
463 /* TODO: check for errors */
464 if (args->ready != args->num_shards) {
465 client_msg(query->sock, eslFAIL, "Not enough compute nodes available for the number of shards specified. %d nodes available, %d required\n", args->ready, args->num_shards);
466 } else if (args->failed > 0) {
467 client_msg(query->sock, eslFAIL, "Errors running search\n");
468 clear_results(args, &results);
469 } else {
470 forward_results(query, &results);
471 }
472
473 esl_stopwatch_Destroy(w);
474 }
475
476
477 static void
478 process_shutdown(WORKERSIDE_ARGS *args, QUEUE_DATA_SHARD *query)
479 {
480 int n;
481 int cnt;
482
483 HMMD_COMMAND_SHARD cmd;
484
485 WORKER_DATA *worker = NULL;
486
487 /* process any changes to the available workers */
488 if ((n = pthread_mutex_lock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
489
490 /* build a list of the currently available workers */
491 update_workers(args);
492
493 /* reset all the idle and active workers */
494 cnt = 0;
495
496 /* build a reset command */
497 cmd.hdr.length = 0;
498 cmd.hdr.command = HMMD_CMD_SHUTDOWN;
499
500 /* look for the active workers to shutdown */
501 worker = args->head;
502 while (worker != NULL) {
503 worker->cmd = &cmd;
504 worker->completed = 0;
505 worker->total = 0;
506
507 worker = worker->next;
508 ++cnt;
509 }
510
511 /* look for the idle workers to shutdown */
512 worker = args->idling;
513 while (worker != NULL) {
514 worker->cmd = &cmd;
515 worker->completed = 0;
516 worker->total = 0;
517
518 worker = worker->next;
519 ++cnt;
520 }
521
522 /* check if there are any workers to shutdown */
523 if (cnt > 0) {
524 args->completed = 0;
525
526 /* notify all the worker threads of the new query */
527 if ((n = pthread_cond_broadcast(&args->start_cond)) != 0) LOG_FATAL_MSG("cond broadcast", n);
528 if ((n = pthread_mutex_unlock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
529
530 /* Wait for all the workers to complete */
531 if ((n = pthread_mutex_lock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
532
533 while (args->completed < cnt) {
534 if ((n = pthread_cond_wait (&args->complete_cond, &args->work_mutex)) != 0) LOG_FATAL_MSG("cond wait", n);
535 }
536 }
537
538 /* build a list of the currently available workers */
539 update_workers(args);
540
541 if ((n = pthread_mutex_unlock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
542 }
543
544
545 void
546 master_process_shard(ESL_GETOPTS *go)
547 {
548 P7_SEQCACHE *seq_db = NULL;
549 P7_HMMCACHE *hmm_db = NULL;
550 ESL_STACK *cmdstack = NULL; /* stack of commands that clients want done */
551 QUEUE_DATA_SHARD *query = NULL;
552 CLIENTSIDE_ARGS client_comm;
553 WORKERSIDE_ARGS worker_comm;
554 int n, i;
555 int shutdown;
556 char errbuf[eslERRBUFSIZE];
557 int status = eslOK;
558
559 impl_Init();
560 p7_FLogsumInit(); /* we're going to use table-driven Logsum() approximations at times */
561
562 if (esl_opt_IsUsed(go, "--seqdb")) {
563 char *name = esl_opt_GetString(go, "--seqdb");
564 if ((status = p7_seqcache_Open_master(name, &seq_db, errbuf)) != eslOK)
565 p7_Fail("Failed to cache %s (%d)", name, status);
566
567 }
568
569 if (esl_opt_IsUsed(go, "--hmmdb")) {
570 char *name = esl_opt_GetString(go, "--hmmdb");
571
572 status = p7_hmmcache_Open(name, &hmm_db, errbuf);
573 if (status == eslENOTFOUND) p7_Fail("Failed to open profile database %s\n %s\n", name, errbuf);
574 else if (status == eslEFORMAT) p7_Fail("Failed to parse profile database %s\n %s\n", name, errbuf);
575 else if (status == eslEINCOMPAT) p7_Fail("Mismatched alphabets in profile db %s\n %s\n", name, errbuf);
576 else if (status != eslOK) p7_Fail("Failed to load profile db %s : code %d\n", name, status);
577
578 p7_hmmcache_SetNumericNames(hmm_db);
579
580 printf("Loaded profile db %s; models: %d memory: %" PRId64 "\n",
581 name, hmm_db->n, (uint64_t) p7_hmmcache_Sizeof(hmm_db));
582 }
583
584 /* if stdout is redirected at the commandline, it causes printf's to be buffered,
585 * which means status logging isn't printed. This line strongly requests unbuffering,
586 * which should be ok, given the low stdout load of hmmpgmd
587 */
588 setvbuf (stdout, NULL, _IONBF, BUFSIZ);
589 printf("Data loaded into memory. Master is ready.\n");
590 setvbuf (stdout, NULL, _IOFBF, BUFSIZ);
591
592 /* initialize the search stack, set it up for interthread communication */
593 cmdstack = esl_stack_PCreate();
594 esl_stack_UseMutex(cmdstack);
595 esl_stack_UseCond(cmdstack);
596
597 /* start the communications with the web clients */
598 client_comm.cmdstack = cmdstack;
599 setup_clientside_comm(go, &client_comm);
600
601 /* initialize the worker structure */
602 if ((n = pthread_mutex_init(&worker_comm.work_mutex, NULL)) != 0) LOG_FATAL_MSG("mutex init", n);
603 if ((n = pthread_cond_init(&worker_comm.start_cond, NULL)) != 0) LOG_FATAL_MSG("cond init", n);
604 if ((n = pthread_cond_init(&worker_comm.complete_cond, NULL)) != 0) LOG_FATAL_MSG("cond init", n);
605
606 worker_comm.sock_fd = -1;
607 worker_comm.head = NULL;
608 worker_comm.tail = NULL;
609 worker_comm.pending = NULL;
610 worker_comm.idling = NULL;
611 worker_comm.seq_db = seq_db;
612 worker_comm.hmm_db = hmm_db;
613 worker_comm.db_version = 1;
614 worker_comm.num_shards = esl_opt_GetInteger(go, "--num_shards");
615 ESL_ALLOC(worker_comm.worker_ips, worker_comm.num_shards * sizeof(uint32_t));
616 for(i = 0; i < worker_comm.num_shards; i++){
617 worker_comm.worker_ips[i] = INVALID_IP;
618 }
619
620 worker_comm.ready = 0;
621 worker_comm.failed = 0;
622 worker_comm.pend_cnt = 0;
623 worker_comm.idle_cnt = 0;
624
625 setup_workerside_comm(go, &worker_comm);
626
627 /* read query hmm/sequence
628 * the PPop() will wait until a client pushes a command to the queue
629 */
630 shutdown = 0;
631 while (!shutdown && esl_stack_PPop(cmdstack, (void **) &query) == eslOK) {
632 printf("Processing command %d from %s\n", query->cmd_type, query->ip_addr);
633 fflush(stdout);
634
635 worker_comm.range_list = NULL;
636
637 switch(query->cmd_type) {
638 case HMMD_CMD_SEARCH:
639 if (esl_opt_IsUsed(query->opts, "--seqdb_ranges")) {
640 ESL_ALLOC(worker_comm.range_list, sizeof(RANGE_LIST));
641 hmmpgmd_GetRanges(worker_comm.range_list, esl_opt_GetString(query->opts, "--seqdb_ranges"));
642 }
643 process_search(&worker_comm, query);
644 break;
645 case HMMD_CMD_SCAN: process_search(&worker_comm, query); break;
646 case HMMD_CMD_SHUTDOWN:
647 process_shutdown(&worker_comm, query);
648 p7_syslog(LOG_ERR,"[%s:%d] - shutting down...\n", __FILE__, __LINE__);
649 shutdown = 1;
650 break;
651 default:
652 p7_syslog(LOG_ERR,"[%s:%d] - unknown command %d from %s\n", __FILE__, __LINE__, query->cmd_type, query->ip_addr);
653 break;
654 }
655
656 free_QueueData_shard(query);
657 }
658
659 esl_stack_ReleaseCond(cmdstack);
660
661 if (hmm_db) p7_hmmcache_Close(hmm_db);
662 if (seq_db) p7_seqcache_Close(seq_db);
663
664 esl_stack_Destroy(cmdstack);
665
666 pthread_mutex_destroy(&worker_comm.work_mutex);
667 pthread_cond_destroy(&worker_comm.start_cond);
668 pthread_cond_destroy(&worker_comm.complete_cond);
669
670
671 if (worker_comm.range_list) {
672 if (worker_comm.range_list->starts) free(worker_comm.range_list->starts);
673 if (worker_comm.range_list->ends) free(worker_comm.range_list->ends);
674 free (worker_comm.range_list);
675 }
676 free(worker_comm.worker_ips);
677 return;
678
679
680 ERROR:
681 p7_Fail("Memory allocation error. Code: %d\n", status);
682
683 }
684
685 // Qsort comparison function to sort a list of pointers to P7_HITs
686 static int
687 hit_sorter2(const void *p1, const void *p2)
688 {
689 int cmp;
690
691 const P7_HIT *h1 = *((P7_HIT **) p1);
692 const P7_HIT *h2 = *((P7_HIT **) p2);
693
694 cmp = (h1->sortkey < h2->sortkey);
695 cmp -= (h1->sortkey > h2->sortkey);
696
697 return cmp;
698 }
699
700
701 static void
702 init_results(SEARCH_RESULTS *results)
703 {
704 results->status.status = eslOK;
705 results->status.msg_size = 0;
706
707 results->stats.nhits = 0;
708 results->stats.nreported = 0;
709 results->stats.nincluded = 0;
710
711 results->stats.nmodels = 0;
712 results->stats.nseqs = 0;
713 results->stats.n_past_msv = 0;
714 results->stats.n_past_bias = 0;
715 results->stats.n_past_vit = 0;
716 results->stats.n_past_fwd = 0;
717 results->stats.Z = 0;
718
719 results->hits = NULL;
720 results->nhits = 0;
721 results->db_inx = 0;
722 results->db_cnt = 0;
723 results->errors = 0;
724 }
725
726
727 static void
728 gather_results(QUEUE_DATA_SHARD *query, WORKERSIDE_ARGS *comm, SEARCH_RESULTS *results)
729 {
730 int cnt;
731 int n;
732 int i0, i1;
733 WORKER_DATA *worker;
734
735 /* allocate spaces to hold all the hits */
736 cnt = results->nhits + MAX_WORKERS;
737 if ((results->hits = realloc(results->hits, sizeof(P7_HIT *) * cnt)) == NULL) LOG_FATAL_MSG("malloc", errno);
738
739 /* lock the workers until we have merged the results */
740 if ((n = pthread_mutex_lock (&comm->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
741
742 /* count the number of hits */
743 cnt = results->nhits;
744 worker = comm->head;
745 while (worker != NULL) {
746 if (worker->completed) {
747 uint32_t previous_hits = results->stats.nhits;
748
749 results->stats.nhits += worker->stats.nhits;
750 results->stats.nreported += worker->stats.nreported;
751 results->stats.nincluded += worker->stats.nincluded;
752
753 results->stats.n_past_msv += worker->stats.n_past_msv;
754 results->stats.n_past_bias += worker->stats.n_past_bias;
755 results->stats.n_past_vit += worker->stats.n_past_vit;
756 results->stats.n_past_fwd += worker->stats.n_past_fwd;
757
758 results->stats.Z_setby = worker->stats.Z_setby;
759 results->stats.domZ_setby = worker->stats.domZ_setby;
760 results->stats.domZ = worker->stats.domZ;
761 results->stats.Z = worker->stats.Z;
762
763 results->status.msg_size += worker->status.msg_size - sizeof(HMMD_SEARCH_STATS);
764 if((results->stats.nhits- previous_hits) >0){ // There are new hits to deal with
765 // Add enough space to the list of hits for all the hits from this worker
766 results->hits = realloc(results->hits, results->stats.nhits * sizeof (P7_HIT *));
767 if(results->hits == NULL){
768 LOG_FATAL_MSG("malloc", n);
769 }
770
771 // copy this worker's hits into the global list
772 for(i0 = 0, i1 = previous_hits; i1 < results->stats.nhits; i0++, i1++){
773 results->hits[i1] = worker->hits[i0];
774 }
775
776 free(worker->hits); // Free the worker's array of pointers to hits. The hits themselves
777 // will be freed by forward_results()
778
779 worker->hits = NULL;
780 }
781 worker->completed = 0;
782 ++cnt;
783 } else {
784 results->errors++;
785 results->db_inx = worker->srch_inx;
786 results->db_cnt = worker->srch_cnt;
787 }
788
789 worker = worker->next;
790 }
791
792 if ((n = pthread_mutex_unlock (&comm->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
793
794 if (query->cmd_type == HMMD_CMD_SEARCH) {
795 results->stats.nmodels = 1;
796 results->stats.nseqs = comm->seq_db->db[query->dbx].K;
797 } else {
798 results->stats.nseqs = 1;
799 results->stats.nmodels = comm->hmm_db->n;
800 }
801
802 if (results->stats.Z_setby == p7_ZSETBY_NTARGETS) {
803 results->stats.Z = (query->cmd_type == HMMD_CMD_SEARCH) ? results->stats.nseqs : results->stats.nmodels;
804 }
805
806 results->nhits = cnt;
807
808 }
809
810 static void
811 forward_results(QUEUE_DATA_SHARD *query, SEARCH_RESULTS *results)
812 {
813 P7_TOPHITS th;
814 P7_PIPELINE *pli = NULL;
815 P7_DOMAIN **dcl = NULL;
816 P7_HIT *hits = NULL;
817 int fd;
818 int n, i;
819 uint8_t **buf, **buf2, **buf3, *buf_ptr, *buf2_ptr, *buf3_ptr;
820 uint32_t nalloc, nalloc2, nalloc3, buf_offset, buf_offset2, buf_offset3;
821 enum p7_pipemodes_e mode;
822
823 // Initialize these pointers-to-pointers that we'll use for sending data
824 buf_ptr = NULL;
825 buf = &(buf_ptr);
826 buf2_ptr = NULL;
827 buf2 = &(buf2_ptr);
828 buf3_ptr = NULL;
829 buf3 = &(buf3_ptr);
830
831 fd = query->sock;
832
833 if (query->cmd_type == HMMD_CMD_SEARCH) mode = p7_SEARCH_SEQS;
834 else mode = p7_SCAN_MODELS;
835
836 /* sort the hits and apply score and E-value thresholds */
837 if (results->nhits > 0) {
838 if(results->stats.hit_offsets != NULL){
839 if ((results->stats.hit_offsets = realloc(results->stats.hit_offsets, results->stats.nhits * sizeof(uint64_t))) == NULL) LOG_FATAL_MSG("malloc", errno);
840 }
841 else{
842 if ((results->stats.hit_offsets = malloc(results->stats.nhits * sizeof(uint64_t))) == NULL) LOG_FATAL_MSG("malloc", errno);
843 }
844
845 // sort the hits
846 qsort(results->hits, results->stats.nhits, sizeof(P7_HIT *), hit_sorter2);
847
848 th.unsrt = NULL;
849 th.N = results->stats.nhits;
850 th.nreported = 0;
851 th.nincluded = 0;
852 th.is_sorted_by_sortkey = 0;
853 th.is_sorted_by_seqidx = 0;
854
855 pli = p7_pipeline_Create(query->opts, 100, 100, FALSE, mode);
856 pli->nmodels = results->stats.nmodels;
857 pli->nseqs = results->stats.nseqs;
858 pli->n_past_msv = results->stats.n_past_msv;
859 pli->n_past_bias = results->stats.n_past_bias;
860 pli->n_past_vit = results->stats.n_past_vit;
861 pli->n_past_fwd = results->stats.n_past_fwd;
862
863 pli->Z = results->stats.Z;
864 pli->domZ = results->stats.domZ;
865 pli->Z_setby = results->stats.Z_setby;
866 pli->domZ_setby = results->stats.domZ_setby;
867
868
869 th.hit = results->hits;
870
871 p7_tophits_Threshold(&th, pli);
872
873 /* after the top hits thresholds are checked, the number of sequences
874 * and domains to be reported can change. */
875 results->stats.nreported = th.nreported;
876 results->stats.nincluded = th.nincluded;
877 results->stats.domZ = pli->domZ;
878 results->stats.Z = pli->Z;
879 }
880
881 /* Build the buffers of serialized results we'll send back to the client.
882 Use three buffers, one for each object, because we need to build them in reverse order.
883 We need to serialize the hits to build the hits_offset array in HMMD_SEARCH_STATS.
884 We need the length of the serialized hits and HMMD_SEARCH_STATS objects to fill out the msg_size
885 field in status, but we want to send status, then stats, then hits */
886
887 nalloc = 0;
888 buf_offset = 0;
889
890 // First, the buffer of hits
891 for(i =0; i< results->stats.nhits; i++){
892
893 results->stats.hit_offsets[i] = buf_offset;
894 if(p7_hit_Serialize(results->hits[i], buf, &buf_offset, &nalloc) != eslOK){
895 LOG_FATAL_MSG("Serializing P7_HIT failed", errno);
896 }
897
898 }
899 if(results->stats.nhits == 0){
900 results->stats.hit_offsets = NULL;
901 }
902
903 // Second, the buffer with the HMMD_SEARCH_STATS object
904
905 buf_offset2 = 0;
906 nalloc2 = 0;
907 if(p7_hmmd_search_stats_Serialize(&(results->stats), buf2, &buf_offset2, &nalloc2) != eslOK){
908 LOG_FATAL_MSG("Serializing HMMD_SEARCH_STATS failed", errno);
909 }
910
911 results->status.msg_size = buf_offset + buf_offset2; // set size of second message
912
913 // Third, the buffer with the HMMD_SEARCH_STATUS object
914 buf_offset3 = 0;
915 nalloc3 = 0;
916 if(hmmd_search_status_Serialize(&(results->status), buf3, &buf_offset3, &nalloc3) != eslOK){
917 LOG_FATAL_MSG("Serializing HMMD_SEARCH_STATUS failed", errno);
918 }
919
920 // Now, send the buffers in the reverse of the order they were built
921 /* send back a successful status message */
922 n = buf_offset3;
923
924 if (writen(fd, buf3_ptr, n) != n) {
925 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, query->ip_addr, errno, strerror(errno));
926 goto CLEAR;
927 }
928
929 // and the stats object
930 n=buf_offset2;
931
932 if (writen(fd, buf2_ptr, n) != n) {
933 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, query->ip_addr, errno, strerror(errno));
934 goto CLEAR;
935 }
936 //printf("%p\n", results->hits[1]);
937 // and finally the hits
938 n=buf_offset;
939
940 if (writen(fd, buf_ptr, n) != n) {
941 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, query->ip_addr, errno, strerror(errno));
942 goto CLEAR;
943 }
944 printf("Results for %s (%d) sent %" PRId64 " bytes\n", query->ip_addr, fd, results->status.msg_size);
945 printf("Hits:%"PRId64 " reported:%" PRId64 " included:%"PRId64 "\n", results->stats.nhits, results->stats.nreported, results->stats.nincluded);
946 fflush(stdout);
947
948 CLEAR:
949 /* free all the data */
950 for(i = 0; i < results->stats.nhits; i++){
951 p7_hit_Destroy(results->hits[i]);
952 }
953
954 free(results->hits);
955 results->hits = NULL;
956
957 if (pli) p7_pipeline_Destroy(pli);
958 if (hits) free(hits);
959 if (dcl) free(dcl);
960 if(buf_ptr != NULL){
961 free(buf_ptr);
962 }
963 if(buf2_ptr != NULL){
964 free(buf2_ptr);
965 }
966 if(buf3_ptr != NULL){
967 free(buf3_ptr);
968 }
969 if(results->stats.hit_offsets != NULL){
970 free(results->stats.hit_offsets);
971 }
972 init_results(results);
973 return;
974 }
975
976 static void
977 destroy_worker(WORKER_DATA *worker)
978 {
979 int i;
980 if (worker == NULL)
981 {
982 if (worker->err_buf != NULL) free(worker->err_buf);
983 if (worker->hits != NULL){
984 for(i = 0; i < worker->allocated_hits; i++){
985 p7_hit_Destroy(worker->hits[i]);
986 }
987 free(worker->hits);
988 }
989 memset(worker, 0, sizeof(WORKER_DATA));
990 free(worker);
991 }
992 }
993
994 static void
995 clear_results(WORKERSIDE_ARGS *args, SEARCH_RESULTS *results)
996 {
997 int i;
998 int n;
999 WORKER_DATA *worker;
1000
1001 /* lock the workers until we have freed the results */
1002 if ((n = pthread_mutex_lock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1003
1004 assert(validate_workers(args));
1005
1006 /* free all the results */
1007 worker = args->head;
1008 while (worker != NULL) {
1009 if (worker->err_buf != NULL) free(worker->err_buf);
1010 if(worker->hits != NULL){
1011 for(i =0; i < worker->allocated_hits; i++){
1012 p7_hit_Destroy(worker->hits[i]);
1013 }
1014 free(worker->hits);
1015 worker->hits = NULL;
1016 }
1017 worker->err_buf = NULL;
1018
1019 worker->completed = 0;
1020 worker = worker->next;
1021 }
1022
1023 if ((n = pthread_mutex_unlock (&args->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1024
1025 for (i = 0; i < results->nhits; ++i) {
1026 if (results->hits[i] != NULL) p7_hit_Destroy(results->hits[i]);
1027 results->hits[i] = NULL;
1028 }
1029
1030 if (results->hits != NULL) free(results->hits);
1031 init_results(results);
1032 }
1033
1034 static void
1035 process_ServerCmd(char *ptr, CLIENTSIDE_ARGS *data)
1036 {
1037 QUEUE_DATA_SHARD *parms = NULL; /* cmd to queue */
1038 HMMD_COMMAND_SHARD *cmd = NULL; /* parsed cmd to process */
1039 int fd = data->sock_fd;
1040 ESL_STACK *cmdstack = data->cmdstack;
1041 char *s;
1042 time_t date;
1043 char timestamp[32];
1044
1045 /* skip leading white spaces */
1046 ++ptr;
1047 while (*ptr == ' ' || *ptr == '\t') ++ptr;
1048
1049 /* skip to the end of the line */
1050 s = ptr;
1051 while (*s && (*s != '\n' && *s != '\r')) ++s;
1052 *s = 0;
1053
1054 /* process the different commands */
1055 s = strsep(&ptr, " \t");
1056 if (strcmp(s, "shutdown") == 0)
1057 {
1058 if ((cmd = malloc(sizeof(HMMD_HEADER))) == NULL) LOG_FATAL_MSG("malloc", errno);
1059 memset(cmd, 0, sizeof(HMMD_HEADER)); /* avoid uninit bytes & valgrind bitching. Remove, if we ever serialize structs correctly. */
1060 cmd->hdr.length = 0;
1061 cmd->hdr.command = HMMD_CMD_SHUTDOWN;
1062 }
1063 else
1064 {
1065 client_msg(fd, eslEINVAL, "Unknown command %s\n", s);
1066 return;
1067 }
1068
1069 if ((parms = malloc(sizeof(QUEUE_DATA_SHARD))) == NULL) LOG_FATAL_MSG("malloc", errno);
1070 memset(parms, 0, sizeof(QUEUE_DATA_SHARD)); /* avoid valgrind bitches about uninit bytes; remove if structs are serialized properly */
1071
1072 parms->hmm = NULL;
1073 parms->seq = NULL;
1074 parms->abc = NULL;
1075 parms->opts = NULL;
1076 parms->dbx = -1;
1077 parms->cmd = cmd;
1078
1079 strcpy(parms->ip_addr, data->ip_addr);
1080 parms->sock = fd;
1081 parms->cmd_type = cmd->hdr.command;
1082 parms->query_type = 0;
1083
1084 date = time(NULL);
1085 ctime_r(&date, timestamp);
1086 printf("\n%s", timestamp); /* note ctime_r() leaves \n on end of timestamp */
1087 printf("Queuing command %d from %s (%d)\n", cmd->hdr.command, parms->ip_addr, parms->sock);
1088 fflush(stdout);
1089
1090 esl_stack_PPush(cmdstack, parms);
1091 }
1092
1093 static int
1094 clientside_loop(CLIENTSIDE_ARGS *data)
1095 {
1096 int status;
1097
1098 char *ptr;
1099 char *buffer;
1100 char opt_str[MAX_BUFFER];
1101
1102 int dbx;
1103 int buf_size;
1104 int remaining;
1105 int amount;
1106 int eod;
1107 int n;
1108
1109 P7_HMM *hmm = NULL; /* query HMM */
1110 ESL_SQ *seq = NULL; /* query sequence */
1111 ESL_SCOREMATRIX *sco = NULL; /* scoring matrix */
1112 P7_HMMFILE *hfp = NULL;
1113 ESL_ALPHABET *abc = NULL; /* digital alphabet */
1114 ESL_GETOPTS *opts = NULL; /* search specific options */
1115 HMMD_COMMAND_SHARD *cmd = NULL; /* search cmd to send to workers */
1116
1117 ESL_STACK *cmdstack = data->cmdstack;
1118 QUEUE_DATA_SHARD *parms;
1119 jmp_buf jmp_env;
1120 time_t date;
1121 char timestamp[32];
1122
1123 buf_size = MAX_BUFFER;
1124 if ((buffer = malloc(buf_size)) == NULL) LOG_FATAL_MSG("malloc", errno);
1125 ptr = buffer;
1126 remaining = buf_size;
1127 amount = 0;
1128
1129 eod = 0;
1130 while (!eod) {
1131 int l;
1132 char *s;
1133
1134 /* Receive message from client */
1135 if ((n = read(data->sock_fd, ptr, remaining)) < 0) {
1136 p7_syslog(LOG_ERR,"[%s:%d] - reading %s error %d - %s\n", __FILE__, __LINE__, data->ip_addr, errno, strerror(errno));
1137 return 1;
1138 }
1139
1140 if (n == 0) return 1;
1141
1142 ptr += n;
1143 amount += n;
1144 remaining -= n;
1145
1146 /* scan backwards till we hit the start of the line */
1147 l = amount;
1148 s = ptr - 1;
1149 while (l-- > 0 && (*s == '\n' || *s == '\r')) --s;
1150 while (l-- > 0 && (*s != '\n' && *s != '\r')) --s;
1151 eod = (amount > 1 && *(s + 1) == '/' && *(s + 2) == '/' );
1152
1153 /* if the buffer is full, make it larger */
1154 if (!eod && remaining == 0) {
1155 if ((buffer = realloc(buffer, buf_size * 2)) == NULL) LOG_FATAL_MSG("realloc", errno);
1156 ptr = buffer + buf_size;
1157 remaining = buf_size;
1158 buf_size *= 2;
1159 }
1160 }
1161
1162 /* zero terminate the buffer */
1163 if (remaining == 0) {
1164 if ((buffer = realloc(buffer, buf_size + 1)) == NULL) LOG_FATAL_MSG("realloc", errno);
1165 ptr = buffer + buf_size;
1166 }
1167 *ptr = 0;
1168
1169 /* skip all leading white spaces */
1170 ptr = buffer;
1171 while (*ptr && isspace(*ptr)) ++ptr;
1172
1173 opt_str[0] = 0;
1174 if (*ptr == '!') {
1175 process_ServerCmd(ptr, data);
1176 free(buffer);
1177 return 0;
1178 } else if (*ptr == '@') {
1179 char *s = ++ptr;
1180
1181 /* skip to the end of the line */
1182 while (*ptr && (*ptr != '\n' && *ptr != '\r')) ++ptr;
1183 *ptr++ = 0;
1184
1185 /* create a commandline string with dummy program name for
1186 * the esl_opt_ProcessSpoof() function to parse.
1187 */
1188 snprintf(opt_str, sizeof(opt_str), "hmmpgmd %s\n", s);
1189
1190 /* skip remaining white spaces */
1191 while (*ptr && isspace(*ptr)) ++ptr;
1192 } else {
1193 client_msg(data->sock_fd, eslEFORMAT, "Missing options string");
1194 free(buffer);
1195 return 0;
1196 }
1197
1198 if (strncmp(ptr, "//", 2) == 0) {
1199 client_msg(data->sock_fd, eslEFORMAT, "Missing search sequence/hmm");
1200 free(buffer);
1201 return 0;
1202 }
1203
1204 if (!setjmp(jmp_env)) {
1205 dbx = 0;
1206
1207 status = process_searchopts(data->sock_fd, opt_str, &opts);
1208 if (status != eslOK) {
1209 client_msg_longjmp(data->sock_fd, status, &jmp_env, "Failed to parse options string: %s", opts->errbuf);
1210 }
1211
1212 /* the options string can handle an optional database */
1213 if (esl_opt_ArgNumber(opts) > 0) {
1214 client_msg_longjmp(data->sock_fd, status, &jmp_env, "Incorrect number of command line arguments.");
1215 }
1216
1217 if (esl_opt_IsUsed(opts, "--seqdb")) {
1218 dbx = esl_opt_GetInteger(opts, "--seqdb");
1219 } else if (esl_opt_IsUsed(opts, "--hmmdb")) {
1220 dbx = esl_opt_GetInteger(opts, "--hmmdb");
1221 } else {
1222 client_msg_longjmp(data->sock_fd, eslEINVAL, &jmp_env, "No search database specified, --seqdb or --hmmdb.");
1223 }
1224
1225
1226 abc = esl_alphabet_Create(eslAMINO);
1227 seq = NULL;
1228 hmm = NULL;
1229
1230 if (*ptr == '>') {
1231 /* try to parse the input buffer as a FASTA sequence */
1232 seq = esl_sq_CreateDigital(abc);
1233 /* try to parse the input buffer as a FASTA sequence */
1234 status = esl_sqio_Parse(ptr, strlen(ptr), seq, eslSQFILE_DAEMON);
1235 if (status != eslOK) client_msg_longjmp(data->sock_fd, status, &jmp_env, "Error parsing FASTA sequence");
1236 if (seq->n < 1) client_msg_longjmp(data->sock_fd, eslEFORMAT, &jmp_env, "Error zero length FASTA sequence");
1237
1238 } else if (strncmp(ptr, "HMM", 3) == 0) {
1239 if (esl_opt_IsUsed(opts, "--hmmdb")) {
1240 client_msg_longjmp(data->sock_fd, status, &jmp_env, "A HMM cannot be used to search a hmm database");
1241 }
1242
1243 /* try to parse the buffer as an hmm */
1244 status = p7_hmmfile_OpenBuffer(ptr, strlen(ptr), &hfp);
1245 if (status != eslOK) client_msg_longjmp(data->sock_fd, status, &jmp_env, "Failed to open query hmm buffer");
1246
1247 status = p7_hmmfile_Read(hfp, &abc, &hmm);
1248 if (status != eslOK) client_msg_longjmp(data->sock_fd, status, &jmp_env, "Error reading query hmm: %s", hfp->errbuf);
1249
1250 p7_hmmfile_Close(hfp);
1251
1252 } else {
1253 /* no idea what we are trying to parse */
1254 client_msg_longjmp(data->sock_fd, eslEFORMAT, &jmp_env, "Unknown query sequence/hmm format");
1255 }
1256 } else {
1257 /* an error occured some where, so try to clean up */
1258 if (opts != NULL) esl_getopts_Destroy(opts);
1259 if (abc != NULL) esl_alphabet_Destroy(abc);
1260 if (hmm != NULL) p7_hmm_Destroy(hmm);
1261 if (seq != NULL) esl_sq_Destroy(seq);
1262 if (sco != NULL) esl_scorematrix_Destroy(sco);
1263
1264 free(buffer);
1265 return 0;
1266 }
1267
1268 if ((parms = malloc(sizeof(QUEUE_DATA_SHARD))) == NULL) LOG_FATAL_MSG("malloc", errno);
1269
1270 /* build the search structure that will be sent to all the workers */
1271 n = sizeof(HMMD_COMMAND_SHARD);
1272 n = n + strlen(opt_str) + 1;
1273
1274 if (seq != NULL) {
1275 n = n + strlen(seq->name) + 1;
1276 n = n + strlen(seq->desc) + 1;
1277 n = n + seq->n + 2;
1278 } else {
1279 n = n + sizeof(P7_HMM);
1280 n = n + sizeof(float) * (hmm->M + 1) * p7H_NTRANSITIONS;
1281 n = n + sizeof(float) * (hmm->M + 1) * abc->K;
1282 n = n + sizeof(float) * (hmm->M + 1) * abc->K;
1283 if (hmm->name != NULL) n = n + strlen(hmm->name) + 1;
1284 if (hmm->acc != NULL) n = n + strlen(hmm->acc) + 1;
1285 if (hmm->desc != NULL) n = n + strlen(hmm->desc) + 1;
1286 if (hmm->flags & p7H_RF) n = n + hmm->M + 2;
1287 if (hmm->flags & p7H_MMASK) n = n + hmm->M + 2;
1288 if (hmm->flags & p7H_CONS) n = n + hmm->M + 2;
1289 if (hmm->flags & p7H_CS) n = n + hmm->M + 2;
1290 if (hmm->flags & p7H_CA) n = n + hmm->M + 2;
1291 if (hmm->flags & p7H_MAP) n = n + sizeof(int) * (hmm->M + 1);
1292 }
1293
1294 if ((cmd = malloc(n)) == NULL) LOG_FATAL_MSG("malloc", errno);
1295 memset(cmd, 0, n); /* silence valgrind bitching about uninit bytes; remove if we ever serialize structs properly */
1296 cmd->hdr.length = n - sizeof(HMMD_HEADER);
1297 cmd->hdr.command = (esl_opt_IsUsed(opts, "--seqdb")) ? HMMD_CMD_SEARCH : HMMD_CMD_SCAN;
1298 cmd->srch.db_inx = dbx - 1; /* the program indexes databases 0 .. n-1 */
1299 cmd->srch.opts_length = strlen(opt_str) + 1;
1300
1301 ptr = cmd->srch.data;
1302
1303 memcpy(ptr, opt_str, cmd->srch.opts_length);
1304 ptr += cmd->srch.opts_length;
1305
1306 if (seq != NULL) {
1307 cmd->srch.query_type = HMMD_SEQUENCE;
1308 cmd->srch.query_length = seq->n + 2;
1309
1310 n = strlen(seq->name) + 1;
1311 memcpy(ptr, seq->name, n);
1312 ptr += n;
1313
1314 n = strlen(seq->desc) + 1;
1315 memcpy(ptr, seq->desc, n);
1316 ptr += n;
1317
1318 n = seq->n + 2;
1319 memcpy(ptr, seq->dsq, n);
1320 ptr += n;
1321 } else {
1322 cmd->srch.query_type = HMMD_HMM;
1323 cmd->srch.query_length = hmm->M;
1324
1325 n = sizeof(P7_HMM);
1326 memcpy(ptr, hmm, n);
1327 ptr += n;
1328
1329 n = sizeof(float) * (hmm->M + 1) * p7H_NTRANSITIONS;
1330 memcpy(ptr, *hmm->t, n);
1331 ptr += n;
1332
1333 n = sizeof(float) * (hmm->M + 1) * abc->K;
1334 memcpy(ptr, *hmm->mat, n);
1335 ptr += n;
1336 memcpy(ptr, *hmm->ins, n);
1337 ptr += n;
1338
1339 if (hmm->name) { n = strlen(hmm->name) + 1; memcpy(ptr, hmm->name, n); ptr += n; }
1340 if (hmm->acc) { n = strlen(hmm->acc) + 1; memcpy(ptr, hmm->acc, n); ptr += n; }
1341 if (hmm->desc) { n = strlen(hmm->desc) + 1; memcpy(ptr, hmm->desc, n); ptr += n; }
1342
1343 n = hmm->M + 2;
1344 if (hmm->flags & p7H_RF) { memcpy(ptr, hmm->rf, n); ptr += n; }
1345 if (hmm->flags & p7H_MMASK) { memcpy(ptr, hmm->mm, n); ptr += n; }
1346 if (hmm->flags & p7H_CONS) { memcpy(ptr, hmm->consensus, n); ptr += n; }
1347 if (hmm->flags & p7H_CS) { memcpy(ptr, hmm->cs, n); ptr += n; }
1348 if (hmm->flags & p7H_CA) { memcpy(ptr, hmm->ca, n); ptr += n; }
1349
1350 if (hmm->flags & p7H_MAP) {
1351 n = sizeof(int) * (hmm->M + 1);
1352 memcpy(ptr, hmm->map, n);
1353 ptr += n;
1354 }
1355 }
1356
1357 parms->hmm = hmm;
1358 parms->seq = seq;
1359 parms->abc = abc;
1360 parms->opts = opts;
1361 parms->dbx = dbx - 1;
1362 parms->cmd = cmd;
1363
1364 strcpy(parms->ip_addr, data->ip_addr);
1365 parms->sock = data->sock_fd;
1366 parms->cmd_type = cmd->hdr.command;
1367 parms->query_type = (seq != NULL) ? HMMD_SEQUENCE : HMMD_HMM;
1368
1369 date = time(NULL);
1370 ctime_r(&date, timestamp);
1371 printf("\n%s", timestamp); /* note ctime_r() leaves \n on end of timestamp */
1372
1373 if (parms->seq != NULL) {
1374 printf("Queuing %s %s from %s (%d)\n", (cmd->hdr.command == HMMD_CMD_SEARCH) ? "search" : "scan", parms->seq->name, parms->ip_addr, parms->sock);
1375 } else {
1376 printf("Queuing hmm %s from %s (%d)\n", parms->hmm->name, parms->ip_addr, parms->sock);
1377 }
1378 printf("%s", opt_str); /* note opt_str already has trailing \n */
1379 fflush(stdout);
1380
1381 esl_stack_PPush(cmdstack, parms);
1382
1383 free(buffer);
1384 return 0;
1385 }
1386
1387
1388 /* discard_function()
1389 * function handed to esl_stack_DiscardSelected() to remove
1390 * all commands in the stack that are associated with a
1391 * particular client socket, because we're closing that
1392 * client down. Prototype to this is dictate by the generalized
1393 * interface to esl_stack_DiscardSelected().
1394 */
1395 static int
1396 discard_function(void *elemp, void *args)
1397 {
1398 QUEUE_DATA_SHARD *elem = (QUEUE_DATA_SHARD *) elemp;
1399 int fd = * (int *) args;
1400
1401 if (elem->sock == fd)
1402 {
1403 free_QueueData_shard(elem);
1404 return TRUE;
1405 }
1406 return FALSE;
1407 }
1408
1409 static void *
1410 clientside_thread(void *arg)
1411 {
1412 int eof;
1413 CLIENTSIDE_ARGS *data = (CLIENTSIDE_ARGS *)arg;
1414
1415 /* Guarantees that thread resources are deallocated upon return */
1416 pthread_detach(pthread_self());
1417
1418 eof = 0;
1419 while (!eof) {
1420 eof = clientside_loop(data);
1421 }
1422
1423 /* remove any commands in stack associated with this client's socket */
1424 esl_stack_DiscardSelected(data->cmdstack, discard_function, &(data->sock_fd));
1425
1426 printf("Closing %s (%d)\n", data->ip_addr, data->sock_fd);
1427 fflush(stdout);
1428
1429 close(data->sock_fd);
1430 free(data);
1431
1432 pthread_exit(NULL);
1433 }
1434
1435 static void *
1436 client_comm_thread(void *arg)
1437 {
1438 int n;
1439 int fd;
1440 int addrlen;
1441 pthread_t thread_id;
1442
1443 struct sockaddr_in addr;
1444
1445 CLIENTSIDE_ARGS *targs = NULL;
1446 CLIENTSIDE_ARGS *data = (CLIENTSIDE_ARGS *)arg;
1447
1448 for ( ;; ) {
1449
1450 /* Wait for a client to connect */
1451 n = sizeof(addr);
1452 if ((fd = accept(data->sock_fd, (struct sockaddr *)&addr, (unsigned int *)&n)) < 0) LOG_FATAL_MSG("accept", errno);
1453
1454 if ((targs = malloc(sizeof(CLIENTSIDE_ARGS))) == NULL) LOG_FATAL_MSG("malloc", errno);
1455 targs->cmdstack = data->cmdstack;
1456 targs->sock_fd = fd;
1457
1458 addrlen = sizeof(targs->ip_addr);
1459 strncpy(targs->ip_addr, inet_ntoa(addr.sin_addr), addrlen);
1460 targs->ip_addr[addrlen-1] = 0;
1461
1462 if ((n = pthread_create(&thread_id, NULL, clientside_thread, targs)) != 0) LOG_FATAL_MSG("thread create", n);
1463 }
1464
1465 pthread_exit(NULL);
1466 }
1467
1468 static void
1469 setup_clientside_comm(ESL_GETOPTS *opts, CLIENTSIDE_ARGS *args)
1470 {
1471 int n;
1472 int reuse;
1473 int sock_fd;
1474 pthread_t thread_id;
1475
1476 struct linger linger;
1477 struct sockaddr_in addr;
1478
1479 /* Create socket for incoming connections */
1480 if ((sock_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) LOG_FATAL_MSG("socket", errno);
1481
1482 /* incase the server went down in an ungraceful way, allow the port to be
1483 * reused avoiding the timeout.
1484 */
1485 reuse = 1;
1486 if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) LOG_FATAL_MSG("setsockopt", errno);
1487
1488 /* the sockets are never closed, so if the server exits, force the kernel to
1489 * close the socket and clear it so the server can be restarted immediately.
1490 */
1491 linger.l_onoff = 1;
1492 linger.l_linger = 0;
1493 if (setsockopt(sock_fd, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger)) < 0) LOG_FATAL_MSG("setsockopt", errno);
1494
1495 /* Construct local address structure */
1496 memset(&addr, 0, sizeof(addr));
1497 addr.sin_family = AF_INET;
1498 addr.sin_addr.s_addr = htonl(INADDR_ANY);
1499 addr.sin_port = htons(esl_opt_GetInteger(opts, "--cport"));
1500
1501 /* Bind to the local address */
1502 if (bind(sock_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) LOG_FATAL_MSG("bind", errno);
1503
1504 /* Mark the socket so it will listen for incoming connections */
1505 if (listen(sock_fd, esl_opt_GetInteger(opts, "--ccncts")) < 0) LOG_FATAL_MSG("listen", errno);
1506 args->sock_fd = sock_fd;
1507
1508 if ((n = pthread_create(&thread_id, NULL, client_comm_thread, (void *)args)) != 0) LOG_FATAL_MSG("socket", n);
1509 }
1510
1511 static void
1512 workerside_loop(WORKERSIDE_ARGS *data, WORKER_DATA *worker)
1513 {
1514 ESL_STOPWATCH *w = NULL;
1515 HMMD_SEARCH_STATS *stats = NULL;
1516 HMMD_COMMAND_SHARD cmd;
1517 int n, i;
1518 int size;
1519 int total;
1520 char *ptr;
1521 uint8_t *buf; // Buffer to receive bytes into over sockets
1522 uint32_t buf_position; //Index into buffer for deserialize
1523 memset(&cmd, 0, sizeof(HMMD_COMMAND_SHARD)); /* silence valgrind. if we ever serialize structs properly, remove */
1524 w = esl_stopwatch_Create();
1525
1526 for ( ; ; ) {
1527
1528 /* wait for the next search object */
1529 if ((n = pthread_mutex_lock (&data->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1530
1531 /* wait for the master's signal to start the calculations */
1532 while (worker->cmd == NULL) {
1533 if ((n = pthread_cond_wait(&data->start_cond, &data->work_mutex)) != 0) LOG_FATAL_MSG("cond wait", n);
1534 }
1535
1536 if ((n = pthread_mutex_unlock (&data->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1537
1538 /* terminate the connection */
1539 if (worker->cmd->hdr.command == HMMD_CMD_SHUTDOWN) {
1540 fd_set rset;
1541 struct timeval tv;
1542
1543 n = MSG_SIZE(worker->cmd);
1544 if (writen(worker->sock_fd, worker->cmd, n) != n) {
1545 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1546 break;
1547 }
1548
1549 FD_ZERO(&rset);
1550 FD_SET(worker->sock_fd, &rset);
1551
1552 tv.tv_sec = 2;
1553 tv.tv_usec = 0;
1554
1555 if ((n = select(worker->sock_fd + 1, &rset, NULL, NULL, &tv)) < 0) {
1556 p7_syslog(LOG_ERR,"[%s:%d] - select %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1557 } else {
1558 if (n == 0) {
1559 p7_syslog(LOG_ERR,"[%s:%d] - shutdown %s is not responding\n", __FILE__, __LINE__, worker->ip_addr);
1560 } else {
1561 n = sizeof(HMMD_HEADER);
1562 if ((size = readn(worker->sock_fd, &cmd, n)) == -1) {
1563 p7_syslog(LOG_ERR,"[%s:%d] - reading %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1564 }
1565 if (cmd.hdr.command == HMMD_CMD_SHUTDOWN) {
1566 p7_syslog(LOG_ERR,"[%s:%d] - shutting down %s\n", __FILE__, __LINE__, worker->ip_addr);
1567 } else {
1568 p7_syslog(LOG_ERR,"[%s:%d] - error shutting down %s - received %d\n", __FILE__, __LINE__, worker->ip_addr, cmd.hdr.command);
1569 }
1570 }
1571 }
1572 break;
1573 }
1574
1575 //printf ("Writing %d bytes to %s [MSG = %d/%d]\n", (int)MSG_SIZE(worker->cmd), worker->ip_addr, worker->cmd->hdr.command, worker->cmd->hdr.length);
1576
1577 esl_stopwatch_Start(w);
1578
1579 /* write search message in two parts */
1580 n = sizeof(HMMD_HEADER) + sizeof(HMMD_SEARCH_CMD);
1581 memcpy(&cmd, worker->cmd, n);
1582 cmd.srch.inx = worker->srch_inx;
1583 cmd.srch.cnt = worker->srch_cnt;
1584 if (writen(worker->sock_fd, &cmd, n) != n) {
1585 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1586 break;
1587 }
1588
1589 /* write remaining data, i.e. sequence, options etc. */
1590 ptr = (char *)worker->cmd;
1591 ptr += n;
1592 n = MSG_SIZE(worker->cmd) - n;
1593 if (writen(worker->sock_fd, ptr, n) != n) {
1594 p7_syslog(LOG_ERR,"[%s:%d] - writing %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1595 break;
1596 }
1597
1598 total = 0;
1599 worker->total = 0;
1600
1601 n = HMMD_SEARCH_STATUS_SERIAL_SIZE;
1602 buf = malloc(n);
1603 if (buf == NULL){
1604 LOG_FATAL_MSG("malloc", errno);
1605 }
1606
1607 total += n;
1608 if ((size = readn(worker->sock_fd, buf, n)) == -1) {
1609 p7_syslog(LOG_ERR,"[%s:%d] - reading %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1610 break;
1611 }
1612
1613 buf_position = 0;
1614 if(hmmd_search_status_Deserialize(buf, &buf_position, &(worker->status)) != eslOK){
1615 LOG_FATAL_MSG("Couldn't deserialize HMMD_SEARCH_STATUS", errno);
1616 }
1617
1618 if (worker->status.status != eslOK) {
1619 n = worker->status.msg_size;
1620 total += n;
1621 if ((worker->err_buf = malloc(n)) == NULL) LOG_FATAL_MSG("malloc", errno);
1622 worker->err_buf[0] = 0;
1623 if ((size = readn(worker->sock_fd, worker->err_buf, n)) == -1) {
1624 p7_syslog(LOG_ERR,"[%s:%d] - reading %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1625 break;
1626 }
1627 } else {
1628
1629 // receive the results from the worker
1630 buf = realloc(buf, worker->status.msg_size);
1631 if(buf == NULL){
1632 LOG_FATAL_MSG("malloc", errno);
1633 }
1634
1635 total += worker->status.msg_size;
1636 if ((size = readn(worker->sock_fd, buf, worker->status.msg_size)) == -1) {
1637 p7_syslog(LOG_ERR,"[%s:%d] - reading %s error %d - %s\n", __FILE__, __LINE__, worker->ip_addr, errno, strerror(errno));
1638 break;
1639 }
1640
1641 buf_position = 0; // start at beginning of new buffer of data
1642 // Now, serialize the data structures out of it
1643 if(p7_hmmd_search_stats_Deserialize(buf, &buf_position, &(worker->stats)) != eslOK){
1644 LOG_FATAL_MSG("Couldn't deserialize HMMD_SEARCH_STATS", errno);
1645 }
1646 stats = &worker->stats;
1647 if(stats->nhits > 0){
1648 worker->hits = malloc(stats->nhits * sizeof(P7_HIT *));
1649 if(worker->hits == NULL){
1650 LOG_FATAL_MSG("malloc", errno);
1651 }
1652 worker->allocated_hits = stats->nhits; // Need this if we have to destroy the worker because of an error
1653 /* read in the hits */
1654 for(i = 0; i < stats->nhits; i++){
1655 worker->hits[i] = p7_hit_Create_empty();
1656 if(worker->hits[i] == NULL){
1657 LOG_FATAL_MSG("malloc", errno);
1658 }
1659 if(p7_hit_Deserialize(buf, &buf_position, worker->hits[i]) != eslOK){
1660 LOG_FATAL_MSG("Couldn't deserialize P7_HIT", errno);
1661 }
1662 }
1663 }
1664 free(buf);
1665 }
1666
1667 /* We've just allocated an array of pointers to P7_HIT objects and a bunch of P7_HIT
1668 objects that we don't free in this function. Here's what happens to them. gather_results() assembles
1669 all of the P7_HIT objects from the different workers into one big list, which it passes to forward_results().
1670 gather_results() frees each worker's array of pointers to P7_HIT objects, and forward_results is responsible for
1671 freeing all of the P7_HIT objects when it's done with them */
1672
1673 esl_stopwatch_Stop(w);
1674
1675 if ((n = pthread_mutex_lock (&data->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1676
1677 /* set the state of the worker to completed */
1678 worker->cmd = NULL;
1679 worker->completed = 1;
1680 worker->total = total;
1681 ++data->completed;
1682
1683 /* notify the master that a worker has completed */
1684 if ((n = pthread_cond_broadcast(&data->complete_cond)) != 0) LOG_FATAL_MSG("cond broadcast", n);
1685 if ((n = pthread_mutex_unlock (&data->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1686
1687 printf ("WORKER %s COMPLETED: %.2f sec received %d bytes\n", worker->ip_addr, w->elapsed, total);
1688 fflush(stdout);
1689 }
1690
1691 esl_stopwatch_Destroy(w);
1692
1693 return;
1694 }
1695
1696 static void *
1697 workerside_thread(void *arg)
1698 {
1699 HMMD_COMMAND_SHARD *cmd = NULL;
1700 WORKER_DATA *worker = (WORKER_DATA *)arg;
1701 WORKERSIDE_ARGS *parent = (WORKERSIDE_ARGS *)worker->parent;
1702 HMMD_HEADER hdr;
1703 int n;
1704 int fd = 0;
1705 int version;
1706 int updated;
1707 int status = eslOK;
1708 char *p;
1709
1710 memset(&hdr, 0, sizeof(HMMD_HEADER)); /* silence valgrind; remove if/when we serialize structs properly */
1711
1712 /* Guarantees that thread resources are deallocated upon return */
1713 pthread_detach(pthread_self());
1714
1715
1716 fflush(stdout);
1717
1718 updated = 0;
1719 while (!updated) {
1720 /* get the database version to load */
1721 if ((n = pthread_mutex_lock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1722 version = parent->db_version;
1723 if ((n = pthread_mutex_unlock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1724
1725 n = sizeof(HMMD_COMMAND_SHARD);
1726 if (parent->seq_db != NULL) n += strlen(parent->seq_db->name) + 1;
1727 if (parent->hmm_db != NULL) n += strlen(parent->hmm_db->name) + 1;
1728
1729 cmd = malloc(n);
1730 if (cmd == NULL) {
1731 p7_syslog(LOG_ERR,"[%s:%d] - malloc %d - %s\n", __FILE__, __LINE__, errno, strerror(errno));
1732 goto EXIT;
1733 }
1734 memset(cmd, 0, n);
1735
1736 cmd->hdr.length = n - sizeof(HMMD_HEADER);
1737 cmd->hdr.command = HMMD_CMD_INIT;
1738
1739 p = cmd->init.data;
1740
1741 if (parent->seq_db != NULL) {
1742 cmd->init.db_cnt = parent->seq_db->db_cnt;
1743 cmd->init.seq_cnt = parent->seq_db->count;
1744 cmd->init.seqdb_off = p - cmd->init.data;
1745
1746 strncpy(cmd->init.sid, parent->seq_db->id, sizeof(cmd->init.sid));
1747 cmd->init.sid[sizeof(cmd->init.sid)-1] = 0;
1748
1749 strcpy(p, parent->seq_db->name);
1750 p += strlen(parent->seq_db->name) + 1;
1751 cmd->init.num_shards = worker->num_shards;
1752 cmd->init.my_shard = worker->my_shard;
1753 }
1754
1755 if (parent->hmm_db != NULL) {
1756 cmd->init.hmm_cnt = 1;
1757 cmd->init.model_cnt = parent->hmm_db->n;
1758 cmd->init.hmmdb_off = p - cmd->init.data;
1759
1760 //strncpy(cmd->init.hid, parent->hmm_db->id, sizeof(cmd->init.hid));
1761 //cmd->init.hid[sizeof(cmd->init.hid)-1] = 0;
1762
1763 strcpy(p, parent->hmm_db->name);
1764 p += strlen(parent->hmm_db->name) + 1;
1765 }
1766
1767 if (writen(worker->sock_fd, cmd, n) != n) {
1768 p7_syslog(LOG_ERR,"[%s:%d] - writing (%d) error %d - %s\n", __FILE__, __LINE__, worker->sock_fd, errno, strerror(errno));
1769 status = eslFAIL;
1770 }
1771
1772 /* process the init command first */
1773 if (readn(worker->sock_fd, &hdr, sizeof(hdr)) == -1) {
1774 p7_syslog(LOG_ERR,"[%s:%d] - reading (%d) error %d - %s\n", __FILE__, __LINE__, worker->sock_fd, errno, strerror(errno));
1775 status = eslFAIL;
1776 }
1777
1778 /* cmd is a HMMD_COMMAND_SHARD.
1779 * consists of HMMD_HEADER: length, command, status
1780 * and a union of HMMD_INIT_CMD, HMMD_SEARCH_COMMAND, HMMD_INIT_RESET.
1781 * we know which is valid, from hdr.command
1782 * the total malloc size for an HMMD_COMMAND_SHARD is calculated from the header, using MSG_SIZE(cmd)
1783 */
1784 n = MSG_SIZE(&hdr);
1785 if ((cmd = realloc(cmd, n)) == NULL) {
1786 p7_syslog(LOG_ERR,"[%s:%d] - realloc error %d - %s\n", __FILE__, __LINE__, errno, strerror(errno));
1787 status = eslFAIL;
1788 }
1789 if (readn(worker->sock_fd, &(cmd->init), hdr.length) == -1) {
1790 p7_syslog(LOG_ERR,"[%s:%d] - reading (%d) error %d - %s\n", __FILE__, __LINE__, worker->sock_fd, errno, strerror(errno));
1791 status = eslFAIL;
1792 }
1793
1794 /* validate the database of the worker before adding him to the list */
1795 if (hdr.command != HMMD_CMD_INIT) {
1796 p7_syslog(LOG_ERR,"[%s:%d] - expecting HMMD_CMD_INIT %d\n", __FILE__, __LINE__, hdr.command);
1797 status = eslFAIL;
1798 }
1799 if (cmd->hdr.status != eslOK) {
1800 p7_syslog(LOG_ERR,"[%s:%d] - workers init status failed %d\n", __FILE__, __LINE__, cmd->hdr.status);
1801 status = eslFAIL;
1802 }
1803
1804 worker->next = NULL;
1805 worker->prev = NULL;
1806
1807 /* add the worker to the pending list */
1808 if ((n = pthread_mutex_lock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1809
1810 assert(validate_workers(parent));
1811
1812 /* make sure the master has not loaded a new database while we were waiting
1813 * for the worker to load and verify the database we started out this. If
1814 * the version has changed, force the worker to reload and verify.
1815 */
1816 if (version == parent->db_version) {
1817 if (status == eslOK) {
1818 worker->next = parent->pending;
1819 parent->pending = worker;
1820 ++parent->pend_cnt;
1821 } else {
1822 worker->next = parent->idling;
1823 parent->idling = worker;
1824 ++parent->idle_cnt;
1825 }
1826 updated = 1;
1827 }
1828
1829 assert(validate_workers(parent));
1830
1831 if ((n = pthread_mutex_unlock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1832 }
1833
1834 printf("Pending worker %s (%d)\n", worker->ip_addr, worker->sock_fd);
1835 fflush(stdout);
1836
1837 workerside_loop(parent, worker);
1838
1839 if ((n = pthread_mutex_lock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex lock", n);
1840
1841 fd = worker->sock_fd;
1842
1843 ++parent->failed;
1844 ++parent->completed;
1845
1846 worker->terminated = 1;
1847 worker->total = 0;
1848 worker->sock_fd = -1;
1849
1850 assert(validate_workers(parent));
1851
1852 /* notify the master that a worker has completed */
1853 if ((n = pthread_cond_broadcast(&parent->complete_cond)) != 0) LOG_FATAL_MSG("cond broadcast", n);
1854 if ((n = pthread_mutex_unlock (&parent->work_mutex)) != 0) LOG_FATAL_MSG("mutex unlock", n);
1855
1856 EXIT:
1857 printf("Closing worker %s (%d)\n", worker->ip_addr, fd);
1858 fflush(stdout);
1859
1860 if (cmd != NULL) free(cmd);
1861 close(fd);
1862
1863 pthread_exit(NULL);
1864 }
1865
1866 static void *
1867 worker_comm_thread(void *arg)
1868 {
1869 WORKERSIDE_ARGS *data = (WORKERSIDE_ARGS *)arg;
1870 WORKER_DATA *worker;
1871 int n, i;
1872 int fd;
1873 int addrlen;
1874 pthread_t thread_id;
1875 struct sockaddr_in addr;
1876 int new_worker_shard;
1877
1878 for ( ;; ) {
1879 /* Wait for a worker to connect */
1880 n = sizeof(addr);
1881 if ((fd = accept(data->sock_fd, (struct sockaddr *)&addr, (unsigned int *)&n)) < 0) LOG_FATAL_MSG("accept", errno);
1882
1883 if ((worker = malloc(sizeof(WORKER_DATA))) == NULL) LOG_FATAL_MSG("thread create", errno);
1884 memset(worker, 0, sizeof(WORKER_DATA));
1885
1886 worker->parent = data;
1887 worker->sock_fd = fd;
1888
1889 addrlen = sizeof(worker->ip_addr);
1890 strncpy(worker->ip_addr, inet_ntoa(addr.sin_addr), addrlen);
1891 worker->ip_addr[addrlen-1] = 0;
1892 new_worker_shard = -1;
1893 update_workers(data); // Check the status of the existing workers to remove any that have died
1894 // Figure out which shard to assign to the new worker
1895 for(i = 0; i < data->num_shards; i++){
1896 if (data->worker_ips[i] == addr.sin_addr.s_addr){ // This IP has connected to this server in the past,
1897 // so re-use its old shard
1898 printf("Found a shard assigned to the same worker as one that just tried to join. This shouldn't happen\n");
1899 }
1900 if(data->worker_ips[i] == INVALID_IP){
1901 // There is no worker node assigned to this shard, so assign it to the new worker
1902 new_worker_shard = i;
1903 break;
1904 }
1905 }
1906
1907 if(new_worker_shard == -1){ // We're unable to find a shard for this worker because all of the shards are taken
1908 LOG_FATAL_MSG("Attempt to add a new worker node when there were already as many workers as shards", 1);
1909 }
1910 else{
1911 worker->num_shards = data->num_shards;
1912 worker->my_shard = new_worker_shard;
1913 data->worker_ips[new_worker_shard] = addr.sin_addr.s_addr; // record the IP of the new warker
1914 if ((n = pthread_create(&thread_id, NULL, workerside_thread, worker)) != 0) LOG_FATAL_MSG("thread create", n);
1915 }
1916 }
1917
1918 pthread_exit(NULL);
1919 }
1920
1921 static void
1922 setup_workerside_comm(ESL_GETOPTS *opts, WORKERSIDE_ARGS *args)
1923 {
1924 int n;
1925 int reuse;
1926 int sock_fd;
1927 pthread_t thread_id;
1928
1929 struct linger linger;
1930 struct sockaddr_in addr;
1931
1932 /* Create socket for incoming connections */
1933 if ((sock_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) LOG_FATAL_MSG("socket", errno);
1934
1935 /* incase the server went down in an ungraceful way, allow the port to be
1936 * reused avoiding the timeout.
1937 */
1938 reuse = 1;
1939 if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (void *)&reuse, sizeof(reuse)) < 0) LOG_FATAL_MSG("setsockopt", errno);
1940
1941 /* the sockets are never closed, so if the server exits, force the kernel to
1942 * close the socket and clear it so the server can be restarted immediately.
1943 */
1944 linger.l_onoff = 1;
1945 linger.l_linger = 0;
1946 if (setsockopt(sock_fd, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger)) < 0) LOG_FATAL_MSG("setsockopt", errno);
1947
1948 /* Construct local address structure */
1949 memset(&addr, 0, sizeof(addr));
1950 addr.sin_family = AF_INET;
1951 addr.sin_addr.s_addr = htonl(INADDR_ANY);
1952 addr.sin_port = htons(esl_opt_GetInteger(opts, "--wport"));
1953
1954 /* Bind to the local address */
1955 if (bind(sock_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) LOG_FATAL_MSG("bind", errno);
1956
1957 /* Mark the socket so it will listen for incoming connections */
1958 if (listen(sock_fd, esl_opt_GetInteger(opts, "--wcncts")) < 0) LOG_FATAL_MSG("listen", errno);
1959
1960 args->sock_fd = sock_fd;
1961
1962 if ((n = pthread_create(&thread_id, NULL, worker_comm_thread, (void *)args)) != 0) LOG_FATAL_MSG("thread create", n);
1963 }
1964
1965 #endif /*HMMER_THREADS*/
1966
1967
1968