1 /* $Id: pazpar2.c,v 1.10 2006-12-04 03:31:24 quinn Exp $ */;
8 #include <sys/socket.h>
14 #include <yaz/comstack.h>
15 #include <yaz/tcpip.h>
16 #include <yaz/proto.h>
17 #include <yaz/readconf.h>
18 #include <yaz/pquery.h>
19 #include <yaz/yaz-util.h>
21 #include <yaz/yaz-ccl.h>
27 #include "termlists.h"
29 #include "relevance.h"
31 #define PAZPAR2_VERSION "0.1"
34 static void client_fatal(struct client *cl);
35 static void connection_destroy(struct connection *co);
36 static int client_prep_connection(struct client *cl);
37 static void ingest_records(struct client *cl, Z_Records *r);
39 IOCHAN channel_list = 0; // Master list of connections we're listening to.
41 static struct connection *connection_freelist = 0;
42 static struct client *client_freelist = 0;
44 static struct host *hosts = 0; // The hosts we know about
45 static struct database *databases = 0; // The databases we know about
47 static char *client_states[] = {
51 "Client_Initializing",
56 "Client_Disconnected",
60 static struct parameters {
61 int timeout; /* operations timeout, in seconds */
62 char implementationId[128];
63 char implementationName[128];
64 char implementationVersion[128];
65 int target_timeout; // seconds
68 CCL_bibset ccl_filter;
76 "Index Data PazPar2 (MasterKey)",
88 static int send_apdu(struct client *c, Z_APDU *a)
90 struct connection *co = c->connection;
94 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
96 odr_perror(global_parameters.odr_out, "Encoding APDU");
99 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
100 r = cs_put(co->link, buf, len);
103 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
108 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
111 odr_reset(global_parameters.odr_out); /* release the APDU structure */
112 co->state = Conn_Waiting;
117 static void send_init(IOCHAN i)
119 struct connection *co = iochan_getdata(i);
120 struct client *cl = co->client;
121 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
123 a->u.initRequest->implementationId = global_parameters.implementationId;
124 a->u.initRequest->implementationName = global_parameters.implementationName;
125 a->u.initRequest->implementationVersion =
126 global_parameters.implementationVersion;
127 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
128 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
129 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
131 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
132 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
133 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
134 if (send_apdu(cl, a) >= 0)
136 iochan_setflags(i, EVENT_INPUT);
137 cl->state = Client_Initializing;
140 cl->state = Client_Error;
141 odr_reset(global_parameters.odr_out);
144 static void send_search(IOCHAN i)
146 struct connection *co = iochan_getdata(i);
147 struct client *cl = co->client;
148 struct session *se = cl->session;
149 struct database *db = cl->database;
150 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
151 int ndb, cerror, cpos;
154 struct ccl_rpn_node *cn;
155 int ssub = 0, lslb = 100000, mspn = 10;
157 yaz_log(YLOG_DEBUG, "Sending search");
159 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
162 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
164 zquery->which = Z_Query_type_1;
165 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
168 for (ndb = 0; *db->databases[ndb]; ndb++)
170 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
171 for (ndb = 0; *db->databases[ndb]; ndb++)
172 databaselist[ndb] = db->databases[ndb];
174 a->u.presentRequest->preferredRecordSyntax =
175 yaz_oidval_to_z3950oid(global_parameters.odr_out,
176 CLASS_RECSYN, VAL_USMARC);
177 a->u.searchRequest->smallSetUpperBound = &ssub;
178 a->u.searchRequest->largeSetLowerBound = &lslb;
179 a->u.searchRequest->mediumSetPresentNumber = &mspn;
180 a->u.searchRequest->resultSetName = "Default";
181 a->u.searchRequest->databaseNames = databaselist;
182 a->u.searchRequest->num_databaseNames = ndb;
184 if (send_apdu(cl, a) >= 0)
186 iochan_setflags(i, EVENT_INPUT);
187 cl->state = Client_Searching;
188 cl->requestid = se->requestid;
191 cl->state = Client_Error;
193 odr_reset(global_parameters.odr_out);
196 static void send_present(IOCHAN i)
198 struct connection *co = iochan_getdata(i);
199 struct client *cl = co->client;
200 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
202 int start = cl->records + 1;
204 toget = global_parameters.chunk;
205 if (toget > cl->hits - cl->records)
206 toget = cl->hits - cl->records;
208 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
210 a->u.presentRequest->resultSetStartPoint = &start;
211 a->u.presentRequest->numberOfRecordsRequested = &toget;
213 a->u.presentRequest->resultSetId = "Default";
215 a->u.presentRequest->preferredRecordSyntax =
216 yaz_oidval_to_z3950oid(global_parameters.odr_out,
217 CLASS_RECSYN, VAL_USMARC);
219 if (send_apdu(cl, a) >= 0)
221 iochan_setflags(i, EVENT_INPUT);
222 cl->state = Client_Presenting;
225 cl->state = Client_Error;
226 odr_reset(global_parameters.odr_out);
229 static void do_initResponse(IOCHAN i, Z_APDU *a)
231 struct connection *co = iochan_getdata(i);
232 struct client *cl = co->client;
233 Z_InitResponse *r = a->u.initResponse;
235 yaz_log(YLOG_DEBUG, "Received init response");
239 cl->state = Client_Idle;
242 cl->state = Client_Failed; // FIXME need to do something to the connection
245 static void do_searchResponse(IOCHAN i, Z_APDU *a)
247 struct connection *co = iochan_getdata(i);
248 struct client *cl = co->client;
249 struct session *se = cl->session;
250 Z_SearchResponse *r = a->u.searchResponse;
252 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
254 if (*r->searchStatus)
256 cl->hits = *r->resultCount;
257 se->total_hits += cl->hits;
258 if (r->presentStatus && !*r->presentStatus && r->records)
260 yaz_log(YLOG_DEBUG, "Records in search response");
261 cl->records += *r->numberOfRecordsReturned;
262 ingest_records(cl, r->records);
264 cl->state = Client_Idle;
269 cl->state = Client_Error;
271 Z_Records *recs = r->records;
272 if (recs->which == Z_Records_NSD)
274 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
275 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
276 cl->state = Client_Error;
282 const char *find_field(const char *rec, const char *field)
288 strcpy(lbuf + 1, field);
290 if ((line = strstr(rec, lbuf)))
296 const char *find_subfield(const char *field, char subfield)
298 const char *p = field;
300 while (*p && *p != '\n')
302 while (*p != '\n' && *p != '\t')
304 if (*p == '\t' && *(++p) == subfield) {
316 // Extract 245 $a $b 100 $a
317 char *extract_title(struct session *s, const char *rec)
319 const char *field, *subfield;
321 unsigned char *obuf, *p;
323 wrbuf_rewind(s->wrbuf);
325 if (!(field = find_field(rec, "245")))
327 if (!(subfield = find_subfield(field, 'a')))
329 ef = index(subfield, '\n');
330 if ((e = index(subfield, '\t')) && e < ef)
334 wrbuf_write(s->wrbuf, subfield, ef - subfield);
335 if ((subfield = find_subfield(field, 'b')))
337 ef = index(subfield, '\n');
338 if ((e = index(subfield, '\t')) && e < ef)
342 wrbuf_putc(s->wrbuf, ' ');
343 wrbuf_write(s->wrbuf, subfield, ef - subfield);
347 if ((field = find_field(rec, "100")))
349 if ((subfield = find_subfield(field, 'a')))
351 ef = index(subfield, '\n');
352 if ((e = index(subfield, '\t')) && e < ef)
356 wrbuf_puts(s->wrbuf, ", by ");
357 wrbuf_write(s->wrbuf, subfield, ef - subfield);
361 wrbuf_putc(s->wrbuf, '\0');
362 obuf = nmem_strdup(s->nmem, wrbuf_buf(s->wrbuf));
363 for (p = obuf; *p; p++)
364 if (*p == '&' || *p == '<' || *p > 122 || *p < ' ')
369 // Extract 245 $a $b 100 $a
370 char *extract_mergekey(struct session *s, const char *rec)
372 const char *field, *subfield;
374 char *out, *p, *pout;
376 wrbuf_rewind(s->wrbuf);
378 if (!(field = find_field(rec, "245")))
380 if (!(subfield = find_subfield(field, 'a')))
382 ef = index(subfield, '\n');
383 if ((e = index(subfield, '\t')) && e < ef)
387 wrbuf_write(s->wrbuf, subfield, ef - subfield);
388 if ((subfield = find_subfield(field, 'b')))
390 ef = index(subfield, '\n');
391 if ((e = index(subfield, '\t')) && e < ef)
395 wrbuf_puts(s->wrbuf, " field ");
396 wrbuf_write(s->wrbuf, subfield, ef - subfield);
400 if ((field = find_field(rec, "100")))
402 if ((subfield = find_subfield(field, 'a')))
404 ef = index(subfield, '\n');
405 if ((e = index(subfield, '\t')) && e < ef)
409 wrbuf_puts(s->wrbuf, " field ");
410 wrbuf_write(s->wrbuf, subfield, ef - subfield);
414 wrbuf_putc(s->wrbuf, '\0');
415 p = wrbuf_buf(s->wrbuf);
416 out = pout = nmem_malloc(s->nmem, strlen(p) + 1);
421 *(pout++) = tolower(*(p++));
422 while (*p && !isalnum(*p))
433 static void push_record(struct session *s, struct record *r)
436 assert(s->recheap_max + 1 < s->recheap_size);
438 s->recheap[p = ++s->recheap_max] = r;
441 int parent = (p - 1) >> 1;
442 if (strcmp(s->recheap[p]->merge_key, s->recheap[parent]->merge_key) < 0)
445 tmp = s->recheap[parent];
446 s->recheap[parent] = s->recheap[p];
455 static struct record *top_record(struct session *s)
457 return s-> recheap_max >= 0 ? s->recheap[0] : 0;
460 static struct record *pop_record(struct session *s)
464 int lastnonleaf = (s->recheap_max - 1) >> 1;
466 if (s->recheap_max < 0)
471 s->recheap[p] = s->recheap[s->recheap_max--];
473 while (p <= lastnonleaf)
475 int right = (p + 1) << 1;
476 int left = right - 1;
479 if (right < s->recheap_max &&
480 strcmp(s->recheap[right]->merge_key, s->recheap[left]->merge_key) < 0)
482 if (strcmp(s->recheap[min]->merge_key, s->recheap[p]->merge_key) < 0)
484 struct record *tmp = s->recheap[min];
485 s->recheap[min] = s->recheap[p];
495 // Like pop_record but collapses identical (merge_key) records
496 // The heap will contain multiple independent matching records and possibly
497 // one cluster, created the last time the list was scanned
498 static struct record *pop_mrecord(struct session *s)
503 if (!(this = pop_record(s)))
506 // Collapse identical records
507 while ((next = top_record(s)))
509 struct record *p, *tmpnext;
510 if (strcmp(this->merge_key, next->merge_key))
512 // Absorb record (and clustersiblings) into a supercluster
513 for (p = next; p; p = tmpnext) {
514 tmpnext = p->next_cluster;
515 p->next_cluster = this->next_cluster;
516 this->next_cluster = p;
524 // Reads records in sort order. Store records in top of heapspace until rewind is called.
525 static struct record *read_recheap(struct session *s)
527 struct record *r = pop_mrecord(s);
531 if (s->recheap_scratch < 0)
532 s->recheap_scratch = s->recheap_size;
533 s->recheap[--s->recheap_scratch] = r;
539 // Return records to heap after read
540 static void rewind_recheap(struct session *s)
542 while (s->recheap_scratch >= 0) {
543 push_record(s, s->recheap[s->recheap_scratch++]);
544 if (s->recheap_scratch >= s->recheap_size)
545 s->recheap_scratch = -1;
551 // FIXME needs to be generalized. Should flexibly generate X lists per search
552 static void extract_subject(struct session *s, const char *rec)
554 const char *field, *subfield;
556 while ((field = find_field(rec, "650")))
559 if ((subfield = find_subfield(field, 'a')))
565 ef = index(subfield, '\n');
568 if ((e = index(subfield, '\t')) && e < ef)
570 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
574 memcpy(buf, subfield, len);
577 termlist_insert(s->termlist, buf);
582 static void pull_relevance_field(struct session *s, struct record *head, const char *rec,
583 char *field, int mult)
586 while ((fb = find_field(rec, field)))
588 char *ffield = strchr(fb, '\t');
591 char *eol = strchr(ffield, '\n');
594 relevance_countwords(s->relevance, head, ffield, eol - ffield, mult);
595 rec = field + 1; // Crude way to cause a loop through repeating fields
599 static void pull_relevance_keys(struct session *s, struct record *head, struct record *rec)
601 relevance_newrec(s->relevance, head);
602 pull_relevance_field(s, head, rec->buf, "100", 2);
603 pull_relevance_field(s, head, rec->buf, "245", 4);
604 //pull_relevance_field(s, head, rec->buf, "530", 1);
605 pull_relevance_field(s, head, rec->buf, "630", 1);
606 pull_relevance_field(s, head, rec->buf, "650", 1);
607 pull_relevance_field(s, head, rec->buf, "700", 1);
608 relevance_donerecord(s->relevance, head);
611 static struct record *ingest_record(struct client *cl, char *buf, int len)
613 struct session *se = cl->session;
618 wrbuf_rewind(se->wrbuf);
619 yaz_marc_xml(global_parameters.yaz_marc, YAZ_MARC_LINE);
620 if (yaz_marc_decode_wrbuf(global_parameters.yaz_marc, buf, len, se->wrbuf) < 0)
622 yaz_log(YLOG_WARN, "Failed to decode MARC record");
625 wrbuf_putc(se->wrbuf, '\0');
626 recbuf = wrbuf_buf(se->wrbuf);
628 res = nmem_malloc(se->nmem, sizeof(struct record));
629 res->buf = nmem_strdup(se->nmem, recbuf);
631 extract_subject(se, res->buf);
633 res->title = extract_title(se, res->buf);
634 res->merge_key = extract_mergekey(se, res->buf);
638 res->next_cluster = 0;
639 res->target_offset = -1;
640 res->term_frequency_vec = 0;
642 head = reclist_insert(se->reclist, res);
644 pull_relevance_keys(se, head, res);
651 static void ingest_records(struct client *cl, Z_Records *r)
654 Z_NamePlusRecordList *rlist;
657 if (r->which != Z_Records_DBOSD)
659 rlist = r->u.databaseOrSurDiagnostics;
660 for (i = 0; i < rlist->num_records; i++)
662 Z_NamePlusRecord *npr = rlist->records[i];
667 if (npr->which != Z_NamePlusRecord_databaseRecord)
669 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
672 e = npr->u.databaseRecord;
673 if (e->which != Z_External_octet)
675 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
678 buf = (char*) e->u.octet_aligned->buf;
679 len = e->u.octet_aligned->len;
681 rec = ingest_record(cl, buf, len);
687 static void do_presentResponse(IOCHAN i, Z_APDU *a)
689 struct connection *co = iochan_getdata(i);
690 struct client *cl = co->client;
691 Z_PresentResponse *r = a->u.presentResponse;
694 Z_Records *recs = r->records;
695 if (recs->which == Z_Records_NSD)
697 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
698 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
699 cl->state = Client_Error;
703 if (!*r->presentStatus && cl->state != Client_Error)
705 yaz_log(YLOG_DEBUG, "Good Present response");
706 cl->records += *r->numberOfRecordsReturned;
707 ingest_records(cl, r->records);
708 cl->state = Client_Idle;
710 else if (*r->presentStatus)
712 yaz_log(YLOG_WARN, "Bad Present response");
713 cl->state = Client_Error;
717 static void handler(IOCHAN i, int event)
719 struct connection *co = iochan_getdata(i);
720 struct client *cl = co->client;
721 struct session *se = 0;
726 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
729 socklen_t errlen = sizeof(errcode);
731 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
732 &errlen) < 0 || errcode != 0)
739 yaz_log(YLOG_DEBUG, "Connect OK");
740 co->state = Conn_Open;
742 cl->state = Client_Connected;
746 else if (event & EVENT_INPUT)
748 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
760 else if (len > 1) // We discard input if we have no connection
762 co->state = Conn_Open;
764 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
768 odr_reset(global_parameters.odr_in);
769 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
770 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
777 case Z_APDU_initResponse:
778 do_initResponse(i, a);
780 case Z_APDU_searchResponse:
781 do_searchResponse(i, a);
783 case Z_APDU_presentResponse:
784 do_presentResponse(i, a);
787 yaz_log(YLOG_WARN, "Unexpected result from server");
791 // We aren't expecting staggered output from target
792 // if (cs_more(t->link))
793 // iochan_setevent(i, EVENT_INPUT);
795 else // we throw away response and go to idle mode
797 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
798 cl->state = Client_Idle;
801 /* if len==1 we do nothing but wait for more input */
804 if (cl->state == Client_Connected) {
808 if (cl->state == Client_Idle)
810 if (cl->requestid != se->requestid && *se->query) {
813 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
814 cl->records < cl->hits) {
820 // Disassociate connection from client
821 static void connection_release(struct connection *co)
823 struct client *cl = co->client;
825 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
832 // Close connection and recycle structure
833 static void connection_destroy(struct connection *co)
835 struct host *h = co->host;
837 iochan_destroy(co->iochan);
839 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
840 if (h->connections == co)
841 h->connections = co->next;
844 struct connection *pco;
845 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
848 pco->next = co->next;
854 if (co->client->state != Client_Idle)
855 co->client->state = Client_Disconnected;
856 co->client->connection = 0;
858 co->next = connection_freelist;
859 connection_freelist = co;
862 // Creates a new connection for client, associated with the host of
864 static struct connection *connection_create(struct client *cl)
866 struct connection *new;
871 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
872 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
874 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
878 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
880 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
884 res = cs_connect(link, addr);
887 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
891 if ((new = connection_freelist))
892 connection_freelist = new->next;
895 new = xmalloc(sizeof (struct connection));
899 new->state = Conn_Connecting;
900 new->host = cl->database->host;
901 new->next = new->host->connections;
902 new->host->connections = new;
904 cl->connection = new;
907 new->iochan = iochan_create(cs_fileno(link), handler, 0);
908 iochan_setdata(new->iochan, new);
909 new->iochan->next = channel_list;
910 channel_list = new->iochan;
914 // Close connection and set state to error
915 static void client_fatal(struct client *cl)
917 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
918 connection_destroy(cl->connection);
919 cl->state = Client_Error;
922 // Ensure that client has a connection associated
923 static int client_prep_connection(struct client *cl)
925 struct connection *co;
926 struct session *se = cl->session;
927 struct host *host = cl->database->host;
931 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
935 // See if someone else has an idle connection
936 // We should look at timestamps here to select the longest-idle connection
937 for (co = host->connections; co; co = co->next)
938 if (co->state == Conn_Open && (!co->client || co->client->session != se))
942 connection_release(co);
947 co = connection_create(cl);
951 if (co->state == Conn_Connecting)
952 cl->state = Client_Connecting;
953 else if (co->state == Conn_Open)
955 if (cl->state == Client_Error || cl->state == Client_Disconnected)
956 cl->state = Client_Idle;
958 iochan_setflag(co->iochan, EVENT_OUTPUT);
965 void load_simpletargets(const char *fn)
967 FILE *f = fopen(fn, "r");
972 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
976 while (fgets(line, 255, f))
980 struct database *database;
982 if (strncmp(line, "target ", 7))
985 url[strlen(url) - 1] = '\0';
986 yaz_log(LOG_DEBUG, "Target: %s", url);
987 if ((db = strchr(url, '/')))
992 for (host = hosts; host; host = host->next)
993 if (!strcmp(url, host->hostport))
997 struct addrinfo *addrinfo, hints;
1000 unsigned char addrbuf[4];
1003 host = xmalloc(sizeof(struct host));
1004 host->hostport = xstrdup(url);
1005 host->connections = 0;
1007 if ((port = strchr(url, ':')))
1013 hints.ai_family = PF_INET;
1014 hints.ai_socktype = SOCK_STREAM;
1015 hints.ai_protocol = IPPROTO_TCP;
1016 hints.ai_addrlen = 0;
1018 hints.ai_canonname = 0;
1020 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1022 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1024 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1027 assert(addrinfo->ai_family == PF_INET);
1028 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1029 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1030 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1031 host->ipport = xstrdup(ipport);
1032 freeaddrinfo(addrinfo);
1036 database = xmalloc(sizeof(struct database));
1037 database->host = host;
1038 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1039 strcpy(database->url, url);
1040 strcat(database->url, "/");
1041 strcat(database->url, db);
1042 strcpy(database->databases[0], db);
1043 *database->databases[1] = '\0';
1044 database->errors = 0;
1045 database->next = databases;
1046 databases = database;
1052 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1060 pull_terms(nmem, n->u.p[0], termlist, num);
1061 pull_terms(nmem, n->u.p[1], termlist, num);
1064 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1071 // Extract terms from query into null-terminated termlist
1072 static int extract_terms(NMEM nmem, char *query, char **termlist)
1075 struct ccl_rpn_node *n;
1078 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1081 pull_terms(nmem, n, termlist, &num);
1087 static struct client *client_create(void)
1090 if (client_freelist)
1092 r = client_freelist;
1093 client_freelist = client_freelist->next;
1096 r = xmalloc(sizeof(struct client));
1105 r->state = Client_Disconnected;
1110 void client_destroy(struct client *c)
1112 struct session *se = c->session;
1113 if (c == se->clients)
1114 se->clients = c->next;
1118 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1124 connection_destroy(c->connection);
1125 c->next = client_freelist;
1126 client_freelist = c;
1129 // This should be extended with parameters to control selection criteria
1130 // Associates a set of clients with a session;
1131 int select_targets(struct session *se)
1133 struct database *db;
1137 client_destroy(se->clients);
1138 for (db = databases; db; db = db->next)
1140 struct client *cl = client_create();
1143 cl->next = se->clients;
1150 char *search(struct session *se, char *query)
1152 int live_channels = 0;
1155 yaz_log(YLOG_DEBUG, "Search");
1157 strcpy(se->query, query);
1159 nmem_reset(se->nmem);
1160 for (cl = se->clients; cl; cl = cl->next)
1166 if (client_prep_connection(cl))
1172 int maxrecs = live_channels * global_parameters.toget;
1173 se->termlist = termlist_create(se->nmem, maxrecs, 15);
1174 se->reclist = reclist_create(se->nmem, maxrecs);
1175 extract_terms(se->nmem, query, p);
1176 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1177 se->total_records = se->total_hits = 0;
1185 struct session *new_session()
1187 struct session *session = xmalloc(sizeof(*session));
1189 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1191 session->total_hits = 0;
1192 session->total_records = 0;
1193 session->termlist = 0;
1194 session->reclist = 0;
1195 session->requestid = -1;
1196 session->clients = 0;
1197 session->query[0] = '\0';
1198 session->nmem = nmem_create();
1199 session->wrbuf = wrbuf_alloc();
1201 select_targets(session);
1206 void session_destroy(struct session *s)
1208 // FIXME do some shit here!!!!
1211 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1213 static struct hitsbytarget res[1000]; // FIXME MM
1217 for (cl = se->clients; cl; cl = cl->next)
1219 strcpy(res[*count].id, cl->database->host->hostport);
1220 res[*count].hits = cl->hits;
1221 res[*count].records = cl->records;
1222 res[*count].diagnostic = cl->diagnostic;
1223 res[*count].state = client_states[cl->state];
1224 res[*count].connected = cl->connection ? 1 : 0;
1231 struct termlist_score **termlist(struct session *s, int *num)
1233 return termlist_highscore(s->termlist, num);
1236 struct record **show(struct session *s, int start, int *num, int *total, int *sumhits)
1238 struct record **recs = nmem_malloc(s->nmem, *num * sizeof(struct record *));
1241 relevance_prepare_read(s->relevance, s->reclist);
1243 *total = s->reclist->num_records;
1244 *sumhits = s->total_hits;
1246 for (i = 0; i < start; i++)
1247 if (!reclist_read_record(s->reclist))
1253 for (i = 0; i < *num; i++)
1255 struct record *r = reclist_read_record(s->reclist);
1266 void statistics(struct session *se, struct statistics *stat)
1271 bzero(stat, sizeof(*stat));
1272 for (cl = se->clients; cl; cl = cl->next)
1274 if (!cl->connection)
1275 stat->num_no_connection++;
1278 case Client_Connecting: stat->num_connecting++; break;
1279 case Client_Initializing: stat->num_initializing++; break;
1280 case Client_Searching: stat->num_searching++; break;
1281 case Client_Presenting: stat->num_presenting++; break;
1282 case Client_Idle: stat->num_idle++; break;
1283 case Client_Failed: stat->num_failed++; break;
1284 case Client_Error: stat->num_error++; break;
1289 stat->num_hits = se->total_hits;
1290 stat->num_records = se->total_records;
1292 stat->num_clients = count;
1295 static CCL_bibset load_cclfile(const char *fn)
1297 CCL_bibset res = ccl_qual_mk();
1298 if (ccl_qual_fname(res, fn) < 0)
1300 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1306 int main(int argc, char **argv)
1312 if (signal(SIGPIPE, SIG_IGN) < 0)
1313 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1315 yaz_log_init(YLOG_DEFAULT_LEVEL|YLOG_DEBUG, "pazpar2", 0);
1317 while ((ret = options("c:h:p:C:s:", argv, argc, &arg)) != -2)
1321 command_init(atoi(arg));
1325 http_init(atoi(arg));
1329 global_parameters.ccl_filter = load_cclfile(arg);
1332 http_set_proxyaddr(arg);
1335 load_simpletargets(arg);
1338 fprintf(stderr, "Usage: pazpar2\n"
1339 " -h httpport (REST)\n"
1340 " -c cmdport (telnet-style)\n"
1342 " -s simpletargetfile\n"
1343 " -p hostname[:portno] (HTTP proxy)\n");
1350 fprintf(stderr, "Set command port with -h or -c\n");
1354 global_parameters.ccl_filter = load_cclfile("default.bib");
1355 global_parameters.yaz_marc = yaz_marc_create();
1356 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1357 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1358 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1360 event_loop(&channel_list);
1368 * indent-tabs-mode: nil
1370 * vim: shiftwidth=4 tabstop=8 expandtab