Added code to do timings for show + ingest of records. Enable by
[pazpar2-moved-to-github.git] / src / pazpar2.c
1 /* $Id: pazpar2.c,v 1.11 2007-01-04 07:27:29 adam Exp $ */;
2
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/time.h>
7 #include <unistd.h>
8 #include <sys/socket.h>
9 #include <netdb.h>
10 #include <signal.h>
11 #include <ctype.h>
12 #include <assert.h>
13
14 #include <yaz/comstack.h>
15 #include <yaz/tcpip.h>
16 #include <yaz/proto.h>
17 #include <yaz/readconf.h>
18 #include <yaz/pquery.h>
19 #include <yaz/yaz-util.h>
20 #include <yaz/nmem.h>
21
22 #define USE_TIMING 0
23 #if USE_TIMING
24 #include <yaz/timing.h>
25 #endif
26
27 #include "pazpar2.h"
28 #include "eventl.h"
29 #include "command.h"
30 #include "http.h"
31 #include "termlists.h"
32 #include "reclists.h"
33 #include "relevance.h"
34 #include "config.h"
35
36 #define PAZPAR2_VERSION "0.1"
37 #define MAX_CHUNK 15
38
39 static void client_fatal(struct client *cl);
40 static void connection_destroy(struct connection *co);
41 static int client_prep_connection(struct client *cl);
42 static void ingest_records(struct client *cl, Z_Records *r);
43 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db);
44 void session_alert_watch(struct session *s, int what);
45
46 IOCHAN channel_list = 0;  // Master list of connections we're handling events to
47
48 static struct connection *connection_freelist = 0;
49 static struct client *client_freelist = 0;
50
51 static struct host *hosts = 0;  // The hosts we know about 
52 static struct database *databases = 0; // The databases we know about
53
54 static char *client_states[] = {
55     "Client_Connecting",
56     "Client_Connected",
57     "Client_Idle",
58     "Client_Initializing",
59     "Client_Searching",
60     "Client_Presenting",
61     "Client_Error",
62     "Client_Failed",
63     "Client_Disconnected",
64     "Client_Stopped"
65 };
66
67 struct parameters global_parameters = 
68 {
69     0,
70     30,
71     "81",
72     "Index Data PazPar2 (MasterKey)",
73     PAZPAR2_VERSION,
74     600, // 10 minutes
75     60,
76     100,
77     MAX_CHUNK,
78     0,
79     0,
80     0,
81     0
82 };
83
84 static int send_apdu(struct client *c, Z_APDU *a)
85 {
86     struct connection *co = c->connection;
87     char *buf;
88     int len, r;
89
90     if (!z_APDU(global_parameters.odr_out, &a, 0, 0))
91     {
92         odr_perror(global_parameters.odr_out, "Encoding APDU");
93         abort();
94     }
95     buf = odr_getbuf(global_parameters.odr_out, &len, 0);
96     r = cs_put(co->link, buf, len);
97     if (r < 0)
98     {
99         yaz_log(YLOG_WARN, "cs_put: %s", cs_errmsg(cs_errno(co->link)));
100         return -1;
101     }
102     else if (r == 1)
103     {
104         fprintf(stderr, "cs_put incomplete (ParaZ does not handle that)\n");
105         exit(1);
106     }
107     odr_reset(global_parameters.odr_out); /* release the APDU structure  */
108     co->state = Conn_Waiting;
109     return 0;
110 }
111
112
113 static void send_init(IOCHAN i)
114 {
115     struct connection *co = iochan_getdata(i);
116     struct client *cl = co->client;
117     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_initRequest);
118
119     a->u.initRequest->implementationId = global_parameters.implementationId;
120     a->u.initRequest->implementationName = global_parameters.implementationName;
121     a->u.initRequest->implementationVersion =
122         global_parameters.implementationVersion;
123     ODR_MASK_SET(a->u.initRequest->options, Z_Options_search);
124     ODR_MASK_SET(a->u.initRequest->options, Z_Options_present);
125     ODR_MASK_SET(a->u.initRequest->options, Z_Options_namedResultSets);
126
127     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_1);
128     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_2);
129     ODR_MASK_SET(a->u.initRequest->protocolVersion, Z_ProtocolVersion_3);
130     if (send_apdu(cl, a) >= 0)
131     {
132         iochan_setflags(i, EVENT_INPUT);
133         cl->state = Client_Initializing;
134     }
135     else
136         cl->state = Client_Error;
137     odr_reset(global_parameters.odr_out);
138 }
139
140 static void send_search(IOCHAN i)
141 {
142     struct connection *co = iochan_getdata(i);
143     struct client *cl = co->client; 
144     struct session *se = cl->session;
145     struct database *db = cl->database;
146     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_searchRequest);
147     int ndb, cerror, cpos;
148     char **databaselist;
149     Z_Query *zquery;
150     struct ccl_rpn_node *cn;
151     int ssub = 0, lslb = 100000, mspn = 10;
152
153     yaz_log(YLOG_DEBUG, "Sending search");
154
155     cn = ccl_find_str(global_parameters.ccl_filter, se->query, &cerror, &cpos);
156     if (!cn)
157         return;
158     a->u.searchRequest->query = zquery = odr_malloc(global_parameters.odr_out,
159             sizeof(Z_Query));
160     zquery->which = Z_Query_type_1;
161     zquery->u.type_1 = ccl_rpn_query(global_parameters.odr_out, cn);
162     ccl_rpn_delete(cn);
163
164     for (ndb = 0; db->databases[ndb]; ndb++)
165         ;
166     databaselist = odr_malloc(global_parameters.odr_out, sizeof(char*) * ndb);
167     for (ndb = 0; db->databases[ndb]; ndb++)
168         databaselist[ndb] = db->databases[ndb];
169
170     a->u.presentRequest->preferredRecordSyntax =
171             yaz_oidval_to_z3950oid(global_parameters.odr_out,
172             CLASS_RECSYN, VAL_USMARC);
173     a->u.searchRequest->smallSetUpperBound = &ssub;
174     a->u.searchRequest->largeSetLowerBound = &lslb;
175     a->u.searchRequest->mediumSetPresentNumber = &mspn;
176     a->u.searchRequest->resultSetName = "Default";
177     a->u.searchRequest->databaseNames = databaselist;
178     a->u.searchRequest->num_databaseNames = ndb;
179
180     if (send_apdu(cl, a) >= 0)
181     {
182         iochan_setflags(i, EVENT_INPUT);
183         cl->state = Client_Searching;
184         cl->requestid = se->requestid;
185     }
186     else
187         cl->state = Client_Error;
188
189     odr_reset(global_parameters.odr_out);
190 }
191
192 static void send_present(IOCHAN i)
193 {
194     struct connection *co = iochan_getdata(i);
195     struct client *cl = co->client; 
196     Z_APDU *a = zget_APDU(global_parameters.odr_out, Z_APDU_presentRequest);
197     int toget;
198     int start = cl->records + 1;
199
200     toget = global_parameters.chunk;
201     if (toget > cl->hits - cl->records)
202         toget = cl->hits - cl->records;
203
204     yaz_log(YLOG_DEBUG, "Trying to present %d records\n", toget);
205
206     a->u.presentRequest->resultSetStartPoint = &start;
207     a->u.presentRequest->numberOfRecordsRequested = &toget;
208
209     a->u.presentRequest->resultSetId = "Default";
210
211     a->u.presentRequest->preferredRecordSyntax =
212             yaz_oidval_to_z3950oid(global_parameters.odr_out,
213             CLASS_RECSYN, VAL_USMARC);
214
215     if (send_apdu(cl, a) >= 0)
216     {
217         iochan_setflags(i, EVENT_INPUT);
218         cl->state = Client_Presenting;
219     }
220     else
221         cl->state = Client_Error;
222     odr_reset(global_parameters.odr_out);
223 }
224
225 static void do_initResponse(IOCHAN i, Z_APDU *a)
226 {
227     struct connection *co = iochan_getdata(i);
228     struct client *cl = co->client;
229     Z_InitResponse *r = a->u.initResponse;
230
231     yaz_log(YLOG_DEBUG, "Received init response");
232
233     if (*r->result)
234     {
235         cl->state = Client_Idle;
236     }
237     else
238         cl->state = Client_Failed; // FIXME need to do something to the connection
239 }
240
241 static void do_searchResponse(IOCHAN i, Z_APDU *a)
242 {
243     struct connection *co = iochan_getdata(i);
244     struct client *cl = co->client;
245     struct session *se = cl->session;
246     Z_SearchResponse *r = a->u.searchResponse;
247
248     yaz_log(YLOG_DEBUG, "Searchresponse (status=%d)", *r->searchStatus);
249
250     if (*r->searchStatus)
251     {
252         cl->hits = *r->resultCount;
253         se->total_hits += cl->hits;
254         if (r->presentStatus && !*r->presentStatus && r->records)
255         {
256             yaz_log(YLOG_DEBUG, "Records in search response");
257             cl->records += *r->numberOfRecordsReturned;
258             ingest_records(cl, r->records);
259         }
260         cl->state = Client_Idle;
261     }
262     else
263     {          /*"FAILED"*/
264         cl->hits = 0;
265         cl->state = Client_Error;
266         if (r->records) {
267             Z_Records *recs = r->records;
268             if (recs->which == Z_Records_NSD)
269             {
270                 yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
271                 cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
272                 cl->state = Client_Error;
273             }
274         }
275     }
276 }
277
278 char *normalize_mergekey(char *buf)
279 {
280     char *p = buf, *pout = buf;
281
282     while (*p)
283     {
284         while (*p && !isalnum(*p))
285             p++;
286         while (isalnum(*p))
287             *(pout++) = tolower(*(p++));
288         if (*p)
289             *(pout++) = ' ';
290         while (*p && !isalnum(*p))
291             p++;
292     }
293     if (buf != pout)
294         *pout = '\0';
295
296     return buf;
297 }
298
299
300 #ifdef GAGA
301 // FIXME needs to be generalized. Should flexibly generate X lists per search
302 static void extract_subject(struct session *s, const char *rec)
303 {
304     const char *field, *subfield;
305
306     while ((field = find_field(rec, "650")))
307     {
308         rec = field; 
309         if ((subfield = find_subfield(field, 'a')))
310         {
311             char *e, *ef;
312             char buf[1024];
313             int len;
314
315             ef = index(subfield, '\n');
316             if (!ef)
317                 return;
318             if ((e = index(subfield, '\t')) && e < ef)
319                 ef = e;
320             while (ef > subfield && !isalpha(*(ef - 1)) && *(ef - 1) != ')')
321                 ef--;
322             len = ef - subfield;
323             assert(len < 1023);
324             memcpy(buf, subfield, len);
325             buf[len] = '\0';
326 #ifdef FIXME
327             if (*buf)
328                 termlist_insert(s->termlist, buf);
329 #endif
330         }
331     }
332 }
333 #endif
334
335 static void add_facet(struct session *s, const char *type, const char *value)
336 {
337     int i;
338
339     for (i = 0; i < s->num_termlists; i++)
340         if (!strcmp(s->termlists[i].name, type))
341             break;
342     if (i == s->num_termlists)
343     {
344         if (i == SESSION_MAX_TERMLISTS)
345         {
346             yaz_log(YLOG_FATAL, "Too many termlists");
347             exit(1);
348         }
349         s->termlists[i].name = nmem_strdup(s->nmem, type);
350         s->termlists[i].termlist = termlist_create(s->nmem, s->expected_maxrecs, 15);
351         s->num_termlists = i + 1;
352     }
353     termlist_insert(s->termlists[i].termlist, value);
354 }
355
356 static xmlDoc *normalize_record(struct client *cl, Z_External *rec)
357 {
358     struct conf_retrievalprofile *rprofile = cl->database->rprofile;
359     struct conf_retrievalmap *m;
360     xmlNode *res;
361     xmlDoc *rdoc;
362
363     // First normalize to XML
364     if (rprofile->native_syntax == Nativesyn_iso2709)
365     {
366         char *buf;
367         int len;
368         if (rec->which != Z_External_octet)
369         {
370             yaz_log(YLOG_WARN, "Unexpected external branch, probably BER");
371             return 0;
372         }
373         buf = (char*) rec->u.octet_aligned->buf;
374         len = rec->u.octet_aligned->len;
375         if (yaz_marc_read_iso2709(rprofile->yaz_marc, buf, len) < 0)
376         {
377             yaz_log(YLOG_WARN, "Failed to decode MARC");
378             return 0;
379         }
380         if (yaz_marc_write_xml(rprofile->yaz_marc, &res,
381                     "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
382         {
383             yaz_log(YLOG_WARN, "Failed to encode as XML");
384             return 0;
385         }
386         rdoc = xmlNewDoc("1.0");
387         xmlDocSetRootElement(rdoc, res);
388     }
389     else
390     {
391         yaz_log(YLOG_FATAL, "Unknown native_syntax in normalize_record");
392         exit(1);
393     }
394     for (m = rprofile->maplist; m; m = m->next)
395     {
396         xmlDoc *new;
397         if (m->type != Map_xslt)
398         {
399             yaz_log(YLOG_WARN, "Unknown map type");
400             return 0;
401         }
402         if (!(new = xsltApplyStylesheet(m->stylesheet, rdoc, 0)))
403         {
404             yaz_log(YLOG_WARN, "XSLT transformation failed");
405             return 0;
406         }
407         xmlFreeDoc(rdoc);
408         rdoc = new;
409     }
410     if (global_parameters.dump_records)
411     {
412         fprintf(stderr, "Record:\n----------------\n");
413         xmlDocFormatDump(stderr, rdoc, 1);
414     }
415     return rdoc;
416 }
417
418 static struct record *ingest_record(struct client *cl, Z_External *rec)
419 {
420     xmlDoc *xdoc = normalize_record(cl, rec);
421     xmlNode *root, *n;
422     struct record *res, *head;
423     struct session *se = cl->session;
424     xmlChar *mergekey, *mergekey_norm;
425
426     if (!xdoc)
427         return 0;
428
429     root = xmlDocGetRootElement(xdoc);
430     if (!(mergekey = xmlGetProp(root, "mergekey")))
431     {
432         yaz_log(YLOG_WARN, "No mergekey found in record");
433         return 0;
434     }
435
436     res = nmem_malloc(se->nmem, sizeof(struct record));
437     res->next_cluster = 0;
438     res->target_offset = -1;
439     res->term_frequency_vec = 0;
440     res->title = "Unknown";
441     res->relevance = 0;
442
443     mergekey_norm = nmem_strdup(se->nmem, (char*) mergekey);
444     xmlFree(mergekey);
445     res->merge_key = normalize_mergekey(mergekey_norm);
446
447     head = reclist_insert(se->reclist, res);
448     relevance_newrec(se->relevance, head);
449
450     for (n = root->children; n; n = n->next)
451     {
452         if (n->type != XML_ELEMENT_NODE)
453             continue;
454         if (!strcmp(n->name, "facet"))
455         {
456             xmlChar *type = xmlGetProp(n, "type");
457             xmlChar *value = xmlNodeListGetString(xdoc, n->children, 0);
458             add_facet(se, type, value);
459             relevance_countwords(se->relevance, head, value, 1);
460             xmlFree(type);
461             xmlFree(value);
462         }
463         else if (!strcmp(n->name, "metadata"))
464         {
465             xmlChar *type = xmlGetProp(n, "type"), *value;
466             if (!strcmp(type, "title"))
467                 res->title = nmem_strdup(se->nmem,
468                         value = xmlNodeListGetString(xdoc, n->children, 0));
469
470             relevance_countwords(se->relevance, head, value, 4);
471             xmlFree(type);
472             xmlFree(value);
473         }
474         else
475             yaz_log(YLOG_WARN, "Unexpected element %s in internal record", n->name);
476     }
477
478     xmlFreeDoc(xdoc);
479
480     relevance_donerecord(se->relevance, head);
481     se->total_records++;
482
483     return res;
484 }
485
486 static void ingest_records(struct client *cl, Z_Records *r)
487 {
488 #if USE_TIMING
489     yaz_timing_t t = yaz_timing_create();
490 #endif
491     struct record *rec;
492     struct session *s = cl->session;
493     Z_NamePlusRecordList *rlist;
494     int i;
495
496     if (r->which != Z_Records_DBOSD)
497         return;
498     rlist = r->u.databaseOrSurDiagnostics;
499     for (i = 0; i < rlist->num_records; i++)
500     {
501         Z_NamePlusRecord *npr = rlist->records[i];
502
503         if (npr->which != Z_NamePlusRecord_databaseRecord)
504         {
505             yaz_log(YLOG_WARN, "Unexpected record type, probably diagnostic");
506             continue;
507         }
508
509         rec = ingest_record(cl, npr->u.databaseRecord);
510         if (!rec)
511             continue;
512     }
513     if (s->watchlist[SESSION_WATCH_RECORDS].fun && rlist->num_records)
514         session_alert_watch(s, SESSION_WATCH_RECORDS);
515
516 #if USE_TIMING
517     yaz_timing_stop(t);
518     yaz_log(YLOG_LOG, "ingest_records %6.5f %3.2f %3.2f", 
519             yaz_timing_get_real(t), yaz_timing_get_user(t),
520             yaz_timing_get_sys(t));
521     yaz_timing_destroy(&t);
522 #endif
523 }
524
525 static void do_presentResponse(IOCHAN i, Z_APDU *a)
526 {
527     struct connection *co = iochan_getdata(i);
528     struct client *cl = co->client;
529     Z_PresentResponse *r = a->u.presentResponse;
530
531     if (r->records) {
532         Z_Records *recs = r->records;
533         if (recs->which == Z_Records_NSD)
534         {
535             yaz_log(YLOG_WARN, "Non-surrogate diagnostic");
536             cl->diagnostic = *recs->u.nonSurrogateDiagnostic->condition;
537             cl->state = Client_Error;
538         }
539     }
540
541     if (!*r->presentStatus && cl->state != Client_Error)
542     {
543         yaz_log(YLOG_DEBUG, "Good Present response");
544         cl->records += *r->numberOfRecordsReturned;
545         ingest_records(cl, r->records);
546         cl->state = Client_Idle;
547     }
548     else if (*r->presentStatus) 
549     {
550         yaz_log(YLOG_WARN, "Bad Present response");
551         cl->state = Client_Error;
552     }
553 }
554
555 static void handler(IOCHAN i, int event)
556 {
557     struct connection *co = iochan_getdata(i);
558     struct client *cl = co->client;
559     struct session *se = 0;
560
561     if (cl)
562         se = cl->session;
563     else
564     {
565         yaz_log(YLOG_WARN, "Destroying orphan connection");
566         connection_destroy(co);
567         return;
568     }
569
570     if (co->state == Conn_Connecting && event & EVENT_OUTPUT)
571     {
572         int errcode;
573         socklen_t errlen = sizeof(errcode);
574
575         if (getsockopt(cs_fileno(co->link), SOL_SOCKET, SO_ERROR, &errcode,
576             &errlen) < 0 || errcode != 0)
577         {
578             client_fatal(cl);
579             return;
580         }
581         else
582         {
583             yaz_log(YLOG_DEBUG, "Connect OK");
584             co->state = Conn_Open;
585             if (cl)
586                 cl->state = Client_Connected;
587         }
588     }
589
590     else if (event & EVENT_INPUT)
591     {
592         int len = cs_get(co->link, &co->ibuf, &co->ibufsize);
593
594         if (len < 0)
595         {
596             yaz_log(YLOG_WARN|YLOG_ERRNO, "Error reading from Z server");
597             connection_destroy(co);
598             return;
599         }
600         else if (len == 0)
601         {
602             yaz_log(YLOG_WARN, "EOF reading from Z server");
603             connection_destroy(co);
604             return;
605         }
606         else if (len > 1) // We discard input if we have no connection
607         {
608             co->state = Conn_Open;
609
610             if (cl && (cl->requestid == se->requestid || cl->state == Client_Initializing))
611             {
612                 Z_APDU *a;
613
614                 odr_reset(global_parameters.odr_in);
615                 odr_setbuf(global_parameters.odr_in, co->ibuf, len, 0);
616                 if (!z_APDU(global_parameters.odr_in, &a, 0, 0))
617                 {
618                     client_fatal(cl);
619                     return;
620                 }
621                 switch (a->which)
622                 {
623                     case Z_APDU_initResponse:
624                         do_initResponse(i, a);
625                         break;
626                     case Z_APDU_searchResponse:
627                         do_searchResponse(i, a);
628                         break;
629                     case Z_APDU_presentResponse:
630                         do_presentResponse(i, a);
631                         break;
632                     default:
633                         yaz_log(YLOG_WARN, "Unexpected result from server");
634                         client_fatal(cl);
635                         return;
636                 }
637                 // We aren't expecting staggered output from target
638                 // if (cs_more(t->link))
639                 //    iochan_setevent(i, EVENT_INPUT);
640             }
641             else  // we throw away response and go to idle mode
642             {
643                 yaz_log(YLOG_DEBUG, "Ignoring result of expired operation");
644                 cl->state = Client_Idle;
645             }
646         }
647         /* if len==1 we do nothing but wait for more input */
648     }
649
650     if (cl->state == Client_Connected) {
651         send_init(i);
652     }
653
654     if (cl->state == Client_Idle)
655     {
656         if (cl->requestid != se->requestid && *se->query) {
657             send_search(i);
658         }
659         else if (cl->hits > 0 && cl->records < global_parameters.toget &&
660             cl->records < cl->hits) {
661             send_present(i);
662         }
663     }
664 }
665
666 // Disassociate connection from client
667 static void connection_release(struct connection *co)
668 {
669     struct client *cl = co->client;
670
671     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
672     if (!cl)
673         return;
674     cl->connection = 0;
675     co->client = 0;
676 }
677
678 // Close connection and recycle structure
679 static void connection_destroy(struct connection *co)
680 {
681     struct host *h = co->host;
682     cs_close(co->link);
683     iochan_destroy(co->iochan);
684
685     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
686     if (h->connections == co)
687         h->connections = co->next;
688     else
689     {
690         struct connection *pco;
691         for (pco = h->connections; pco && pco->next != co; pco = pco->next)
692             ;
693         if (pco)
694             pco->next = co->next;
695         else
696             abort();
697     }
698     if (co->client)
699     {
700         if (co->client->state != Client_Idle)
701             co->client->state = Client_Disconnected;
702         co->client->connection = 0;
703     }
704     co->next = connection_freelist;
705     connection_freelist = co;
706 }
707
708 // Creates a new connection for client, associated with the host of 
709 // client's database
710 static struct connection *connection_create(struct client *cl)
711 {
712     struct connection *new;
713     COMSTACK link; 
714     int res;
715     void *addr;
716
717     yaz_log(YLOG_DEBUG, "Connection create %s", cl->database->url);
718     if (!(link = cs_create(tcpip_type, 0, PROTO_Z3950)))
719     {
720         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create comstack");
721         exit(1);
722     }
723
724     if (!(addr = cs_straddr(link, cl->database->host->ipport)))
725     {
726         yaz_log(YLOG_WARN|YLOG_ERRNO, "Lookup of IP address failed?");
727         return 0;
728     }
729
730     res = cs_connect(link, addr);
731     if (res < 0)
732     {
733         yaz_log(YLOG_WARN|YLOG_ERRNO, "cs_connect %s", cl->database->url);
734         return 0;
735     }
736
737     if ((new = connection_freelist))
738         connection_freelist = new->next;
739     else
740     {
741         new = xmalloc(sizeof (struct connection));
742         new->ibuf = 0;
743         new->ibufsize = 0;
744     }
745     new->state = Conn_Connecting;
746     new->host = cl->database->host;
747     new->next = new->host->connections;
748     new->host->connections = new;
749     new->client = cl;
750     cl->connection = new;
751     new->link = link;
752
753     new->iochan = iochan_create(cs_fileno(link), handler, 0);
754     iochan_setdata(new->iochan, new);
755     new->iochan->next = channel_list;
756     channel_list = new->iochan;
757     return new;
758 }
759
760 // Close connection and set state to error
761 static void client_fatal(struct client *cl)
762 {
763     yaz_log(YLOG_WARN, "Fatal error from %s", cl->database->url);
764     connection_destroy(cl->connection);
765     cl->state = Client_Error;
766 }
767
768 // Ensure that client has a connection associated
769 static int client_prep_connection(struct client *cl)
770 {
771     struct connection *co;
772     struct session *se = cl->session;
773     struct host *host = cl->database->host;
774
775     co = cl->connection;
776
777     yaz_log(YLOG_DEBUG, "Client prep %s", cl->database->url);
778
779     if (!co)
780     {
781         // See if someone else has an idle connection
782         // We should look at timestamps here to select the longest-idle connection
783         for (co = host->connections; co; co = co->next)
784             if (co->state == Conn_Open && (!co->client || co->client->session != se))
785                 break;
786         if (co)
787         {
788             connection_release(co);
789             cl->connection = co;
790             co->client = cl;
791         }
792         else
793             co = connection_create(cl);
794     }
795     if (co)
796     {
797         if (co->state == Conn_Connecting)
798         {
799             cl->state = Client_Connecting;
800             iochan_setflag(co->iochan, EVENT_OUTPUT);
801         }
802         else if (co->state == Conn_Open)
803         {
804             if (cl->state == Client_Error || cl->state == Client_Disconnected)
805                 cl->state = Client_Idle;
806             iochan_setflag(co->iochan, EVENT_OUTPUT);
807         }
808         return 1;
809     }
810     else
811         return 0;
812 }
813
814 // This function will most likely vanish when a proper target profile mechanism is
815 // introduced.
816 void load_simpletargets(const char *fn)
817 {
818     FILE *f = fopen(fn, "r");
819     char line[256];
820
821     if (!f)
822     {
823         yaz_log(YLOG_WARN|YLOG_ERRNO, "open %s", fn);
824         exit(1);
825     }
826
827     while (fgets(line, 255, f))
828     {
829         char *url, *db;
830         struct host *host;
831         struct database *database;
832
833         if (strncmp(line, "target ", 7))
834             continue;
835         url = line + 7;
836         url[strlen(url) - 1] = '\0';
837         yaz_log(YLOG_DEBUG, "Target: %s", url);
838         if ((db = strchr(url, '/')))
839             *(db++) = '\0';
840         else
841             db = "Default";
842
843         for (host = hosts; host; host = host->next)
844             if (!strcmp(url, host->hostport))
845                 break;
846         if (!host)
847         {
848             struct addrinfo *addrinfo, hints;
849             char *port;
850             char ipport[128];
851             unsigned char addrbuf[4];
852             int res;
853
854             host = xmalloc(sizeof(struct host));
855             host->hostport = xstrdup(url);
856             host->connections = 0;
857
858             if ((port = strchr(url, ':')))
859                 *(port++) = '\0';
860             else
861                 port = "210";
862
863             hints.ai_flags = 0;
864             hints.ai_family = PF_INET;
865             hints.ai_socktype = SOCK_STREAM;
866             hints.ai_protocol = IPPROTO_TCP;
867             hints.ai_addrlen = 0;
868             hints.ai_addr = 0;
869             hints.ai_canonname = 0;
870             hints.ai_next = 0;
871             // This is not robust code. It assumes that getaddrinfo returns AF_INET
872             // address.
873             if ((res = getaddrinfo(url, port, &hints, &addrinfo)))
874             {
875                 yaz_log(YLOG_WARN, "Failed to resolve %s: %s", url, gai_strerror(res));
876                 xfree(host->hostport);
877                 xfree(host);
878                 continue;
879             }
880             assert(addrinfo->ai_family == PF_INET);
881             memcpy(addrbuf, &((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr.s_addr, 4);
882             sprintf(ipport, "%hhd.%hhd.%hhd.%hhd:%s",
883                     addrbuf[0], addrbuf[1], addrbuf[2], addrbuf[3], port);
884             host->ipport = xstrdup(ipport);
885             freeaddrinfo(addrinfo);
886             host->next = hosts;
887             hosts = host;
888         }
889         database = xmalloc(sizeof(struct database));
890         database->host = host;
891         database->url = xmalloc(strlen(url) + strlen(db) + 2);
892         strcpy(database->url, url);
893         strcat(database->url, "/");
894         strcat(database->url, db);
895         
896         database->databases = xmalloc(2 * sizeof(char *));
897         database->databases[0] = xstrdup(db);
898         database->databases[1] = 0;
899         database->errors = 0;
900         database->qprofile = 0;
901         database->rprofile = database_retrieval_profile(database);
902         database->next = databases;
903         databases = database;
904
905     }
906     fclose(f);
907 }
908
909 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
910 {
911     switch (n->kind)
912     {
913         case CCL_RPN_AND:
914         case CCL_RPN_OR:
915         case CCL_RPN_NOT:
916         case CCL_RPN_PROX:
917             pull_terms(nmem, n->u.p[0], termlist, num);
918             pull_terms(nmem, n->u.p[1], termlist, num);
919             break;
920         case CCL_RPN_TERM:
921             termlist[(*num)++] = nmem_strdup(nmem, n->u.t.term);
922             break;
923         default: // NOOP
924             break;
925     }
926 }
927
928 // Extract terms from query into null-terminated termlist
929 static int extract_terms(NMEM nmem, char *query, char **termlist)
930 {
931     int error, pos;
932     struct ccl_rpn_node *n;
933     int num = 0;
934
935     n = ccl_find_str(global_parameters.ccl_filter, query, &error, &pos);
936     if (!n)
937         return -1;
938     pull_terms(nmem, n, termlist, &num);
939     termlist[num] = 0;
940     ccl_rpn_delete(n);
941     return 0;
942 }
943
944 static struct client *client_create(void)
945 {
946     struct client *r;
947     if (client_freelist)
948     {
949         r = client_freelist;
950         client_freelist = client_freelist->next;
951     }
952     else
953         r = xmalloc(sizeof(struct client));
954     r->database = 0;
955     r->connection = 0;
956     r->session = 0;
957     r->hits = 0;
958     r->records = 0;
959     r->setno = 0;
960     r->requestid = -1;
961     r->diagnostic = 0;
962     r->state = Client_Disconnected;
963     r->next = 0;
964     return r;
965 }
966
967 void client_destroy(struct client *c)
968 {
969     struct session *se = c->session;
970     if (c == se->clients)
971         se->clients = c->next;
972     else
973     {
974         struct client *cc;
975         for (cc = se->clients; cc && cc->next != c; cc = cc->next)
976             ;
977         if (cc)
978             cc->next = c->next;
979     }
980     if (c->connection)
981         connection_release(c->connection);
982     c->next = client_freelist;
983     client_freelist = c;
984 }
985
986 void session_set_watch(struct session *s, int what, session_watchfun fun, void *data)
987 {
988     s->watchlist[what].fun = fun;
989     s->watchlist[what].data = data;
990 }
991
992 void session_alert_watch(struct session *s, int what)
993 {
994     if (!s->watchlist[what].fun)
995         return;
996     (*s->watchlist[what].fun)(s->watchlist[what].data);
997     s->watchlist[what].fun = 0;
998     s->watchlist[what].data = 0;
999 }
1000
1001 // This needs to be extended with selection criteria
1002 static struct conf_retrievalprofile *database_retrieval_profile(struct database *db)
1003 {
1004     if (!config)
1005     {
1006         yaz_log(YLOG_FATAL, "Must load configuration (-f)");
1007         exit(1);
1008     }
1009     if (!config->retrievalprofiles)
1010     {
1011         yaz_log(YLOG_FATAL, "No retrieval profiles defined");
1012     }
1013     return config->retrievalprofiles;
1014 }
1015
1016 // This should be extended with parameters to control selection criteria
1017 // Associates a set of clients with a session;
1018 int select_targets(struct session *se)
1019 {
1020     struct database *db;
1021     int c = 0;
1022
1023     while (se->clients)
1024         client_destroy(se->clients);
1025     for (db = databases; db; db = db->next)
1026     {
1027         struct client *cl = client_create();
1028         cl->database = db;
1029         cl->session = se;
1030         cl->next = se->clients;
1031         se->clients = cl;
1032         c++;
1033     }
1034     return c;
1035 }
1036
1037 int session_active_clients(struct session *s)
1038 {
1039     struct client *c;
1040     int res = 0;
1041
1042     for (c = s->clients; c; c = c->next)
1043         if (c->connection && (c->state == Client_Connecting ||
1044                     c->state == Client_Initializing ||
1045                     c->state == Client_Searching ||
1046                     c->state == Client_Presenting))
1047             res++;
1048
1049     return res;
1050 }
1051
1052 char *search(struct session *se, char *query)
1053 {
1054     int live_channels = 0;
1055     struct client *cl;
1056
1057     yaz_log(YLOG_DEBUG, "Search");
1058
1059     strcpy(se->query, query);
1060     se->requestid++;
1061     nmem_reset(se->nmem);
1062     for (cl = se->clients; cl; cl = cl->next)
1063     {
1064         cl->hits = -1;
1065         cl->records = 0;
1066         cl->diagnostic = 0;
1067
1068         if (client_prep_connection(cl))
1069             live_channels++;
1070     }
1071     if (live_channels)
1072     {
1073         char *p[512];
1074         int maxrecs = live_channels * global_parameters.toget;
1075         se->num_termlists = 0;
1076         se->reclist = reclist_create(se->nmem, maxrecs);
1077         extract_terms(se->nmem, query, p);
1078         se->relevance = relevance_create(se->nmem, (const char **) p, maxrecs);
1079         se->total_records = se->total_hits = 0;
1080         se->expected_maxrecs = maxrecs;
1081     }
1082     else
1083         return "NOTARGETS";
1084
1085     return 0;
1086 }
1087
1088 void destroy_session(struct session *s)
1089 {
1090     yaz_log(YLOG_LOG, "Destroying session");
1091     while (s->clients)
1092         client_destroy(s->clients);
1093     nmem_destroy(s->nmem);
1094     wrbuf_free(s->wrbuf, 1);
1095 }
1096
1097 struct session *new_session() 
1098 {
1099     int i;
1100     struct session *session = xmalloc(sizeof(*session));
1101
1102     yaz_log(YLOG_DEBUG, "New pazpar2 session");
1103     
1104     session->total_hits = 0;
1105     session->total_records = 0;
1106     session->num_termlists = 0;
1107     session->reclist = 0;
1108     session->requestid = -1;
1109     session->clients = 0;
1110     session->expected_maxrecs = 0;
1111     session->query[0] = '\0';
1112     session->nmem = nmem_create();
1113     session->wrbuf = wrbuf_alloc();
1114     for (i = 0; i <= SESSION_WATCH_MAX; i++)
1115     {
1116         session->watchlist[i].data = 0;
1117         session->watchlist[i].fun = 0;
1118     }
1119
1120     select_targets(session);
1121
1122     return session;
1123 }
1124
1125 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
1126 {
1127     static struct hitsbytarget res[1000]; // FIXME MM
1128     struct client *cl;
1129
1130     *count = 0;
1131     for (cl = se->clients; cl; cl = cl->next)
1132     {
1133         strcpy(res[*count].id, cl->database->host->hostport);
1134         res[*count].hits = cl->hits;
1135         res[*count].records = cl->records;
1136         res[*count].diagnostic = cl->diagnostic;
1137         res[*count].state = client_states[cl->state];
1138         res[*count].connected  = cl->connection ? 1 : 0;
1139         (*count)++;
1140     }
1141
1142     return res;
1143 }
1144
1145 struct termlist_score **termlist(struct session *s, const char *name, int *num)
1146 {
1147     int i;
1148
1149     for (i = 0; i < s->num_termlists; i++)
1150         if (!strcmp(s->termlists[i].name, name))
1151             return termlist_highscore(s->termlists[i].termlist, num);
1152     return 0;
1153 }
1154
1155 #ifdef REPORT_NMEM
1156 // conditional compilation by SH: This lead to a warning with currently installed
1157 // YAZ header files on us1
1158 void report_nmem_stats(void)
1159 {
1160     size_t in_use, is_free;
1161
1162     nmem_get_memory_in_use(&in_use);
1163     nmem_get_memory_free(&is_free);
1164
1165     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
1166             (long) in_use, (long) is_free);
1167 }
1168 #endif
1169
1170 struct record **show(struct session *s, int start, int *num, int *total,
1171                      int *sumhits, NMEM nmem_show)
1172 {
1173     struct record **recs = nmem_malloc(nmem_show, *num 
1174                                        * sizeof(struct record *));
1175     int i;
1176 #if USE_TIMING    
1177     yaz_timing_t t = yaz_timing_create();
1178 #endif
1179     relevance_prepare_read(s->relevance, s->reclist);
1180
1181     *total = s->reclist->num_records;
1182     *sumhits = s->total_hits;
1183
1184     for (i = 0; i < start; i++)
1185         if (!reclist_read_record(s->reclist))
1186         {
1187             *num = 0;
1188             recs = 0;
1189             break;
1190         }
1191
1192     for (i = 0; i < *num; i++)
1193     {
1194         struct record *r = reclist_read_record(s->reclist);
1195         if (!r)
1196         {
1197             *num = i;
1198             break;
1199         }
1200         recs[i] = r;
1201     }
1202 #if USE_TIMING
1203     yaz_timing_stop(t);
1204     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
1205             yaz_timing_get_real(t), yaz_timing_get_user(t),
1206             yaz_timing_get_sys(t));
1207     yaz_timing_destroy(&t);
1208 #endif
1209     return recs;
1210 }
1211
1212 void statistics(struct session *se, struct statistics *stat)
1213 {
1214     struct client *cl;
1215     int count = 0;
1216
1217     bzero(stat, sizeof(*stat));
1218     for (cl = se->clients; cl; cl = cl->next)
1219     {
1220         if (!cl->connection)
1221             stat->num_no_connection++;
1222         switch (cl->state)
1223         {
1224             case Client_Connecting: stat->num_connecting++; break;
1225             case Client_Initializing: stat->num_initializing++; break;
1226             case Client_Searching: stat->num_searching++; break;
1227             case Client_Presenting: stat->num_presenting++; break;
1228             case Client_Idle: stat->num_idle++; break;
1229             case Client_Failed: stat->num_failed++; break;
1230             case Client_Error: stat->num_error++; break;
1231             default: break;
1232         }
1233         count++;
1234     }
1235     stat->num_hits = se->total_hits;
1236     stat->num_records = se->total_records;
1237
1238     stat->num_clients = count;
1239 }
1240
1241 static CCL_bibset load_cclfile(const char *fn)
1242 {
1243     CCL_bibset res = ccl_qual_mk();
1244     if (ccl_qual_fname(res, fn) < 0)
1245     {
1246         yaz_log(YLOG_FATAL|YLOG_ERRNO, "%s", fn);
1247         exit(1);
1248     }
1249     return res;
1250 }
1251
1252 int main(int argc, char **argv)
1253 {
1254     int ret;
1255     char *arg;
1256     int setport = 0;
1257
1258     if (signal(SIGPIPE, SIG_IGN) < 0)
1259         yaz_log(YLOG_WARN|YLOG_ERRNO, "signal");
1260
1261     yaz_log_init(YLOG_DEFAULT_LEVEL, "pazpar2", 0);
1262
1263     while ((ret = options("f:x:c:h:p:C:s:d", argv, argc, &arg)) != -2)
1264     {
1265         switch (ret) {
1266             case 'f':
1267                 if (!read_config(arg))
1268                     exit(1);
1269                 break;
1270             case 'c':
1271                 command_init(atoi(arg));
1272                 setport++;
1273                 break;
1274             case 'h':
1275                 http_init(arg);
1276                 setport++;
1277                 break;
1278             case 'C':
1279                 global_parameters.ccl_filter = load_cclfile(arg);
1280                 break;
1281             case 'p':
1282                 http_set_proxyaddr(arg);
1283                 break;
1284             case 's':
1285                 load_simpletargets(arg);
1286                 break;
1287             case 'd':
1288                 global_parameters.dump_records = 1;
1289                 break;
1290             default:
1291                 fprintf(stderr, "Usage: pazpar2\n"
1292                         "    -f configfile\n"
1293                         "    -h [host:]port          (REST protocol listener)\n"
1294                         "    -c cmdport              (telnet-style)\n"
1295                         "    -C cclconfig\n"
1296                         "    -s simpletargetfile\n"
1297                         "    -p hostname[:portno]    (HTTP proxy)\n");
1298                 exit(1);
1299         }
1300     }
1301
1302     if (!setport)
1303     {
1304         fprintf(stderr, "Set command port with -h or -c\n");
1305         exit(1);
1306     }
1307
1308     global_parameters.ccl_filter = load_cclfile("../etc/default.bib");
1309     global_parameters.yaz_marc = yaz_marc_create();
1310     yaz_marc_subfield_str(global_parameters.yaz_marc, "\t");
1311     global_parameters.odr_in = odr_createmem(ODR_DECODE);
1312     global_parameters.odr_out = odr_createmem(ODR_ENCODE);
1313
1314     event_loop(&channel_list);
1315
1316     return 0;
1317 }
1318
1319 /*
1320  * Local variables:
1321  * c-basic-offset: 4
1322  * indent-tabs-mode: nil
1323  * End:
1324  * vim: shiftwidth=4 tabstop=8 expandtab
1325  */