1 /* $Id: pazpar2.c,v 1.13 2006-12-14 14:58:03 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>
25 #include "termlists.h"
27 #include "relevance.h"
29 #define PAZPAR2_VERSION "0.1"
32 static void client_fatal(struct client *cl);
33 static void connection_destroy(struct connection *co);
34 static int client_prep_connection(struct client *cl);
35 static void ingest_records(struct client *cl, Z_Records *r);
37 IOCHAN channel_list = 0; // Master list of connections we're listening to.
39 static struct connection *connection_freelist = 0;
40 static struct client *client_freelist = 0;
42 static struct host *hosts = 0; // The hosts we know about
43 static struct database *databases = 0; // The databases we know about
45 static char *client_states[] = {
49 "Client_Initializing",
54 "Client_Disconnected",
58 struct parameters global_parameters =
62 "Index Data PazPar2 (MasterKey)",
75 static int send_apdu(struct client *c, Z_APDU *a)
77 struct connection *co = c->connection;
81 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
83 odr_perror(global_parameters.odr_out, "Encoding APDU");
86 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
87 r = cs_put(co->link, buf, len);
90 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
95 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
98 odr_reset(global_parameters.odr_out); /* release the APDU structure */
99 co->state = Conn_Waiting;
104 static void send_init(IOCHAN i)
106 struct connection *co = iochan_getdata(i);
107 struct client *cl = co->client;
108 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
110 a->u.initRequest->implementationId = global_parameters.implementationId;
111 a->u.initRequest->implementationName = global_parameters.implementationName;
112 a->u.initRequest->implementationVersion =
113 global_parameters.implementationVersion;
114 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
115 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
116 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
118 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
119 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
120 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
121 if (send_apdu(cl, a) >= 0)
123 iochan_setflags(i, EVENT_INPUT);
124 cl->state = Client_Initializing;
127 cl->state = Client_Error;
128 odr_reset(global_parameters.odr_out);
131 static void send_search(IOCHAN i)
133 struct connection *co = iochan_getdata(i);
134 struct client *cl = co->client;
135 struct session *se = cl->session;
136 struct database *db = cl->database;
137 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
138 int ndb, cerror, cpos;
141 struct ccl_rpn_node *cn;
142 int ssub = 0, lslb = 100000, mspn = 10;
144 yaz_log(YLOG_DEBUG, "Sending search");
146 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
149 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
151 zquery->which = Z_Query_type_1;
152 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
155 for (ndb = 0; *db->databases[ndb]; ndb++)
157 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
158 for (ndb = 0; *db->databases[ndb]; ndb++)
159 databaselist[ndb] = db->databases[ndb];
161 a->u.presentRequest->preferredRecordSyntax =
162 yaz_oidval_to_z3950oid(global_parameters.odr_out,
163 CLASS_RECSYN, VAL_USMARC);
164 a->u.searchRequest->smallSetUpperBound = &ssub;
165 a->u.searchRequest->largeSetLowerBound = &lslb;
166 a->u.searchRequest->mediumSetPresentNumber = &mspn;
167 a->u.searchRequest->resultSetName = "Default";
168 a->u.searchRequest->databaseNames = databaselist;
169 a->u.searchRequest->num_databaseNames = ndb;
171 if (send_apdu(cl, a) >= 0)
173 iochan_setflags(i, EVENT_INPUT);
174 cl->state = Client_Searching;
175 cl->requestid = se->requestid;
178 cl->state = Client_Error;
180 odr_reset(global_parameters.odr_out);
183 static void send_present(IOCHAN i)
185 struct connection *co = iochan_getdata(i);
186 struct client *cl = co->client;
187 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
189 int start = cl->records + 1;
191 toget = global_parameters.chunk;
192 if (toget > cl->hits - cl->records)
193 toget = cl->hits - cl->records;
195 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
197 a->u.presentRequest->resultSetStartPoint = &start;
198 a->u.presentRequest->numberOfRecordsRequested = &toget;
200 a->u.presentRequest->resultSetId = "Default";
202 a->u.presentRequest->preferredRecordSyntax =
203 yaz_oidval_to_z3950oid(global_parameters.odr_out,
204 CLASS_RECSYN, VAL_USMARC);
206 if (send_apdu(cl, a) >= 0)
208 iochan_setflags(i, EVENT_INPUT);
209 cl->state = Client_Presenting;
212 cl->state = Client_Error;
213 odr_reset(global_parameters.odr_out);
216 static void do_initResponse(IOCHAN i, Z_APDU *a)
218 struct connection *co = iochan_getdata(i);
219 struct client *cl = co->client;
220 Z_InitResponse *r = a->u.initResponse;
222 yaz_log(YLOG_DEBUG, "Received init response");
226 cl->state = Client_Idle;
229 cl->state = Client_Failed; // FIXME need to do something to the connection
232 static void do_searchResponse(IOCHAN i, Z_APDU *a)
234 struct connection *co = iochan_getdata(i);
235 struct client *cl = co->client;
236 struct session *se = cl->session;
237 Z_SearchResponse *r = a->u.searchResponse;
239 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
241 if (*r->searchStatus)
243 cl->hits = *r->resultCount;
244 se->total_hits += cl->hits;
245 if (r->presentStatus && !*r->presentStatus && r->records)
247 yaz_log(YLOG_DEBUG, "Records in search response");
248 cl->records += *r->numberOfRecordsReturned;
249 ingest_records(cl, r->records);
251 cl->state = Client_Idle;
256 cl->state = Client_Error;
258 Z_Records *recs = r->records;
259 if (recs->which == Z_Records_NSD)
261 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
262 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
263 cl->state = Client_Error;
269 const char *find_field(const char *rec, const char *field)
275 strcpy(lbuf + 1, field);
277 if ((line = strstr(rec, lbuf)))
283 const char *find_subfield(const char *field, char subfield)
285 const char *p = field;
287 while (*p && *p != '\n')
289 while (*p != '\n' && *p != '\t')
291 if (*p == '\t' && *(++p) == subfield) {
303 // Extract 245 $a $b 100 $a
304 char *extract_title(struct session *s, const char *rec)
306 const char *field, *subfield;
308 unsigned char *obuf, *p;
310 wrbuf_rewind(s->wrbuf);
312 if (!(field = find_field(rec, "245")))
314 if (!(subfield = find_subfield(field, 'a')))
316 ef = index(subfield, '\n');
317 if ((e = index(subfield, '\t')) && e < ef)
321 wrbuf_write(s->wrbuf, subfield, ef - subfield);
322 if ((subfield = find_subfield(field, 'b')))
324 ef = index(subfield, '\n');
325 if ((e = index(subfield, '\t')) && e < ef)
329 wrbuf_putc(s->wrbuf, ' ');
330 wrbuf_write(s->wrbuf, subfield, ef - subfield);
334 if ((field = find_field(rec, "100")))
336 if ((subfield = find_subfield(field, 'a')))
338 ef = index(subfield, '\n');
339 if ((e = index(subfield, '\t')) && e < ef)
343 wrbuf_puts(s->wrbuf, ", by ");
344 wrbuf_write(s->wrbuf, subfield, ef - subfield);
348 wrbuf_putc(s->wrbuf, '\0');
349 obuf = (unsigned char*) nmem_strdup(s->nmem, wrbuf_buf(s->wrbuf));
350 for (p = obuf; *p; p++)
351 if (*p == '&' || *p == '<' || *p > 122 || *p < ' ')
356 // Extract 245 $a $b 100 $a
357 char *extract_mergekey(struct session *s, const char *rec)
359 const char *field, *subfield;
361 char *out, *p, *pout;
363 wrbuf_rewind(s->wrbuf);
365 if (!(field = find_field(rec, "245")))
367 if (!(subfield = find_subfield(field, 'a')))
369 ef = index(subfield, '\n');
370 if ((e = index(subfield, '\t')) && e < ef)
374 wrbuf_write(s->wrbuf, subfield, ef - subfield);
375 if ((subfield = find_subfield(field, 'b')))
377 ef = index(subfield, '\n');
378 if ((e = index(subfield, '\t')) && e < ef)
382 wrbuf_puts(s->wrbuf, " field ");
383 wrbuf_write(s->wrbuf, subfield, ef - subfield);
387 if ((field = find_field(rec, "100")))
389 if ((subfield = find_subfield(field, 'a')))
391 ef = index(subfield, '\n');
392 if ((e = index(subfield, '\t')) && e < ef)
396 wrbuf_puts(s->wrbuf, " field ");
397 wrbuf_write(s->wrbuf, subfield, ef - subfield);
401 wrbuf_putc(s->wrbuf, '\0');
402 p = wrbuf_buf(s->wrbuf);
403 out = pout = nmem_malloc(s->nmem, strlen(p) + 1);
408 *(pout++) = tolower(*(p++));
409 while (*p && !isalnum(*p))
420 static void push_record(struct session *s, struct record *r)
423 assert(s->recheap_max + 1 < s->recheap_size);
425 s->recheap[p = ++s->recheap_max] = r;
428 int parent = (p - 1) >> 1;
429 if (strcmp(s->recheap[p]->merge_key, s->recheap[parent]->merge_key) < 0)
432 tmp = s->recheap[parent];
433 s->recheap[parent] = s->recheap[p];
442 static struct record *top_record(struct session *s)
444 return s-> recheap_max >= 0 ? s->recheap[0] : 0;
447 static struct record *pop_record(struct session *s)
451 int lastnonleaf = (s->recheap_max - 1) >> 1;
453 if (s->recheap_max < 0)
458 s->recheap[p] = s->recheap[s->recheap_max--];
460 while (p <= lastnonleaf)
462 int right = (p + 1) << 1;
463 int left = right - 1;
466 if (right < s->recheap_max &&
467 strcmp(s->recheap[right]->merge_key, s->recheap[left]->merge_key) < 0)
469 if (strcmp(s->recheap[min]->merge_key, s->recheap[p]->merge_key) < 0)
471 struct record *tmp = s->recheap[min];
472 s->recheap[min] = s->recheap[p];
482 // Like pop_record but collapses identical (merge_key) records
483 // The heap will contain multiple independent matching records and possibly
484 // one cluster, created the last time the list was scanned
485 static struct record *pop_mrecord(struct session *s)
490 if (!(this = pop_record(s)))
493 // Collapse identical records
494 while ((next = top_record(s)))
496 struct record *p, *tmpnext;
497 if (strcmp(this->merge_key, next->merge_key))
499 // Absorb record (and clustersiblings) into a supercluster
500 for (p = next; p; p = tmpnext) {
501 tmpnext = p->next_cluster;
502 p->next_cluster = this->next_cluster;
503 this->next_cluster = p;
511 // Reads records in sort order. Store records in top of heapspace until rewind is called.
512 static struct record *read_recheap(struct session *s)
514 struct record *r = pop_mrecord(s);
518 if (s->recheap_scratch < 0)
519 s->recheap_scratch = s->recheap_size;
520 s->recheap[--s->recheap_scratch] = r;
526 // Return records to heap after read
527 static void rewind_recheap(struct session *s)
529 while (s->recheap_scratch >= 0) {
530 push_record(s, s->recheap[s->recheap_scratch++]);
531 if (s->recheap_scratch >= s->recheap_size)
532 s->recheap_scratch = -1;
538 // FIXME needs to be generalized. Should flexibly generate X lists per search
539 static void extract_subject(struct session *s, const char *rec)
541 const char *field, *subfield;
543 while ((field = find_field(rec, "650")))
546 if ((subfield = find_subfield(field, 'a')))
552 ef = index(subfield, '\n');
555 if ((e = index(subfield, '\t')) && e < ef)
557 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
561 memcpy(buf, subfield, len);
564 termlist_insert(s->termlist, buf);
569 static void pull_relevance_field(struct session *s, struct record *head, const char *rec,
570 char *field, int mult)
573 while ((fb = find_field(rec, field)))
575 char *ffield = strchr(fb, '\t');
578 char *eol = strchr(ffield, '\n');
581 relevance_countwords(s->relevance, head, ffield, eol - ffield, mult);
582 rec = field + 1; // Crude way to cause a loop through repeating fields
586 static void pull_relevance_keys(struct session *s, struct record *head, struct record *rec)
588 relevance_newrec(s->relevance, head);
589 pull_relevance_field(s, head, rec->buf, "100", 2);
590 pull_relevance_field(s, head, rec->buf, "245", 4);
591 //pull_relevance_field(s, head, rec->buf, "530", 1);
592 pull_relevance_field(s, head, rec->buf, "630", 1);
593 pull_relevance_field(s, head, rec->buf, "650", 1);
594 pull_relevance_field(s, head, rec->buf, "700", 1);
595 relevance_donerecord(s->relevance, head);
598 static struct record *ingest_record(struct client *cl, char *buf, int len)
600 struct session *se = cl->session;
605 wrbuf_rewind(se->wrbuf);
606 yaz_marc_xml(global_parameters.yaz_marc, YAZ_MARC_LINE);
607 if (yaz_marc_decode_wrbuf(global_parameters.yaz_marc, buf, len, se->wrbuf) < 0)
609 yaz_log(YLOG_WARN, "Failed to decode MARC record");
612 wrbuf_putc(se->wrbuf, '\0');
613 recbuf = wrbuf_buf(se->wrbuf);
615 res = nmem_malloc(se->nmem, sizeof(struct record));
616 res->buf = nmem_strdup(se->nmem, recbuf);
618 extract_subject(se, res->buf);
620 res->title = extract_title(se, res->buf);
621 res->merge_key = extract_mergekey(se, res->buf);
625 res->next_cluster = 0;
626 res->target_offset = -1;
627 res->term_frequency_vec = 0;
629 head = reclist_insert(se->reclist, res);
631 pull_relevance_keys(se, head, res);
638 static void ingest_records(struct client *cl, Z_Records *r)
641 Z_NamePlusRecordList *rlist;
644 if (r->which != Z_Records_DBOSD)
646 rlist = r->u.databaseOrSurDiagnostics;
647 for (i = 0; i < rlist->num_records; i++)
649 Z_NamePlusRecord *npr = rlist->records[i];
654 if (npr->which != Z_NamePlusRecord_databaseRecord)
656 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
659 e = npr->u.databaseRecord;
660 if (e->which != Z_External_octet)
662 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
665 buf = (char*) e->u.octet_aligned->buf;
666 len = e->u.octet_aligned->len;
668 rec = ingest_record(cl, buf, len);
674 static void do_presentResponse(IOCHAN i, Z_APDU *a)
676 struct connection *co = iochan_getdata(i);
677 struct client *cl = co->client;
678 Z_PresentResponse *r = a->u.presentResponse;
681 Z_Records *recs = r->records;
682 if (recs->which == Z_Records_NSD)
684 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
685 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
686 cl->state = Client_Error;
690 if (!*r->presentStatus && cl->state != Client_Error)
692 yaz_log(YLOG_DEBUG, "Good Present response");
693 cl->records += *r->numberOfRecordsReturned;
694 ingest_records(cl, r->records);
695 cl->state = Client_Idle;
697 else if (*r->presentStatus)
699 yaz_log(YLOG_WARN, "Bad Present response");
700 cl->state = Client_Error;
704 static void handler(IOCHAN i, int event)
706 struct connection *co = iochan_getdata(i);
707 struct client *cl = co->client;
708 struct session *se = 0;
713 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
716 socklen_t errlen = sizeof(errcode);
718 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
719 &errlen) < 0 || errcode != 0)
726 yaz_log(YLOG_DEBUG, "Connect OK");
727 co->state = Conn_Open;
729 cl->state = Client_Connected;
733 else if (event & EVENT_INPUT)
735 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
739 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
740 connection_destroy(co);
745 yaz_log(YLOG_WARN, "EOF reading from Z server");
746 connection_destroy(co);
749 else if (len > 1) // We discard input if we have no connection
751 co->state = Conn_Open;
753 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
757 odr_reset(global_parameters.odr_in);
758 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
759 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
766 case Z_APDU_initResponse:
767 do_initResponse(i, a);
769 case Z_APDU_searchResponse:
770 do_searchResponse(i, a);
772 case Z_APDU_presentResponse:
773 do_presentResponse(i, a);
776 yaz_log(YLOG_WARN, "Unexpected result from server");
780 // We aren't expecting staggered output from target
781 // if (cs_more(t->link))
782 // iochan_setevent(i, EVENT_INPUT);
784 else // we throw away response and go to idle mode
786 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
787 cl->state = Client_Idle;
790 /* if len==1 we do nothing but wait for more input */
793 if (cl->state == Client_Connected) {
797 if (cl->state == Client_Idle)
799 if (cl->requestid != se->requestid && *se->query) {
802 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
803 cl->records < cl->hits) {
809 // Disassociate connection from client
810 static void connection_release(struct connection *co)
812 struct client *cl = co->client;
814 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
821 // Close connection and recycle structure
822 static void connection_destroy(struct connection *co)
824 struct host *h = co->host;
826 iochan_destroy(co->iochan);
828 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
829 if (h->connections == co)
830 h->connections = co->next;
833 struct connection *pco;
834 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
837 pco->next = co->next;
843 if (co->client->state != Client_Idle)
844 co->client->state = Client_Disconnected;
845 co->client->connection = 0;
847 co->next = connection_freelist;
848 connection_freelist = co;
851 // Creates a new connection for client, associated with the host of
853 static struct connection *connection_create(struct client *cl)
855 struct connection *new;
860 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
861 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
863 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
867 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
869 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
873 res = cs_connect(link, addr);
876 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
880 if ((new = connection_freelist))
881 connection_freelist = new->next;
884 new = xmalloc(sizeof (struct connection));
888 new->state = Conn_Connecting;
889 new->host = cl->database->host;
890 new->next = new->host->connections;
891 new->host->connections = new;
893 cl->connection = new;
896 new->iochan = iochan_create(cs_fileno(link), handler, 0);
897 iochan_setdata(new->iochan, new);
898 new->iochan->next = channel_list;
899 channel_list = new->iochan;
903 // Close connection and set state to error
904 static void client_fatal(struct client *cl)
906 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
907 connection_destroy(cl->connection);
908 cl->state = Client_Error;
911 // Ensure that client has a connection associated
912 static int client_prep_connection(struct client *cl)
914 struct connection *co;
915 struct session *se = cl->session;
916 struct host *host = cl->database->host;
920 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
924 // See if someone else has an idle connection
925 // We should look at timestamps here to select the longest-idle connection
926 for (co = host->connections; co; co = co->next)
927 if (co->state == Conn_Open && (!co->client || co->client->session != se))
931 connection_release(co);
936 co = connection_create(cl);
940 if (co->state == Conn_Connecting)
941 cl->state = Client_Connecting;
942 else if (co->state == Conn_Open)
944 if (cl->state == Client_Error || cl->state == Client_Disconnected)
945 cl->state = Client_Idle;
947 iochan_setflag(co->iochan, EVENT_OUTPUT);
954 void load_simpletargets(const char *fn)
956 FILE *f = fopen(fn, "r");
961 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
965 while (fgets(line, 255, f))
969 struct database *database;
971 if (strncmp(line, "target ", 7))
974 url[strlen(url) - 1] = '\0';
975 yaz_log(LOG_DEBUG, "Target: %s", url);
976 if ((db = strchr(url, '/')))
981 for (host = hosts; host; host = host->next)
982 if (!strcmp(url, host->hostport))
986 struct addrinfo *addrinfo, hints;
989 unsigned char addrbuf[4];
992 host = xmalloc(sizeof(struct host));
993 host->hostport = xstrdup(url);
994 host->connections = 0;
996 if ((port = strchr(url, ':')))
1002 hints.ai_family = PF_INET;
1003 hints.ai_socktype = SOCK_STREAM;
1004 hints.ai_protocol = IPPROTO_TCP;
1005 hints.ai_addrlen = 0;
1007 hints.ai_canonname = 0;
1009 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1011 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1013 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1016 assert(addrinfo->ai_family == PF_INET);
1017 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1018 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1019 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1020 host->ipport = xstrdup(ipport);
1021 freeaddrinfo(addrinfo);
1025 database = xmalloc(sizeof(struct database));
1026 database->host = host;
1027 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1028 strcpy(database->url, url);
1029 strcat(database->url, "/");
1030 strcat(database->url, db);
1031 strcpy(database->databases[0], db);
1032 *database->databases[1] = '\0';
1033 database->errors = 0;
1034 database->next = databases;
1035 databases = database;
1041 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1049 pull_terms(nmem, n->u.p[0], termlist, num);
1050 pull_terms(nmem, n->u.p[1], termlist, num);
1053 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1060 // Extract terms from query into null-terminated termlist
1061 static int extract_terms(NMEM nmem, char *query, char **termlist)
1064 struct ccl_rpn_node *n;
1067 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1070 pull_terms(nmem, n, termlist, &num);
1076 static struct client *client_create(void)
1079 if (client_freelist)
1081 r = client_freelist;
1082 client_freelist = client_freelist->next;
1085 r = xmalloc(sizeof(struct client));
1094 r->state = Client_Disconnected;
1099 void client_destroy(struct client *c)
1101 struct session *se = c->session;
1102 if (c == se->clients)
1103 se->clients = c->next;
1107 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1113 connection_release(c->connection);
1114 c->next = client_freelist;
1115 client_freelist = c;
1118 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1120 s->watchlist[what].fun = fun;
1121 s->watchlist[what].data = data;
1124 // This should be extended with parameters to control selection criteria
1125 // Associates a set of clients with a session;
1126 int select_targets(struct session *se)
1128 struct database *db;
1132 client_destroy(se->clients);
1133 for (db = databases; db; db = db->next)
1135 struct client *cl = client_create();
1138 cl->next = se->clients;
1145 char *search(struct session *se, char *query)
1147 int live_channels = 0;
1150 yaz_log(YLOG_DEBUG, "Search");
1152 strcpy(se->query, query);
1154 nmem_reset(se->nmem);
1155 for (cl = se->clients; cl; cl = cl->next)
1161 if (client_prep_connection(cl))
1167 int maxrecs = live_channels * global_parameters.toget;
1168 se->termlist = termlist_create(se->nmem, maxrecs, 15);
1169 se->reclist = reclist_create(se->nmem, maxrecs);
1170 extract_terms(se->nmem, query, p);
1171 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1172 se->total_records = se->total_hits = 0;
1180 void destroy_session(struct session *s)
1182 yaz_log(YLOG_LOG, "Destroying session");
1184 client_destroy(s->clients);
1185 nmem_destroy(s->nmem);
1186 wrbuf_free(s->wrbuf, 1);
1189 struct session *new_session()
1192 struct session *session = xmalloc(sizeof(*session));
1194 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1196 session->total_hits = 0;
1197 session->total_records = 0;
1198 session->termlist = 0;
1199 session->reclist = 0;
1200 session->requestid = -1;
1201 session->clients = 0;
1202 session->query[0] = '\0';
1203 session->nmem = nmem_create();
1204 session->wrbuf = wrbuf_alloc();
1205 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1207 session->watchlist[i].data = 0;
1208 session->watchlist[i].fun = 0;
1211 select_targets(session);
1216 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1218 static struct hitsbytarget res[1000]; // FIXME MM
1222 for (cl = se->clients; cl; cl = cl->next)
1224 strcpy(res[*count].id, cl->database->host->hostport);
1225 res[*count].hits = cl->hits;
1226 res[*count].records = cl->records;
1227 res[*count].diagnostic = cl->diagnostic;
1228 res[*count].state = client_states[cl->state];
1229 res[*count].connected = cl->connection ? 1 : 0;
1236 struct termlist_score **termlist(struct session *s, int *num)
1238 return termlist_highscore(s->termlist, num);
1241 struct record **show(struct session *s, int start, int *num, int *total, int *sumhits)
1243 struct record **recs = nmem_malloc(s->nmem, *num * sizeof(struct record *));
1246 relevance_prepare_read(s->relevance, s->reclist);
1248 *total = s->reclist->num_records;
1249 *sumhits = s->total_hits;
1251 for (i = 0; i < start; i++)
1252 if (!reclist_read_record(s->reclist))
1258 for (i = 0; i < *num; i++)
1260 struct record *r = reclist_read_record(s->reclist);
1271 void statistics(struct session *se, struct statistics *stat)
1276 bzero(stat, sizeof(*stat));
1277 for (cl = se->clients; cl; cl = cl->next)
1279 if (!cl->connection)
1280 stat->num_no_connection++;
1283 case Client_Connecting: stat->num_connecting++; break;
1284 case Client_Initializing: stat->num_initializing++; break;
1285 case Client_Searching: stat->num_searching++; break;
1286 case Client_Presenting: stat->num_presenting++; break;
1287 case Client_Idle: stat->num_idle++; break;
1288 case Client_Failed: stat->num_failed++; break;
1289 case Client_Error: stat->num_error++; break;
1294 stat->num_hits = se->total_hits;
1295 stat->num_records = se->total_records;
1297 stat->num_clients = count;
1300 static CCL_bibset load_cclfile(const char *fn)
1302 CCL_bibset res = ccl_qual_mk();
1303 if (ccl_qual_fname(res, fn) < 0)
1305 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1311 int main(int argc, char **argv)
1317 if (signal(SIGPIPE, SIG_IGN) < 0)
1318 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1320 yaz_log_init(YLOG_DEFAULT_LEVEL|YLOG_DEBUG, "pazpar2", 0);
1322 while ((ret = options("c:h:p:C:s:", argv, argc, &arg)) != -2)
1326 command_init(atoi(arg));
1330 http_init(atoi(arg));
1334 global_parameters.ccl_filter = load_cclfile(arg);
1337 http_set_proxyaddr(arg);
1340 load_simpletargets(arg);
1343 fprintf(stderr, "Usage: pazpar2\n"
1344 " -h httpport (REST)\n"
1345 " -c cmdport (telnet-style)\n"
1347 " -s simpletargetfile\n"
1348 " -p hostname[:portno] (HTTP proxy)\n");
1355 fprintf(stderr, "Set command port with -h or -c\n");
1359 global_parameters.ccl_filter = load_cclfile("default.bib");
1360 global_parameters.yaz_marc = yaz_marc_create();
1361 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1362 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1363 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1365 event_loop(&channel_list);
1373 * indent-tabs-mode: nil
1375 * vim: shiftwidth=4 tabstop=8 expandtab