1 /* $Id: pazpar2.c,v 1.25 2007-01-10 10:48:27 adam 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->metadata = nmem_malloc(se->nmem,
482 sizeof(struct record_metadata*) * service->num_metadata);
483 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
485 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
487 normalize_mergekey(mergekey_norm);
489 cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
492 /* no room for record */
496 relevance_newrec(se->relevance, cluster);
499 for (n = root->children; n; n = n->next)
507 if (n->type != XML_ELEMENT_NODE)
509 if (!strcmp(n->name, "metadata"))
511 type = xmlGetProp(n, "type");
512 value = xmlNodeListGetString(xdoc, n->children, 0);
513 struct conf_metadata *md = 0;
514 struct record_metadata **wheretoput, *newm;
518 // First, find out what field we're looking at
519 for (imeta = 0; imeta < service->num_metadata; imeta++)
520 if (!strcmp(type, service->metadata[imeta].name))
522 md = &service->metadata[imeta];
527 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
531 // Find out where we are putting it
532 if (md->merge == Metadata_merge_no)
533 wheretoput = &res->metadata[imeta];
535 wheretoput = &cluster->metadata[imeta];
538 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
540 if (md->type == Metadata_type_generic)
542 newm->data.text = nmem_strdup(se->nmem, value);
544 else if (md->type == Metadata_type_year)
546 if (extract_years(value, &first, &last) < 0)
551 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
554 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
556 yaz_log(YLOG_WARN, "Only range merging supported for years");
559 if (md->merge == Metadata_merge_unique)
561 struct record_metadata *mnode;
562 for (mnode = *wheretoput; mnode; mnode = mnode->next)
563 if (!strcmp(mnode->data.text, mnode->data.text))
567 newm->next = *wheretoput;
571 else if (md->merge == Metadata_merge_longest)
574 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
577 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
579 newm->next = *wheretoput;
582 else if (md->merge == Metadata_merge_range)
584 assert(md->type == Metadata_type_year);
588 (*wheretoput)->data.year.year1 = first;
589 (*wheretoput)->data.year.year2 = last;
593 if (first < (*wheretoput)->data.year.year1)
594 (*wheretoput)->data.year.year1 = first;
595 if (last > (*wheretoput)->data.year.year2)
596 (*wheretoput)->data.year.year2 = last;
600 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
603 relevance_countwords(se->relevance, cluster, value, md->rank);
605 add_facet(se, type, value);
611 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
616 relevance_donerecord(se->relevance, cluster);
622 static void ingest_records(struct client *cl, Z_Records *r)
625 yaz_timing_t t = yaz_timing_create();
628 struct session *s = cl->session;
629 Z_NamePlusRecordList *rlist;
632 if (r->which != Z_Records_DBOSD)
634 rlist = r->u.databaseOrSurDiagnostics;
635 for (i = 0; i < rlist->num_records; i++)
637 Z_NamePlusRecord *npr = rlist->records[i];
639 if (npr->which != Z_NamePlusRecord_databaseRecord)
641 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
645 rec = ingest_record(cl, npr->u.databaseRecord);
649 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
650 session_alert_watch(s, SESSION_WATCH_RECORDS);
654 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
655 yaz_timing_get_real(t), yaz_timing_get_user(t),
656 yaz_timing_get_sys(t));
657 yaz_timing_destroy(&t);
661 static void do_presentResponse(IOCHAN i, Z_APDU *a)
663 struct connection *co = iochan_getdata(i);
664 struct client *cl = co->client;
665 Z_PresentResponse *r = a->u.presentResponse;
668 Z_Records *recs = r->records;
669 if (recs->which == Z_Records_NSD)
671 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
672 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
673 cl->state = Client_Error;
677 if (!*r->presentStatus && cl->state != Client_Error)
679 yaz_log(YLOG_DEBUG, "Good Present response");
680 cl->records += *r->numberOfRecordsReturned;
681 ingest_records(cl, r->records);
682 cl->state = Client_Idle;
684 else if (*r->presentStatus)
686 yaz_log(YLOG_WARN, "Bad Present response");
687 cl->state = Client_Error;
691 static void handler(IOCHAN i, int event)
693 struct connection *co = iochan_getdata(i);
694 struct client *cl = co->client;
695 struct session *se = 0;
701 yaz_log(YLOG_WARN, "Destroying orphan connection");
702 connection_destroy(co);
706 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
709 socklen_t errlen = sizeof(errcode);
711 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
712 &errlen) < 0 || errcode != 0)
719 yaz_log(YLOG_DEBUG, "Connect OK");
720 co->state = Conn_Open;
722 cl->state = Client_Connected;
726 else if (event & EVENT_INPUT)
728 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
732 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
733 connection_destroy(co);
738 yaz_log(YLOG_WARN, "EOF reading from Z server");
739 connection_destroy(co);
742 else if (len > 1) // We discard input if we have no connection
744 co->state = Conn_Open;
746 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
750 odr_reset(global_parameters.odr_in);
751 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
752 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
759 case Z_APDU_initResponse:
760 do_initResponse(i, a);
762 case Z_APDU_searchResponse:
763 do_searchResponse(i, a);
765 case Z_APDU_presentResponse:
766 do_presentResponse(i, a);
769 yaz_log(YLOG_WARN, "Unexpected result from server");
773 // We aren't expecting staggered output from target
774 // if (cs_more(t->link))
775 // iochan_setevent(i, EVENT_INPUT);
777 else // we throw away response and go to idle mode
779 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
780 cl->state = Client_Idle;
783 /* if len==1 we do nothing but wait for more input */
786 if (cl->state == Client_Connected) {
790 if (cl->state == Client_Idle)
792 if (cl->requestid != se->requestid && *se->query) {
795 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
796 cl->records < cl->hits) {
802 // Disassociate connection from client
803 static void connection_release(struct connection *co)
805 struct client *cl = co->client;
807 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
814 // Close connection and recycle structure
815 static void connection_destroy(struct connection *co)
817 struct host *h = co->host;
819 iochan_destroy(co->iochan);
821 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
822 if (h->connections == co)
823 h->connections = co->next;
826 struct connection *pco;
827 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
830 pco->next = co->next;
836 if (co->client->state != Client_Idle)
837 co->client->state = Client_Disconnected;
838 co->client->connection = 0;
840 co->next = connection_freelist;
841 connection_freelist = co;
844 // Creates a new connection for client, associated with the host of
846 static struct connection *connection_create(struct client *cl)
848 struct connection *new;
853 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
854 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
856 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
860 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
862 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?",
863 cl->database->host->ipport);
867 res = cs_connect(link, addr);
870 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
874 if ((new = connection_freelist))
875 connection_freelist = new->next;
878 new = xmalloc(sizeof (struct connection));
882 new->state = Conn_Connecting;
883 new->host = cl->database->host;
884 new->next = new->host->connections;
885 new->host->connections = new;
887 cl->connection = new;
890 new->iochan = iochan_create(cs_fileno(link), handler, 0);
891 iochan_setdata(new->iochan, new);
892 new->iochan->next = channel_list;
893 channel_list = new->iochan;
897 // Close connection and set state to error
898 static void client_fatal(struct client *cl)
900 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
901 connection_destroy(cl->connection);
902 cl->state = Client_Error;
905 // Ensure that client has a connection associated
906 static int client_prep_connection(struct client *cl)
908 struct connection *co;
909 struct session *se = cl->session;
910 struct host *host = cl->database->host;
914 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
918 // See if someone else has an idle connection
919 // We should look at timestamps here to select the longest-idle connection
920 for (co = host->connections; co; co = co->next)
921 if (co->state == Conn_Open && (!co->client || co->client->session != se))
925 connection_release(co);
930 co = connection_create(cl);
934 if (co->state == Conn_Connecting)
936 cl->state = Client_Connecting;
937 iochan_setflag(co->iochan, EVENT_OUTPUT);
939 else if (co->state == Conn_Open)
941 if (cl->state == Client_Error || cl->state == Client_Disconnected)
942 cl->state = Client_Idle;
943 iochan_setflag(co->iochan, EVENT_OUTPUT);
951 // This function will most likely vanish when a proper target profile mechanism is
953 void load_simpletargets(const char *fn)
955 FILE *f = fopen(fn, "r");
960 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
964 while (fgets(line, 255, f))
968 struct database *database;
970 if (strncmp(line, "target ", 7))
973 url[strlen(url) - 1] = '\0';
974 yaz_log(YLOG_DEBUG, "Target: %s", url);
975 if ((db = strchr(url, '/')))
980 for (host = hosts; host; host = host->next)
981 if (!strcmp(url, host->hostport))
985 struct addrinfo *addrinfo, hints;
988 unsigned char addrbuf[4];
991 host = xmalloc(sizeof(struct host));
992 host->hostport = xstrdup(url);
993 host->connections = 0;
995 if ((port = strchr(url, ':')))
1001 hints.ai_family = PF_INET;
1002 hints.ai_socktype = SOCK_STREAM;
1003 hints.ai_protocol = IPPROTO_TCP;
1004 hints.ai_addrlen = 0;
1006 hints.ai_canonname = 0;
1008 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1010 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1012 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1013 xfree(host->hostport);
1017 assert(addrinfo->ai_family == PF_INET);
1018 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1019 sprintf(ipport, "%u.%u.%u.%u:%s",
1020 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1021 host->ipport = xstrdup(ipport);
1022 freeaddrinfo(addrinfo);
1026 database = xmalloc(sizeof(struct database));
1027 database->host = host;
1028 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1029 strcpy(database->url, url);
1030 strcat(database->url, "/");
1031 strcat(database->url, db);
1033 database->databases = xmalloc(2 * sizeof(char *));
1034 database->databases[0] = xstrdup(db);
1035 database->databases[1] = 0;
1036 database->errors = 0;
1037 database->qprofile = 0;
1038 database->rprofile = database_retrieval_profile(database);
1039 database->next = databases;
1040 databases = database;
1046 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1054 pull_terms(nmem, n->u.p[0], termlist, num);
1055 pull_terms(nmem, n->u.p[1], termlist, num);
1058 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1065 // Extract terms from query into null-terminated termlist
1066 static int extract_terms(NMEM nmem, char *query, char **termlist)
1069 struct ccl_rpn_node *n;
1072 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1075 pull_terms(nmem, n, termlist, &num);
1081 static struct client *client_create(void)
1084 if (client_freelist)
1086 r = client_freelist;
1087 client_freelist = client_freelist->next;
1090 r = xmalloc(sizeof(struct client));
1099 r->state = Client_Disconnected;
1104 void client_destroy(struct client *c)
1106 struct session *se = c->session;
1107 if (c == se->clients)
1108 se->clients = c->next;
1112 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1118 connection_release(c->connection);
1119 c->next = client_freelist;
1120 client_freelist = c;
1123 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1125 s->watchlist[what].fun = fun;
1126 s->watchlist[what].data = data;
1129 void session_alert_watch(struct session *s, int what)
1131 if (!s->watchlist[what].fun)
1133 (*s->watchlist[what].fun)(s->watchlist[what].data);
1134 s->watchlist[what].fun = 0;
1135 s->watchlist[what].data = 0;
1138 // This needs to be extended with selection criteria
1139 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1143 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1146 if (!config->retrievalprofiles)
1148 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1150 return config->retrievalprofiles;
1153 // This should be extended with parameters to control selection criteria
1154 // Associates a set of clients with a session;
1155 int select_targets(struct session *se)
1157 struct database *db;
1161 client_destroy(se->clients);
1162 for (db = databases; db; db = db->next)
1164 struct client *cl = client_create();
1167 cl->next = se->clients;
1174 int session_active_clients(struct session *s)
1179 for (c = s->clients; c; c = c->next)
1180 if (c->connection && (c->state == Client_Connecting ||
1181 c->state == Client_Initializing ||
1182 c->state == Client_Searching ||
1183 c->state == Client_Presenting))
1189 char *search(struct session *se, char *query)
1191 int live_channels = 0;
1194 yaz_log(YLOG_DEBUG, "Search");
1196 strcpy(se->query, query);
1198 nmem_reset(se->nmem);
1199 for (cl = se->clients; cl; cl = cl->next)
1205 if (client_prep_connection(cl))
1211 int maxrecs = live_channels * global_parameters.toget;
1212 se->num_termlists = 0;
1213 se->reclist = reclist_create(se->nmem, maxrecs);
1214 extract_terms(se->nmem, query, p);
1215 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1216 se->total_records = se->total_hits = se->total_merged = 0;
1217 se->expected_maxrecs = maxrecs;
1225 void destroy_session(struct session *s)
1227 yaz_log(YLOG_LOG, "Destroying session");
1229 client_destroy(s->clients);
1230 nmem_destroy(s->nmem);
1231 wrbuf_free(s->wrbuf, 1);
1234 struct session *new_session()
1237 struct session *session = xmalloc(sizeof(*session));
1239 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1241 session->total_hits = 0;
1242 session->total_records = 0;
1243 session->num_termlists = 0;
1244 session->reclist = 0;
1245 session->requestid = -1;
1246 session->clients = 0;
1247 session->expected_maxrecs = 0;
1248 session->query[0] = '\0';
1249 session->nmem = nmem_create();
1250 session->wrbuf = wrbuf_alloc();
1251 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1253 session->watchlist[i].data = 0;
1254 session->watchlist[i].fun = 0;
1257 select_targets(session);
1262 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1264 static struct hitsbytarget res[1000]; // FIXME MM
1268 for (cl = se->clients; cl; cl = cl->next)
1270 strcpy(res[*count].id, cl->database->host->hostport);
1271 res[*count].hits = cl->hits;
1272 res[*count].records = cl->records;
1273 res[*count].diagnostic = cl->diagnostic;
1274 res[*count].state = client_states[cl->state];
1275 res[*count].connected = cl->connection ? 1 : 0;
1282 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1286 for (i = 0; i < s->num_termlists; i++)
1287 if (!strcmp(s->termlists[i].name, name))
1288 return termlist_highscore(s->termlists[i].termlist, num);
1292 #ifdef MISSING_HEADERS
1293 void report_nmem_stats(void)
1295 size_t in_use, is_free;
1297 nmem_get_memory_in_use(&in_use);
1298 nmem_get_memory_free(&is_free);
1300 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1301 (long) in_use, (long) is_free);
1305 struct record_cluster *show_single(struct session *s, int id)
1307 struct record_cluster *r;
1309 reclist_rewind(s->reclist);
1310 while ((r = reclist_read_record(s->reclist)))
1316 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1317 int *sumhits, NMEM nmem_show)
1319 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1320 * sizeof(struct record_cluster *));
1323 yaz_timing_t t = yaz_timing_create();
1325 relevance_prepare_read(s->relevance, s->reclist);
1327 *total = s->reclist->num_records;
1328 *sumhits = s->total_hits;
1330 for (i = 0; i < start; i++)
1331 if (!reclist_read_record(s->reclist))
1338 for (i = 0; i < *num; i++)
1340 struct record_cluster *r = reclist_read_record(s->reclist);
1350 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1351 yaz_timing_get_real(t), yaz_timing_get_user(t),
1352 yaz_timing_get_sys(t));
1353 yaz_timing_destroy(&t);
1358 void statistics(struct session *se, struct statistics *stat)
1363 memset(stat, 0, sizeof(*stat));
1364 for (cl = se->clients; cl; cl = cl->next)
1366 if (!cl->connection)
1367 stat->num_no_connection++;
1370 case Client_Connecting: stat->num_connecting++; break;
1371 case Client_Initializing: stat->num_initializing++; break;
1372 case Client_Searching: stat->num_searching++; break;
1373 case Client_Presenting: stat->num_presenting++; break;
1374 case Client_Idle: stat->num_idle++; break;
1375 case Client_Failed: stat->num_failed++; break;
1376 case Client_Error: stat->num_error++; break;
1381 stat->num_hits = se->total_hits;
1382 stat->num_records = se->total_records;
1384 stat->num_clients = count;
1387 static CCL_bibset load_cclfile(const char *fn)
1389 CCL_bibset res = ccl_qual_mk();
1390 if (ccl_qual_fname(res, fn) < 0)
1392 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1398 int main(int argc, char **argv)
1404 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1405 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1407 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1409 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1413 if (!read_config(arg))
1421 global_parameters.ccl_filter = load_cclfile(arg);
1424 http_set_proxyaddr(arg);
1427 load_simpletargets(arg);
1430 global_parameters.dump_records = 1;
1433 fprintf(stderr, "Usage: pazpar2\n"
1435 " -h [host:]port (REST protocol listener)\n"
1437 " -s simpletargetfile\n"
1438 " -p hostname[:portno] (HTTP proxy)\n");
1445 yaz_log(YLOG_FATAL, "Load config with -f");
1448 global_parameters.server = config->servers;
1452 fprintf(stderr, "Set command port with -h\n");
1456 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1457 global_parameters.yaz_marc = yaz_marc_create();
1458 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1459 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1460 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1462 event_loop(&channel_list);
1470 * indent-tabs-mode: nil
1472 * vim: shiftwidth=4 tabstop=8 expandtab