1 /* $Id: pazpar2.c,v 1.28 2007-01-12 23:37:15 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>
32 #include <netinet/in.h>
37 #include "termlists.h"
39 #include "relevance.h"
44 static void client_fatal(struct client *cl);
45 static void connection_destroy(struct connection *co);
46 static int client_prep_connection(struct client *cl);
47 static void ingest_records(struct client *cl, Z_Records *r);
48 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
49 void session_alert_watch(struct session *s, int what);
51 IOCHAN channel_list = 0; // Master list of connections we're handling events to
53 static struct connection *connection_freelist = 0;
54 static struct client *client_freelist = 0;
56 static struct host *hosts = 0; // The hosts we know about
57 static struct database *databases = 0; // The databases we know about
59 static char *client_states[] = {
63 "Client_Initializing",
68 "Client_Disconnected",
72 // Note: Some things in this structure will eventually move to configuration
73 struct parameters global_parameters =
81 "Index Data PazPar2 (MasterKey)",
93 static int send_apdu(struct client *c, Z_APDU *a)
95 struct connection *co = c->connection;
99 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
101 odr_perror(global_parameters.odr_out, "Encoding APDU");
104 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
105 r = cs_put(co->link, buf, len);
108 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
113 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
116 odr_reset(global_parameters.odr_out); /* release the APDU structure */
117 co->state = Conn_Waiting;
122 static void send_init(IOCHAN i)
124 struct connection *co = iochan_getdata(i);
125 struct client *cl = co->client;
126 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
128 a->u.initRequest->implementationId = global_parameters.implementationId;
129 a->u.initRequest->implementationName = global_parameters.implementationName;
130 a->u.initRequest->implementationVersion =
131 global_parameters.implementationVersion;
132 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
133 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
134 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
136 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
137 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
138 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
139 if (send_apdu(cl, a) >= 0)
141 iochan_setflags(i, EVENT_INPUT);
142 cl->state = Client_Initializing;
145 cl->state = Client_Error;
146 odr_reset(global_parameters.odr_out);
149 static void send_search(IOCHAN i)
151 struct connection *co = iochan_getdata(i);
152 struct client *cl = co->client;
153 struct session *se = cl->session;
154 struct database *db = cl->database;
155 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
156 int ndb, cerror, cpos;
159 struct ccl_rpn_node *cn;
160 int ssub = 0, lslb = 100000, mspn = 10;
162 yaz_log(YLOG_DEBUG, "Sending search");
164 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
167 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
169 zquery->which = Z_Query_type_1;
170 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
173 for (ndb = 0; db->databases[ndb]; ndb++)
175 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
176 for (ndb = 0; db->databases[ndb]; ndb++)
177 databaselist[ndb] = db->databases[ndb];
179 a->u.presentRequest->preferredRecordSyntax =
180 yaz_oidval_to_z3950oid(global_parameters.odr_out,
181 CLASS_RECSYN, VAL_USMARC);
182 a->u.searchRequest->smallSetUpperBound = &ssub;
183 a->u.searchRequest->largeSetLowerBound = &lslb;
184 a->u.searchRequest->mediumSetPresentNumber = &mspn;
185 a->u.searchRequest->resultSetName = "Default";
186 a->u.searchRequest->databaseNames = databaselist;
187 a->u.searchRequest->num_databaseNames = ndb;
189 if (send_apdu(cl, a) >= 0)
191 iochan_setflags(i, EVENT_INPUT);
192 cl->state = Client_Searching;
193 cl->requestid = se->requestid;
196 cl->state = Client_Error;
198 odr_reset(global_parameters.odr_out);
201 static void send_present(IOCHAN i)
203 struct connection *co = iochan_getdata(i);
204 struct client *cl = co->client;
205 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
207 int start = cl->records + 1;
209 toget = global_parameters.chunk;
210 if (toget > global_parameters.toget - cl->records)
211 toget = global_parameters.toget - cl->records;
212 if (toget > cl->hits - cl->records)
213 toget = cl->hits - cl->records;
215 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
217 a->u.presentRequest->resultSetStartPoint = &start;
218 a->u.presentRequest->numberOfRecordsRequested = &toget;
220 a->u.presentRequest->resultSetId = "Default";
222 a->u.presentRequest->preferredRecordSyntax =
223 yaz_oidval_to_z3950oid(global_parameters.odr_out,
224 CLASS_RECSYN, VAL_USMARC);
226 if (send_apdu(cl, a) >= 0)
228 iochan_setflags(i, EVENT_INPUT);
229 cl->state = Client_Presenting;
232 cl->state = Client_Error;
233 odr_reset(global_parameters.odr_out);
236 static void do_initResponse(IOCHAN i, Z_APDU *a)
238 struct connection *co = iochan_getdata(i);
239 struct client *cl = co->client;
240 Z_InitResponse *r = a->u.initResponse;
242 yaz_log(YLOG_DEBUG, "Received init response");
246 cl->state = Client_Idle;
249 cl->state = Client_Failed; // FIXME need to do something to the connection
252 static void do_searchResponse(IOCHAN i, Z_APDU *a)
254 struct connection *co = iochan_getdata(i);
255 struct client *cl = co->client;
256 struct session *se = cl->session;
257 Z_SearchResponse *r = a->u.searchResponse;
259 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
261 if (*r->searchStatus)
263 cl->hits = *r->resultCount;
264 se->total_hits += cl->hits;
265 if (r->presentStatus && !*r->presentStatus && r->records)
267 yaz_log(YLOG_DEBUG, "Records in search response");
268 cl->records += *r->numberOfRecordsReturned;
269 ingest_records(cl, r->records);
271 cl->state = Client_Idle;
276 cl->state = Client_Error;
278 Z_Records *recs = r->records;
279 if (recs->which == Z_Records_NSD)
281 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
282 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
283 cl->state = Client_Error;
289 char *normalize_mergekey(char *buf)
291 char *p = buf, *pout = buf;
295 while (*p && !isalnum(*p))
298 *(pout++) = tolower(*(p++));
301 while (*p && !isalnum(*p))
312 // FIXME needs to be generalized. Should flexibly generate X lists per search
313 static void extract_subject(struct session *s, const char *rec)
315 const char *field, *subfield;
317 while ((field = find_field(rec, "650")))
320 if ((subfield = find_subfield(field, 'a')))
326 ef = index(subfield, '\n');
329 if ((e = index(subfield, '\t')) && e < ef)
331 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
335 memcpy(buf, subfield, len);
339 termlist_insert(s->termlist, buf);
346 static void add_facet(struct session *s, const char *type, const char *value)
350 for (i = 0; i < s->num_termlists; i++)
351 if (!strcmp(s->termlists[i].name, type))
353 if (i == s->num_termlists)
355 if (i == SESSION_MAX_TERMLISTS)
357 yaz_log(YLOG_FATAL, "Too many termlists");
360 s->termlists[i].name = nmem_strdup(s->nmem, type);
361 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
362 s->num_termlists = i + 1;
364 termlist_insert(s->termlists[i].termlist, value);
367 int yaz_marc_write_xml();
369 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
371 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
372 struct conf_retrievalmap *m;
376 // First normalize to XML
377 if (rprofile->native_syntax == Nativesyn_iso2709)
381 if (rec->which != Z_External_octet)
383 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
386 buf = (char*) rec->u.octet_aligned->buf;
387 len = rec->u.octet_aligned->len;
388 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
390 yaz_log(YLOG_WARN, "Failed to decode MARC");
393 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
394 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
396 yaz_log(YLOG_WARN, "Failed to encode as XML");
399 rdoc = xmlNewDoc("1.0");
400 xmlDocSetRootElement(rdoc, res);
404 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
407 for (m = rprofile->maplist; m; m = m->next)
410 if (m->type != Map_xslt)
412 yaz_log(YLOG_WARN, "Unknown map type");
415 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
417 yaz_log(YLOG_WARN, "XSLT transformation failed");
423 if (global_parameters.dump_records)
425 fprintf(stderr, "Record:\n----------------\n");
426 xmlDocFormatDump(stderr, rdoc, 1);
431 // Extract what appears to be years from buf, storing highest and
433 static int extract_years(const char *buf, int *first, int *last)
442 while (*buf && !isdigit(*buf))
445 for (e = buf; *e && isdigit(*e); e++)
449 int value = atoi(buf);
450 if (*first < 0 || value < *first)
452 if (*last < 0 || value > *last)
460 static struct record *ingest_record(struct client *cl, Z_External *rec)
462 xmlDoc *xdoc = normalize_record(cl, rec);
465 struct record_cluster *cluster;
466 struct session *se = cl->session;
467 xmlChar *mergekey, *mergekey_norm;
470 struct conf_service *service = global_parameters.server->service;
475 root = xmlDocGetRootElement(xdoc);
476 if (!(mergekey = xmlGetProp(root, "mergekey")))
478 yaz_log(YLOG_WARN, "No mergekey found in record");
483 res = nmem_malloc(se->nmem, sizeof(struct record));
485 res->metadata = nmem_malloc(se->nmem,
486 sizeof(struct record_metadata*) * service->num_metadata);
487 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
489 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
491 normalize_mergekey(mergekey_norm);
493 cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
496 /* no room for record */
500 relevance_newrec(se->relevance, cluster);
503 for (n = root->children; n; n = n->next)
511 if (n->type != XML_ELEMENT_NODE)
513 if (!strcmp(n->name, "metadata"))
515 struct conf_metadata *md = 0;
516 struct record_metadata **wheretoput, *newm;
520 type = xmlGetProp(n, "type");
521 value = xmlNodeListGetString(xdoc, n->children, 0);
522 // First, find out what field we're looking at
523 for (imeta = 0; imeta < service->num_metadata; imeta++)
524 if (!strcmp(type, service->metadata[imeta].name))
526 md = &service->metadata[imeta];
531 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
535 // Find out where we are putting it
536 if (md->merge == Metadata_merge_no)
537 wheretoput = &res->metadata[imeta];
539 wheretoput = &cluster->metadata[imeta];
542 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
544 if (md->type == Metadata_type_generic)
546 newm->data.text = nmem_strdup(se->nmem, value);
548 else if (md->type == Metadata_type_year)
550 if (extract_years(value, &first, &last) < 0)
555 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
558 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
560 yaz_log(YLOG_WARN, "Only range merging supported for years");
563 if (md->merge == Metadata_merge_unique)
565 struct record_metadata *mnode;
566 for (mnode = *wheretoput; mnode; mnode = mnode->next)
567 if (!strcmp(mnode->data.text, mnode->data.text))
571 newm->next = *wheretoput;
575 else if (md->merge == Metadata_merge_longest)
578 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
581 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
583 newm->next = *wheretoput;
586 else if (md->merge == Metadata_merge_range)
588 assert(md->type == Metadata_type_year);
592 (*wheretoput)->data.year.year1 = first;
593 (*wheretoput)->data.year.year2 = last;
597 if (first < (*wheretoput)->data.year.year1)
598 (*wheretoput)->data.year.year1 = first;
599 if (last > (*wheretoput)->data.year.year2)
600 (*wheretoput)->data.year.year2 = last;
604 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
607 relevance_countwords(se->relevance, cluster, value, md->rank);
609 add_facet(se, type, value);
615 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
620 relevance_donerecord(se->relevance, cluster);
626 static void ingest_records(struct client *cl, Z_Records *r)
629 yaz_timing_t t = yaz_timing_create();
632 struct session *s = cl->session;
633 Z_NamePlusRecordList *rlist;
636 if (r->which != Z_Records_DBOSD)
638 rlist = r->u.databaseOrSurDiagnostics;
639 for (i = 0; i < rlist->num_records; i++)
641 Z_NamePlusRecord *npr = rlist->records[i];
643 if (npr->which != Z_NamePlusRecord_databaseRecord)
645 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
649 rec = ingest_record(cl, npr->u.databaseRecord);
653 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
654 session_alert_watch(s, SESSION_WATCH_RECORDS);
658 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
659 yaz_timing_get_real(t), yaz_timing_get_user(t),
660 yaz_timing_get_sys(t));
661 yaz_timing_destroy(&t);
665 static void do_presentResponse(IOCHAN i, Z_APDU *a)
667 struct connection *co = iochan_getdata(i);
668 struct client *cl = co->client;
669 Z_PresentResponse *r = a->u.presentResponse;
672 Z_Records *recs = r->records;
673 if (recs->which == Z_Records_NSD)
675 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
676 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
677 cl->state = Client_Error;
681 if (!*r->presentStatus && cl->state != Client_Error)
683 yaz_log(YLOG_DEBUG, "Good Present response");
684 cl->records += *r->numberOfRecordsReturned;
685 ingest_records(cl, r->records);
686 cl->state = Client_Idle;
688 else if (*r->presentStatus)
690 yaz_log(YLOG_WARN, "Bad Present response");
691 cl->state = Client_Error;
695 static void handler(IOCHAN i, int event)
697 struct connection *co = iochan_getdata(i);
698 struct client *cl = co->client;
699 struct session *se = 0;
705 yaz_log(YLOG_WARN, "Destroying orphan connection");
706 connection_destroy(co);
710 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
713 socklen_t errlen = sizeof(errcode);
715 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
716 &errlen) < 0 || errcode != 0)
723 yaz_log(YLOG_DEBUG, "Connect OK");
724 co->state = Conn_Open;
726 cl->state = Client_Connected;
730 else if (event & EVENT_INPUT)
732 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
736 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
737 connection_destroy(co);
742 yaz_log(YLOG_WARN, "EOF reading from Z server");
743 connection_destroy(co);
746 else if (len > 1) // We discard input if we have no connection
748 co->state = Conn_Open;
750 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
754 odr_reset(global_parameters.odr_in);
755 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
756 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
763 case Z_APDU_initResponse:
764 do_initResponse(i, a);
766 case Z_APDU_searchResponse:
767 do_searchResponse(i, a);
769 case Z_APDU_presentResponse:
770 do_presentResponse(i, a);
773 yaz_log(YLOG_WARN, "Unexpected result from server");
777 // We aren't expecting staggered output from target
778 // if (cs_more(t->link))
779 // iochan_setevent(i, EVENT_INPUT);
781 else // we throw away response and go to idle mode
783 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
784 cl->state = Client_Idle;
787 /* if len==1 we do nothing but wait for more input */
790 if (cl->state == Client_Connected) {
794 if (cl->state == Client_Idle)
796 if (cl->requestid != se->requestid && *se->query) {
799 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
800 cl->records < cl->hits) {
806 // Disassociate connection from client
807 static void connection_release(struct connection *co)
809 struct client *cl = co->client;
811 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
818 // Close connection and recycle structure
819 static void connection_destroy(struct connection *co)
821 struct host *h = co->host;
823 iochan_destroy(co->iochan);
825 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
826 if (h->connections == co)
827 h->connections = co->next;
830 struct connection *pco;
831 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
834 pco->next = co->next;
840 if (co->client->state != Client_Idle)
841 co->client->state = Client_Disconnected;
842 co->client->connection = 0;
844 co->next = connection_freelist;
845 connection_freelist = co;
848 // Creates a new connection for client, associated with the host of
850 static struct connection *connection_create(struct client *cl)
852 struct connection *new;
857 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
858 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
860 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
864 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
866 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?",
867 cl->database->host->ipport);
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)
940 cl->state = Client_Connecting;
941 iochan_setflag(co->iochan, EVENT_OUTPUT);
943 else if (co->state == Conn_Open)
945 if (cl->state == Client_Error || cl->state == Client_Disconnected)
946 cl->state = Client_Idle;
947 iochan_setflag(co->iochan, EVENT_OUTPUT);
955 // This function will most likely vanish when a proper target profile mechanism is
957 void load_simpletargets(const char *fn)
959 FILE *f = fopen(fn, "r");
964 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
968 while (fgets(line, 255, f))
972 struct database *database;
974 if (strncmp(line, "target ", 7))
977 url[strlen(url) - 1] = '\0';
978 yaz_log(YLOG_DEBUG, "Target: %s", url);
979 if ((db = strchr(url, '/')))
984 for (host = hosts; host; host = host->next)
985 if (!strcmp(url, host->hostport))
989 struct addrinfo *addrinfo, hints;
992 unsigned char addrbuf[4];
995 host = xmalloc(sizeof(struct host));
996 host->hostport = xstrdup(url);
997 host->connections = 0;
999 if ((port = strchr(url, ':')))
1005 hints.ai_family = PF_INET;
1006 hints.ai_socktype = SOCK_STREAM;
1007 hints.ai_protocol = IPPROTO_TCP;
1008 hints.ai_addrlen = 0;
1010 hints.ai_canonname = 0;
1012 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1014 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1016 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1017 xfree(host->hostport);
1021 assert(addrinfo->ai_family == PF_INET);
1022 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1023 sprintf(ipport, "%u.%u.%u.%u:%s",
1024 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1025 host->ipport = xstrdup(ipport);
1026 freeaddrinfo(addrinfo);
1030 database = xmalloc(sizeof(struct database));
1031 database->host = host;
1032 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1033 strcpy(database->url, url);
1034 strcat(database->url, "/");
1035 strcat(database->url, db);
1037 database->databases = xmalloc(2 * sizeof(char *));
1038 database->databases[0] = xstrdup(db);
1039 database->databases[1] = 0;
1040 database->errors = 0;
1041 database->qprofile = 0;
1042 database->rprofile = database_retrieval_profile(database);
1043 database->next = databases;
1044 databases = database;
1050 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1058 pull_terms(nmem, n->u.p[0], termlist, num);
1059 pull_terms(nmem, n->u.p[1], termlist, num);
1062 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1069 // Extract terms from query into null-terminated termlist
1070 static int extract_terms(NMEM nmem, char *query, char **termlist)
1073 struct ccl_rpn_node *n;
1076 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1079 pull_terms(nmem, n, termlist, &num);
1085 static struct client *client_create(void)
1088 if (client_freelist)
1090 r = client_freelist;
1091 client_freelist = client_freelist->next;
1094 r = xmalloc(sizeof(struct client));
1103 r->state = Client_Disconnected;
1108 void client_destroy(struct client *c)
1110 struct session *se = c->session;
1111 if (c == se->clients)
1112 se->clients = c->next;
1116 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1122 connection_release(c->connection);
1123 c->next = client_freelist;
1124 client_freelist = c;
1127 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1129 s->watchlist[what].fun = fun;
1130 s->watchlist[what].data = data;
1133 void session_alert_watch(struct session *s, int what)
1135 if (!s->watchlist[what].fun)
1137 (*s->watchlist[what].fun)(s->watchlist[what].data);
1138 s->watchlist[what].fun = 0;
1139 s->watchlist[what].data = 0;
1142 // This needs to be extended with selection criteria
1143 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1147 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1150 if (!config->retrievalprofiles)
1152 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1154 return config->retrievalprofiles;
1157 // This should be extended with parameters to control selection criteria
1158 // Associates a set of clients with a session;
1159 int select_targets(struct session *se)
1161 struct database *db;
1165 client_destroy(se->clients);
1166 for (db = databases; db; db = db->next)
1168 struct client *cl = client_create();
1171 cl->next = se->clients;
1178 int session_active_clients(struct session *s)
1183 for (c = s->clients; c; c = c->next)
1184 if (c->connection && (c->state == Client_Connecting ||
1185 c->state == Client_Initializing ||
1186 c->state == Client_Searching ||
1187 c->state == Client_Presenting))
1193 char *search(struct session *se, char *query)
1195 int live_channels = 0;
1198 yaz_log(YLOG_DEBUG, "Search");
1200 strcpy(se->query, query);
1202 nmem_reset(se->nmem);
1203 for (cl = se->clients; cl; cl = cl->next)
1209 if (client_prep_connection(cl))
1215 int maxrecs = live_channels * global_parameters.toget;
1216 se->num_termlists = 0;
1217 se->reclist = reclist_create(se->nmem, maxrecs);
1218 extract_terms(se->nmem, query, p);
1219 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1220 se->total_records = se->total_hits = se->total_merged = 0;
1221 se->expected_maxrecs = maxrecs;
1229 void destroy_session(struct session *s)
1231 yaz_log(YLOG_LOG, "Destroying session");
1233 client_destroy(s->clients);
1234 nmem_destroy(s->nmem);
1235 wrbuf_free(s->wrbuf, 1);
1238 struct session *new_session()
1241 struct session *session = xmalloc(sizeof(*session));
1243 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1245 session->total_hits = 0;
1246 session->total_records = 0;
1247 session->num_termlists = 0;
1248 session->reclist = 0;
1249 session->requestid = -1;
1250 session->clients = 0;
1251 session->expected_maxrecs = 0;
1252 session->query[0] = '\0';
1253 session->nmem = nmem_create();
1254 session->wrbuf = wrbuf_alloc();
1255 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1257 session->watchlist[i].data = 0;
1258 session->watchlist[i].fun = 0;
1261 select_targets(session);
1266 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1268 static struct hitsbytarget res[1000]; // FIXME MM
1272 for (cl = se->clients; cl; cl = cl->next)
1274 strcpy(res[*count].id, cl->database->host->hostport);
1275 res[*count].hits = cl->hits;
1276 res[*count].records = cl->records;
1277 res[*count].diagnostic = cl->diagnostic;
1278 res[*count].state = client_states[cl->state];
1279 res[*count].connected = cl->connection ? 1 : 0;
1286 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1290 for (i = 0; i < s->num_termlists; i++)
1291 if (!strcmp(s->termlists[i].name, name))
1292 return termlist_highscore(s->termlists[i].termlist, num);
1296 #ifdef MISSING_HEADERS
1297 void report_nmem_stats(void)
1299 size_t in_use, is_free;
1301 nmem_get_memory_in_use(&in_use);
1302 nmem_get_memory_free(&is_free);
1304 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1305 (long) in_use, (long) is_free);
1309 struct record_cluster *show_single(struct session *s, int id)
1311 struct record_cluster *r;
1313 reclist_rewind(s->reclist);
1314 while ((r = reclist_read_record(s->reclist)))
1320 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1321 int *sumhits, NMEM nmem_show)
1323 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1324 * sizeof(struct record_cluster *));
1327 yaz_timing_t t = yaz_timing_create();
1329 relevance_prepare_read(s->relevance, s->reclist);
1331 *total = s->reclist->num_records;
1332 *sumhits = s->total_hits;
1334 for (i = 0; i < start; i++)
1335 if (!reclist_read_record(s->reclist))
1342 for (i = 0; i < *num; i++)
1344 struct record_cluster *r = reclist_read_record(s->reclist);
1354 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1355 yaz_timing_get_real(t), yaz_timing_get_user(t),
1356 yaz_timing_get_sys(t));
1357 yaz_timing_destroy(&t);
1362 void statistics(struct session *se, struct statistics *stat)
1367 memset(stat, 0, sizeof(*stat));
1368 for (cl = se->clients; cl; cl = cl->next)
1370 if (!cl->connection)
1371 stat->num_no_connection++;
1374 case Client_Connecting: stat->num_connecting++; break;
1375 case Client_Initializing: stat->num_initializing++; break;
1376 case Client_Searching: stat->num_searching++; break;
1377 case Client_Presenting: stat->num_presenting++; break;
1378 case Client_Idle: stat->num_idle++; break;
1379 case Client_Failed: stat->num_failed++; break;
1380 case Client_Error: stat->num_error++; break;
1385 stat->num_hits = se->total_hits;
1386 stat->num_records = se->total_records;
1388 stat->num_clients = count;
1391 static CCL_bibset load_cclfile(const char *fn)
1393 CCL_bibset res = ccl_qual_mk();
1394 if (ccl_qual_fname(res, fn) < 0)
1396 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1402 static void start_http_listener(void)
1405 struct conf_server *ser = global_parameters.server;
1407 if (*global_parameters.listener_override)
1408 strcpy(hp, global_parameters.listener_override);
1411 strcpy(hp, ser->host ? ser->host : "");
1416 sprintf(hp + strlen(hp), "%d", ser->port);
1422 static void start_proxy(void)
1425 struct conf_server *ser = global_parameters.server;
1427 if (*global_parameters.proxy_override)
1428 strcpy(hp, global_parameters.proxy_override);
1429 else if (ser->proxy_host || ser->proxy_port)
1431 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1432 if (ser->proxy_port)
1436 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1442 http_set_proxyaddr(hp);
1445 int main(int argc, char **argv)
1450 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1451 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1453 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1455 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1459 if (!read_config(arg))
1463 strcpy(global_parameters.listener_override, arg);
1466 global_parameters.ccl_filter = load_cclfile(arg);
1469 strcpy(global_parameters.proxy_override, arg);
1472 load_simpletargets(arg);
1475 global_parameters.dump_records = 1;
1478 fprintf(stderr, "Usage: pazpar2\n"
1480 " -h [host:]port (REST protocol listener)\n"
1482 " -s simpletargetfile\n"
1483 " -p hostname[:portno] (HTTP proxy)\n");
1490 yaz_log(YLOG_FATAL, "Load config with -f");
1493 global_parameters.server = config->servers;
1495 start_http_listener();
1497 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1498 global_parameters.yaz_marc = yaz_marc_create();
1499 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1500 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1501 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1503 event_loop(&channel_list);
1511 * indent-tabs-mode: nil
1513 * vim: shiftwidth=4 tabstop=8 expandtab