1 /* $Id: pazpar2.c,v 1.48 2007-02-05 16:15:41 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.searchRequest->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 ingest_records(cl, r->records);
270 cl->state = Client_Idle;
275 cl->state = Client_Error;
277 Z_Records *recs = r->records;
278 if (recs->which == Z_Records_NSD)
280 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
281 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
282 cl->state = Client_Error;
288 char *normalize_mergekey(char *buf, int skiparticle)
290 char *p = buf, *pout = buf;
295 char articles[] = "the den der die des an a "; // must end in space
297 while (*p && !isalnum(*p))
300 while (*p && *p != ' ' && pout - firstword < 62)
301 *(pout++) = tolower(*(p++));
304 if (!strstr(articles, firstword))
311 while (*p && !isalnum(*p))
314 *(pout++) = tolower(*(p++));
317 while (*p && !isalnum(*p))
324 while (pout > buf && *pout == ' ');
331 // FIXME needs to be generalized. Should flexibly generate X lists per search
332 static void extract_subject(struct session *s, const char *rec)
334 const char *field, *subfield;
336 while ((field = find_field(rec, "650")))
339 if ((subfield = find_subfield(field, 'a')))
345 ef = index(subfield, '\n');
348 if ((e = index(subfield, '\t')) && e < ef)
350 while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
354 memcpy(buf, subfield, len);
358 termlist_insert(s->termlist, buf);
365 static void add_facet(struct session *s, const char *type, const char *value)
371 for (i = 0; i < s->num_termlists; i++)
372 if (!strcmp(s->termlists[i].name, type))
374 if (i == s->num_termlists)
376 if (i == SESSION_MAX_TERMLISTS)
378 yaz_log(YLOG_FATAL, "Too many termlists");
381 s->termlists[i].name = nmem_strdup(s->nmem, type);
382 s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
383 s->num_termlists = i + 1;
385 termlist_insert(s->termlists[i].termlist, value);
388 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
390 struct conf_retrievalprofile *rprofile = cl->database->rprofile;
391 struct conf_retrievalmap *m;
395 // First normalize to XML
396 if (rprofile->native_syntax == Nativesyn_iso2709)
400 if (rec->which != Z_External_octet)
402 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
405 buf = (char*) rec->u.octet_aligned->buf;
406 len = rec->u.octet_aligned->len;
407 if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
409 yaz_log(YLOG_WARN, "Failed to decode MARC");
412 if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
413 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
415 yaz_log(YLOG_WARN, "Failed to encode as XML");
418 rdoc = xmlNewDoc("1.0");
419 xmlDocSetRootElement(rdoc, res);
423 yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
427 if (global_parameters.dump_records)
429 fprintf(stderr, "Input Record (normalized):\n----------------\n");
430 #if LIBXML_VERSION >= 20600
431 xmlDocFormatDump(stderr, rdoc, 1);
433 xmlDocDump(stderr, rdoc);
437 for (m = rprofile->maplist; m; m = m->next)
440 if (m->type != Map_xslt)
442 yaz_log(YLOG_WARN, "Unknown map type");
445 if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
447 yaz_log(YLOG_WARN, "XSLT transformation failed");
453 if (global_parameters.dump_records)
455 fprintf(stderr, "Record:\n----------------\n");
456 #if LIBXML_VERSION >= 20600
457 xmlDocFormatDump(stderr, rdoc, 1);
459 xmlDocDump(stderr, rdoc);
465 // Extract what appears to be years from buf, storing highest and
467 static int extract_years(const char *buf, int *first, int *last)
476 while (*buf && !isdigit(*buf))
479 for (e = buf; *e && isdigit(*e); e++)
483 int value = atoi(buf);
484 if (*first < 0 || value < *first)
486 if (*last < 0 || value > *last)
494 static struct record *ingest_record(struct client *cl, Z_External *rec)
496 xmlDoc *xdoc = normalize_record(cl, rec);
499 struct record_cluster *cluster;
500 struct session *se = cl->session;
501 xmlChar *mergekey, *mergekey_norm;
504 struct conf_service *service = global_parameters.server->service;
509 root = xmlDocGetRootElement(xdoc);
510 if (!(mergekey = xmlGetProp(root, "mergekey")))
512 yaz_log(YLOG_WARN, "No mergekey found in record");
517 res = nmem_malloc(se->nmem, sizeof(struct record));
520 res->metadata = nmem_malloc(se->nmem,
521 sizeof(struct record_metadata*) * service->num_metadata);
522 memset(res->metadata, 0, sizeof(struct record_metadata*) * service->num_metadata);
524 mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
526 normalize_mergekey(mergekey_norm, 0);
528 cluster = reclist_insert(se->reclist, res, mergekey_norm, &se->total_merged);
529 if (global_parameters.dump_records)
530 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
531 cl->database->url, cl->records);
534 /* no room for record */
538 relevance_newrec(se->relevance, cluster);
540 for (n = root->children; n; n = n->next)
548 if (n->type != XML_ELEMENT_NODE)
550 if (!strcmp(n->name, "metadata"))
552 struct conf_metadata *md = 0;
553 struct conf_sortkey *sk = 0;
554 struct record_metadata **wheretoput, *newm;
558 type = xmlGetProp(n, "type");
559 value = xmlNodeListGetString(xdoc, n->children, 0);
564 // First, find out what field we're looking at
565 for (imeta = 0; imeta < service->num_metadata; imeta++)
566 if (!strcmp(type, service->metadata[imeta].name))
568 md = &service->metadata[imeta];
569 if (md->sortkey_offset >= 0)
570 sk = &service->sortkeys[md->sortkey_offset];
575 yaz_log(YLOG_WARN, "Ignoring unknown metadata element: %s", type);
579 // Find out where we are putting it
580 if (md->merge == Metadata_merge_no)
581 wheretoput = &res->metadata[imeta];
583 wheretoput = &cluster->metadata[imeta];
586 newm = nmem_malloc(se->nmem, sizeof(struct record_metadata));
588 if (md->type == Metadata_type_generic)
591 for (p = value; *p && isspace(*p); p++)
593 for (pe = p + strlen(p) - 1;
594 pe > p && strchr(" ,/.:([", *pe); pe--)
596 newm->data.text = nmem_strdup(se->nmem, p);
599 else if (md->type == Metadata_type_year)
601 if (extract_years(value, &first, &last) < 0)
606 yaz_log(YLOG_WARN, "Unknown type in metadata element %s", type);
609 if (md->type == Metadata_type_year && md->merge != Metadata_merge_range)
611 yaz_log(YLOG_WARN, "Only range merging supported for years");
614 if (md->merge == Metadata_merge_unique)
616 struct record_metadata *mnode;
617 for (mnode = *wheretoput; mnode; mnode = mnode->next)
618 if (!strcmp(mnode->data.text, newm->data.text))
622 newm->next = *wheretoput;
626 else if (md->merge == Metadata_merge_longest)
629 strlen(newm->data.text) > strlen((*wheretoput)->data.text))
634 char *s = nmem_strdup(se->nmem, newm->data.text);
635 if (!cluster->sortkeys[md->sortkey_offset])
636 cluster->sortkeys[md->sortkey_offset] =
637 nmem_malloc(se->nmem, sizeof(union data_types));
638 normalize_mergekey(s,
639 (sk->type == Metadata_sortkey_skiparticle));
640 cluster->sortkeys[md->sortkey_offset]->text = s;
644 else if (md->merge == Metadata_merge_all || md->merge == Metadata_merge_no)
646 newm->next = *wheretoput;
649 else if (md->merge == Metadata_merge_range)
651 assert(md->type == Metadata_type_year);
655 (*wheretoput)->data.number.min = first;
656 (*wheretoput)->data.number.max = last;
658 cluster->sortkeys[md->sortkey_offset] = &newm->data;
662 if (first < (*wheretoput)->data.number.min)
663 (*wheretoput)->data.number.min = first;
664 if (last > (*wheretoput)->data.number.max)
665 (*wheretoput)->data.number.max = last;
670 union data_types *sdata = cluster->sortkeys[md->sortkey_offset];
671 yaz_log(YLOG_LOG, "SK range: %d-%d", sdata->number.min, sdata->number.max);
676 yaz_log(YLOG_WARN, "Don't know how to merge on element name %s", md->name);
679 relevance_countwords(se->relevance, cluster, value, md->rank);
682 if (md->type == Metadata_type_year)
685 sprintf(year, "%d", last);
686 add_facet(se, type, year);
689 sprintf(year, "%d", first);
690 add_facet(se, type, year);
694 add_facet(se, type, value);
701 yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
710 relevance_donerecord(se->relevance, cluster);
716 static void ingest_records(struct client *cl, Z_Records *r)
719 yaz_timing_t t = yaz_timing_create();
722 struct session *s = cl->session;
723 Z_NamePlusRecordList *rlist;
726 if (r->which != Z_Records_DBOSD)
728 rlist = r->u.databaseOrSurDiagnostics;
729 for (i = 0; i < rlist->num_records; i++)
731 Z_NamePlusRecord *npr = rlist->records[i];
734 if (npr->which != Z_NamePlusRecord_databaseRecord)
736 yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
740 rec = ingest_record(cl, npr->u.databaseRecord);
744 if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
745 session_alert_watch(s, SESSION_WATCH_RECORDS);
749 yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f",
750 yaz_timing_get_real(t), yaz_timing_get_user(t),
751 yaz_timing_get_sys(t));
752 yaz_timing_destroy(&t);
756 static void do_presentResponse(IOCHAN i, Z_APDU *a)
758 struct connection *co = iochan_getdata(i);
759 struct client *cl = co->client;
760 Z_PresentResponse *r = a->u.presentResponse;
763 Z_Records *recs = r->records;
764 if (recs->which == Z_Records_NSD)
766 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
767 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
768 cl->state = Client_Error;
772 if (!*r->presentStatus && cl->state != Client_Error)
774 yaz_log(YLOG_DEBUG, "Good Present response");
775 ingest_records(cl, r->records);
776 cl->state = Client_Idle;
778 else if (*r->presentStatus)
780 yaz_log(YLOG_WARN, "Bad Present response");
781 cl->state = Client_Error;
785 static void handler(IOCHAN i, int event)
787 struct connection *co = iochan_getdata(i);
788 struct client *cl = co->client;
789 struct session *se = 0;
795 yaz_log(YLOG_WARN, "Destroying orphan connection");
796 connection_destroy(co);
800 if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
803 socklen_t errlen = sizeof(errcode);
805 if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
806 &errlen) < 0 || errcode != 0)
813 yaz_log(YLOG_DEBUG, "Connect OK");
814 co->state = Conn_Open;
816 cl->state = Client_Connected;
820 else if (event & EVENT_INPUT)
822 int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
826 yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
827 connection_destroy(co);
832 yaz_log(YLOG_WARN, "EOF reading from Z server");
833 connection_destroy(co);
836 else if (len > 1) // We discard input if we have no connection
838 co->state = Conn_Open;
840 if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
844 odr_reset(global_parameters.odr_in);
845 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
846 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
853 case Z_APDU_initResponse:
854 do_initResponse(i, a);
856 case Z_APDU_searchResponse:
857 do_searchResponse(i, a);
859 case Z_APDU_presentResponse:
860 do_presentResponse(i, a);
863 yaz_log(YLOG_WARN, "Unexpected result from server");
867 // We aren't expecting staggered output from target
868 // if (cs_more(t->link))
869 // iochan_setevent(i, EVENT_INPUT);
871 else // we throw away response and go to idle mode
873 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
874 cl->state = Client_Idle;
877 /* if len==1 we do nothing but wait for more input */
880 if (cl->state == Client_Connected) {
884 if (cl->state == Client_Idle)
886 if (cl->requestid != se->requestid && *se->query) {
889 else if (cl->hits > 0 && cl->records < global_parameters.toget &&
890 cl->records < cl->hits) {
896 // Disassociate connection from client
897 static void connection_release(struct connection *co)
899 struct client *cl = co->client;
901 yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
908 // Close connection and recycle structure
909 static void connection_destroy(struct connection *co)
911 struct host *h = co->host;
913 iochan_destroy(co->iochan);
915 yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
916 if (h->connections == co)
917 h->connections = co->next;
920 struct connection *pco;
921 for (pco = h->connections; pco && pco->next != co; pco = pco->next)
924 pco->next = co->next;
930 if (co->client->state != Client_Idle)
931 co->client->state = Client_Disconnected;
932 co->client->connection = 0;
934 co->next = connection_freelist;
935 connection_freelist = co;
938 // Creates a new connection for client, associated with the host of
940 static struct connection *connection_create(struct client *cl)
942 struct connection *new;
947 yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
948 if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
950 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
954 if (!(addr = cs_straddr(link, cl->database->host->ipport)))
956 yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address %s failed?",
957 cl->database->host->ipport);
961 res = cs_connect(link, addr);
964 yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
968 if ((new = connection_freelist))
969 connection_freelist = new->next;
972 new = xmalloc(sizeof (struct connection));
976 new->state = Conn_Connecting;
977 new->host = cl->database->host;
978 new->next = new->host->connections;
979 new->host->connections = new;
981 cl->connection = new;
984 new->iochan = iochan_create(cs_fileno(link), handler, 0);
985 iochan_setdata(new->iochan, new);
986 new->iochan->next = channel_list;
987 channel_list = new->iochan;
991 // Close connection and set state to error
992 static void client_fatal(struct client *cl)
994 yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
995 connection_destroy(cl->connection);
996 cl->state = Client_Error;
999 // Ensure that client has a connection associated
1000 static int client_prep_connection(struct client *cl)
1002 struct connection *co;
1003 struct session *se = cl->session;
1004 struct host *host = cl->database->host;
1006 co = cl->connection;
1008 yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
1012 // See if someone else has an idle connection
1013 // We should look at timestamps here to select the longest-idle connection
1014 for (co = host->connections; co; co = co->next)
1015 if (co->state == Conn_Open && (!co->client || co->client->session != se))
1019 connection_release(co);
1020 cl->connection = co;
1024 co = connection_create(cl);
1028 if (co->state == Conn_Connecting)
1030 cl->state = Client_Connecting;
1031 iochan_setflag(co->iochan, EVENT_OUTPUT);
1033 else if (co->state == Conn_Open)
1035 if (cl->state == Client_Error || cl->state == Client_Disconnected)
1036 cl->state = Client_Idle;
1037 iochan_setflag(co->iochan, EVENT_OUTPUT);
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;
1149 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
1157 pull_terms(nmem, n->u.p[0], termlist, num);
1158 pull_terms(nmem, n->u.p[1], termlist, num);
1161 termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
1168 // Extract terms from query into null-terminated termlist
1169 static int extract_terms(NMEM nmem, char *query, char **termlist)
1172 struct ccl_rpn_node *n;
1175 n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
1178 pull_terms(nmem, n, termlist, &num);
1184 static struct client *client_create(void)
1187 if (client_freelist)
1189 r = client_freelist;
1190 client_freelist = client_freelist->next;
1193 r = xmalloc(sizeof(struct client));
1202 r->state = Client_Disconnected;
1207 void client_destroy(struct client *c)
1209 struct session *se = c->session;
1210 if (c == se->clients)
1211 se->clients = c->next;
1215 for (cc = se->clients; cc && cc->next != c; cc = cc->next)
1221 connection_release(c->connection);
1222 c->next = client_freelist;
1223 client_freelist = c;
1226 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
1228 s->watchlist[what].fun = fun;
1229 s->watchlist[what].data = data;
1232 void session_alert_watch(struct session *s, int what)
1234 if (!s->watchlist[what].fun)
1236 (*s->watchlist[what].fun)(s->watchlist[what].data);
1237 s->watchlist[what].fun = 0;
1238 s->watchlist[what].data = 0;
1241 // This needs to be extended with selection criteria
1242 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1246 yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1249 if (!config->retrievalprofiles)
1251 yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1253 return config->retrievalprofiles;
1256 // This should be extended with parameters to control selection criteria
1257 // Associates a set of clients with a session;
1258 int select_targets(struct session *se)
1260 struct database *db;
1264 client_destroy(se->clients);
1265 for (db = databases; db; db = db->next)
1267 struct client *cl = client_create();
1270 cl->next = se->clients;
1277 int session_active_clients(struct session *s)
1282 for (c = s->clients; c; c = c->next)
1283 if (c->connection && (c->state == Client_Connecting ||
1284 c->state == Client_Initializing ||
1285 c->state == Client_Searching ||
1286 c->state == Client_Presenting))
1292 char *search(struct session *se, char *query)
1294 int live_channels = 0;
1297 yaz_log(YLOG_DEBUG, "Search");
1299 strcpy(se->query, query);
1301 nmem_reset(se->nmem);
1302 for (cl = se->clients; cl; cl = cl->next)
1308 if (client_prep_connection(cl))
1314 int maxrecs = live_channels * global_parameters.toget;
1315 se->num_termlists = 0;
1316 se->reclist = reclist_create(se->nmem, maxrecs);
1317 extract_terms(se->nmem, query, p);
1318 se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1319 se->total_records = se->total_hits = se->total_merged = 0;
1320 se->expected_maxrecs = maxrecs;
1328 void destroy_session(struct session *s)
1330 yaz_log(YLOG_LOG, "Destroying session");
1332 client_destroy(s->clients);
1333 nmem_destroy(s->nmem);
1334 wrbuf_free(s->wrbuf, 1);
1337 struct session *new_session()
1340 struct session *session = xmalloc(sizeof(*session));
1342 yaz_log(YLOG_DEBUG, "New pazpar2 session");
1344 session->total_hits = 0;
1345 session->total_records = 0;
1346 session->num_termlists = 0;
1347 session->reclist = 0;
1348 session->requestid = -1;
1349 session->clients = 0;
1350 session->expected_maxrecs = 0;
1351 session->query[0] = '\0';
1352 session->nmem = nmem_create();
1353 session->wrbuf = wrbuf_alloc();
1354 for (i = 0; i <= SESSION_WATCH_MAX; i++)
1356 session->watchlist[i].data = 0;
1357 session->watchlist[i].fun = 0;
1360 select_targets(session);
1365 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1367 static struct hitsbytarget res[1000]; // FIXME MM
1371 for (cl = se->clients; cl; cl = cl->next)
1373 res[*count].id = cl->database->url;
1374 res[*count].name = cl->database->name;
1375 res[*count].hits = cl->hits;
1376 res[*count].records = cl->records;
1377 res[*count].diagnostic = cl->diagnostic;
1378 res[*count].state = client_states[cl->state];
1379 res[*count].connected = cl->connection ? 1 : 0;
1386 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1390 for (i = 0; i < s->num_termlists; i++)
1391 if (!strcmp(s->termlists[i].name, name))
1392 return termlist_highscore(s->termlists[i].termlist, num);
1396 #ifdef MISSING_HEADERS
1397 void report_nmem_stats(void)
1399 size_t in_use, is_free;
1401 nmem_get_memory_in_use(&in_use);
1402 nmem_get_memory_free(&is_free);
1404 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1405 (long) in_use, (long) is_free);
1409 struct record_cluster *show_single(struct session *s, int id)
1411 struct record_cluster *r;
1413 reclist_rewind(s->reclist);
1414 while ((r = reclist_read_record(s->reclist)))
1420 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, int start,
1421 int *num, int *total, int *sumhits, NMEM nmem_show)
1423 struct record_cluster **recs = nmem_malloc(nmem_show, *num
1424 * sizeof(struct record_cluster *));
1425 struct reclist_sortparms *spp;
1428 yaz_timing_t t = yaz_timing_create();
1431 for (spp = sp; spp; spp = spp->next)
1432 if (spp->type == Metadata_sortkey_relevance)
1434 relevance_prepare_read(s->relevance, s->reclist);
1437 reclist_sort(s->reclist, sp);
1439 *total = s->reclist->num_records;
1440 *sumhits = s->total_hits;
1442 for (i = 0; i < start; i++)
1443 if (!reclist_read_record(s->reclist))
1450 for (i = 0; i < *num; i++)
1452 struct record_cluster *r = reclist_read_record(s->reclist);
1462 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1463 yaz_timing_get_real(t), yaz_timing_get_user(t),
1464 yaz_timing_get_sys(t));
1465 yaz_timing_destroy(&t);
1470 void statistics(struct session *se, struct statistics *stat)
1475 memset(stat, 0, sizeof(*stat));
1476 for (cl = se->clients; cl; cl = cl->next)
1478 if (!cl->connection)
1479 stat->num_no_connection++;
1482 case Client_Connecting: stat->num_connecting++; break;
1483 case Client_Initializing: stat->num_initializing++; break;
1484 case Client_Searching: stat->num_searching++; break;
1485 case Client_Presenting: stat->num_presenting++; break;
1486 case Client_Idle: stat->num_idle++; break;
1487 case Client_Failed: stat->num_failed++; break;
1488 case Client_Error: stat->num_error++; break;
1493 stat->num_hits = se->total_hits;
1494 stat->num_records = se->total_records;
1496 stat->num_clients = count;
1499 static CCL_bibset load_cclfile(const char *fn)
1501 CCL_bibset res = ccl_qual_mk();
1502 if (ccl_qual_fname(res, fn) < 0)
1504 yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1510 static void start_http_listener(void)
1513 struct conf_server *ser = global_parameters.server;
1515 if (*global_parameters.listener_override)
1516 strcpy(hp, global_parameters.listener_override);
1519 strcpy(hp, ser->host ? ser->host : "");
1524 sprintf(hp + strlen(hp), "%d", ser->port);
1530 static void start_proxy(void)
1533 struct conf_server *ser = global_parameters.server;
1535 if (*global_parameters.proxy_override)
1536 strcpy(hp, global_parameters.proxy_override);
1537 else if (ser->proxy_host || ser->proxy_port)
1539 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
1540 if (ser->proxy_port)
1544 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
1550 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
1553 int main(int argc, char **argv)
1558 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1559 yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1561 yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1563 while ((ret = options("f:x:h:p:C:s:d", argv, argc, &arg)) != -2)
1567 if (!read_config(arg))
1571 strcpy(global_parameters.listener_override, arg);
1574 global_parameters.ccl_filter = load_cclfile(arg);
1577 strcpy(global_parameters.proxy_override, arg);
1580 load_simpletargets(arg);
1583 global_parameters.dump_records = 1;
1586 fprintf(stderr, "Usage: pazpar2\n"
1588 " -h [host:]port (REST protocol listener)\n"
1590 " -s simpletargetfile\n"
1591 " -p hostname[:portno] (HTTP proxy)\n"
1592 " -d (show internal records)\n");
1599 yaz_log(YLOG_FATAL, "Load config with -f");
1602 global_parameters.server = config->servers;
1604 start_http_listener();
1606 if (!global_parameters.ccl_filter)
1607 global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1608 global_parameters.yaz_marc = yaz_marc_create();
1609 yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1610 global_parameters.odr_in = odr_createmem(ODR_DECODE);
1611 global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1613 event_loop(&channel_list);
1621 * indent-tabs-mode: nil
1623 * vim: shiftwidth=4 tabstop=8 expandtab