1 /* $Id: pazpar2.c,v 1.31 2007-01-15 05:40:24 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"
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, int skiparticle)
291 char *p = buf, *pout = buf;
296 char articles[] = "the den der die des an a "; // must end in space
298 while (*p && !isalnum(*p))
301 while (*p && *p != ' ' && pout - firstword < 62)
302 *(pout++) = tolower(*(p++));
305 if (!strstr(articles, firstword))
312 while (*p && !isalnum(*p))
315 *(pout++) = tolower(*(p++));
318 while (*p && !isalnum(*p))
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)
367 for (i = 0; i < s->num_termlists; i++)
368 if (!strcmp(s->termlists[i].name, type))
370 if (i == s->num_termlists)
372 if (i == SESSION_MAX_TERMLISTS)
374 yaz_log(YLOG_FATAL, "Too many termlists");
377 s->termlists[i].name = nmem_strdup(s->nmem, type);
378 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
379 s->num_termlists = i + 1;
381 termlist_insert(s->termlists[i].termlist, value);
384 int yaz_marc_write_xml();
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");
424 for (m = rprofile->maplist; m; m = m->next)
427 if (m->type != Map_xslt)
429 yaz_log(YLOG_WARN, "Unknown map type");
432 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
434 yaz_log(YLOG_WARN, "XSLT transformation failed");
440 if (global_parameters.dump_records)
442 fprintf(stderr, "Record:\n----------------\n");
443 #if LIBXML_VERSION >= 20600
444 xmlDocFormatDump(stderr, rdoc, 1);
446 xmlDocDump(stderr, rdoc);
452 // Extract what appears to be years from buf, storing highest and
454 static int extract_years(const char *buf, int *first, int *last)
463 while (*buf && !isdigit(*buf))
466 for (e = buf; *e && isdigit(*e); e++)
470 int value = atoi(buf);
471 if (*first < 0 || value < *first)
473 if (*last < 0 || value > *last)
481 static struct record *ingest_record(struct client *cl, Z_External *rec)
483 xmlDoc *xdoc = normalize_record(cl, rec);
486 struct record_cluster *cluster;
487 struct session *se = cl->session;
488 xmlChar *mergekey, *mergekey_norm;
491 struct conf_service *service = global_parameters.server->service;
496 root = xmlDocGetRootElement(xdoc);
497 if (!(mergekey = xmlGetProp(root, "mergekey")))
499 yaz_log(YLOG_WARN, "No mergekey found in record");
504 res = nmem_malloc(se->nmem, sizeof(struct record));
506 res->metadata = nmem_malloc(se->nmem,
507 sizeof(struct record_metadata*) * service->num_metadata);
508 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
510 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
512 normalize_mergekey(mergekey_norm, 0);
514 cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
517 /* no room for record */
521 relevance_newrec(se->relevance, cluster);
524 for (n = root->children; n; n = n->next)
532 if (n->type != XML_ELEMENT_NODE)
534 if (!strcmp(n->name, "metadata"))
536 struct conf_metadata *md = 0;
537 struct conf_sortkey *sk = 0;
538 struct record_metadata **wheretoput, *newm;
542 type = xmlGetProp(n, "type");
543 value = xmlNodeListGetString(xdoc, n->children, 0);
544 // First, find out what field we're looking at
545 for (imeta = 0; imeta < service->num_metadata; imeta++)
546 if (!strcmp(type, service->metadata[imeta].name))
548 md = &service->metadata[imeta];
549 if (md->sortkey_offset >= 0)
550 sk = &service->sortkeys[md->sortkey_offset];
555 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
559 // Find out where we are putting it
560 if (md->merge == Metadata_merge_no)
561 wheretoput = &res->metadata[imeta];
563 wheretoput = &cluster->metadata[imeta];
566 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
568 if (md->type == Metadata_type_generic)
570 newm->data.text = nmem_strdup(se->nmem, value);
572 else if (md->type == Metadata_type_year)
574 if (extract_years(value, &first, &last) < 0)
579 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
582 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
584 yaz_log(YLOG_WARN, "Only range merging supported for years");
587 if (md->merge == Metadata_merge_unique)
589 struct record_metadata *mnode;
590 for (mnode = *wheretoput; mnode; mnode = mnode->next)
591 if (!strcmp(mnode->data.text, mnode->data.text))
595 newm->next = *wheretoput;
599 else if (md->merge == Metadata_merge_longest)
602 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
607 char *s = nmem_strdup(se->nmem, newm->data.text);
608 if (!cluster->sortkeys[md->sortkey_offset])
609 cluster->sortkeys[md->sortkey_offset] =
610 nmem_malloc(se->nmem, sizeof(union data_types));
611 normalize_mergekey(s,
612 (sk->type == Metadata_sortkey_skiparticle));
613 cluster->sortkeys[md->sortkey_offset]->text = s;
617 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
619 newm->next = *wheretoput;
622 else if (md->merge == Metadata_merge_range)
624 assert(md->type == Metadata_type_year);
628 (*wheretoput)->data.number.min = first;
629 (*wheretoput)->data.number.max = last;
631 cluster->sortkeys[md->sortkey_offset] = &newm->data;
635 if (first < (*wheretoput)->data.number.min)
636 (*wheretoput)->data.number.min = first;
637 if (last > (*wheretoput)->data.number.max)
638 (*wheretoput)->data.number.max = last;
641 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
642 sdata->number.min = first;
643 sdata->number.max = last;
649 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
650 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
655 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
658 relevance_countwords(se->relevance, cluster, value, md->rank);
660 add_facet(se, type, value);
666 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
671 relevance_donerecord(se->relevance, cluster);
677 static void ingest_records(struct client *cl, Z_Records *r)
680 yaz_timing_t t = yaz_timing_create();
683 struct session *s = cl->session;
684 Z_NamePlusRecordList *rlist;
687 if (r->which != Z_Records_DBOSD)
689 rlist = r->u.databaseOrSurDiagnostics;
690 for (i = 0; i < rlist->num_records; i++)
692 Z_NamePlusRecord *npr = rlist->records[i];
694 if (npr->which != Z_NamePlusRecord_databaseRecord)
696 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
700 rec = ingest_record(cl, npr->u.databaseRecord);
704 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
705 session_alert_watch(s, SESSION_WATCH_RECORDS);
709 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
710 yaz_timing_get_real(t), yaz_timing_get_user(t),
711 yaz_timing_get_sys(t));
712 yaz_timing_destroy(&t);
716 static void do_presentResponse(IOCHAN i, Z_APDU *a)
718 struct connection *co = iochan_getdata(i);
719 struct client *cl = co->client;
720 Z_PresentResponse *r = a->u.presentResponse;
723 Z_Records *recs = r->records;
724 if (recs->which == Z_Records_NSD)
726 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
727 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
728 cl->state = Client_Error;
732 if (!*r->presentStatus && cl->state != Client_Error)
734 yaz_log(YLOG_DEBUG, "Good Present response");
735 cl->records += *r->numberOfRecordsReturned;
736 ingest_records(cl, r->records);
737 cl->state = Client_Idle;
739 else if (*r->presentStatus)
741 yaz_log(YLOG_WARN, "Bad Present response");
742 cl->state = Client_Error;
746 static void handler(IOCHAN i, int event)
748 struct connection *co = iochan_getdata(i);
749 struct client *cl = co->client;
750 struct session *se = 0;
756 yaz_log(YLOG_WARN, "Destroying orphan connection");
757 connection_destroy(co);
761 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
764 socklen_t errlen = sizeof(errcode);
766 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
767 &errlen) < 0 || errcode != 0)
774 yaz_log(YLOG_DEBUG, "Connect OK");
775 co->state = Conn_Open;
777 cl->state = Client_Connected;
781 else if (event & EVENT_INPUT)
783 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
787 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
788 connection_destroy(co);
793 yaz_log(YLOG_WARN, "EOF reading from Z server");
794 connection_destroy(co);
797 else if (len > 1) // We discard input if we have no connection
799 co->state = Conn_Open;
801 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
805 odr_reset(global_parameters.odr_in);
806 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
807 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
814 case Z_APDU_initResponse:
815 do_initResponse(i, a);
817 case Z_APDU_searchResponse:
818 do_searchResponse(i, a);
820 case Z_APDU_presentResponse:
821 do_presentResponse(i, a);
824 yaz_log(YLOG_WARN, "Unexpected result from server");
828 // We aren't expecting staggered output from target
829 // if (cs_more(t->link))
830 // iochan_setevent(i, EVENT_INPUT);
832 else // we throw away response and go to idle mode
834 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
835 cl->state = Client_Idle;
838 /* if len==1 we do nothing but wait for more input */
841 if (cl->state == Client_Connected) {
845 if (cl->state == Client_Idle)
847 if (cl->requestid != se->requestid && *se->query) {
850 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
851 cl->records < cl->hits) {
857 // Disassociate connection from client
858 static void connection_release(struct connection *co)
860 struct client *cl = co->client;
862 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
869 // Close connection and recycle structure
870 static void connection_destroy(struct connection *co)
872 struct host *h = co->host;
874 iochan_destroy(co->iochan);
876 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
877 if (h->connections == co)
878 h->connections = co->next;
881 struct connection *pco;
882 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
885 pco->next = co->next;
891 if (co->client->state != Client_Idle)
892 co->client->state = Client_Disconnected;
893 co->client->connection = 0;
895 co->next = connection_freelist;
896 connection_freelist = co;
899 // Creates a new connection for client, associated with the host of
901 static struct connection *connection_create(struct client *cl)
903 struct connection *new;
908 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
909 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
911 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
915 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
917 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?",
918 cl->database->host->ipport);
922 res = cs_connect(link, addr);
925 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
929 if ((new = connection_freelist))
930 connection_freelist = new->next;
933 new = xmalloc(sizeof (struct connection));
937 new->state = Conn_Connecting;
938 new->host = cl->database->host;
939 new->next = new->host->connections;
940 new->host->connections = new;
942 cl->connection = new;
945 new->iochan = iochan_create(cs_fileno(link), handler, 0);
946 iochan_setdata(new->iochan, new);
947 new->iochan->next = channel_list;
948 channel_list = new->iochan;
952 // Close connection and set state to error
953 static void client_fatal(struct client *cl)
955 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
956 connection_destroy(cl->connection);
957 cl->state = Client_Error;
960 // Ensure that client has a connection associated
961 static int client_prep_connection(struct client *cl)
963 struct connection *co;
964 struct session *se = cl->session;
965 struct host *host = cl->database->host;
969 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
973 // See if someone else has an idle connection
974 // We should look at timestamps here to select the longest-idle connection
975 for (co = host->connections; co; co = co->next)
976 if (co->state == Conn_Open && (!co->client || co->client->session != se))
980 connection_release(co);
985 co = connection_create(cl);
989 if (co->state == Conn_Connecting)
991 cl->state = Client_Connecting;
992 iochan_setflag(co->iochan, EVENT_OUTPUT);
994 else if (co->state == Conn_Open)
996 if (cl->state == Client_Error || cl->state == Client_Disconnected)
997 cl->state = Client_Idle;
998 iochan_setflag(co->iochan, EVENT_OUTPUT);
1006 // This function will most likely vanish when a proper target profile mechanism is
1008 void load_simpletargets(const char *fn)
1010 FILE *f = fopen(fn, "r");
1015 yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
1019 while (fgets(line, 255, f))
1023 struct database *database;
1025 if (strncmp(line, "target ", 7))
1028 url[strlen(url) - 1] = '\0';
1029 yaz_log(YLOG_DEBUG, "Target: %s", url);
1030 if ((db = strchr(url, '/')))
1035 for (host = hosts; host; host = host->next)
1036 if (!strcmp(url, host->hostport))
1040 struct addrinfo *addrinfo, hints;
1043 unsigned char addrbuf[4];
1046 host = xmalloc(sizeof(struct host));
1047 host->hostport = xstrdup(url);
1048 host->connections = 0;
1050 if ((port = strchr(url, ':')))
1056 hints.ai_family = PF_INET;
1057 hints.ai_socktype = SOCK_STREAM;
1058 hints.ai_protocol = IPPROTO_TCP;
1059 hints.ai_addrlen = 0;
1061 hints.ai_canonname = 0;
1063 // This is not robust code. It assumes that getaddrinfo returns AF_INET
1065 if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
1067 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
1068 xfree(host->hostport);
1072 assert(addrinfo->ai_family == PF_INET);
1073 memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
1074 sprintf(ipport, "%u.%u.%u.%u:%s",
1075 addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
1076 host->ipport = xstrdup(ipport);
1077 freeaddrinfo(addrinfo);
1081 database = xmalloc(sizeof(struct database));
1082 database->host = host;
1083 database->url = xmalloc(strlen(url) + strlen(db) + 2);
1084 strcpy(database->url, url);
1085 strcat(database->url, "/");
1086 strcat(database->url, db);
1088 database->databases = xmalloc(2 * sizeof(char *));
1089 database->databases[0] = xstrdup(db);
1090 database->databases[1] = 0;
1091 database->errors = 0;
1092 database->qprofile = 0;
1093 database->rprofile = database_retrieval_profile(database);
1094 database->next = databases;
1095 databases = database;
1101 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1109 pull_terms(nmem, n->u.p[0], termlist, num);
1110 pull_terms(nmem, n->u.p[1], termlist, num);
1113 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1120 // Extract terms from query into null-terminated termlist
1121 static int extract_terms(NMEM nmem, char *query, char **termlist)
1124 struct ccl_rpn_node *n;
1127 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1130 pull_terms(nmem, n, termlist, &num);
1136 static struct client *client_create(void)
1139 if (client_freelist)
1141 r = client_freelist;
1142 client_freelist = client_freelist->next;
1145 r = xmalloc(sizeof(struct client));
1154 r->state = Client_Disconnected;
1159 void client_destroy(struct client *c)
1161 struct session *se = c->session;
1162 if (c == se->clients)
1163 se->clients = c->next;
1167 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1173 connection_release(c->connection);
1174 c->next = client_freelist;
1175 client_freelist = c;
1178 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1180 s->watchlist[what].fun = fun;
1181 s->watchlist[what].data = data;
1184 void session_alert_watch(struct session *s, int what)
1186 if (!s->watchlist[what].fun)
1188 (*s->watchlist[what].fun)(s->watchlist[what].data);
1189 s->watchlist[what].fun = 0;
1190 s->watchlist[what].data = 0;
1193 // This needs to be extended with selection criteria
1194 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1198 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1201 if (!config->retrievalprofiles)
1203 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1205 return config->retrievalprofiles;
1208 // This should be extended with parameters to control selection criteria
1209 // Associates a set of clients with a session;
1210 int select_targets(struct session *se)
1212 struct database *db;
1216 client_destroy(se->clients);
1217 for (db = databases; db; db = db->next)
1219 struct client *cl = client_create();
1222 cl->next = se->clients;
1229 int session_active_clients(struct session *s)
1234 for (c = s->clients; c; c = c->next)
1235 if (c->connection && (c->state == Client_Connecting ||
1236 c->state == Client_Initializing ||
1237 c->state == Client_Searching ||
1238 c->state == Client_Presenting))
1244 char *search(struct session *se, char *query)
1246 int live_channels = 0;
1249 yaz_log(YLOG_DEBUG, "Search");
1251 strcpy(se->query, query);
1253 nmem_reset(se->nmem);
1254 for (cl = se->clients; cl; cl = cl->next)
1260 if (client_prep_connection(cl))
1266 int maxrecs = live_channels * global_parameters.toget;
1267 se->num_termlists = 0;
1268 se->reclist = reclist_create(se->nmem, maxrecs);
1269 extract_terms(se->nmem, query, p);
1270 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1271 se->total_records = se->total_hits = se->total_merged = 0;
1272 se->expected_maxrecs = maxrecs;
1280 void destroy_session(struct session *s)
1282 yaz_log(YLOG_LOG, "Destroying session");
1284 client_destroy(s->clients);
1285 nmem_destroy(s->nmem);
1286 wrbuf_free(s->wrbuf, 1);
1289 struct session *new_session()
1292 struct session *session = xmalloc(sizeof(*session));
1294 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1296 session->total_hits = 0;
1297 session->total_records = 0;
1298 session->num_termlists = 0;
1299 session->reclist = 0;
1300 session->requestid = -1;
1301 session->clients = 0;
1302 session->expected_maxrecs = 0;
1303 session->query[0] = '\0';
1304 session->nmem = nmem_create();
1305 session->wrbuf = wrbuf_alloc();
1306 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1308 session->watchlist[i].data = 0;
1309 session->watchlist[i].fun = 0;
1312 select_targets(session);
1317 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1319 static struct hitsbytarget res[1000]; // FIXME MM
1323 for (cl = se->clients; cl; cl = cl->next)
1325 strcpy(res[*count].id, cl->database->host->hostport);
1326 res[*count].hits = cl->hits;
1327 res[*count].records = cl->records;
1328 res[*count].diagnostic = cl->diagnostic;
1329 res[*count].state = client_states[cl->state];
1330 res[*count].connected = cl->connection ? 1 : 0;
1337 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1341 for (i = 0; i < s->num_termlists; i++)
1342 if (!strcmp(s->termlists[i].name, name))
1343 return termlist_highscore(s->termlists[i].termlist, num);
1347 #ifdef MISSING_HEADERS
1348 void report_nmem_stats(void)
1350 size_t in_use, is_free;
1352 nmem_get_memory_in_use(&in_use);
1353 nmem_get_memory_free(&is_free);
1355 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1356 (long) in_use, (long) is_free);
1360 struct record_cluster *show_single(struct session *s, int id)
1362 struct record_cluster *r;
1364 reclist_rewind(s->reclist);
1365 while ((r = reclist_read_record(s->reclist)))
1371 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1372 int *num, int *total, int *sumhits, NMEM nmem_show)
1374 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1375 * sizeof(struct record_cluster *));
1376 struct reclist_sortparms *spp;
1379 yaz_timing_t t = yaz_timing_create();
1382 for (spp = sp; spp; spp = spp->next)
1383 if (spp->type == Metadata_sortkey_relevance)
1385 relevance_prepare_read(s->relevance, s->reclist);
1388 reclist_sort(s->reclist, sp);
1390 *total = s->reclist->num_records;
1391 *sumhits = s->total_hits;
1393 for (i = 0; i < start; i++)
1394 if (!reclist_read_record(s->reclist))
1401 for (i = 0; i < *num; i++)
1403 struct record_cluster *r = reclist_read_record(s->reclist);
1413 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1414 yaz_timing_get_real(t), yaz_timing_get_user(t),
1415 yaz_timing_get_sys(t));
1416 yaz_timing_destroy(&t);
1421 void statistics(struct session *se, struct statistics *stat)
1426 memset(stat, 0, sizeof(*stat));
1427 for (cl = se->clients; cl; cl = cl->next)
1429 if (!cl->connection)
1430 stat->num_no_connection++;
1433 case Client_Connecting: stat->num_connecting++; break;
1434 case Client_Initializing: stat->num_initializing++; break;
1435 case Client_Searching: stat->num_searching++; break;
1436 case Client_Presenting: stat->num_presenting++; break;
1437 case Client_Idle: stat->num_idle++; break;
1438 case Client_Failed: stat->num_failed++; break;
1439 case Client_Error: stat->num_error++; break;
1444 stat->num_hits = se->total_hits;
1445 stat->num_records = se->total_records;
1447 stat->num_clients = count;
1450 static CCL_bibset load_cclfile(const char *fn)
1452 CCL_bibset res = ccl_qual_mk();
1453 if (ccl_qual_fname(res, fn) < 0)
1455 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1461 static void start_http_listener(void)
1464 struct conf_server *ser = global_parameters.server;
1466 if (*global_parameters.listener_override)
1467 strcpy(hp, global_parameters.listener_override);
1470 strcpy(hp, ser->host ? ser->host : "");
1475 sprintf(hp + strlen(hp), "%d", ser->port);
1481 static void start_proxy(void)
1484 struct conf_server *ser = global_parameters.server;
1486 if (*global_parameters.proxy_override)
1487 strcpy(hp, global_parameters.proxy_override);
1488 else if (ser->proxy_host || ser->proxy_port)
1490 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1491 if (ser->proxy_port)
1495 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1501 http_set_proxyaddr(hp);
1504 int main(int argc, char **argv)
1509 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1510 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1512 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1514 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1518 if (!read_config(arg))
1522 strcpy(global_parameters.listener_override, arg);
1525 global_parameters.ccl_filter = load_cclfile(arg);
1528 strcpy(global_parameters.proxy_override, arg);
1531 load_simpletargets(arg);
1534 global_parameters.dump_records = 1;
1537 fprintf(stderr, "Usage: pazpar2\n"
1539 " -h [host:]port (REST protocol listener)\n"
1541 " -s simpletargetfile\n"
1542 " -p hostname[:portno] (HTTP proxy)\n");
1549 yaz_log(YLOG_FATAL, "Load config with -f");
1552 global_parameters.server = config->servers;
1554 start_http_listener();
1556 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1557 global_parameters.yaz_marc = yaz_marc_create();
1558 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1559 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1560 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1562 event_loop(&channel_list);
1570 * indent-tabs-mode: nil
1572 * vim: shiftwidth=4 tabstop=8 expandtab