1 /* $Id: pazpar2.c,v 1.16 2007-01-06 03:02:47 quinn Exp $ */;
8 #include <sys/socket.h>
14 #include <yaz/marcdisp.h>
15 #include <yaz/comstack.h>
16 #include <yaz/tcpip.h>
17 #include <yaz/proto.h>
18 #include <yaz/readconf.h>
19 #include <yaz/pquery.h>
20 #include <yaz/yaz-util.h>
25 #include <yaz/timing.h>
32 #include "termlists.h"
34 #include "relevance.h"
37 #define PAZPAR2_VERSION "0.1"
40 static void client_fatal(struct client *cl);
41 static void connection_destroy(struct connection *co);
42 static int client_prep_connection(struct client *cl);
43 static void ingest_records(struct client *cl, Z_Records *r);
44 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
45 void session_alert_watch(struct session *s, int what);
47 IOCHAN channel_list = 0; // Master list of connections we're handling events to
49 static struct connection *connection_freelist = 0;
50 static struct client *client_freelist = 0;
52 static struct host *hosts = 0; // The hosts we know about
53 static struct database *databases = 0; // The databases we know about
55 static char *client_states[] = {
59 "Client_Initializing",
64 "Client_Disconnected",
68 struct parameters global_parameters =
73 "Index Data PazPar2 (MasterKey)",
85 static int send_apdu(struct client *c, Z_APDU *a)
87 struct connection *co = c->connection;
91 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
93 odr_perror(global_parameters.odr_out, "Encoding APDU");
96 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
97 r = cs_put(co->link, buf, len);
100 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
105 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
108 odr_reset(global_parameters.odr_out); /* release the APDU structure */
109 co->state = Conn_Waiting;
114 static void send_init(IOCHAN i)
116 struct connection *co = iochan_getdata(i);
117 struct client *cl = co->client;
118 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
120 a->u.initRequest->implementationId = global_parameters.implementationId;
121 a->u.initRequest->implementationName = global_parameters.implementationName;
122 a->u.initRequest->implementationVersion =
123 global_parameters.implementationVersion;
124 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
125 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
126 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
128 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
129 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
130 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
131 if (send_apdu(cl, a) >= 0)
133 iochan_setflags(i, EVENT_INPUT);
134 cl->state = Client_Initializing;
137 cl->state = Client_Error;
138 odr_reset(global_parameters.odr_out);
141 static void send_search(IOCHAN i)
143 struct connection *co = iochan_getdata(i);
144 struct client *cl = co->client;
145 struct session *se = cl->session;
146 struct database *db = cl->database;
147 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
148 int ndb, cerror, cpos;
151 struct ccl_rpn_node *cn;
152 int ssub = 0, lslb = 100000, mspn = 10;
154 yaz_log(YLOG_DEBUG, "Sending search");
156 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
159 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
161 zquery->which = Z_Query_type_1;
162 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
165 for (ndb = 0; db->databases[ndb]; ndb++)
167 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
168 for (ndb = 0; db->databases[ndb]; ndb++)
169 databaselist[ndb] = db->databases[ndb];
171 a->u.presentRequest->preferredRecordSyntax =
172 yaz_oidval_to_z3950oid(global_parameters.odr_out,
173 CLASS_RECSYN, VAL_USMARC);
174 a->u.searchRequest->smallSetUpperBound = &ssub;
175 a->u.searchRequest->largeSetLowerBound = &lslb;
176 a->u.searchRequest->mediumSetPresentNumber = &mspn;
177 a->u.searchRequest->resultSetName = "Default";
178 a->u.searchRequest->databaseNames = databaselist;
179 a->u.searchRequest->num_databaseNames = ndb;
181 if (send_apdu(cl, a) >= 0)
183 iochan_setflags(i, EVENT_INPUT);
184 cl->state = Client_Searching;
185 cl->requestid = se->requestid;
188 cl->state = Client_Error;
190 odr_reset(global_parameters.odr_out);
193 static void send_present(IOCHAN i)
195 struct connection *co = iochan_getdata(i);
196 struct client *cl = co->client;
197 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
199 int start = cl->records + 1;
201 toget = global_parameters.chunk;
202 if (toget > global_parameters.toget - cl->records)
203 toget = global_parameters.toget - cl->records;
204 if (toget > cl->hits - cl->records)
205 toget = cl->hits - cl->records;
207 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
209 a->u.presentRequest->resultSetStartPoint = &start;
210 a->u.presentRequest->numberOfRecordsRequested = &toget;
212 a->u.presentRequest->resultSetId = "Default";
214 a->u.presentRequest->preferredRecordSyntax =
215 yaz_oidval_to_z3950oid(global_parameters.odr_out,
216 CLASS_RECSYN, VAL_USMARC);
218 if (send_apdu(cl, a) >= 0)
220 iochan_setflags(i, EVENT_INPUT);
221 cl->state = Client_Presenting;
224 cl->state = Client_Error;
225 odr_reset(global_parameters.odr_out);
228 static void do_initResponse(IOCHAN i, Z_APDU *a)
230 struct connection *co = iochan_getdata(i);
231 struct client *cl = co->client;
232 Z_InitResponse *r = a->u.initResponse;
234 yaz_log(YLOG_DEBUG, "Received init response");
238 cl->state = Client_Idle;
241 cl->state = Client_Failed; // FIXME need to do something to the connection
244 static void do_searchResponse(IOCHAN i, Z_APDU *a)
246 struct connection *co = iochan_getdata(i);
247 struct client *cl = co->client;
248 struct session *se = cl->session;
249 Z_SearchResponse *r = a->u.searchResponse;
251 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
253 if (*r->searchStatus)
255 cl->hits = *r->resultCount;
256 se->total_hits += cl->hits;
257 if (r->presentStatus && !*r->presentStatus && r->records)
259 yaz_log(YLOG_DEBUG, "Records in search response");
260 cl->records += *r->numberOfRecordsReturned;
261 ingest_records(cl, r->records);
263 cl->state = Client_Idle;
268 cl->state = Client_Error;
270 Z_Records *recs = r->records;
271 if (recs->which == Z_Records_NSD)
273 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
274 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
275 cl->state = Client_Error;
281 char *normalize_mergekey(char *buf)
283 char *p = buf, *pout = buf;
287 while (*p && !isalnum(*p))
290 *(pout++) = tolower(*(p++));
293 while (*p && !isalnum(*p))
304 // FIXME needs to be generalized. Should flexibly generate X lists per search
305 static void extract_subject(struct session *s, const char *rec)
307 const char *field, *subfield;
309 while ((field = find_field(rec, "650")))
312 if ((subfield = find_subfield(field, 'a')))
318 ef = index(subfield, '\n');
321 if ((e = index(subfield, '\t')) && e < ef)
323 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
327 memcpy(buf, subfield, len);
331 termlist_insert(s->termlist, buf);
338 static void add_facet(struct session *s, const char *type, const char *value)
342 for (i = 0; i < s->num_termlists; i++)
343 if (!strcmp(s->termlists[i].name, type))
345 if (i == s->num_termlists)
347 if (i == SESSION_MAX_TERMLISTS)
349 yaz_log(YLOG_FATAL, "Too many termlists");
352 s->termlists[i].name = nmem_strdup(s->nmem, type);
353 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
354 s->num_termlists = i + 1;
356 termlist_insert(s->termlists[i].termlist, value);
359 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
361 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
362 struct conf_retrievalmap *m;
366 // First normalize to XML
367 if (rprofile->native_syntax == Nativesyn_iso2709)
371 if (rec->which != Z_External_octet)
373 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
376 buf = (char*) rec->u.octet_aligned->buf;
377 len = rec->u.octet_aligned->len;
378 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
380 yaz_log(YLOG_WARN, "Failed to decode MARC");
383 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
384 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
386 yaz_log(YLOG_WARN, "Failed to encode as XML");
389 rdoc = xmlNewDoc("1.0");
390 xmlDocSetRootElement(rdoc, res);
394 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
397 for (m = rprofile->maplist; m; m = m->next)
400 if (m->type != Map_xslt)
402 yaz_log(YLOG_WARN, "Unknown map type");
405 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
407 yaz_log(YLOG_WARN, "XSLT transformation failed");
413 if (global_parameters.dump_records)
415 fprintf(stderr, "Record:\n----------------\n");
416 xmlDocFormatDump(stderr, rdoc, 1);
421 static struct record *ingest_record(struct client *cl, Z_External *rec)
423 xmlDoc *xdoc = normalize_record(cl, rec);
425 struct record *res, *head;
426 struct session *se = cl->session;
427 xmlChar *mergekey, *mergekey_norm;
432 root = xmlDocGetRootElement(xdoc);
433 if (!(mergekey = xmlGetProp(root, "mergekey")))
435 yaz_log(YLOG_WARN, "No mergekey found in record");
440 res = nmem_malloc(se->nmem, sizeof(struct record));
441 res->next_cluster = 0;
442 res->target_offset = -1;
443 res->term_frequency_vec = 0;
444 res->title = "Unknown";
447 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
449 res->merge_key = normalize_mergekey(mergekey_norm);
451 head = reclist_insert(se->reclist, res);
454 /* no room for record */
458 relevance_newrec(se->relevance, head);
460 for (n = root->children; n; n = n->next)
462 if (n->type != XML_ELEMENT_NODE)
464 if (!strcmp(n->name, "facet"))
466 xmlChar *type = xmlGetProp(n, "type");
467 xmlChar *value = xmlNodeListGetString(xdoc, n->children, 0);
470 add_facet(se, type, value);
471 relevance_countwords(se->relevance, head, value, 1);
476 else if (!strcmp(n->name, "metadata"))
478 xmlChar *type = xmlGetProp(n, "type");
479 if (type && !strcmp(type, "title"))
481 xmlChar *value = xmlNodeListGetString(xdoc, n->children, 0);
484 res->title = nmem_strdup(se->nmem, value);
485 relevance_countwords(se->relevance, head, value, 4);
492 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
497 relevance_donerecord(se->relevance, head);
503 static void ingest_records(struct client *cl, Z_Records *r)
506 yaz_timing_t t = yaz_timing_create();
509 struct session *s = cl->session;
510 Z_NamePlusRecordList *rlist;
513 if (r->which != Z_Records_DBOSD)
515 rlist = r->u.databaseOrSurDiagnostics;
516 for (i = 0; i < rlist->num_records; i++)
518 Z_NamePlusRecord *npr = rlist->records[i];
520 if (npr->which != Z_NamePlusRecord_databaseRecord)
522 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
526 rec = ingest_record(cl, npr->u.databaseRecord);
530 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
531 session_alert_watch(s, SESSION_WATCH_RECORDS);
535 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
536 yaz_timing_get_real(t), yaz_timing_get_user(t),
537 yaz_timing_get_sys(t));
538 yaz_timing_destroy(&t);
542 static void do_presentResponse(IOCHAN i, Z_APDU *a)
544 struct connection *co = iochan_getdata(i);
545 struct client *cl = co->client;
546 Z_PresentResponse *r = a->u.presentResponse;
549 Z_Records *recs = r->records;
550 if (recs->which == Z_Records_NSD)
552 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
553 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
554 cl->state = Client_Error;
558 if (!*r->presentStatus && cl->state != Client_Error)
560 yaz_log(YLOG_DEBUG, "Good Present response");
561 cl->records += *r->numberOfRecordsReturned;
562 ingest_records(cl, r->records);
563 cl->state = Client_Idle;
565 else if (*r->presentStatus)
567 yaz_log(YLOG_WARN, "Bad Present response");
568 cl->state = Client_Error;
572 static void handler(IOCHAN i, int event)
574 struct connection *co = iochan_getdata(i);
575 struct client *cl = co->client;
576 struct session *se = 0;
582 yaz_log(YLOG_WARN, "Destroying orphan connection");
583 connection_destroy(co);
587 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
590 socklen_t errlen = sizeof(errcode);
592 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
593 &errlen) < 0 || errcode != 0)
600 yaz_log(YLOG_DEBUG, "Connect OK");
601 co->state = Conn_Open;
603 cl->state = Client_Connected;
607 else if (event & EVENT_INPUT)
609 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
613 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
614 connection_destroy(co);
619 yaz_log(YLOG_WARN, "EOF reading from Z server");
620 connection_destroy(co);
623 else if (len > 1) // We discard input if we have no connection
625 co->state = Conn_Open;
627 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
631 odr_reset(global_parameters.odr_in);
632 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
633 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
640 case Z_APDU_initResponse:
641 do_initResponse(i, a);
643 case Z_APDU_searchResponse:
644 do_searchResponse(i, a);
646 case Z_APDU_presentResponse:
647 do_presentResponse(i, a);
650 yaz_log(YLOG_WARN, "Unexpected result from server");
654 // We aren't expecting staggered output from target
655 // if (cs_more(t->link))
656 // iochan_setevent(i, EVENT_INPUT);
658 else // we throw away response and go to idle mode
660 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
661 cl->state = Client_Idle;
664 /* if len==1 we do nothing but wait for more input */
667 if (cl->state == Client_Connected) {
671 if (cl->state == Client_Idle)
673 if (cl->requestid != se->requestid && *se->query) {
676 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
677 cl->records < cl->hits) {
683 // Disassociate connection from client
684 static void connection_release(struct connection *co)
686 struct client *cl = co->client;
688 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
695 // Close connection and recycle structure
696 static void connection_destroy(struct connection *co)
698 struct host *h = co->host;
700 iochan_destroy(co->iochan);
702 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
703 if (h->connections == co)
704 h->connections = co->next;
707 struct connection *pco;
708 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
711 pco->next = co->next;
717 if (co->client->state != Client_Idle)
718 co->client->state = Client_Disconnected;
719 co->client->connection = 0;
721 co->next = connection_freelist;
722 connection_freelist = co;
725 // Creates a new connection for client, associated with the host of
727 static struct connection *connection_create(struct client *cl)
729 struct connection *new;
734 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
735 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
737 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
741 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
743 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
747 res = cs_connect(link, addr);
750 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
754 if ((new = connection_freelist))
755 connection_freelist = new->next;
758 new = xmalloc(sizeof (struct connection));
762 new->state = Conn_Connecting;
763 new->host = cl->database->host;
764 new->next = new->host->connections;
765 new->host->connections = new;
767 cl->connection = new;
770 new->iochan = iochan_create(cs_fileno(link), handler, 0);
771 iochan_setdata(new->iochan, new);
772 new->iochan->next = channel_list;
773 channel_list = new->iochan;
777 // Close connection and set state to error
778 static void client_fatal(struct client *cl)
780 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
781 connection_destroy(cl->connection);
782 cl->state = Client_Error;
785 // Ensure that client has a connection associated
786 static int client_prep_connection(struct client *cl)
788 struct connection *co;
789 struct session *se = cl->session;
790 struct host *host = cl->database->host;
794 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
798 // See if someone else has an idle connection
799 // We should look at timestamps here to select the longest-idle connection
800 for (co = host->connections; co; co = co->next)
801 if (co->state == Conn_Open && (!co->client || co->client->session != se))
805 connection_release(co);
810 co = connection_create(cl);
814 if (co->state == Conn_Connecting)
816 cl->state = Client_Connecting;
817 iochan_setflag(co->iochan, EVENT_OUTPUT);
819 else if (co->state == Conn_Open)
821 if (cl->state == Client_Error || cl->state == Client_Disconnected)
822 cl->state = Client_Idle;
823 iochan_setflag(co->iochan, EVENT_OUTPUT);
831 // This function will most likely vanish when a proper target profile mechanism is
833 void load_simpletargets(const char *fn)
835 FILE *f = fopen(fn, "r");
840 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
844 while (fgets(line, 255, f))
848 struct database *database;
850 if (strncmp(line, "target ", 7))
853 url[strlen(url) - 1] = '\0';
854 yaz_log(YLOG_DEBUG, "Target: %s", url);
855 if ((db = strchr(url, '/')))
860 for (host = hosts; host; host = host->next)
861 if (!strcmp(url, host->hostport))
865 struct addrinfo *addrinfo, hints;
868 unsigned char addrbuf[4];
871 host = xmalloc(sizeof(struct host));
872 host->hostport = xstrdup(url);
873 host->connections = 0;
875 if ((port = strchr(url, ':')))
881 hints.ai_family = PF_INET;
882 hints.ai_socktype = SOCK_STREAM;
883 hints.ai_protocol = IPPROTO_TCP;
884 hints.ai_addrlen = 0;
886 hints.ai_canonname = 0;
888 // This is not robust code. It assumes that getaddrinfo returns AF_INET
890 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
892 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
893 xfree(host->hostport);
897 assert(addrinfo->ai_family == PF_INET);
898 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
899 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
900 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
901 host->ipport = xstrdup(ipport);
902 freeaddrinfo(addrinfo);
906 database = xmalloc(sizeof(struct database));
907 database->host = host;
908 database->url = xmalloc(strlen(url) + strlen(db) + 2);
909 strcpy(database->url, url);
910 strcat(database->url, "/");
911 strcat(database->url, db);
913 database->databases = xmalloc(2 * sizeof(char *));
914 database->databases[0] = xstrdup(db);
915 database->databases[1] = 0;
916 database->errors = 0;
917 database->qprofile = 0;
918 database->rprofile = database_retrieval_profile(database);
919 database->next = databases;
920 databases = database;
926 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
934 pull_terms(nmem, n->u.p[0], termlist, num);
935 pull_terms(nmem, n->u.p[1], termlist, num);
938 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
945 // Extract terms from query into null-terminated termlist
946 static int extract_terms(NMEM nmem, char *query, char **termlist)
949 struct ccl_rpn_node *n;
952 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
955 pull_terms(nmem, n, termlist, &num);
961 static struct client *client_create(void)
967 client_freelist = client_freelist->next;
970 r = xmalloc(sizeof(struct client));
979 r->state = Client_Disconnected;
984 void client_destroy(struct client *c)
986 struct session *se = c->session;
987 if (c == se->clients)
988 se->clients = c->next;
992 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
998 connection_release(c->connection);
999 c->next = client_freelist;
1000 client_freelist = c;
1003 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1005 s->watchlist[what].fun = fun;
1006 s->watchlist[what].data = data;
1009 void session_alert_watch(struct session *s, int what)
1011 if (!s->watchlist[what].fun)
1013 (*s->watchlist[what].fun)(s->watchlist[what].data);
1014 s->watchlist[what].fun = 0;
1015 s->watchlist[what].data = 0;
1018 // This needs to be extended with selection criteria
1019 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1023 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1026 if (!config->retrievalprofiles)
1028 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1030 return config->retrievalprofiles;
1033 // This should be extended with parameters to control selection criteria
1034 // Associates a set of clients with a session;
1035 int select_targets(struct session *se)
1037 struct database *db;
1041 client_destroy(se->clients);
1042 for (db = databases; db; db = db->next)
1044 struct client *cl = client_create();
1047 cl->next = se->clients;
1054 int session_active_clients(struct session *s)
1059 for (c = s->clients; c; c = c->next)
1060 if (c->connection && (c->state == Client_Connecting ||
1061 c->state == Client_Initializing ||
1062 c->state == Client_Searching ||
1063 c->state == Client_Presenting))
1069 char *search(struct session *se, char *query)
1071 int live_channels = 0;
1074 yaz_log(YLOG_DEBUG, "Search");
1076 strcpy(se->query, query);
1078 nmem_reset(se->nmem);
1079 for (cl = se->clients; cl; cl = cl->next)
1085 if (client_prep_connection(cl))
1091 int maxrecs = live_channels * global_parameters.toget;
1092 se->num_termlists = 0;
1093 se->reclist = reclist_create(se->nmem, maxrecs);
1094 extract_terms(se->nmem, query, p);
1095 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1096 se->total_records = se->total_hits = 0;
1097 se->expected_maxrecs = maxrecs;
1105 void destroy_session(struct session *s)
1107 yaz_log(YLOG_LOG, "Destroying session");
1109 client_destroy(s->clients);
1110 nmem_destroy(s->nmem);
1111 wrbuf_free(s->wrbuf, 1);
1114 struct session *new_session()
1117 struct session *session = xmalloc(sizeof(*session));
1119 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1121 session->total_hits = 0;
1122 session->total_records = 0;
1123 session->num_termlists = 0;
1124 session->reclist = 0;
1125 session->requestid = -1;
1126 session->clients = 0;
1127 session->expected_maxrecs = 0;
1128 session->query[0] = '\0';
1129 session->nmem = nmem_create();
1130 session->wrbuf = wrbuf_alloc();
1131 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1133 session->watchlist[i].data = 0;
1134 session->watchlist[i].fun = 0;
1137 select_targets(session);
1142 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1144 static struct hitsbytarget res[1000]; // FIXME MM
1148 for (cl = se->clients; cl; cl = cl->next)
1150 strcpy(res[*count].id, cl->database->host->hostport);
1151 res[*count].hits = cl->hits;
1152 res[*count].records = cl->records;
1153 res[*count].diagnostic = cl->diagnostic;
1154 res[*count].state = client_states[cl->state];
1155 res[*count].connected = cl->connection ? 1 : 0;
1162 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1166 for (i = 0; i < s->num_termlists; i++)
1167 if (!strcmp(s->termlists[i].name, name))
1168 return termlist_highscore(s->termlists[i].termlist, num);
1172 #ifdef MISSING_HEADERS
1173 void report_nmem_stats(void)
1175 size_t in_use, is_free;
1177 nmem_get_memory_in_use(&in_use);
1178 nmem_get_memory_free(&is_free);
1180 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1181 (long) in_use, (long) is_free);
1185 struct record **show(struct session *s, int start, int *num, int *total,
1186 int *sumhits, NMEM nmem_show)
1188 struct record **recs = nmem_malloc(nmem_show, *num
1189 * sizeof(struct record *));
1192 yaz_timing_t t = yaz_timing_create();
1194 relevance_prepare_read(s->relevance, s->reclist);
1196 *total = s->reclist->num_records;
1197 *sumhits = s->total_hits;
1199 for (i = 0; i < start; i++)
1200 if (!reclist_read_record(s->reclist))
1207 for (i = 0; i < *num; i++)
1209 struct record *r = reclist_read_record(s->reclist);
1219 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1220 yaz_timing_get_real(t), yaz_timing_get_user(t),
1221 yaz_timing_get_sys(t));
1222 yaz_timing_destroy(&t);
1227 void statistics(struct session *se, struct statistics *stat)
1232 bzero(stat, sizeof(*stat));
1233 for (cl = se->clients; cl; cl = cl->next)
1235 if (!cl->connection)
1236 stat->num_no_connection++;
1239 case Client_Connecting: stat->num_connecting++; break;
1240 case Client_Initializing: stat->num_initializing++; break;
1241 case Client_Searching: stat->num_searching++; break;
1242 case Client_Presenting: stat->num_presenting++; break;
1243 case Client_Idle: stat->num_idle++; break;
1244 case Client_Failed: stat->num_failed++; break;
1245 case Client_Error: stat->num_error++; break;
1250 stat->num_hits = se->total_hits;
1251 stat->num_records = se->total_records;
1253 stat->num_clients = count;
1256 static CCL_bibset load_cclfile(const char *fn)
1258 CCL_bibset res = ccl_qual_mk();
1259 if (ccl_qual_fname(res, fn) < 0)
1261 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1267 int main(int argc, char **argv)
1273 if (signal(SIGPIPE, SIG_IGN) < 0)
1274 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1276 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1278 while ((ret = options("f:x:c:h:p:C:s:d", argv, argc, &arg)) != -2)
1282 if (!read_config(arg))
1286 command_init(atoi(arg));
1294 global_parameters.ccl_filter = load_cclfile(arg);
1297 http_set_proxyaddr(arg);
1300 load_simpletargets(arg);
1303 global_parameters.dump_records = 1;
1306 fprintf(stderr, "Usage: pazpar2\n"
1308 " -h [host:]port (REST protocol listener)\n"
1309 " -c cmdport (telnet-style)\n"
1311 " -s simpletargetfile\n"
1312 " -p hostname[:portno] (HTTP proxy)\n");
1319 fprintf(stderr, "Set command port with -h or -c\n");
1323 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1324 global_parameters.yaz_marc = yaz_marc_create();
1325 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1326 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1327 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1329 event_loop(&channel_list);
1337 * indent-tabs-mode: nil
1339 * vim: shiftwidth=4 tabstop=8 expandtab