1 /* $Id: pazpar2.c,v 1.20 2007-01-08 19:39:12 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 static struct record *ingest_record(struct client *cl, Z_External *rec)
429 xmlDoc *xdoc = normalize_record(cl, rec);
432 struct record_cluster *cluster;
433 struct session *se = cl->session;
434 xmlChar *mergekey, *mergekey_norm;
437 struct conf_service *service = global_parameters.server->service;
442 root = xmlDocGetRootElement(xdoc);
443 if (!(mergekey = xmlGetProp(root, "mergekey")))
445 yaz_log(YLOG_WARN, "No mergekey found in record");
450 res = nmem_malloc(se->nmem, sizeof(struct record));
452 res->target_offset = -1;
453 res->term_frequency_vec = 0;
454 res->metadata = nmem_malloc(se->nmem,
455 sizeof(struct record_metadata*) * service->num_metadata);
456 bzero(res->metadata, sizeof(struct record_metadata*) * service->num_metadata);
459 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
461 normalize_mergekey(mergekey_norm);
463 cluster = reclist_insert(se->reclist, res, mergekey_norm);
466 /* no room for record */
470 relevance_newrec(se->relevance, cluster);
473 for (n = root->children; n; n = n->next)
481 if (n->type != XML_ELEMENT_NODE)
483 if (!strcmp(n->name, "metadata"))
485 type = xmlGetProp(n, "type");
486 value = xmlNodeListGetString(xdoc, n->children, 0);
487 struct conf_metadata *md = 0;
488 struct record_metadata **wheretoput, *newm;
491 // First, find out what field we're looking at
492 for (imeta = 0; imeta < service->num_metadata; imeta++)
493 if (!strcmp(type, service->metadata[imeta].name))
495 md = &service->metadata[imeta];
500 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
504 // Find out where we are putting it
505 if (md->merge == Metadata_merge_no)
506 wheretoput = &res->metadata[imeta];
508 wheretoput = &cluster->metadata[imeta];
511 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
513 if (md->type == Metadata_type_generic)
515 newm->data.text = nmem_strdup(se->nmem, value);
519 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
522 if (md->merge == Metadata_merge_unique)
524 struct record_metadata *mnode;
525 for (mnode = *wheretoput; mnode; mnode = mnode->next)
526 if (!strcmp(mnode->data.text, mnode->data.text))
530 newm->next = *wheretoput;
534 else if (md->merge == Metadata_merge_longest)
537 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
540 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
542 newm->next = *wheretoput;
546 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
549 relevance_countwords(se->relevance, cluster, value, md->rank);
551 add_facet(se, type, value);
557 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
562 relevance_donerecord(se->relevance, cluster);
568 static void ingest_records(struct client *cl, Z_Records *r)
571 yaz_timing_t t = yaz_timing_create();
574 struct session *s = cl->session;
575 Z_NamePlusRecordList *rlist;
578 if (r->which != Z_Records_DBOSD)
580 rlist = r->u.databaseOrSurDiagnostics;
581 for (i = 0; i < rlist->num_records; i++)
583 Z_NamePlusRecord *npr = rlist->records[i];
585 if (npr->which != Z_NamePlusRecord_databaseRecord)
587 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
591 rec = ingest_record(cl, npr->u.databaseRecord);
595 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
596 session_alert_watch(s, SESSION_WATCH_RECORDS);
600 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
601 yaz_timing_get_real(t), yaz_timing_get_user(t),
602 yaz_timing_get_sys(t));
603 yaz_timing_destroy(&t);
607 static void do_presentResponse(IOCHAN i, Z_APDU *a)
609 struct connection *co = iochan_getdata(i);
610 struct client *cl = co->client;
611 Z_PresentResponse *r = a->u.presentResponse;
614 Z_Records *recs = r->records;
615 if (recs->which == Z_Records_NSD)
617 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
618 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
619 cl->state = Client_Error;
623 if (!*r->presentStatus && cl->state != Client_Error)
625 yaz_log(YLOG_DEBUG, "Good Present response");
626 cl->records += *r->numberOfRecordsReturned;
627 ingest_records(cl, r->records);
628 cl->state = Client_Idle;
630 else if (*r->presentStatus)
632 yaz_log(YLOG_WARN, "Bad Present response");
633 cl->state = Client_Error;
637 static void handler(IOCHAN i, int event)
639 struct connection *co = iochan_getdata(i);
640 struct client *cl = co->client;
641 struct session *se = 0;
647 yaz_log(YLOG_WARN, "Destroying orphan connection");
648 connection_destroy(co);
652 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
655 socklen_t errlen = sizeof(errcode);
657 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
658 &errlen) < 0 || errcode != 0)
665 yaz_log(YLOG_DEBUG, "Connect OK");
666 co->state = Conn_Open;
668 cl->state = Client_Connected;
672 else if (event & EVENT_INPUT)
674 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
678 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
679 connection_destroy(co);
684 yaz_log(YLOG_WARN, "EOF reading from Z server");
685 connection_destroy(co);
688 else if (len > 1) // We discard input if we have no connection
690 co->state = Conn_Open;
692 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
696 odr_reset(global_parameters.odr_in);
697 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
698 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
705 case Z_APDU_initResponse:
706 do_initResponse(i, a);
708 case Z_APDU_searchResponse:
709 do_searchResponse(i, a);
711 case Z_APDU_presentResponse:
712 do_presentResponse(i, a);
715 yaz_log(YLOG_WARN, "Unexpected result from server");
719 // We aren't expecting staggered output from target
720 // if (cs_more(t->link))
721 // iochan_setevent(i, EVENT_INPUT);
723 else // we throw away response and go to idle mode
725 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
726 cl->state = Client_Idle;
729 /* if len==1 we do nothing but wait for more input */
732 if (cl->state == Client_Connected) {
736 if (cl->state == Client_Idle)
738 if (cl->requestid != se->requestid && *se->query) {
741 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
742 cl->records < cl->hits) {
748 // Disassociate connection from client
749 static void connection_release(struct connection *co)
751 struct client *cl = co->client;
753 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
760 // Close connection and recycle structure
761 static void connection_destroy(struct connection *co)
763 struct host *h = co->host;
765 iochan_destroy(co->iochan);
767 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
768 if (h->connections == co)
769 h->connections = co->next;
772 struct connection *pco;
773 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
776 pco->next = co->next;
782 if (co->client->state != Client_Idle)
783 co->client->state = Client_Disconnected;
784 co->client->connection = 0;
786 co->next = connection_freelist;
787 connection_freelist = co;
790 // Creates a new connection for client, associated with the host of
792 static struct connection *connection_create(struct client *cl)
794 struct connection *new;
799 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
800 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
802 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
806 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
808 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
812 res = cs_connect(link, addr);
815 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
819 if ((new = connection_freelist))
820 connection_freelist = new->next;
823 new = xmalloc(sizeof (struct connection));
827 new->state = Conn_Connecting;
828 new->host = cl->database->host;
829 new->next = new->host->connections;
830 new->host->connections = new;
832 cl->connection = new;
835 new->iochan = iochan_create(cs_fileno(link), handler, 0);
836 iochan_setdata(new->iochan, new);
837 new->iochan->next = channel_list;
838 channel_list = new->iochan;
842 // Close connection and set state to error
843 static void client_fatal(struct client *cl)
845 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
846 connection_destroy(cl->connection);
847 cl->state = Client_Error;
850 // Ensure that client has a connection associated
851 static int client_prep_connection(struct client *cl)
853 struct connection *co;
854 struct session *se = cl->session;
855 struct host *host = cl->database->host;
859 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
863 // See if someone else has an idle connection
864 // We should look at timestamps here to select the longest-idle connection
865 for (co = host->connections; co; co = co->next)
866 if (co->state == Conn_Open && (!co->client || co->client->session != se))
870 connection_release(co);
875 co = connection_create(cl);
879 if (co->state == Conn_Connecting)
881 cl->state = Client_Connecting;
882 iochan_setflag(co->iochan, EVENT_OUTPUT);
884 else if (co->state == Conn_Open)
886 if (cl->state == Client_Error || cl->state == Client_Disconnected)
887 cl->state = Client_Idle;
888 iochan_setflag(co->iochan, EVENT_OUTPUT);
896 // This function will most likely vanish when a proper target profile mechanism is
898 void load_simpletargets(const char *fn)
900 FILE *f = fopen(fn, "r");
905 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
909 while (fgets(line, 255, f))
913 struct database *database;
915 if (strncmp(line, "target ", 7))
918 url[strlen(url) - 1] = '\0';
919 yaz_log(YLOG_DEBUG, "Target: %s", url);
920 if ((db = strchr(url, '/')))
925 for (host = hosts; host; host = host->next)
926 if (!strcmp(url, host->hostport))
930 struct addrinfo *addrinfo, hints;
933 unsigned char addrbuf[4];
936 host = xmalloc(sizeof(struct host));
937 host->hostport = xstrdup(url);
938 host->connections = 0;
940 if ((port = strchr(url, ':')))
946 hints.ai_family = PF_INET;
947 hints.ai_socktype = SOCK_STREAM;
948 hints.ai_protocol = IPPROTO_TCP;
949 hints.ai_addrlen = 0;
951 hints.ai_canonname = 0;
953 // This is not robust code. It assumes that getaddrinfo returns AF_INET
955 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
957 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
958 xfree(host->hostport);
962 assert(addrinfo->ai_family == PF_INET);
963 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
964 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
965 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
966 host->ipport = xstrdup(ipport);
967 freeaddrinfo(addrinfo);
971 database = xmalloc(sizeof(struct database));
972 database->host = host;
973 database->url = xmalloc(strlen(url) + strlen(db) + 2);
974 strcpy(database->url, url);
975 strcat(database->url, "/");
976 strcat(database->url, db);
978 database->databases = xmalloc(2 * sizeof(char *));
979 database->databases[0] = xstrdup(db);
980 database->databases[1] = 0;
981 database->errors = 0;
982 database->qprofile = 0;
983 database->rprofile = database_retrieval_profile(database);
984 database->next = databases;
985 databases = database;
991 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
999 pull_terms(nmem, n->u.p[0], termlist, num);
1000 pull_terms(nmem, n->u.p[1], termlist, num);
1003 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1010 // Extract terms from query into null-terminated termlist
1011 static int extract_terms(NMEM nmem, char *query, char **termlist)
1014 struct ccl_rpn_node *n;
1017 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1020 pull_terms(nmem, n, termlist, &num);
1026 static struct client *client_create(void)
1029 if (client_freelist)
1031 r = client_freelist;
1032 client_freelist = client_freelist->next;
1035 r = xmalloc(sizeof(struct client));
1044 r->state = Client_Disconnected;
1049 void client_destroy(struct client *c)
1051 struct session *se = c->session;
1052 if (c == se->clients)
1053 se->clients = c->next;
1057 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1063 connection_release(c->connection);
1064 c->next = client_freelist;
1065 client_freelist = c;
1068 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1070 s->watchlist[what].fun = fun;
1071 s->watchlist[what].data = data;
1074 void session_alert_watch(struct session *s, int what)
1076 if (!s->watchlist[what].fun)
1078 (*s->watchlist[what].fun)(s->watchlist[what].data);
1079 s->watchlist[what].fun = 0;
1080 s->watchlist[what].data = 0;
1083 // This needs to be extended with selection criteria
1084 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1088 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1091 if (!config->retrievalprofiles)
1093 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1095 return config->retrievalprofiles;
1098 // This should be extended with parameters to control selection criteria
1099 // Associates a set of clients with a session;
1100 int select_targets(struct session *se)
1102 struct database *db;
1106 client_destroy(se->clients);
1107 for (db = databases; db; db = db->next)
1109 struct client *cl = client_create();
1112 cl->next = se->clients;
1119 int session_active_clients(struct session *s)
1124 for (c = s->clients; c; c = c->next)
1125 if (c->connection && (c->state == Client_Connecting ||
1126 c->state == Client_Initializing ||
1127 c->state == Client_Searching ||
1128 c->state == Client_Presenting))
1134 char *search(struct session *se, char *query)
1136 int live_channels = 0;
1139 yaz_log(YLOG_DEBUG, "Search");
1141 strcpy(se->query, query);
1143 nmem_reset(se->nmem);
1144 for (cl = se->clients; cl; cl = cl->next)
1150 if (client_prep_connection(cl))
1156 int maxrecs = live_channels * global_parameters.toget;
1157 se->num_termlists = 0;
1158 se->reclist = reclist_create(se->nmem, maxrecs);
1159 extract_terms(se->nmem, query, p);
1160 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1161 se->total_records = se->total_hits = 0;
1162 se->expected_maxrecs = maxrecs;
1170 void destroy_session(struct session *s)
1172 yaz_log(YLOG_LOG, "Destroying session");
1174 client_destroy(s->clients);
1175 nmem_destroy(s->nmem);
1176 wrbuf_free(s->wrbuf, 1);
1179 struct session *new_session()
1182 struct session *session = xmalloc(sizeof(*session));
1184 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1186 session->total_hits = 0;
1187 session->total_records = 0;
1188 session->num_termlists = 0;
1189 session->reclist = 0;
1190 session->requestid = -1;
1191 session->clients = 0;
1192 session->expected_maxrecs = 0;
1193 session->query[0] = '\0';
1194 session->nmem = nmem_create();
1195 session->wrbuf = wrbuf_alloc();
1196 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1198 session->watchlist[i].data = 0;
1199 session->watchlist[i].fun = 0;
1202 select_targets(session);
1207 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1209 static struct hitsbytarget res[1000]; // FIXME MM
1213 for (cl = se->clients; cl; cl = cl->next)
1215 strcpy(res[*count].id, cl->database->host->hostport);
1216 res[*count].hits = cl->hits;
1217 res[*count].records = cl->records;
1218 res[*count].diagnostic = cl->diagnostic;
1219 res[*count].state = client_states[cl->state];
1220 res[*count].connected = cl->connection ? 1 : 0;
1227 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1231 for (i = 0; i < s->num_termlists; i++)
1232 if (!strcmp(s->termlists[i].name, name))
1233 return termlist_highscore(s->termlists[i].termlist, num);
1237 #ifdef MISSING_HEADERS
1238 void report_nmem_stats(void)
1240 size_t in_use, is_free;
1242 nmem_get_memory_in_use(&in_use);
1243 nmem_get_memory_free(&is_free);
1245 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1246 (long) in_use, (long) is_free);
1250 struct record_cluster **show(struct session *s, int start, int *num, int *total,
1251 int *sumhits, NMEM nmem_show)
1253 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1254 * sizeof(struct record_cluster *));
1257 yaz_timing_t t = yaz_timing_create();
1259 relevance_prepare_read(s->relevance, s->reclist);
1261 *total = s->reclist->num_records;
1262 *sumhits = s->total_hits;
1264 for (i = 0; i < start; i++)
1265 if (!reclist_read_record(s->reclist))
1272 for (i = 0; i < *num; i++)
1274 struct record_cluster *r = reclist_read_record(s->reclist);
1284 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1285 yaz_timing_get_real(t), yaz_timing_get_user(t),
1286 yaz_timing_get_sys(t));
1287 yaz_timing_destroy(&t);
1292 void statistics(struct session *se, struct statistics *stat)
1297 bzero(stat, sizeof(*stat));
1298 for (cl = se->clients; cl; cl = cl->next)
1300 if (!cl->connection)
1301 stat->num_no_connection++;
1304 case Client_Connecting: stat->num_connecting++; break;
1305 case Client_Initializing: stat->num_initializing++; break;
1306 case Client_Searching: stat->num_searching++; break;
1307 case Client_Presenting: stat->num_presenting++; break;
1308 case Client_Idle: stat->num_idle++; break;
1309 case Client_Failed: stat->num_failed++; break;
1310 case Client_Error: stat->num_error++; break;
1315 stat->num_hits = se->total_hits;
1316 stat->num_records = se->total_records;
1318 stat->num_clients = count;
1321 static CCL_bibset load_cclfile(const char *fn)
1323 CCL_bibset res = ccl_qual_mk();
1324 if (ccl_qual_fname(res, fn) < 0)
1326 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1332 int main(int argc, char **argv)
1338 if (signal(SIGPIPE, SIG_IGN) < 0)
1339 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1341 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1343 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1347 if (!read_config(arg))
1355 global_parameters.ccl_filter = load_cclfile(arg);
1358 http_set_proxyaddr(arg);
1361 load_simpletargets(arg);
1364 global_parameters.dump_records = 1;
1367 fprintf(stderr, "Usage: pazpar2\n"
1369 " -h [host:]port (REST protocol listener)\n"
1371 " -s simpletargetfile\n"
1372 " -p hostname[:portno] (HTTP proxy)\n");
1379 yaz_log(YLOG_FATAL, "Load config with -f");
1382 global_parameters.server = config->servers;
1386 fprintf(stderr, "Set command port with -h\n");
1390 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1391 global_parameters.yaz_marc = yaz_marc_create();
1392 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1393 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1394 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1396 event_loop(&channel_list);
1404 * indent-tabs-mode: nil
1406 * vim: shiftwidth=4 tabstop=8 expandtab