1 /* $Id: pazpar2.c,v 1.12 2006-12-12 02:36: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>
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);
747 else if (len > 1) // We discard input if we have no connection
749 co->state = Conn_Open;
751 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
755 odr_reset(global_parameters.odr_in);
756 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
757 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
764 case Z_APDU_initResponse:
765 do_initResponse(i, a);
767 case Z_APDU_searchResponse:
768 do_searchResponse(i, a);
770 case Z_APDU_presentResponse:
771 do_presentResponse(i, a);
774 yaz_log(YLOG_WARN, "Unexpected result from server");
778 // We aren't expecting staggered output from target
779 // if (cs_more(t->link))
780 // iochan_setevent(i, EVENT_INPUT);
782 else // we throw away response and go to idle mode
784 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
785 cl->state = Client_Idle;
788 /* if len==1 we do nothing but wait for more input */
791 if (cl->state == Client_Connected) {
795 if (cl->state == Client_Idle)
797 if (cl->requestid != se->requestid && *se->query) {
800 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
801 cl->records < cl->hits) {
807 // Disassociate connection from client
808 static void connection_release(struct connection *co)
810 struct client *cl = co->client;
812 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
819 // Close connection and recycle structure
820 static void connection_destroy(struct connection *co)
822 struct host *h = co->host;
824 iochan_destroy(co->iochan);
826 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
827 if (h->connections == co)
828 h->connections = co->next;
831 struct connection *pco;
832 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
835 pco->next = co->next;
841 if (co->client->state != Client_Idle)
842 co->client->state = Client_Disconnected;
843 co->client->connection = 0;
845 co->next = connection_freelist;
846 connection_freelist = co;
849 // Creates a new connection for client, associated with the host of
851 static struct connection *connection_create(struct client *cl)
853 struct connection *new;
858 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
859 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
861 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
865 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
867 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
871 res = cs_connect(link, addr);
874 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
878 if ((new = connection_freelist))
879 connection_freelist = new->next;
882 new = xmalloc(sizeof (struct connection));
886 new->state = Conn_Connecting;
887 new->host = cl->database->host;
888 new->next = new->host->connections;
889 new->host->connections = new;
891 cl->connection = new;
894 new->iochan = iochan_create(cs_fileno(link), handler, 0);
895 iochan_setdata(new->iochan, new);
896 new->iochan->next = channel_list;
897 channel_list = new->iochan;
901 // Close connection and set state to error
902 static void client_fatal(struct client *cl)
904 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
905 connection_destroy(cl->connection);
906 cl->state = Client_Error;
909 // Ensure that client has a connection associated
910 static int client_prep_connection(struct client *cl)
912 struct connection *co;
913 struct session *se = cl->session;
914 struct host *host = cl->database->host;
918 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
922 // See if someone else has an idle connection
923 // We should look at timestamps here to select the longest-idle connection
924 for (co = host->connections; co; co = co->next)
925 if (co->state == Conn_Open && (!co->client || co->client->session != se))
929 connection_release(co);
934 co = connection_create(cl);
938 if (co->state == Conn_Connecting)
939 cl->state = Client_Connecting;
940 else if (co->state == Conn_Open)
942 if (cl->state == Client_Error || cl->state == Client_Disconnected)
943 cl->state = Client_Idle;
945 iochan_setflag(co->iochan, EVENT_OUTPUT);
952 void load_simpletargets(const char *fn)
954 FILE *f = fopen(fn, "r");
959 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
963 while (fgets(line, 255, f))
967 struct database *database;
969 if (strncmp(line, "target ", 7))
972 url[strlen(url) - 1] = '\0';
973 yaz_log(LOG_DEBUG, "Target: %s", url);
974 if ((db = strchr(url, '/')))
979 for (host = hosts; host; host = host->next)
980 if (!strcmp(url, host->hostport))
984 struct addrinfo *addrinfo, hints;
987 unsigned char addrbuf[4];
990 host = xmalloc(sizeof(struct host));
991 host->hostport = xstrdup(url);
992 host->connections = 0;
994 if ((port = strchr(url, ':')))
1000 hints.ai_family = PF_INET;
1001 hints.ai_socktype = SOCK_STREAM;
1002 hints.ai_protocol = IPPROTO_TCP;
1003 hints.ai_addrlen = 0;
1005 hints.ai_canonname = 0;
1007 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1009 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1011 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1014 assert(addrinfo->ai_family == PF_INET);
1015 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1016 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1017 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1018 host->ipport = xstrdup(ipport);
1019 freeaddrinfo(addrinfo);
1023 database = xmalloc(sizeof(struct database));
1024 database->host = host;
1025 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1026 strcpy(database->url, url);
1027 strcat(database->url, "/");
1028 strcat(database->url, db);
1029 strcpy(database->databases[0], db);
1030 *database->databases[1] = '\0';
1031 database->errors = 0;
1032 database->next = databases;
1033 databases = database;
1039 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1047 pull_terms(nmem, n->u.p[0], termlist, num);
1048 pull_terms(nmem, n->u.p[1], termlist, num);
1051 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1058 // Extract terms from query into null-terminated termlist
1059 static int extract_terms(NMEM nmem, char *query, char **termlist)
1062 struct ccl_rpn_node *n;
1065 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1068 pull_terms(nmem, n, termlist, &num);
1074 static struct client *client_create(void)
1077 if (client_freelist)
1079 r = client_freelist;
1080 client_freelist = client_freelist->next;
1083 r = xmalloc(sizeof(struct client));
1092 r->state = Client_Disconnected;
1097 void client_destroy(struct client *c)
1099 struct session *se = c->session;
1100 if (c == se->clients)
1101 se->clients = c->next;
1105 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1111 connection_release(c->connection);
1112 c->next = client_freelist;
1113 client_freelist = c;
1116 // This should be extended with parameters to control selection criteria
1117 // Associates a set of clients with a session;
1118 int select_targets(struct session *se)
1120 struct database *db;
1124 client_destroy(se->clients);
1125 for (db = databases; db; db = db->next)
1127 struct client *cl = client_create();
1130 cl->next = se->clients;
1137 char *search(struct session *se, char *query)
1139 int live_channels = 0;
1142 yaz_log(YLOG_DEBUG, "Search");
1144 strcpy(se->query, query);
1146 nmem_reset(se->nmem);
1147 for (cl = se->clients; cl; cl = cl->next)
1153 if (client_prep_connection(cl))
1159 int maxrecs = live_channels * global_parameters.toget;
1160 se->termlist = termlist_create(se->nmem, maxrecs, 15);
1161 se->reclist = reclist_create(se->nmem, maxrecs);
1162 extract_terms(se->nmem, query, p);
1163 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1164 se->total_records = se->total_hits = 0;
1172 void destroy_session(struct session *s)
1174 yaz_log(YLOG_LOG, "Destroying session");
1176 client_destroy(s->clients);
1177 nmem_destroy(s->nmem);
1178 wrbuf_free(s->wrbuf, 1);
1181 struct session *new_session()
1183 struct session *session = xmalloc(sizeof(*session));
1185 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1187 session->total_hits = 0;
1188 session->total_records = 0;
1189 session->termlist = 0;
1190 session->reclist = 0;
1191 session->requestid = -1;
1192 session->clients = 0;
1193 session->query[0] = '\0';
1194 session->nmem = nmem_create();
1195 session->wrbuf = wrbuf_alloc();
1197 select_targets(session);
1202 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1204 static struct hitsbytarget res[1000]; // FIXME MM
1208 for (cl = se->clients; cl; cl = cl->next)
1210 strcpy(res[*count].id, cl->database->host->hostport);
1211 res[*count].hits = cl->hits;
1212 res[*count].records = cl->records;
1213 res[*count].diagnostic = cl->diagnostic;
1214 res[*count].state = client_states[cl->state];
1215 res[*count].connected = cl->connection ? 1 : 0;
1222 struct termlist_score **termlist(struct session *s, int *num)
1224 return termlist_highscore(s->termlist, num);
1227 struct record **show(struct session *s, int start, int *num, int *total, int *sumhits)
1229 struct record **recs = nmem_malloc(s->nmem, *num * sizeof(struct record *));
1232 relevance_prepare_read(s->relevance, s->reclist);
1234 *total = s->reclist->num_records;
1235 *sumhits = s->total_hits;
1237 for (i = 0; i < start; i++)
1238 if (!reclist_read_record(s->reclist))
1244 for (i = 0; i < *num; i++)
1246 struct record *r = reclist_read_record(s->reclist);
1257 void statistics(struct session *se, struct statistics *stat)
1262 bzero(stat, sizeof(*stat));
1263 for (cl = se->clients; cl; cl = cl->next)
1265 if (!cl->connection)
1266 stat->num_no_connection++;
1269 case Client_Connecting: stat->num_connecting++; break;
1270 case Client_Initializing: stat->num_initializing++; break;
1271 case Client_Searching: stat->num_searching++; break;
1272 case Client_Presenting: stat->num_presenting++; break;
1273 case Client_Idle: stat->num_idle++; break;
1274 case Client_Failed: stat->num_failed++; break;
1275 case Client_Error: stat->num_error++; break;
1280 stat->num_hits = se->total_hits;
1281 stat->num_records = se->total_records;
1283 stat->num_clients = count;
1286 static CCL_bibset load_cclfile(const char *fn)
1288 CCL_bibset res = ccl_qual_mk();
1289 if (ccl_qual_fname(res, fn) < 0)
1291 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1297 int main(int argc, char **argv)
1303 if (signal(SIGPIPE, SIG_IGN) < 0)
1304 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1306 yaz_log_init(YLOG_DEFAULT_LEVEL|YLOG_DEBUG, "pazpar2", 0);
1308 while ((ret = options("c:h:p:C:s:", argv, argc, &arg)) != -2)
1312 command_init(atoi(arg));
1316 http_init(atoi(arg));
1320 global_parameters.ccl_filter = load_cclfile(arg);
1323 http_set_proxyaddr(arg);
1326 load_simpletargets(arg);
1329 fprintf(stderr, "Usage: pazpar2\n"
1330 " -h httpport (REST)\n"
1331 " -c cmdport (telnet-style)\n"
1333 " -s simpletargetfile\n"
1334 " -p hostname[:portno] (HTTP proxy)\n");
1341 fprintf(stderr, "Set command port with -h or -c\n");
1345 global_parameters.ccl_filter = load_cclfile("default.bib");
1346 global_parameters.yaz_marc = yaz_marc_create();
1347 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1348 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1349 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1351 event_loop(&channel_list);
1359 * indent-tabs-mode: nil
1361 * vim: shiftwidth=4 tabstop=8 expandtab