1 /* $Id: pazpar2.c,v 1.49 2007-03-15 16:50:56 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>
32 #include <netinet/in.h>
37 #include "termlists.h"
39 #include "relevance.h"
45 static void client_fatal(struct client *cl);
46 static void connection_destroy(struct connection *co);
47 static int client_prep_connection(struct client *cl);
48 static void ingest_records(struct client *cl, Z_Records *r);
49 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
50 void session_alert_watch(struct session *s, int what);
52 IOCHAN channel_list = 0; // Master list of connections we're handling events to
54 static struct connection *connection_freelist = 0;
55 static struct client *client_freelist = 0;
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 =
79 "Index Data PazPar2 (MasterKey)",
91 static int send_apdu(struct client *c, Z_APDU *a)
93 struct connection *co = c->connection;
97 if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
99 odr_perror(global_parameters.odr_out, "Encoding APDU");
102 buf = odr_getbuf(global_parameters.odr_out, &len, 0);
103 r = cs_put(co->link, buf, len);
106 yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
111 fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
114 odr_reset(global_parameters.odr_out); /* release the APDU structure */
115 co->state = Conn_Waiting;
120 static void send_init(IOCHAN i)
122 struct connection *co = iochan_getdata(i);
123 struct client *cl = co->client;
124 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
126 a->u.initRequest->implementationId = global_parameters.implementationId;
127 a->u.initRequest->implementationName = global_parameters.implementationName;
128 a->u.initRequest->implementationVersion =
129 global_parameters.implementationVersion;
130 ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
131 ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
132 ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
134 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
135 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
136 ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
137 if (send_apdu(cl, a) >= 0)
139 iochan_setflags(i, EVENT_INPUT);
140 cl->state = Client_Initializing;
143 cl->state = Client_Error;
144 odr_reset(global_parameters.odr_out);
147 static void send_search(IOCHAN i)
149 struct connection *co = iochan_getdata(i);
150 struct client *cl = co->client;
151 struct session *se = cl->session;
152 struct database *db = cl->database;
153 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
154 int ndb, cerror, cpos;
157 struct ccl_rpn_node *cn;
158 int ssub = 0, lslb = 100000, mspn = 10;
160 yaz_log(YLOG_DEBUG, "Sending search");
162 cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
165 a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
167 zquery->which = Z_Query_type_1;
168 zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
171 for (ndb = 0; db->databases[ndb]; ndb++)
173 databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
174 for (ndb = 0; db->databases[ndb]; ndb++)
175 databaselist[ndb] = db->databases[ndb];
177 a->u.searchRequest->preferredRecordSyntax =
178 yaz_oidval_to_z3950oid(global_parameters.odr_out,
179 CLASS_RECSYN, VAL_USMARC);
180 a->u.searchRequest->smallSetUpperBound = &ssub;
181 a->u.searchRequest->largeSetLowerBound = &lslb;
182 a->u.searchRequest->mediumSetPresentNumber = &mspn;
183 a->u.searchRequest->resultSetName = "Default";
184 a->u.searchRequest->databaseNames = databaselist;
185 a->u.searchRequest->num_databaseNames = ndb;
187 if (send_apdu(cl, a) >= 0)
189 iochan_setflags(i, EVENT_INPUT);
190 cl->state = Client_Searching;
191 cl->requestid = se->requestid;
194 cl->state = Client_Error;
196 odr_reset(global_parameters.odr_out);
199 static void send_present(IOCHAN i)
201 struct connection *co = iochan_getdata(i);
202 struct client *cl = co->client;
203 Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
205 int start = cl->records + 1;
207 toget = global_parameters.chunk;
208 if (toget > global_parameters.toget - cl->records)
209 toget = global_parameters.toget - cl->records;
210 if (toget > cl->hits - cl->records)
211 toget = cl->hits - cl->records;
213 yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
215 a->u.presentRequest->resultSetStartPoint = &start;
216 a->u.presentRequest->numberOfRecordsRequested = &toget;
218 a->u.presentRequest->resultSetId = "Default";
220 a->u.presentRequest->preferredRecordSyntax =
221 yaz_oidval_to_z3950oid(global_parameters.odr_out,
222 CLASS_RECSYN, VAL_USMARC);
224 if (send_apdu(cl, a) >= 0)
226 iochan_setflags(i, EVENT_INPUT);
227 cl->state = Client_Presenting;
230 cl->state = Client_Error;
231 odr_reset(global_parameters.odr_out);
234 static void do_initResponse(IOCHAN i, Z_APDU *a)
236 struct connection *co = iochan_getdata(i);
237 struct client *cl = co->client;
238 Z_InitResponse *r = a->u.initResponse;
240 yaz_log(YLOG_DEBUG, "Received init response");
244 cl->state = Client_Idle;
247 cl->state = Client_Failed; // FIXME need to do something to the connection
250 static void do_searchResponse(IOCHAN i, Z_APDU *a)
252 struct connection *co = iochan_getdata(i);
253 struct client *cl = co->client;
254 struct session *se = cl->session;
255 Z_SearchResponse *r = a->u.searchResponse;
257 yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
259 if (*r->searchStatus)
261 cl->hits = *r->resultCount;
262 se->total_hits += cl->hits;
263 if (r->presentStatus && !*r->presentStatus && r->records)
265 yaz_log(YLOG_DEBUG, "Records in search response");
266 ingest_records(cl, r->records);
268 cl->state = Client_Idle;
273 cl->state = Client_Error;
275 Z_Records *recs = r->records;
276 if (recs->which == Z_Records_NSD)
278 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
279 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
280 cl->state = Client_Error;
286 char *normalize_mergekey(char *buf, int skiparticle)
288 char *p = buf, *pout = buf;
293 char articles[] = "the den der die des an a "; // must end in space
295 while (*p && !isalnum(*p))
298 while (*p && *p != ' ' && pout - firstword < 62)
299 *(pout++) = tolower(*(p++));
302 if (!strstr(articles, firstword))
309 while (*p && !isalnum(*p))
312 *(pout++) = tolower(*(p++));
315 while (*p && !isalnum(*p))
322 while (pout > buf && *pout == ' ');
329 // FIXME needs to be generalized. Should flexibly generate X lists per search
330 static void extract_subject(struct session *s, const char *rec)
332 const char *field, *subfield;
334 while ((field = find_field(rec, "650")))
337 if ((subfield = find_subfield(field, 'a')))
343 ef = index(subfield, '\n');
346 if ((e = index(subfield, '\t')) && e < ef)
348 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
352 memcpy(buf, subfield, len);
356 termlist_insert(s->termlist, buf);
363 static void add_facet(struct session *s, const char *type, const char *value)
369 for (i = 0; i < s->num_termlists; i++)
370 if (!strcmp(s->termlists[i].name, type))
372 if (i == s->num_termlists)
374 if (i == SESSION_MAX_TERMLISTS)
376 yaz_log(YLOG_FATAL, "Too many termlists");
379 s->termlists[i].name = nmem_strdup(s->nmem, type);
380 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
381 s->num_termlists = i + 1;
383 termlist_insert(s->termlists[i].termlist, value);
386 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
388 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
389 struct conf_retrievalmap *m;
393 // First normalize to XML
394 if (rprofile->native_syntax == Nativesyn_iso2709)
398 if (rec->which != Z_External_octet)
400 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
403 buf = (char*) rec->u.octet_aligned->buf;
404 len = rec->u.octet_aligned->len;
405 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
407 yaz_log(YLOG_WARN, "Failed to decode MARC");
410 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
411 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
413 yaz_log(YLOG_WARN, "Failed to encode as XML");
416 rdoc = xmlNewDoc("1.0");
417 xmlDocSetRootElement(rdoc, res);
421 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
425 if (global_parameters.dump_records)
427 fprintf(stderr, "Input Record (normalized):\n----------------\n");
428 #if LIBXML_VERSION >= 20600
429 xmlDocFormatDump(stderr, rdoc, 1);
431 xmlDocDump(stderr, rdoc);
435 for (m = rprofile->maplist; m; m = m->next)
438 if (m->type != Map_xslt)
440 yaz_log(YLOG_WARN, "Unknown map type");
443 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
445 yaz_log(YLOG_WARN, "XSLT transformation failed");
451 if (global_parameters.dump_records)
453 fprintf(stderr, "Record:\n----------------\n");
454 #if LIBXML_VERSION >= 20600
455 xmlDocFormatDump(stderr, rdoc, 1);
457 xmlDocDump(stderr, rdoc);
463 // Extract what appears to be years from buf, storing highest and
465 static int extract_years(const char *buf, int *first, int *last)
474 while (*buf && !isdigit(*buf))
477 for (e = buf; *e && isdigit(*e); e++)
481 int value = atoi(buf);
482 if (*first < 0 || value < *first)
484 if (*last < 0 || value > *last)
492 static struct record *ingest_record(struct client *cl, Z_External *rec)
494 xmlDoc *xdoc = normalize_record(cl, rec);
497 struct record_cluster *cluster;
498 struct session *se = cl->session;
499 xmlChar *mergekey, *mergekey_norm;
502 struct conf_service *service = global_parameters.server->service;
507 root = xmlDocGetRootElement(xdoc);
508 if (!(mergekey = xmlGetProp(root, "mergekey")))
510 yaz_log(YLOG_WARN, "No mergekey found in record");
515 res = nmem_malloc(se->nmem, sizeof(struct record));
518 res->metadata = nmem_malloc(se->nmem,
519 sizeof(struct record_metadata*) * service->num_metadata);
520 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
522 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
524 normalize_mergekey(mergekey_norm, 0);
526 cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
527 if (global_parameters.dump_records)
528 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
529 cl->database->url, cl->records);
532 /* no room for record */
536 relevance_newrec(se->relevance, cluster);
538 for (n = root->children; n; n = n->next)
546 if (n->type != XML_ELEMENT_NODE)
548 if (!strcmp(n->name, "metadata"))
550 struct conf_metadata *md = 0;
551 struct conf_sortkey *sk = 0;
552 struct record_metadata **wheretoput, *newm;
556 type = xmlGetProp(n, "type");
557 value = xmlNodeListGetString(xdoc, n->children, 0);
562 // First, find out what field we're looking at
563 for (imeta = 0; imeta < service->num_metadata; imeta++)
564 if (!strcmp(type, service->metadata[imeta].name))
566 md = &service->metadata[imeta];
567 if (md->sortkey_offset >= 0)
568 sk = &service->sortkeys[md->sortkey_offset];
573 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
577 // Find out where we are putting it
578 if (md->merge == Metadata_merge_no)
579 wheretoput = &res->metadata[imeta];
581 wheretoput = &cluster->metadata[imeta];
584 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
586 if (md->type == Metadata_type_generic)
589 for (p = value; *p && isspace(*p); p++)
591 for (pe = p + strlen(p) - 1;
592 pe > p && strchr(" ,/.:([", *pe); pe--)
594 newm->data.text = nmem_strdup(se->nmem, p);
597 else if (md->type == Metadata_type_year)
599 if (extract_years(value, &first, &last) < 0)
604 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
607 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
609 yaz_log(YLOG_WARN, "Only range merging supported for years");
612 if (md->merge == Metadata_merge_unique)
614 struct record_metadata *mnode;
615 for (mnode = *wheretoput; mnode; mnode = mnode->next)
616 if (!strcmp(mnode->data.text, newm->data.text))
620 newm->next = *wheretoput;
624 else if (md->merge == Metadata_merge_longest)
627 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
632 char *s = nmem_strdup(se->nmem, newm->data.text);
633 if (!cluster->sortkeys[md->sortkey_offset])
634 cluster->sortkeys[md->sortkey_offset] =
635 nmem_malloc(se->nmem, sizeof(union data_types));
636 normalize_mergekey(s,
637 (sk->type == Metadata_sortkey_skiparticle));
638 cluster->sortkeys[md->sortkey_offset]->text = s;
642 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
644 newm->next = *wheretoput;
647 else if (md->merge == Metadata_merge_range)
649 assert(md->type == Metadata_type_year);
653 (*wheretoput)->data.number.min = first;
654 (*wheretoput)->data.number.max = last;
656 cluster->sortkeys[md->sortkey_offset] = &newm->data;
660 if (first < (*wheretoput)->data.number.min)
661 (*wheretoput)->data.number.min = first;
662 if (last > (*wheretoput)->data.number.max)
663 (*wheretoput)->data.number.max = last;
668 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
669 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
674 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
677 relevance_countwords(se->relevance, cluster, value, md->rank);
680 if (md->type == Metadata_type_year)
683 sprintf(year, "%d", last);
684 add_facet(se, type, year);
687 sprintf(year, "%d", first);
688 add_facet(se, type, year);
692 add_facet(se, type, value);
699 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
708 relevance_donerecord(se->relevance, cluster);
714 static void ingest_records(struct client *cl, Z_Records *r)
717 yaz_timing_t t = yaz_timing_create();
720 struct session *s = cl->session;
721 Z_NamePlusRecordList *rlist;
724 if (r->which != Z_Records_DBOSD)
726 rlist = r->u.databaseOrSurDiagnostics;
727 for (i = 0; i < rlist->num_records; i++)
729 Z_NamePlusRecord *npr = rlist->records[i];
732 if (npr->which != Z_NamePlusRecord_databaseRecord)
734 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
738 rec = ingest_record(cl, npr->u.databaseRecord);
742 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
743 session_alert_watch(s, SESSION_WATCH_RECORDS);
747 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
748 yaz_timing_get_real(t), yaz_timing_get_user(t),
749 yaz_timing_get_sys(t));
750 yaz_timing_destroy(&t);
754 static void do_presentResponse(IOCHAN i, Z_APDU *a)
756 struct connection *co = iochan_getdata(i);
757 struct client *cl = co->client;
758 Z_PresentResponse *r = a->u.presentResponse;
761 Z_Records *recs = r->records;
762 if (recs->which == Z_Records_NSD)
764 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
765 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
766 cl->state = Client_Error;
770 if (!*r->presentStatus && cl->state != Client_Error)
772 yaz_log(YLOG_DEBUG, "Good Present response");
773 ingest_records(cl, r->records);
774 cl->state = Client_Idle;
776 else if (*r->presentStatus)
778 yaz_log(YLOG_WARN, "Bad Present response");
779 cl->state = Client_Error;
783 static void handler(IOCHAN i, int event)
785 struct connection *co = iochan_getdata(i);
786 struct client *cl = co->client;
787 struct session *se = 0;
793 yaz_log(YLOG_WARN, "Destroying orphan connection");
794 connection_destroy(co);
798 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
801 socklen_t errlen = sizeof(errcode);
803 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
804 &errlen) < 0 || errcode != 0)
811 yaz_log(YLOG_DEBUG, "Connect OK");
812 co->state = Conn_Open;
814 cl->state = Client_Connected;
818 else if (event & EVENT_INPUT)
820 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
824 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
825 connection_destroy(co);
830 yaz_log(YLOG_WARN, "EOF reading from Z server");
831 connection_destroy(co);
834 else if (len > 1) // We discard input if we have no connection
836 co->state = Conn_Open;
838 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
842 odr_reset(global_parameters.odr_in);
843 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
844 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
851 case Z_APDU_initResponse:
852 do_initResponse(i, a);
854 case Z_APDU_searchResponse:
855 do_searchResponse(i, a);
857 case Z_APDU_presentResponse:
858 do_presentResponse(i, a);
861 yaz_log(YLOG_WARN, "Unexpected result from server");
865 // We aren't expecting staggered output from target
866 // if (cs_more(t->link))
867 // iochan_setevent(i, EVENT_INPUT);
869 else // we throw away response and go to idle mode
871 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
872 cl->state = Client_Idle;
875 /* if len==1 we do nothing but wait for more input */
878 if (cl->state == Client_Connected) {
882 if (cl->state == Client_Idle)
884 if (cl->requestid != se->requestid && *se->query) {
887 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
888 cl->records < cl->hits) {
894 // Disassociate connection from client
895 static void connection_release(struct connection *co)
897 struct client *cl = co->client;
899 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
906 // Close connection and recycle structure
907 static void connection_destroy(struct connection *co)
909 struct host *h = co->host;
911 iochan_destroy(co->iochan);
913 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
914 if (h->connections == co)
915 h->connections = co->next;
918 struct connection *pco;
919 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
922 pco->next = co->next;
928 if (co->client->state != Client_Idle)
929 co->client->state = Client_Disconnected;
930 co->client->connection = 0;
932 co->next = connection_freelist;
933 connection_freelist = co;
936 // Creates a new connection for client, associated with the host of
938 static struct connection *connection_create(struct client *cl)
940 struct connection *new;
945 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
946 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
948 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
952 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
954 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?",
955 cl->database->host->ipport);
959 res = cs_connect(link, addr);
962 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
966 if ((new = connection_freelist))
967 connection_freelist = new->next;
970 new = xmalloc(sizeof (struct connection));
974 new->state = Conn_Connecting;
975 new->host = cl->database->host;
976 new->next = new->host->connections;
977 new->host->connections = new;
979 cl->connection = new;
982 new->iochan = iochan_create(cs_fileno(link), handler, 0);
983 iochan_setdata(new->iochan, new);
984 new->iochan->next = channel_list;
985 channel_list = new->iochan;
989 // Close connection and set state to error
990 static void client_fatal(struct client *cl)
992 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
993 connection_destroy(cl->connection);
994 cl->state = Client_Error;
997 // Ensure that client has a connection associated
998 static int client_prep_connection(struct client *cl)
1000 struct connection *co;
1001 struct session *se = cl->session;
1002 struct host *host = cl->database->host;
1004 co = cl->connection;
1006 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1010 // See if someone else has an idle connection
1011 // We should look at timestamps here to select the longest-idle connection
1012 for (co = host->connections; co; co = co->next)
1013 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1017 connection_release(co);
1018 cl->connection = co;
1022 co = connection_create(cl);
1026 if (co->state == Conn_Connecting)
1028 cl->state = Client_Connecting;
1029 iochan_setflag(co->iochan, EVENT_OUTPUT);
1031 else if (co->state == Conn_Open)
1033 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1034 cl->state = Client_Idle;
1035 iochan_setflag(co->iochan, EVENT_OUTPUT);
1043 #ifdef GAGA // Moved to database.c
1045 // This function will most likely vanish when a proper target profile mechanism is
1047 void load_simpletargets(const char *fn)
1049 FILE *f = fopen(fn, "r");
1054 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1058 while (fgets(line, 255, f))
1063 struct database *database;
1065 if (strncmp(line, "target ", 7))
1067 line[strlen(line) - 1] = '\0';
1069 if ((name = strchr(line, ';')))
1073 if ((db = strchr(url, '/')))
1078 yaz_log(YLOG_LOG, "Target: %s, '%s'", url, db);
1079 for (host = hosts; host; host = host->next)
1080 if (!strcmp(url, host->hostport))
1084 struct addrinfo *addrinfo, hints;
1087 unsigned char addrbuf[4];
1090 host = xmalloc(sizeof(struct host));
1091 host->hostport = xstrdup(url);
1092 host->connections = 0;
1094 if ((port = strchr(url, ':')))
1100 hints.ai_family = PF_INET;
1101 hints.ai_socktype = SOCK_STREAM;
1102 hints.ai_protocol = IPPROTO_TCP;
1103 hints.ai_addrlen = 0;
1105 hints.ai_canonname = 0;
1107 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1109 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1111 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1112 xfree(host->hostport);
1116 assert(addrinfo->ai_family == PF_INET);
1117 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1118 sprintf(ipport, "%u.%u.%u.%u:%s",
1119 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1120 host->ipport = xstrdup(ipport);
1121 freeaddrinfo(addrinfo);
1125 database = xmalloc(sizeof(struct database));
1126 database->host = host;
1127 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1128 strcpy(database->url, url);
1129 strcat(database->url, "/");
1130 strcat(database->url, db);
1132 database->name = xstrdup(name);
1136 database->databases = xmalloc(2 * sizeof(char *));
1137 database->databases[0] = xstrdup(db);
1138 database->databases[1] = 0;
1139 database->errors = 0;
1140 database->qprofile = 0;
1141 database->rprofile = database_retrieval_profile(database);
1142 database->next = databases;
1143 databases = database;
1151 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1159 pull_terms(nmem, n->u.p[0], termlist, num);
1160 pull_terms(nmem, n->u.p[1], termlist, num);
1163 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1170 // Extract terms from query into null-terminated termlist
1171 static int extract_terms(NMEM nmem, char *query, char **termlist)
1174 struct ccl_rpn_node *n;
1177 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1180 pull_terms(nmem, n, termlist, &num);
1186 static struct client *client_create(void)
1189 if (client_freelist)
1191 r = client_freelist;
1192 client_freelist = client_freelist->next;
1195 r = xmalloc(sizeof(struct client));
1204 r->state = Client_Disconnected;
1209 void client_destroy(struct client *c)
1211 struct session *se = c->session;
1212 if (c == se->clients)
1213 se->clients = c->next;
1217 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1223 connection_release(c->connection);
1224 c->next = client_freelist;
1225 client_freelist = c;
1228 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1230 s->watchlist[what].fun = fun;
1231 s->watchlist[what].data = data;
1234 void session_alert_watch(struct session *s, int what)
1236 if (!s->watchlist[what].fun)
1238 (*s->watchlist[what].fun)(s->watchlist[what].data);
1239 s->watchlist[what].fun = 0;
1240 s->watchlist[what].data = 0;
1243 //callback for grep_databases
1244 static void select_targets_callback(void *context, struct database *db)
1246 struct session *se = (struct session*) context;
1247 struct client *cl = client_create();
1250 cl->next = se->clients;
1254 // This should be extended with parameters to control selection criteria
1255 // Associates a set of clients with a session;
1256 int select_targets(struct session *se)
1259 client_destroy(se->clients);
1261 return grep_databases(se, select_targets_callback);
1264 int session_active_clients(struct session *s)
1269 for (c = s->clients; c; c = c->next)
1270 if (c->connection && (c->state == Client_Connecting ||
1271 c->state == Client_Initializing ||
1272 c->state == Client_Searching ||
1273 c->state == Client_Presenting))
1279 char *search(struct session *se, char *query)
1281 int live_channels = 0;
1284 yaz_log(YLOG_DEBUG, "Search");
1286 strcpy(se->query, query);
1288 nmem_reset(se->nmem);
1289 for (cl = se->clients; cl; cl = cl->next)
1295 if (client_prep_connection(cl))
1301 int maxrecs = live_channels * global_parameters.toget;
1302 se->num_termlists = 0;
1303 se->reclist = reclist_create(se->nmem, maxrecs);
1304 extract_terms(se->nmem, query, p);
1305 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1306 se->total_records = se->total_hits = se->total_merged = 0;
1307 se->expected_maxrecs = maxrecs;
1315 void destroy_session(struct session *s)
1317 yaz_log(YLOG_LOG, "Destroying session");
1319 client_destroy(s->clients);
1320 nmem_destroy(s->nmem);
1321 wrbuf_free(s->wrbuf, 1);
1324 struct session *new_session()
1327 struct session *session = xmalloc(sizeof(*session));
1329 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1331 session->total_hits = 0;
1332 session->total_records = 0;
1333 session->num_termlists = 0;
1334 session->reclist = 0;
1335 session->requestid = -1;
1336 session->clients = 0;
1337 session->expected_maxrecs = 0;
1338 session->query[0] = '\0';
1339 session->nmem = nmem_create();
1340 session->wrbuf = wrbuf_alloc();
1341 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1343 session->watchlist[i].data = 0;
1344 session->watchlist[i].fun = 0;
1347 select_targets(session);
1352 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1354 static struct hitsbytarget res[1000]; // FIXME MM
1358 for (cl = se->clients; cl; cl = cl->next)
1360 res[*count].id = cl->database->url;
1361 res[*count].name = cl->database->name;
1362 res[*count].hits = cl->hits;
1363 res[*count].records = cl->records;
1364 res[*count].diagnostic = cl->diagnostic;
1365 res[*count].state = client_states[cl->state];
1366 res[*count].connected = cl->connection ? 1 : 0;
1373 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1377 for (i = 0; i < s->num_termlists; i++)
1378 if (!strcmp(s->termlists[i].name, name))
1379 return termlist_highscore(s->termlists[i].termlist, num);
1383 #ifdef MISSING_HEADERS
1384 void report_nmem_stats(void)
1386 size_t in_use, is_free;
1388 nmem_get_memory_in_use(&in_use);
1389 nmem_get_memory_free(&is_free);
1391 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1392 (long) in_use, (long) is_free);
1396 struct record_cluster *show_single(struct session *s, int id)
1398 struct record_cluster *r;
1400 reclist_rewind(s->reclist);
1401 while ((r = reclist_read_record(s->reclist)))
1407 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1408 int *num, int *total, int *sumhits, NMEM nmem_show)
1410 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1411 * sizeof(struct record_cluster *));
1412 struct reclist_sortparms *spp;
1415 yaz_timing_t t = yaz_timing_create();
1418 for (spp = sp; spp; spp = spp->next)
1419 if (spp->type == Metadata_sortkey_relevance)
1421 relevance_prepare_read(s->relevance, s->reclist);
1424 reclist_sort(s->reclist, sp);
1426 *total = s->reclist->num_records;
1427 *sumhits = s->total_hits;
1429 for (i = 0; i < start; i++)
1430 if (!reclist_read_record(s->reclist))
1437 for (i = 0; i < *num; i++)
1439 struct record_cluster *r = reclist_read_record(s->reclist);
1449 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1450 yaz_timing_get_real(t), yaz_timing_get_user(t),
1451 yaz_timing_get_sys(t));
1452 yaz_timing_destroy(&t);
1457 void statistics(struct session *se, struct statistics *stat)
1462 memset(stat, 0, sizeof(*stat));
1463 for (cl = se->clients; cl; cl = cl->next)
1465 if (!cl->connection)
1466 stat->num_no_connection++;
1469 case Client_Connecting: stat->num_connecting++; break;
1470 case Client_Initializing: stat->num_initializing++; break;
1471 case Client_Searching: stat->num_searching++; break;
1472 case Client_Presenting: stat->num_presenting++; break;
1473 case Client_Idle: stat->num_idle++; break;
1474 case Client_Failed: stat->num_failed++; break;
1475 case Client_Error: stat->num_error++; break;
1480 stat->num_hits = se->total_hits;
1481 stat->num_records = se->total_records;
1483 stat->num_clients = count;
1486 static CCL_bibset load_cclfile(const char *fn)
1488 CCL_bibset res = ccl_qual_mk();
1489 if (ccl_qual_fname(res, fn) < 0)
1491 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1497 static void start_http_listener(void)
1500 struct conf_server *ser = global_parameters.server;
1502 if (*global_parameters.listener_override)
1503 strcpy(hp, global_parameters.listener_override);
1506 strcpy(hp, ser->host ? ser->host : "");
1511 sprintf(hp + strlen(hp), "%d", ser->port);
1517 static void start_proxy(void)
1520 struct conf_server *ser = global_parameters.server;
1522 if (*global_parameters.proxy_override)
1523 strcpy(hp, global_parameters.proxy_override);
1524 else if (ser->proxy_host || ser->proxy_port)
1526 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1527 if (ser->proxy_port)
1531 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1537 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1540 int main(int argc, char **argv)
1545 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1546 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1548 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1550 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1554 if (!read_config(arg))
1558 strcpy(global_parameters.listener_override, arg);
1561 global_parameters.ccl_filter = load_cclfile(arg);
1564 strcpy(global_parameters.proxy_override, arg);
1567 load_simpletargets(arg);
1570 global_parameters.dump_records = 1;
1573 fprintf(stderr, "Usage: pazpar2\n"
1575 " -h [host:]port (REST protocol listener)\n"
1577 " -s simpletargetfile\n"
1578 " -p hostname[:portno] (HTTP proxy)\n"
1579 " -d (show internal records)\n");
1586 yaz_log(YLOG_FATAL, "Load config with -f");
1589 global_parameters.server = config->servers;
1591 start_http_listener();
1593 if (!global_parameters.ccl_filter)
1594 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1595 global_parameters.yaz_marc = yaz_marc_create();
1596 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1597 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1598 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1600 event_loop(&channel_list);
1608 * indent-tabs-mode: nil
1610 * vim: shiftwidth=4 tabstop=8 expandtab