1 /* $Id: pazpar2.c,v 1.15 2007-01-05 20:33:05 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>
25 #include <yaz/timing.h>
32 #include "termlists.h"
34 #include "relevance.h"
37 #define PAZPAR2_VERSION "0.1"
40 static void client_fatal(struct client *cl);
41 static void connection_destroy(struct connection *co);
42 static int client_prep_connection(struct client *cl);
43 static void ingest_records(struct client *cl, Z_Records *r);
44 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
45 void session_alert_watch(struct session *s, int what);
47 IOCHAN channel_list = 0; // Master list of connections we're handling events to
49 static struct connection *connection_freelist = 0;
50 static struct client *client_freelist = 0;
52 static struct host *hosts = 0; // The hosts we know about
53 static struct database *databases = 0; // The databases we know about
55 static char *client_states[] = {
59 "Client_Initializing",
64 "Client_Disconnected",
68 struct parameters global_parameters =
73 "Index Data PazPar2 (MasterKey)",
85 static int send_apdu(struct client *c, Z_APDU *a)
87 struct connection *co = c->connection;
91 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
93 odr_perror(global_parameters.odr_out, "Encoding APDU");
96 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
97 r = cs_put(co->link, buf, len);
100 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
105 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
108 odr_reset(global_parameters.odr_out); /* release the APDU structure */
109 co->state = Conn_Waiting;
114 static void send_init(IOCHAN i)
116 struct connection *co = iochan_getdata(i);
117 struct client *cl = co->client;
118 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
120 a->u.initRequest->implementationId = global_parameters.implementationId;
121 a->u.initRequest->implementationName = global_parameters.implementationName;
122 a->u.initRequest->implementationVersion =
123 global_parameters.implementationVersion;
124 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
125 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
126 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
128 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
129 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
130 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
131 if (send_apdu(cl, a) >= 0)
133 iochan_setflags(i, EVENT_INPUT);
134 cl->state = Client_Initializing;
137 cl->state = Client_Error;
138 odr_reset(global_parameters.odr_out);
141 static void send_search(IOCHAN i)
143 struct connection *co = iochan_getdata(i);
144 struct client *cl = co->client;
145 struct session *se = cl->session;
146 struct database *db = cl->database;
147 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
148 int ndb, cerror, cpos;
151 struct ccl_rpn_node *cn;
152 int ssub = 0, lslb = 100000, mspn = 10;
154 yaz_log(YLOG_DEBUG, "Sending search");
156 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
159 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
161 zquery->which = Z_Query_type_1;
162 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
165 for (ndb = 0; db->databases[ndb]; ndb++)
167 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
168 for (ndb = 0; db->databases[ndb]; ndb++)
169 databaselist[ndb] = db->databases[ndb];
171 a->u.presentRequest->preferredRecordSyntax =
172 yaz_oidval_to_z3950oid(global_parameters.odr_out,
173 CLASS_RECSYN, VAL_USMARC);
174 a->u.searchRequest->smallSetUpperBound = &ssub;
175 a->u.searchRequest->largeSetLowerBound = &lslb;
176 a->u.searchRequest->mediumSetPresentNumber = &mspn;
177 a->u.searchRequest->resultSetName = "Default";
178 a->u.searchRequest->databaseNames = databaselist;
179 a->u.searchRequest->num_databaseNames = ndb;
181 if (send_apdu(cl, a) >= 0)
183 iochan_setflags(i, EVENT_INPUT);
184 cl->state = Client_Searching;
185 cl->requestid = se->requestid;
188 cl->state = Client_Error;
190 odr_reset(global_parameters.odr_out);
193 static void send_present(IOCHAN i)
195 struct connection *co = iochan_getdata(i);
196 struct client *cl = co->client;
197 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
199 int start = cl->records + 1;
201 toget = global_parameters.chunk;
202 if (toget > cl->hits - cl->records)
203 toget = cl->hits - cl->records;
205 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
207 a->u.presentRequest->resultSetStartPoint = &start;
208 a->u.presentRequest->numberOfRecordsRequested = &toget;
210 a->u.presentRequest->resultSetId = "Default";
212 a->u.presentRequest->preferredRecordSyntax =
213 yaz_oidval_to_z3950oid(global_parameters.odr_out,
214 CLASS_RECSYN, VAL_USMARC);
216 if (send_apdu(cl, a) >= 0)
218 iochan_setflags(i, EVENT_INPUT);
219 cl->state = Client_Presenting;
222 cl->state = Client_Error;
223 odr_reset(global_parameters.odr_out);
226 static void do_initResponse(IOCHAN i, Z_APDU *a)
228 struct connection *co = iochan_getdata(i);
229 struct client *cl = co->client;
230 Z_InitResponse *r = a->u.initResponse;
232 yaz_log(YLOG_DEBUG, "Received init response");
236 cl->state = Client_Idle;
239 cl->state = Client_Failed; // FIXME need to do something to the connection
242 static void do_searchResponse(IOCHAN i, Z_APDU *a)
244 struct connection *co = iochan_getdata(i);
245 struct client *cl = co->client;
246 struct session *se = cl->session;
247 Z_SearchResponse *r = a->u.searchResponse;
249 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
251 if (*r->searchStatus)
253 cl->hits = *r->resultCount;
254 se->total_hits += cl->hits;
255 if (r->presentStatus && !*r->presentStatus && r->records)
257 yaz_log(YLOG_DEBUG, "Records in search response");
258 cl->records += *r->numberOfRecordsReturned;
259 ingest_records(cl, r->records);
261 cl->state = Client_Idle;
266 cl->state = Client_Error;
268 Z_Records *recs = r->records;
269 if (recs->which == Z_Records_NSD)
271 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
272 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
273 cl->state = Client_Error;
279 char *normalize_mergekey(char *buf)
281 char *p = buf, *pout = buf;
285 while (*p && !isalnum(*p))
288 *(pout++) = tolower(*(p++));
291 while (*p && !isalnum(*p))
302 // FIXME needs to be generalized. Should flexibly generate X lists per search
303 static void extract_subject(struct session *s, const char *rec)
305 const char *field, *subfield;
307 while ((field = find_field(rec, "650")))
310 if ((subfield = find_subfield(field, 'a')))
316 ef = index(subfield, '\n');
319 if ((e = index(subfield, '\t')) && e < ef)
321 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
325 memcpy(buf, subfield, len);
329 termlist_insert(s->termlist, buf);
336 static void add_facet(struct session *s, const char *type, const char *value)
340 for (i = 0; i < s->num_termlists; i++)
341 if (!strcmp(s->termlists[i].name, type))
343 if (i == s->num_termlists)
345 if (i == SESSION_MAX_TERMLISTS)
347 yaz_log(YLOG_FATAL, "Too many termlists");
350 s->termlists[i].name = nmem_strdup(s->nmem, type);
351 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
352 s->num_termlists = i + 1;
354 termlist_insert(s->termlists[i].termlist, value);
357 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
359 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
360 struct conf_retrievalmap *m;
364 // First normalize to XML
365 if (rprofile->native_syntax == Nativesyn_iso2709)
369 if (rec->which != Z_External_octet)
371 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
374 buf = (char*) rec->u.octet_aligned->buf;
375 len = rec->u.octet_aligned->len;
376 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
378 yaz_log(YLOG_WARN, "Failed to decode MARC");
381 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
382 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
384 yaz_log(YLOG_WARN, "Failed to encode as XML");
387 rdoc = xmlNewDoc("1.0");
388 xmlDocSetRootElement(rdoc, res);
392 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
395 for (m = rprofile->maplist; m; m = m->next)
398 if (m->type != Map_xslt)
400 yaz_log(YLOG_WARN, "Unknown map type");
403 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
405 yaz_log(YLOG_WARN, "XSLT transformation failed");
411 if (global_parameters.dump_records)
413 fprintf(stderr, "Record:\n----------------\n");
414 xmlDocFormatDump(stderr, rdoc, 1);
419 static struct record *ingest_record(struct client *cl, Z_External *rec)
421 xmlDoc *xdoc = normalize_record(cl, rec);
423 struct record *res, *head;
424 struct session *se = cl->session;
425 xmlChar *mergekey, *mergekey_norm;
430 root = xmlDocGetRootElement(xdoc);
431 if (!(mergekey = xmlGetProp(root, "mergekey")))
433 yaz_log(YLOG_WARN, "No mergekey found in record");
438 res = nmem_malloc(se->nmem, sizeof(struct record));
439 res->next_cluster = 0;
440 res->target_offset = -1;
441 res->term_frequency_vec = 0;
442 res->title = "Unknown";
445 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
447 res->merge_key = normalize_mergekey(mergekey_norm);
449 head = reclist_insert(se->reclist, res);
452 /* no room for record */
456 relevance_newrec(se->relevance, head);
458 for (n = root->children; n; n = n->next)
460 if (n->type != XML_ELEMENT_NODE)
462 if (!strcmp(n->name, "facet"))
464 xmlChar *type = xmlGetProp(n, "type");
465 xmlChar *value = xmlNodeListGetString(xdoc, n->children, 0);
468 add_facet(se, type, value);
469 relevance_countwords(se->relevance, head, value, 1);
474 else if (!strcmp(n->name, "metadata"))
476 xmlChar *type = xmlGetProp(n, "type");
477 if (type && !strcmp(type, "title"))
479 xmlChar *value = xmlNodeListGetString(xdoc, n->children, 0);
482 res->title = nmem_strdup(se->nmem, value);
483 relevance_countwords(se->relevance, head, value, 4);
490 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
495 relevance_donerecord(se->relevance, head);
501 static void ingest_records(struct client *cl, Z_Records *r)
504 yaz_timing_t t = yaz_timing_create();
507 struct session *s = cl->session;
508 Z_NamePlusRecordList *rlist;
511 if (r->which != Z_Records_DBOSD)
513 rlist = r->u.databaseOrSurDiagnostics;
514 for (i = 0; i < rlist->num_records; i++)
516 Z_NamePlusRecord *npr = rlist->records[i];
518 if (npr->which != Z_NamePlusRecord_databaseRecord)
520 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
524 rec = ingest_record(cl, npr->u.databaseRecord);
528 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
529 session_alert_watch(s, SESSION_WATCH_RECORDS);
533 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
534 yaz_timing_get_real(t), yaz_timing_get_user(t),
535 yaz_timing_get_sys(t));
536 yaz_timing_destroy(&t);
540 static void do_presentResponse(IOCHAN i, Z_APDU *a)
542 struct connection *co = iochan_getdata(i);
543 struct client *cl = co->client;
544 Z_PresentResponse *r = a->u.presentResponse;
547 Z_Records *recs = r->records;
548 if (recs->which == Z_Records_NSD)
550 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
551 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
552 cl->state = Client_Error;
556 if (!*r->presentStatus && cl->state != Client_Error)
558 yaz_log(YLOG_DEBUG, "Good Present response");
559 cl->records += *r->numberOfRecordsReturned;
560 ingest_records(cl, r->records);
561 cl->state = Client_Idle;
563 else if (*r->presentStatus)
565 yaz_log(YLOG_WARN, "Bad Present response");
566 cl->state = Client_Error;
570 static void handler(IOCHAN i, int event)
572 struct connection *co = iochan_getdata(i);
573 struct client *cl = co->client;
574 struct session *se = 0;
580 yaz_log(YLOG_WARN, "Destroying orphan connection");
581 connection_destroy(co);
585 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
588 socklen_t errlen = sizeof(errcode);
590 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
591 &errlen) < 0 || errcode != 0)
598 yaz_log(YLOG_DEBUG, "Connect OK");
599 co->state = Conn_Open;
601 cl->state = Client_Connected;
605 else if (event & EVENT_INPUT)
607 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
611 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
612 connection_destroy(co);
617 yaz_log(YLOG_WARN, "EOF reading from Z server");
618 connection_destroy(co);
621 else if (len > 1) // We discard input if we have no connection
623 co->state = Conn_Open;
625 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
629 odr_reset(global_parameters.odr_in);
630 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
631 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
638 case Z_APDU_initResponse:
639 do_initResponse(i, a);
641 case Z_APDU_searchResponse:
642 do_searchResponse(i, a);
644 case Z_APDU_presentResponse:
645 do_presentResponse(i, a);
648 yaz_log(YLOG_WARN, "Unexpected result from server");
652 // We aren't expecting staggered output from target
653 // if (cs_more(t->link))
654 // iochan_setevent(i, EVENT_INPUT);
656 else // we throw away response and go to idle mode
658 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
659 cl->state = Client_Idle;
662 /* if len==1 we do nothing but wait for more input */
665 if (cl->state == Client_Connected) {
669 if (cl->state == Client_Idle)
671 if (cl->requestid != se->requestid && *se->query) {
674 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
675 cl->records < cl->hits) {
681 // Disassociate connection from client
682 static void connection_release(struct connection *co)
684 struct client *cl = co->client;
686 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
693 // Close connection and recycle structure
694 static void connection_destroy(struct connection *co)
696 struct host *h = co->host;
698 iochan_destroy(co->iochan);
700 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
701 if (h->connections == co)
702 h->connections = co->next;
705 struct connection *pco;
706 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
709 pco->next = co->next;
715 if (co->client->state != Client_Idle)
716 co->client->state = Client_Disconnected;
717 co->client->connection = 0;
719 co->next = connection_freelist;
720 connection_freelist = co;
723 // Creates a new connection for client, associated with the host of
725 static struct connection *connection_create(struct client *cl)
727 struct connection *new;
732 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
733 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
735 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
739 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
741 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
745 res = cs_connect(link, addr);
748 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
752 if ((new = connection_freelist))
753 connection_freelist = new->next;
756 new = xmalloc(sizeof (struct connection));
760 new->state = Conn_Connecting;
761 new->host = cl->database->host;
762 new->next = new->host->connections;
763 new->host->connections = new;
765 cl->connection = new;
768 new->iochan = iochan_create(cs_fileno(link), handler, 0);
769 iochan_setdata(new->iochan, new);
770 new->iochan->next = channel_list;
771 channel_list = new->iochan;
775 // Close connection and set state to error
776 static void client_fatal(struct client *cl)
778 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
779 connection_destroy(cl->connection);
780 cl->state = Client_Error;
783 // Ensure that client has a connection associated
784 static int client_prep_connection(struct client *cl)
786 struct connection *co;
787 struct session *se = cl->session;
788 struct host *host = cl->database->host;
792 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
796 // See if someone else has an idle connection
797 // We should look at timestamps here to select the longest-idle connection
798 for (co = host->connections; co; co = co->next)
799 if (co->state == Conn_Open && (!co->client || co->client->session != se))
803 connection_release(co);
808 co = connection_create(cl);
812 if (co->state == Conn_Connecting)
814 cl->state = Client_Connecting;
815 iochan_setflag(co->iochan, EVENT_OUTPUT);
817 else if (co->state == Conn_Open)
819 if (cl->state == Client_Error || cl->state == Client_Disconnected)
820 cl->state = Client_Idle;
821 iochan_setflag(co->iochan, EVENT_OUTPUT);
829 // This function will most likely vanish when a proper target profile mechanism is
831 void load_simpletargets(const char *fn)
833 FILE *f = fopen(fn, "r");
838 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
842 while (fgets(line, 255, f))
846 struct database *database;
848 if (strncmp(line, "target ", 7))
851 url[strlen(url) - 1] = '\0';
852 yaz_log(YLOG_DEBUG, "Target: %s", url);
853 if ((db = strchr(url, '/')))
858 for (host = hosts; host; host = host->next)
859 if (!strcmp(url, host->hostport))
863 struct addrinfo *addrinfo, hints;
866 unsigned char addrbuf[4];
869 host = xmalloc(sizeof(struct host));
870 host->hostport = xstrdup(url);
871 host->connections = 0;
873 if ((port = strchr(url, ':')))
879 hints.ai_family = PF_INET;
880 hints.ai_socktype = SOCK_STREAM;
881 hints.ai_protocol = IPPROTO_TCP;
882 hints.ai_addrlen = 0;
884 hints.ai_canonname = 0;
886 // This is not robust code. It assumes that getaddrinfo returns AF_INET
888 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
890 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
891 xfree(host->hostport);
895 assert(addrinfo->ai_family == PF_INET);
896 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
897 sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
898 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
899 host->ipport = xstrdup(ipport);
900 freeaddrinfo(addrinfo);
904 database = xmalloc(sizeof(struct database));
905 database->host = host;
906 database->url = xmalloc(strlen(url) + strlen(db) + 2);
907 strcpy(database->url, url);
908 strcat(database->url, "/");
909 strcat(database->url, db);
911 database->databases = xmalloc(2 * sizeof(char *));
912 database->databases[0] = xstrdup(db);
913 database->databases[1] = 0;
914 database->errors = 0;
915 database->qprofile = 0;
916 database->rprofile = database_retrieval_profile(database);
917 database->next = databases;
918 databases = database;
924 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
932 pull_terms(nmem, n->u.p[0], termlist, num);
933 pull_terms(nmem, n->u.p[1], termlist, num);
936 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
943 // Extract terms from query into null-terminated termlist
944 static int extract_terms(NMEM nmem, char *query, char **termlist)
947 struct ccl_rpn_node *n;
950 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
953 pull_terms(nmem, n, termlist, &num);
959 static struct client *client_create(void)
965 client_freelist = client_freelist->next;
968 r = xmalloc(sizeof(struct client));
977 r->state = Client_Disconnected;
982 void client_destroy(struct client *c)
984 struct session *se = c->session;
985 if (c == se->clients)
986 se->clients = c->next;
990 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
996 connection_release(c->connection);
997 c->next = client_freelist;
1001 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1003 s->watchlist[what].fun = fun;
1004 s->watchlist[what].data = data;
1007 void session_alert_watch(struct session *s, int what)
1009 if (!s->watchlist[what].fun)
1011 (*s->watchlist[what].fun)(s->watchlist[what].data);
1012 s->watchlist[what].fun = 0;
1013 s->watchlist[what].data = 0;
1016 // This needs to be extended with selection criteria
1017 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1021 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1024 if (!config->retrievalprofiles)
1026 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1028 return config->retrievalprofiles;
1031 // This should be extended with parameters to control selection criteria
1032 // Associates a set of clients with a session;
1033 int select_targets(struct session *se)
1035 struct database *db;
1039 client_destroy(se->clients);
1040 for (db = databases; db; db = db->next)
1042 struct client *cl = client_create();
1045 cl->next = se->clients;
1052 int session_active_clients(struct session *s)
1057 for (c = s->clients; c; c = c->next)
1058 if (c->connection && (c->state == Client_Connecting ||
1059 c->state == Client_Initializing ||
1060 c->state == Client_Searching ||
1061 c->state == Client_Presenting))
1067 char *search(struct session *se, char *query)
1069 int live_channels = 0;
1072 yaz_log(YLOG_DEBUG, "Search");
1074 strcpy(se->query, query);
1076 nmem_reset(se->nmem);
1077 for (cl = se->clients; cl; cl = cl->next)
1083 if (client_prep_connection(cl))
1089 int maxrecs = live_channels * global_parameters.toget;
1090 se->num_termlists = 0;
1091 se->reclist = reclist_create(se->nmem, maxrecs);
1092 extract_terms(se->nmem, query, p);
1093 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1094 se->total_records = se->total_hits = 0;
1095 se->expected_maxrecs = maxrecs;
1103 void destroy_session(struct session *s)
1105 yaz_log(YLOG_LOG, "Destroying session");
1107 client_destroy(s->clients);
1108 nmem_destroy(s->nmem);
1109 wrbuf_free(s->wrbuf, 1);
1112 struct session *new_session()
1115 struct session *session = xmalloc(sizeof(*session));
1117 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1119 session->total_hits = 0;
1120 session->total_records = 0;
1121 session->num_termlists = 0;
1122 session->reclist = 0;
1123 session->requestid = -1;
1124 session->clients = 0;
1125 session->expected_maxrecs = 0;
1126 session->query[0] = '\0';
1127 session->nmem = nmem_create();
1128 session->wrbuf = wrbuf_alloc();
1129 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1131 session->watchlist[i].data = 0;
1132 session->watchlist[i].fun = 0;
1135 select_targets(session);
1140 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1142 static struct hitsbytarget res[1000]; // FIXME MM
1146 for (cl = se->clients; cl; cl = cl->next)
1148 strcpy(res[*count].id, cl->database->host->hostport);
1149 res[*count].hits = cl->hits;
1150 res[*count].records = cl->records;
1151 res[*count].diagnostic = cl->diagnostic;
1152 res[*count].state = client_states[cl->state];
1153 res[*count].connected = cl->connection ? 1 : 0;
1160 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1164 for (i = 0; i < s->num_termlists; i++)
1165 if (!strcmp(s->termlists[i].name, name))
1166 return termlist_highscore(s->termlists[i].termlist, num);
1170 #ifdef MISSING_HEADERS
1171 void report_nmem_stats(void)
1173 size_t in_use, is_free;
1175 nmem_get_memory_in_use(&in_use);
1176 nmem_get_memory_free(&is_free);
1178 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1179 (long) in_use, (long) is_free);
1183 struct record **show(struct session *s, int start, int *num, int *total,
1184 int *sumhits, NMEM nmem_show)
1186 struct record **recs = nmem_malloc(nmem_show, *num
1187 * sizeof(struct record *));
1190 yaz_timing_t t = yaz_timing_create();
1192 relevance_prepare_read(s->relevance, s->reclist);
1194 *total = s->reclist->num_records;
1195 *sumhits = s->total_hits;
1197 for (i = 0; i < start; i++)
1198 if (!reclist_read_record(s->reclist))
1205 for (i = 0; i < *num; i++)
1207 struct record *r = reclist_read_record(s->reclist);
1217 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1218 yaz_timing_get_real(t), yaz_timing_get_user(t),
1219 yaz_timing_get_sys(t));
1220 yaz_timing_destroy(&t);
1225 void statistics(struct session *se, struct statistics *stat)
1230 bzero(stat, sizeof(*stat));
1231 for (cl = se->clients; cl; cl = cl->next)
1233 if (!cl->connection)
1234 stat->num_no_connection++;
1237 case Client_Connecting: stat->num_connecting++; break;
1238 case Client_Initializing: stat->num_initializing++; break;
1239 case Client_Searching: stat->num_searching++; break;
1240 case Client_Presenting: stat->num_presenting++; break;
1241 case Client_Idle: stat->num_idle++; break;
1242 case Client_Failed: stat->num_failed++; break;
1243 case Client_Error: stat->num_error++; break;
1248 stat->num_hits = se->total_hits;
1249 stat->num_records = se->total_records;
1251 stat->num_clients = count;
1254 static CCL_bibset load_cclfile(const char *fn)
1256 CCL_bibset res = ccl_qual_mk();
1257 if (ccl_qual_fname(res, fn) < 0)
1259 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1265 int main(int argc, char **argv)
1271 if (signal(SIGPIPE, SIG_IGN) < 0)
1272 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1274 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1276 while ((ret = options("f:x:c:h:p:C:s:d", argv, argc, &arg)) != -2)
1280 if (!read_config(arg))
1284 command_init(atoi(arg));
1292 global_parameters.ccl_filter = load_cclfile(arg);
1295 http_set_proxyaddr(arg);
1298 load_simpletargets(arg);
1301 global_parameters.dump_records = 1;
1304 fprintf(stderr, "Usage: pazpar2\n"
1306 " -h [host:]port (REST protocol listener)\n"
1307 " -c cmdport (telnet-style)\n"
1309 " -s simpletargetfile\n"
1310 " -p hostname[:portno] (HTTP proxy)\n");
1317 fprintf(stderr, "Set command port with -h or -c\n");
1321 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1322 global_parameters.yaz_marc = yaz_marc_create();
1323 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1324 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1325 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1327 event_loop(&channel_list);
1335 * indent-tabs-mode: nil
1337 * vim: shiftwidth=4 tabstop=8 expandtab