1 /* $Id: pazpar2.c,v 1.21 2007-01-09 18:06:28 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>
29 #include <yaz/timing.h>
35 #include "termlists.h"
37 #include "relevance.h"
42 static void client_fatal(struct client *cl);
43 static void connection_destroy(struct connection *co);
44 static int client_prep_connection(struct client *cl);
45 static void ingest_records(struct client *cl, Z_Records *r);
46 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
47 void session_alert_watch(struct session *s, int what);
49 IOCHAN channel_list = 0; // Master list of connections we're handling events to
51 static struct connection *connection_freelist = 0;
52 static struct client *client_freelist = 0;
54 static struct host *hosts = 0; // The hosts we know about
55 static struct database *databases = 0; // The databases we know about
57 static char *client_states[] = {
61 "Client_Initializing",
66 "Client_Disconnected",
70 // Note: Some things in this structure will eventually move to configuration
71 struct parameters global_parameters =
77 "Index Data PazPar2 (MasterKey)",
89 static int send_apdu(struct client *c, Z_APDU *a)
91 struct connection *co = c->connection;
95 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
97 odr_perror(global_parameters.odr_out, "Encoding APDU");
100 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
101 r = cs_put(co->link, buf, len);
104 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
109 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
112 odr_reset(global_parameters.odr_out); /* release the APDU structure */
113 co->state = Conn_Waiting;
118 static void send_init(IOCHAN i)
120 struct connection *co = iochan_getdata(i);
121 struct client *cl = co->client;
122 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
124 a->u.initRequest->implementationId = global_parameters.implementationId;
125 a->u.initRequest->implementationName = global_parameters.implementationName;
126 a->u.initRequest->implementationVersion =
127 global_parameters.implementationVersion;
128 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
129 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
130 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
132 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
133 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
134 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
135 if (send_apdu(cl, a) >= 0)
137 iochan_setflags(i, EVENT_INPUT);
138 cl->state = Client_Initializing;
141 cl->state = Client_Error;
142 odr_reset(global_parameters.odr_out);
145 static void send_search(IOCHAN i)
147 struct connection *co = iochan_getdata(i);
148 struct client *cl = co->client;
149 struct session *se = cl->session;
150 struct database *db = cl->database;
151 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
152 int ndb, cerror, cpos;
155 struct ccl_rpn_node *cn;
156 int ssub = 0, lslb = 100000, mspn = 10;
158 yaz_log(YLOG_DEBUG, "Sending search");
160 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
163 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
165 zquery->which = Z_Query_type_1;
166 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
169 for (ndb = 0; db->databases[ndb]; ndb++)
171 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
172 for (ndb = 0; db->databases[ndb]; ndb++)
173 databaselist[ndb] = db->databases[ndb];
175 a->u.presentRequest->preferredRecordSyntax =
176 yaz_oidval_to_z3950oid(global_parameters.odr_out,
177 CLASS_RECSYN, VAL_USMARC);
178 a->u.searchRequest->smallSetUpperBound = &ssub;
179 a->u.searchRequest->largeSetLowerBound = &lslb;
180 a->u.searchRequest->mediumSetPresentNumber = &mspn;
181 a->u.searchRequest->resultSetName = "Default";
182 a->u.searchRequest->databaseNames = databaselist;
183 a->u.searchRequest->num_databaseNames = ndb;
185 if (send_apdu(cl, a) >= 0)
187 iochan_setflags(i, EVENT_INPUT);
188 cl->state = Client_Searching;
189 cl->requestid = se->requestid;
192 cl->state = Client_Error;
194 odr_reset(global_parameters.odr_out);
197 static void send_present(IOCHAN i)
199 struct connection *co = iochan_getdata(i);
200 struct client *cl = co->client;
201 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
203 int start = cl->records + 1;
205 toget = global_parameters.chunk;
206 if (toget > global_parameters.toget - cl->records)
207 toget = global_parameters.toget - cl->records;
208 if (toget > cl->hits - cl->records)
209 toget = cl->hits - cl->records;
211 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
213 a->u.presentRequest->resultSetStartPoint = &start;
214 a->u.presentRequest->numberOfRecordsRequested = &toget;
216 a->u.presentRequest->resultSetId = "Default";
218 a->u.presentRequest->preferredRecordSyntax =
219 yaz_oidval_to_z3950oid(global_parameters.odr_out,
220 CLASS_RECSYN, VAL_USMARC);
222 if (send_apdu(cl, a) >= 0)
224 iochan_setflags(i, EVENT_INPUT);
225 cl->state = Client_Presenting;
228 cl->state = Client_Error;
229 odr_reset(global_parameters.odr_out);
232 static void do_initResponse(IOCHAN i, Z_APDU *a)
234 struct connection *co = iochan_getdata(i);
235 struct client *cl = co->client;
236 Z_InitResponse *r = a->u.initResponse;
238 yaz_log(YLOG_DEBUG, "Received init response");
242 cl->state = Client_Idle;
245 cl->state = Client_Failed; // FIXME need to do something to the connection
248 static void do_searchResponse(IOCHAN i, Z_APDU *a)
250 struct connection *co = iochan_getdata(i);
251 struct client *cl = co->client;
252 struct session *se = cl->session;
253 Z_SearchResponse *r = a->u.searchResponse;
255 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
257 if (*r->searchStatus)
259 cl->hits = *r->resultCount;
260 se->total_hits += cl->hits;
261 if (r->presentStatus && !*r->presentStatus && r->records)
263 yaz_log(YLOG_DEBUG, "Records in search response");
264 cl->records += *r->numberOfRecordsReturned;
265 ingest_records(cl, r->records);
267 cl->state = Client_Idle;
272 cl->state = Client_Error;
274 Z_Records *recs = r->records;
275 if (recs->which == Z_Records_NSD)
277 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
278 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
279 cl->state = Client_Error;
285 char *normalize_mergekey(char *buf)
287 char *p = buf, *pout = buf;
291 while (*p && !isalnum(*p))
294 *(pout++) = tolower(*(p++));
297 while (*p && !isalnum(*p))
308 // FIXME needs to be generalized. Should flexibly generate X lists per search
309 static void extract_subject(struct session *s, const char *rec)
311 const char *field, *subfield;
313 while ((field = find_field(rec, "650")))
316 if ((subfield = find_subfield(field, 'a')))
322 ef = index(subfield, '\n');
325 if ((e = index(subfield, '\t')) && e < ef)
327 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
331 memcpy(buf, subfield, len);
335 termlist_insert(s->termlist, buf);
342 static void add_facet(struct session *s, const char *type, const char *value)
346 for (i = 0; i < s->num_termlists; i++)
347 if (!strcmp(s->termlists[i].name, type))
349 if (i == s->num_termlists)
351 if (i == SESSION_MAX_TERMLISTS)
353 yaz_log(YLOG_FATAL, "Too many termlists");
356 s->termlists[i].name = nmem_strdup(s->nmem, type);
357 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
358 s->num_termlists = i + 1;
360 termlist_insert(s->termlists[i].termlist, value);
363 int yaz_marc_write_xml();
365 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
367 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
368 struct conf_retrievalmap *m;
372 // First normalize to XML
373 if (rprofile->native_syntax == Nativesyn_iso2709)
377 if (rec->which != Z_External_octet)
379 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
382 buf = (char*) rec->u.octet_aligned->buf;
383 len = rec->u.octet_aligned->len;
384 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
386 yaz_log(YLOG_WARN, "Failed to decode MARC");
389 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
390 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
392 yaz_log(YLOG_WARN, "Failed to encode as XML");
395 rdoc = xmlNewDoc("1.0");
396 xmlDocSetRootElement(rdoc, res);
400 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
403 for (m = rprofile->maplist; m; m = m->next)
406 if (m->type != Map_xslt)
408 yaz_log(YLOG_WARN, "Unknown map type");
411 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
413 yaz_log(YLOG_WARN, "XSLT transformation failed");
419 if (global_parameters.dump_records)
421 fprintf(stderr, "Record:\n----------------\n");
422 xmlDocFormatDump(stderr, rdoc, 1);
427 // Extract what appears to be years from buf, storing highest and
429 static int extract_years(const char *buf, int *first, int *last)
438 while (*buf && !isdigit(*buf))
441 for (e = buf; *e && isdigit(*e); e++)
445 int value = atoi(buf);
446 if (*first < 0 || value < *first)
448 if (*last < 0 || value > *last)
456 static struct record *ingest_record(struct client *cl, Z_External *rec)
458 xmlDoc *xdoc = normalize_record(cl, rec);
461 struct record_cluster *cluster;
462 struct session *se = cl->session;
463 xmlChar *mergekey, *mergekey_norm;
466 struct conf_service *service = global_parameters.server->service;
471 root = xmlDocGetRootElement(xdoc);
472 if (!(mergekey = xmlGetProp(root, "mergekey")))
474 yaz_log(YLOG_WARN, "No mergekey found in record");
479 res = nmem_malloc(se->nmem, sizeof(struct record));
481 res->target_offset = -1;
482 res->term_frequency_vec = 0;
483 res->metadata = nmem_malloc(se->nmem,
484 sizeof(struct record_metadata*) * service->num_metadata);
485 bzero(res->metadata, sizeof(struct record_metadata*) * service->num_metadata);
488 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
490 normalize_mergekey(mergekey_norm);
492 cluster = reclist_insert(se->reclist, res, mergekey_norm);
495 /* no room for record */
499 relevance_newrec(se->relevance, cluster);
502 for (n = root->children; n; n = n->next)
510 if (n->type != XML_ELEMENT_NODE)
512 if (!strcmp(n->name, "metadata"))
514 type = xmlGetProp(n, "type");
515 value = xmlNodeListGetString(xdoc, n->children, 0);
516 struct conf_metadata *md = 0;
517 struct record_metadata **wheretoput, *newm;
521 // First, find out what field we're looking at
522 for (imeta = 0; imeta < service->num_metadata; imeta++)
523 if (!strcmp(type, service->metadata[imeta].name))
525 md = &service->metadata[imeta];
530 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
534 // Find out where we are putting it
535 if (md->merge == Metadata_merge_no)
536 wheretoput = &res->metadata[imeta];
538 wheretoput = &cluster->metadata[imeta];
541 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
543 if (md->type == Metadata_type_generic)
545 newm->data.text = nmem_strdup(se->nmem, value);
547 else if (md->type == Metadata_type_year)
549 if (extract_years(value, &first, &last) < 0)
554 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
557 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
559 yaz_log(YLOG_WARN, "Only range merging supported for years");
562 if (md->merge == Metadata_merge_unique)
564 struct record_metadata *mnode;
565 for (mnode = *wheretoput; mnode; mnode = mnode->next)
566 if (!strcmp(mnode->data.text, mnode->data.text))
570 newm->next = *wheretoput;
574 else if (md->merge == Metadata_merge_longest)
577 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
580 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
582 newm->next = *wheretoput;
585 else if (md->merge == Metadata_merge_range)
587 assert(md->type == Metadata_type_year);
591 (*wheretoput)->data.year.year1 = first;
592 (*wheretoput)->data.year.year2 = last;
596 if (first < (*wheretoput)->data.year.year1)
597 (*wheretoput)->data.year.year1 = first;
598 if (last > (*wheretoput)->data.year.year2)
599 (*wheretoput)->data.year.year2 = last;
603 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
606 relevance_countwords(se->relevance, cluster, value, md->rank);
608 add_facet(se, type, value);
614 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
619 relevance_donerecord(se->relevance, cluster);
625 static void ingest_records(struct client *cl, Z_Records *r)
628 yaz_timing_t t = yaz_timing_create();
631 struct session *s = cl->session;
632 Z_NamePlusRecordList *rlist;
635 if (r->which != Z_Records_DBOSD)
637 rlist = r->u.databaseOrSurDiagnostics;
638 for (i = 0; i < rlist->num_records; i++)
640 Z_NamePlusRecord *npr = rlist->records[i];
642 if (npr->which != Z_NamePlusRecord_databaseRecord)
644 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
648 rec = ingest_record(cl, npr->u.databaseRecord);
652 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
653 session_alert_watch(s, SESSION_WATCH_RECORDS);
657 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
658 yaz_timing_get_real(t), yaz_timing_get_user(t),
659 yaz_timing_get_sys(t));
660 yaz_timing_destroy(&t);
664 static void do_presentResponse(IOCHAN i, Z_APDU *a)
666 struct connection *co = iochan_getdata(i);
667 struct client *cl = co->client;
668 Z_PresentResponse *r = a->u.presentResponse;
671 Z_Records *recs = r->records;
672 if (recs->which == Z_Records_NSD)
674 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
675 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
676 cl->state = Client_Error;
680 if (!*r->presentStatus && cl->state != Client_Error)
682 yaz_log(YLOG_DEBUG, "Good Present response");
683 cl->records += *r->numberOfRecordsReturned;
684 ingest_records(cl, r->records);
685 cl->state = Client_Idle;
687 else if (*r->presentStatus)
689 yaz_log(YLOG_WARN, "Bad Present response");
690 cl->state = Client_Error;
694 static void handler(IOCHAN i, int event)
696 struct connection *co = iochan_getdata(i);
697 struct client *cl = co->client;
698 struct session *se = 0;
704 yaz_log(YLOG_WARN, "Destroying orphan connection");
705 connection_destroy(co);
709 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
712 socklen_t errlen = sizeof(errcode);
714 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
715 &errlen) < 0 || errcode != 0)
722 yaz_log(YLOG_DEBUG, "Connect OK");
723 co->state = Conn_Open;
725 cl->state = Client_Connected;
729 else if (event & EVENT_INPUT)
731 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
735 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
736 connection_destroy(co);
741 yaz_log(YLOG_WARN, "EOF reading from Z server");
742 connection_destroy(co);
745 else if (len > 1) // We discard input if we have no connection
747 co->state = Conn_Open;
749 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
753 odr_reset(global_parameters.odr_in);
754 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
755 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
762 case Z_APDU_initResponse:
763 do_initResponse(i, a);
765 case Z_APDU_searchResponse:
766 do_searchResponse(i, a);
768 case Z_APDU_presentResponse:
769 do_presentResponse(i, a);
772 yaz_log(YLOG_WARN, "Unexpected result from server");
776 // We aren't expecting staggered output from target
777 // if (cs_more(t->link))
778 // iochan_setevent(i, EVENT_INPUT);
780 else // we throw away response and go to idle mode
782 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
783 cl->state = Client_Idle;
786 /* if len==1 we do nothing but wait for more input */
789 if (cl->state == Client_Connected) {
793 if (cl->state == Client_Idle)
795 if (cl->requestid != se->requestid && *se->query) {
798 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
799 cl->records < cl->hits) {
805 // Disassociate connection from client
806 static void connection_release(struct connection *co)
808 struct client *cl = co->client;
810 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
817 // Close connection and recycle structure
818 static void connection_destroy(struct connection *co)
820 struct host *h = co->host;
822 iochan_destroy(co->iochan);
824 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
825 if (h->connections == co)
826 h->connections = co->next;
829 struct connection *pco;
830 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
833 pco->next = co->next;
839 if (co->client->state != Client_Idle)
840 co->client->state = Client_Disconnected;
841 co->client->connection = 0;
843 co->next = connection_freelist;
844 connection_freelist = co;
847 // Creates a new connection for client, associated with the host of
849 static struct connection *connection_create(struct client *cl)
851 struct connection *new;
856 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
857 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
859 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
863 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
865 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
869 res = cs_connect(link, addr);
872 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
876 if ((new = connection_freelist))
877 connection_freelist = new->next;
880 new = xmalloc(sizeof (struct connection));
884 new->state = Conn_Connecting;
885 new->host = cl->database->host;
886 new->next = new->host->connections;
887 new->host->connections = new;
889 cl->connection = new;
892 new->iochan = iochan_create(cs_fileno(link), handler, 0);
893 iochan_setdata(new->iochan, new);
894 new->iochan->next = channel_list;
895 channel_list = new->iochan;
899 // Close connection and set state to error
900 static void client_fatal(struct client *cl)
902 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
903 connection_destroy(cl->connection);
904 cl->state = Client_Error;
907 // Ensure that client has a connection associated
908 static int client_prep_connection(struct client *cl)
910 struct connection *co;
911 struct session *se = cl->session;
912 struct host *host = cl->database->host;
916 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
920 // See if someone else has an idle connection
921 // We should look at timestamps here to select the longest-idle connection
922 for (co = host->connections; co; co = co->next)
923 if (co->state == Conn_Open && (!co->client || co->client->session != se))
927 connection_release(co);
932 co = connection_create(cl);
936 if (co->state == Conn_Connecting)
938 cl->state = Client_Connecting;
939 iochan_setflag(co->iochan, EVENT_OUTPUT);
941 else if (co->state == Conn_Open)
943 if (cl->state == Client_Error || cl->state == Client_Disconnected)
944 cl->state = Client_Idle;
945 iochan_setflag(co->iochan, EVENT_OUTPUT);
953 // This function will most likely vanish when a proper target profile mechanism is
955 void load_simpletargets(const char *fn)
957 FILE *f = fopen(fn, "r");
962 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
966 while (fgets(line, 255, f))
970 struct database *database;
972 if (strncmp(line, "target ", 7))
975 url[strlen(url) - 1] = '\0';
976 yaz_log(YLOG_DEBUG, "Target: %s", url);
977 if ((db = strchr(url, '/')))
982 for (host = hosts; host; host = host->next)
983 if (!strcmp(url, host->hostport))
987 struct addrinfo *addrinfo, hints;
990 unsigned char addrbuf[4];
993 host = xmalloc(sizeof(struct host));
994 host->hostport = xstrdup(url);
995 host->connections = 0;
997 if ((port = strchr(url, ':')))
1003 hints.ai_family = PF_INET;
1004 hints.ai_socktype = SOCK_STREAM;
1005 hints.ai_protocol = IPPROTO_TCP;
1006 hints.ai_addrlen = 0;
1008 hints.ai_canonname = 0;
1010 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1012 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1014 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1015 xfree(host->hostport);
1019 assert(addrinfo->ai_family == PF_INET);
1020 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1021 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
1022 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1023 host->ipport = xstrdup(ipport);
1024 freeaddrinfo(addrinfo);
1028 database = xmalloc(sizeof(struct database));
1029 database->host = host;
1030 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1031 strcpy(database->url, url);
1032 strcat(database->url, "/");
1033 strcat(database->url, db);
1035 database->databases = xmalloc(2 * sizeof(char *));
1036 database->databases[0] = xstrdup(db);
1037 database->databases[1] = 0;
1038 database->errors = 0;
1039 database->qprofile = 0;
1040 database->rprofile = database_retrieval_profile(database);
1041 database->next = databases;
1042 databases = database;
1048 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1056 pull_terms(nmem, n->u.p[0], termlist, num);
1057 pull_terms(nmem, n->u.p[1], termlist, num);
1060 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1067 // Extract terms from query into null-terminated termlist
1068 static int extract_terms(NMEM nmem, char *query, char **termlist)
1071 struct ccl_rpn_node *n;
1074 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1077 pull_terms(nmem, n, termlist, &num);
1083 static struct client *client_create(void)
1086 if (client_freelist)
1088 r = client_freelist;
1089 client_freelist = client_freelist->next;
1092 r = xmalloc(sizeof(struct client));
1101 r->state = Client_Disconnected;
1106 void client_destroy(struct client *c)
1108 struct session *se = c->session;
1109 if (c == se->clients)
1110 se->clients = c->next;
1114 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1120 connection_release(c->connection);
1121 c->next = client_freelist;
1122 client_freelist = c;
1125 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1127 s->watchlist[what].fun = fun;
1128 s->watchlist[what].data = data;
1131 void session_alert_watch(struct session *s, int what)
1133 if (!s->watchlist[what].fun)
1135 (*s->watchlist[what].fun)(s->watchlist[what].data);
1136 s->watchlist[what].fun = 0;
1137 s->watchlist[what].data = 0;
1140 // This needs to be extended with selection criteria
1141 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1145 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1148 if (!config->retrievalprofiles)
1150 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1152 return config->retrievalprofiles;
1155 // This should be extended with parameters to control selection criteria
1156 // Associates a set of clients with a session;
1157 int select_targets(struct session *se)
1159 struct database *db;
1163 client_destroy(se->clients);
1164 for (db = databases; db; db = db->next)
1166 struct client *cl = client_create();
1169 cl->next = se->clients;
1176 int session_active_clients(struct session *s)
1181 for (c = s->clients; c; c = c->next)
1182 if (c->connection && (c->state == Client_Connecting ||
1183 c->state == Client_Initializing ||
1184 c->state == Client_Searching ||
1185 c->state == Client_Presenting))
1191 char *search(struct session *se, char *query)
1193 int live_channels = 0;
1196 yaz_log(YLOG_DEBUG, "Search");
1198 strcpy(se->query, query);
1200 nmem_reset(se->nmem);
1201 for (cl = se->clients; cl; cl = cl->next)
1207 if (client_prep_connection(cl))
1213 int maxrecs = live_channels * global_parameters.toget;
1214 se->num_termlists = 0;
1215 se->reclist = reclist_create(se->nmem, maxrecs);
1216 extract_terms(se->nmem, query, p);
1217 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1218 se->total_records = se->total_hits = 0;
1219 se->expected_maxrecs = maxrecs;
1227 void destroy_session(struct session *s)
1229 yaz_log(YLOG_LOG, "Destroying session");
1231 client_destroy(s->clients);
1232 nmem_destroy(s->nmem);
1233 wrbuf_free(s->wrbuf, 1);
1236 struct session *new_session()
1239 struct session *session = xmalloc(sizeof(*session));
1241 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1243 session->total_hits = 0;
1244 session->total_records = 0;
1245 session->num_termlists = 0;
1246 session->reclist = 0;
1247 session->requestid = -1;
1248 session->clients = 0;
1249 session->expected_maxrecs = 0;
1250 session->query[0] = '\0';
1251 session->nmem = nmem_create();
1252 session->wrbuf = wrbuf_alloc();
1253 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1255 session->watchlist[i].data = 0;
1256 session->watchlist[i].fun = 0;
1259 select_targets(session);
1264 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1266 static struct hitsbytarget res[1000]; // FIXME MM
1270 for (cl = se->clients; cl; cl = cl->next)
1272 strcpy(res[*count].id, cl->database->host->hostport);
1273 res[*count].hits = cl->hits;
1274 res[*count].records = cl->records;
1275 res[*count].diagnostic = cl->diagnostic;
1276 res[*count].state = client_states[cl->state];
1277 res[*count].connected = cl->connection ? 1 : 0;
1284 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1288 for (i = 0; i < s->num_termlists; i++)
1289 if (!strcmp(s->termlists[i].name, name))
1290 return termlist_highscore(s->termlists[i].termlist, num);
1294 #ifdef MISSING_HEADERS
1295 void report_nmem_stats(void)
1297 size_t in_use, is_free;
1299 nmem_get_memory_in_use(&in_use);
1300 nmem_get_memory_free(&is_free);
1302 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1303 (long) in_use, (long) is_free);
1307 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1308 int *sumhits, NMEM nmem_show)
1310 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1311 * sizeof(struct record_cluster *));
1314 yaz_timing_t t = yaz_timing_create();
1316 relevance_prepare_read(s->relevance, s->reclist);
1318 *total = s->reclist->num_records;
1319 *sumhits = s->total_hits;
1321 for (i = 0; i < start; i++)
1322 if (!reclist_read_record(s->reclist))
1329 for (i = 0; i < *num; i++)
1331 struct record_cluster *r = reclist_read_record(s->reclist);
1341 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1342 yaz_timing_get_real(t), yaz_timing_get_user(t),
1343 yaz_timing_get_sys(t));
1344 yaz_timing_destroy(&t);
1349 void statistics(struct session *se, struct statistics *stat)
1354 bzero(stat, sizeof(*stat));
1355 for (cl = se->clients; cl; cl = cl->next)
1357 if (!cl->connection)
1358 stat->num_no_connection++;
1361 case Client_Connecting: stat->num_connecting++; break;
1362 case Client_Initializing: stat->num_initializing++; break;
1363 case Client_Searching: stat->num_searching++; break;
1364 case Client_Presenting: stat->num_presenting++; break;
1365 case Client_Idle: stat->num_idle++; break;
1366 case Client_Failed: stat->num_failed++; break;
1367 case Client_Error: stat->num_error++; break;
1372 stat->num_hits = se->total_hits;
1373 stat->num_records = se->total_records;
1375 stat->num_clients = count;
1378 static CCL_bibset load_cclfile(const char *fn)
1380 CCL_bibset res = ccl_qual_mk();
1381 if (ccl_qual_fname(res, fn) < 0)
1383 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1389 int main(int argc, char **argv)
1395 if (signal(SIGPIPE, SIG_IGN) < 0)
1396 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1398 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1400 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1404 if (!read_config(arg))
1412 global_parameters.ccl_filter = load_cclfile(arg);
1415 http_set_proxyaddr(arg);
1418 load_simpletargets(arg);
1421 global_parameters.dump_records = 1;
1424 fprintf(stderr, "Usage: pazpar2\n"
1426 " -h [host:]port (REST protocol listener)\n"
1428 " -s simpletargetfile\n"
1429 " -p hostname[:portno] (HTTP proxy)\n");
1436 yaz_log(YLOG_FATAL, "Load config with -f");
1439 global_parameters.server = config->servers;
1443 fprintf(stderr, "Set command port with -h\n");
1447 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1448 global_parameters.yaz_marc = yaz_marc_create();
1449 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1450 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1451 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1453 event_loop(&channel_list);
1461 * indent-tabs-mode: nil
1463 * vim: shiftwidth=4 tabstop=8 expandtab