ce3eee61a2cebfbcd8b6cf5c0433021affe0fd6a
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.51 2007-07-13 09:25:41 adam Exp $
2    Copyright (c) 2006-2007, Index Data.
3
4 This file is part of Pazpar2.
5
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 /** \file logic.c
23     \brief high-level logic; mostly user sessions and settings
24 */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <sys/time.h>
30 #include <unistd.h>
31 #include <sys/socket.h>
32 #include <netdb.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <assert.h>
36
37 #include <yaz/marcdisp.h>
38 #include <yaz/comstack.h>
39 #include <yaz/tcpip.h>
40 #include <yaz/proto.h>
41 #include <yaz/readconf.h>
42 #include <yaz/pquery.h>
43 #include <yaz/otherinfo.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/nmem.h>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #include <yaz/oid_db.h>
49
50 #if HAVE_CONFIG_H
51 #include "cconfig.h"
52 #endif
53
54 #define USE_TIMING 0
55 #if USE_TIMING
56 #include <yaz/timing.h>
57 #endif
58
59 #include <netinet/in.h>
60
61 #include "pazpar2.h"
62 #include "eventl.h"
63 #include "http.h"
64 #include "termlists.h"
65 #include "reclists.h"
66 #include "relevance.h"
67 #include "config.h"
68 #include "database.h"
69 #include "client.h"
70 #include "settings.h"
71 #include "normalize7bit.h"
72
73 #define TERMLIST_HIGH_SCORE 25
74
75 #define MAX_CHUNK 15
76
77 // Note: Some things in this structure will eventually move to configuration
78 struct parameters global_parameters = 
79 {
80     "",
81     "",
82     "", 
83     0,
84     0, /* dump_records */
85     0, /* debug_mode */
86     30,
87     "81",
88     "Index Data PazPar2",
89     VERSION,
90     600, // 10 minutes
91     60,
92     100,
93     MAX_CHUNK,
94     0,
95     0
96 };
97
98
99 // Recursively traverse query structure to extract terms.
100 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
101 {
102     char **words;
103     int numwords;
104     int i;
105
106     switch (n->kind)
107     {
108         case CCL_RPN_AND:
109         case CCL_RPN_OR:
110         case CCL_RPN_NOT:
111         case CCL_RPN_PROX:
112             pull_terms(nmem, n->u.p[0], termlist, num);
113             pull_terms(nmem, n->u.p[1], termlist, num);
114             break;
115         case CCL_RPN_TERM:
116             nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
117             for (i = 0; i < numwords; i++)
118                 termlist[(*num)++] = words[i];
119             break;
120         default: // NOOP
121             break;
122     }
123 }
124
125
126
127 static void add_facet(struct session *s, const char *type, const char *value)
128 {
129     int i;
130
131     if (!*value)
132         return;
133     for (i = 0; i < s->num_termlists; i++)
134         if (!strcmp(s->termlists[i].name, type))
135             break;
136     if (i == s->num_termlists)
137     {
138         if (i == SESSION_MAX_TERMLISTS)
139         {
140             yaz_log(YLOG_FATAL, "Too many termlists");
141             return;
142         }
143
144         s->termlists[i].name = nmem_strdup(s->nmem, type);
145         s->termlists[i].termlist 
146             = termlist_create(s->nmem, s->expected_maxrecs,
147                               TERMLIST_HIGH_SCORE);
148         s->num_termlists = i + 1;
149     }
150     termlist_insert(s->termlists[i].termlist, value);
151 }
152
153 xmlDoc *record_to_xml(struct session_database *sdb, Z_External *rec)
154 {
155     struct database *db = sdb->database;
156     xmlDoc *rdoc = 0;
157     const Odr_oid *oid = rec->direct_reference;
158
159     /* convert response record to XML somehow */
160     if (rec->which == Z_External_octet && oid
161         && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
162     {
163         /* xml already */
164         rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
165                               rec->u.octet_aligned->len);
166         if (!rdoc)
167         {
168             yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
169                     db->url);
170             return 0;
171         }
172     }
173     else if (rec->which == Z_External_OPAC)
174     {
175         if (!sdb->yaz_marc)
176         {
177             yaz_log(YLOG_WARN, "MARC decoding not configured");
178             return 0;
179         }
180         else
181         {
182             /* OPAC gets converted to XML too */
183             WRBUF wrbuf_opac = wrbuf_alloc();
184             /* MARCXML inside the OPAC XML. Charset is in effect because we
185                use the yaz_marc handle */
186             yaz_marc_xml(sdb->yaz_marc, YAZ_MARC_MARCXML);
187             yaz_opac_decode_wrbuf(sdb->yaz_marc, rec->u.opac, wrbuf_opac);
188             
189             rdoc = xmlParseMemory((char*) wrbuf_buf(wrbuf_opac),
190                                   wrbuf_len(wrbuf_opac));
191             if (!rdoc)
192                 yaz_log(YLOG_WARN, "Unable to parse OPAC XML");
193             wrbuf_destroy(wrbuf_opac);
194         }
195     }
196     else if (oid && yaz_oid_is_iso2709(oid))
197     {
198         /* ISO2709 gets converted to MARCXML */
199         if (!sdb->yaz_marc)
200         {
201             yaz_log(YLOG_WARN, "MARC decoding not configured");
202             return 0;
203         }
204         else
205         {
206             xmlNode *res;
207             char *buf;
208             int len;
209             
210             if (rec->which != Z_External_octet)
211             {
212                 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
213                         db->url);
214                 return 0;
215             }
216             buf = (char*) rec->u.octet_aligned->buf;
217             len = rec->u.octet_aligned->len;
218             if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
219             {
220                 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
221                 return 0;
222             }
223             
224             yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
225             if (yaz_marc_write_xml(sdb->yaz_marc, &res,
226                                    "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
227             {
228                 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
229                         db->url);
230                 return 0;
231             }
232             rdoc = xmlNewDoc((xmlChar *) "1.0");
233             xmlDocSetRootElement(rdoc, res);
234         }
235     }
236     else
237     {
238         char oid_name_buf[OID_STR_MAX];
239         const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
240         yaz_log(YLOG_FATAL, 
241                 "Unable to handle record of type %s from %s", 
242                 oid_name, db->url);
243         return 0;
244     }
245     
246     if (global_parameters.dump_records){
247         fprintf(stderr, 
248                 "Input Record (normalized) from %s\n----------------\n",
249                 db->url);
250 #if LIBXML_VERSION >= 20600
251         xmlDocFormatDump(stderr, rdoc, 1);
252 #else
253         xmlDocDump(stderr, rdoc);
254 #endif
255     }
256     return rdoc;
257 }
258
259 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
260 {
261     struct database_retrievalmap *m;
262     xmlDoc *rdoc = record_to_xml(sdb, rec);
263     if (rdoc)
264     {
265         for (m = sdb->map; m; m = m->next){
266             xmlDoc *new = 0;
267             
268             {
269                 xmlNodePtr root = 0;
270                 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
271                 root= xmlDocGetRootElement(new);
272                 if (!new || !root || !(root->children))
273                 {
274                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
275                             sdb->database->url);
276                     xmlFreeDoc(new);
277                     xmlFreeDoc(rdoc);
278                     return 0;
279                 }
280             }
281             
282             xmlFreeDoc(rdoc);
283             rdoc = new;
284         }
285         if (global_parameters.dump_records)
286         {
287             fprintf(stderr, "Record from %s\n----------------\n", 
288                     sdb->database->url);
289 #if LIBXML_VERSION >= 20600
290             xmlDocFormatDump(stderr, rdoc, 1);
291 #else
292             xmlDocDump(stderr, rdoc);
293 #endif
294         }
295     }
296     return rdoc;
297 }
298
299 // Retrieve first defined value for 'name' for given database.
300 // Will be extended to take into account user associated with session
301 char *session_setting_oneval(struct session_database *db, int offset)
302 {
303     if (!db->settings[offset])
304         return "";
305     return db->settings[offset]->value;
306 }
307
308
309
310 // Initialize YAZ Map structures for MARC-based targets
311 static int prepare_yazmarc(struct session_database *sdb)
312 {
313     char *s;
314
315     if (!sdb->settings)
316     {
317         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
318         return -1;
319     }
320     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
321         && !strncmp(s, "iso2709", 7))
322     {
323         char *encoding = "marc-8s", *e;
324         yaz_iconv_t cm;
325
326         // See if a native encoding is specified
327         if ((e = strchr(s, ';')))
328             encoding = e + 1;
329
330         sdb->yaz_marc = yaz_marc_create();
331         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
332         
333         cm = yaz_iconv_open("utf-8", encoding);
334         if (!cm)
335         {
336             yaz_log(YLOG_FATAL, 
337                     "Unable to map from %s to UTF-8 for target %s", 
338                     encoding, sdb->database->url);
339             return -1;
340         }
341         yaz_marc_iconv(sdb->yaz_marc, cm);
342     }
343     return 0;
344 }
345
346 // Prepare XSLT stylesheets for record normalization
347 // Structures are allocated on the session_wide nmem to avoid having
348 // to recompute this for every search. This would lead
349 // to leaking if a single session was to repeatedly change the PZ_XSLT
350 // setting. However, this is not a realistic use scenario.
351 static int prepare_map(struct session *se, struct session_database *sdb)
352 {
353    char *s;
354
355     if (!sdb->settings)
356     {
357         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
358         return -1;
359     }
360     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
361     {
362         char **stylesheets;
363         struct database_retrievalmap **m = &sdb->map;
364         int num, i;
365
366         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
367         for (i = 0; i < num; i++)
368         {
369             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
370             (*m)->next = 0;
371             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
372             {
373                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
374                         stylesheets[i]);
375                 return -1;
376             }
377             m = &(*m)->next;
378         }
379     }
380     if (!sdb->map)
381         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
382                 sdb->database->url);
383     return 0;
384 }
385
386 // This analyzes settings and recomputes any supporting data structures
387 // if necessary.
388 static int prepare_session_database(struct session *se, 
389                                     struct session_database *sdb)
390 {
391     if (!sdb->settings)
392     {
393         yaz_log(YLOG_WARN, 
394                 "No settings associated with %s", sdb->database->url);
395         return -1;
396     }
397     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
398     {
399         if (prepare_yazmarc(sdb) < 0)
400             return -1;
401     }
402     if (sdb->settings[PZ_XSLT] && !sdb->map)
403     {
404         if (prepare_map(se, sdb) < 0)
405             return -1;
406     }
407     return 0;
408 }
409
410 // called if watch should be removed because http_channel is to be destroyed
411 static void session_watch_cancel(void *data, struct http_channel *c)
412 {
413     struct session_watchentry *ent = data;
414
415     ent->fun = 0;
416     ent->data = 0;
417     ent->obs = 0;
418 }
419
420 // set watch. Returns 0=OK, -1 if watch is already set
421 int session_set_watch(struct session *s, int what, 
422                       session_watchfun fun, void *data,
423                       struct http_channel *chan)
424 {
425     if (s->watchlist[what].fun)
426         return -1;
427     s->watchlist[what].fun = fun;
428     s->watchlist[what].data = data;
429     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
430                                                session_watch_cancel);
431     return 0;
432 }
433
434 void session_alert_watch(struct session *s, int what)
435 {
436     if (!s->watchlist[what].fun)
437         return;
438     http_remove_observer(s->watchlist[what].obs);
439     (*s->watchlist[what].fun)(s->watchlist[what].data);
440     s->watchlist[what].fun = 0;
441     s->watchlist[what].data = 0;
442     s->watchlist[what].obs = 0;
443 }
444
445 //callback for grep_databases
446 static void select_targets_callback(void *context, struct session_database *db)
447 {
448     struct session *se = (struct session*) context;
449     struct client *cl = client_create();
450     client_set_database(cl, db);
451     client_set_session(cl, se);
452 }
453
454 // Associates a set of clients with a session;
455 // Note: Session-databases represent databases with per-session 
456 // setting overrides
457 int select_targets(struct session *se, struct database_criterion *crit)
458 {
459     while (se->clients)
460         client_destroy(se->clients);
461
462     return session_grep_databases(se, crit, select_targets_callback);
463 }
464
465 int session_active_clients(struct session *s)
466 {
467     struct client *c;
468     int res = 0;
469
470     for (c = s->clients; c; c = client_next_in_session(c))
471         if (client_is_active(c))
472             res++;
473
474     return res;
475 }
476
477 // parses crit1=val1,crit2=val2|val3,...
478 static struct database_criterion *parse_filter(NMEM m, const char *buf)
479 {
480     struct database_criterion *res = 0;
481     char **values;
482     int num;
483     int i;
484
485     if (!buf || !*buf)
486         return 0;
487     nmem_strsplit(m, ",", buf,  &values, &num);
488     for (i = 0; i < num; i++)
489     {
490         char **subvalues;
491         int subnum;
492         int subi;
493         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
494         char *eq = strchr(values[i], '=');
495         if (!eq)
496         {
497             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
498             return 0;
499         }
500         *(eq++) = '\0';
501         new->name = values[i];
502         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
503         new->values = 0;
504         for (subi = 0; subi < subnum; subi++)
505         {
506             struct database_criterion_value *newv
507                 = nmem_malloc(m, sizeof(*newv));
508             newv->value = subvalues[subi];
509             newv->next = new->values;
510             new->values = newv;
511         }
512         new->next = res;
513         res = new;
514     }
515     return res;
516 }
517
518 enum pazpar2_error_code search(struct session *se,
519                                char *query, char *filter,
520                                const char **addinfo)
521 {
522     int live_channels = 0;
523     int no_working = 0;
524     int no_failed = 0;
525     struct client *cl;
526     struct database_criterion *criteria;
527
528     yaz_log(YLOG_DEBUG, "Search");
529
530     *addinfo = 0;
531     nmem_reset(se->nmem);
532     criteria = parse_filter(se->nmem, filter);
533     se->requestid++;
534     live_channels = select_targets(se, criteria);
535     if (live_channels)
536     {
537         int maxrecs = live_channels * global_parameters.toget;
538         se->num_termlists = 0;
539         se->reclist = reclist_create(se->nmem, maxrecs);
540         // This will be initialized in send_search()
541         se->total_records = se->total_hits = se->total_merged = 0;
542         se->expected_maxrecs = maxrecs;
543     }
544     else
545         return PAZPAR2_NO_TARGETS;
546
547     se->relevance = 0;
548
549     for (cl = se->clients; cl; cl = client_next_in_session(cl))
550     {
551         if (prepare_session_database(se, client_get_database(cl)) < 0)
552         {
553             *addinfo = client_get_database(cl)->database->url;
554             return PAZPAR2_CONFIG_TARGET;
555         }
556         // Parse query for target
557         if (client_parse_query(cl, query) < 0)
558             no_failed++;
559         else
560         {
561             no_working++;
562             client_prep_connection(cl);
563         }
564     }
565
566     // If no queries could be mapped, we signal an error
567     if (no_working == 0)
568     {
569         *addinfo = "query";
570         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
571     }
572     return PAZPAR2_NO_ERROR;
573 }
574
575 // Creates a new session_database object for a database
576 static void session_init_databases_fun(void *context, struct database *db)
577 {
578     struct session *se = (struct session *) context;
579     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
580     int num = settings_num();
581     int i;
582
583     new->database = db;
584     new->yaz_marc = 0;
585     
586 #ifdef HAVE_ICU
587     if (global_parameters.server && global_parameters.server->icu_chn)
588         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
589     else
590         new->pct = pp2_charset_create(0);
591 #else // HAVE_ICU
592     new->pct = pp2_charset_create(0);
593 #endif // HAVE_ICU
594
595     new->map = 0;
596     new->settings 
597         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
598     memset(new->settings, 0, sizeof(struct settings*) * num);
599
600     if (db->settings)
601     {
602         for (i = 0; i < num; i++)
603             new->settings[i] = db->settings[i];
604     }
605     new->next = se->databases;
606     se->databases = new;
607 }
608
609 // Doesn't free memory associated with sdb -- nmem takes care of that
610 static void session_database_destroy(struct session_database *sdb)
611 {
612     struct database_retrievalmap *m;
613
614     for (m = sdb->map; m; m = m->next)
615         xsltFreeStylesheet(m->stylesheet);
616     if (sdb->yaz_marc)
617         yaz_marc_destroy(sdb->yaz_marc);
618     if (sdb->pct)
619         pp2_charset_destroy(sdb->pct);
620 }
621
622 // Initialize session_database list -- this represents this session's view
623 // of the database list -- subject to modification by the settings ws command
624 void session_init_databases(struct session *se)
625 {
626     se->databases = 0;
627     predef_grep_databases(se, 0, session_init_databases_fun);
628 }
629
630 // Probably session_init_databases_fun should be refactored instead of
631 // called here.
632 static struct session_database *load_session_database(struct session *se, 
633                                                       char *id)
634 {
635     struct database *db = find_database(id, 0);
636
637     session_init_databases_fun((void*) se, db);
638     // New sdb is head of se->databases list
639     return se->databases;
640 }
641
642 // Find an existing session database. If not found, load it
643 static struct session_database *find_session_database(struct session *se, 
644                                                       char *id)
645 {
646     struct session_database *sdb;
647
648     for (sdb = se->databases; sdb; sdb = sdb->next)
649         if (!strcmp(sdb->database->url, id))
650             return sdb;
651     return load_session_database(se, id);
652 }
653
654 // Apply a session override to a database
655 void session_apply_setting(struct session *se, char *dbname, char *setting,
656                            char *value)
657 {
658     struct session_database *sdb = find_session_database(se, dbname);
659     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
660     int offset = settings_offset_cprefix(setting);
661
662     if (offset < 0)
663     {
664         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
665         return;
666     }
667     // Jakub: This breaks the filter setting.
668     /*if (offset == PZ_ID)
669     {
670         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
671         return;
672     }*/
673     new->precedence = 0;
674     new->target = dbname;
675     new->name = setting;
676     new->value = value;
677     new->next = sdb->settings[offset];
678     sdb->settings[offset] = new;
679
680     // Force later recompute of settings-driven data structures
681     // (happens when a search starts and client connections are prepared)
682     switch (offset)
683     {
684         case PZ_NATIVESYNTAX:
685             if (sdb->yaz_marc)
686             {
687                 yaz_marc_destroy(sdb->yaz_marc);
688                 sdb->yaz_marc = 0;
689             }
690             break;
691         case PZ_XSLT:
692             if (sdb->map)
693             {
694                 struct database_retrievalmap *m;
695                 // We don't worry about the map structure -- it's in nmem
696                 for (m = sdb->map; m; m = m->next)
697                     xsltFreeStylesheet(m->stylesheet);
698                 sdb->map = 0;
699             }
700             break;
701     }
702 }
703
704 void destroy_session(struct session *s)
705 {
706     struct session_database *sdb;
707
708     while (s->clients)
709         client_destroy(s->clients);
710     for (sdb = s->databases; sdb; sdb = sdb->next)
711         session_database_destroy(sdb);
712     nmem_destroy(s->nmem);
713     wrbuf_destroy(s->wrbuf);
714 }
715
716 struct session *new_session(NMEM nmem) 
717 {
718     int i;
719     struct session *session = nmem_malloc(nmem, sizeof(*session));
720
721     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
722     
723     session->relevance = 0;
724     session->total_hits = 0;
725     session->total_records = 0;
726     session->num_termlists = 0;
727     session->reclist = 0;
728     session->requestid = -1;
729     session->clients = 0;
730     session->expected_maxrecs = 0;
731     session->session_nmem = nmem;
732     session->nmem = nmem_create();
733     session->wrbuf = wrbuf_alloc();
734     session->databases = 0;
735     for (i = 0; i <= SESSION_WATCH_MAX; i++)
736     {
737         session->watchlist[i].data = 0;
738         session->watchlist[i].fun = 0;
739     }
740
741     return session;
742 }
743
744 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
745 {
746     static struct hitsbytarget res[1000]; // FIXME MM
747     struct client *cl;
748
749     *count = 0;
750     for (cl = se->clients; cl; cl = client_next_in_session(cl))
751     {
752         char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
753
754         res[*count].id = client_get_database(cl)->database->url;
755         res[*count].name = *name ? name : "Unknown";
756         res[*count].hits = client_get_hits(cl);
757         res[*count].records = client_get_num_records(cl);
758         res[*count].diagnostic = client_get_diagnostic(cl);
759         res[*count].state = client_get_state_str(cl);
760         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
761         (*count)++;
762     }
763
764     return res;
765 }
766
767 struct termlist_score **termlist(struct session *s, const char *name, int *num)
768 {
769     int i;
770
771     for (i = 0; i < s->num_termlists; i++)
772         if (!strcmp((const char *) s->termlists[i].name, name))
773             return termlist_highscore(s->termlists[i].termlist, num);
774     return 0;
775 }
776
777 #ifdef MISSING_HEADERS
778 void report_nmem_stats(void)
779 {
780     size_t in_use, is_free;
781
782     nmem_get_memory_in_use(&in_use);
783     nmem_get_memory_free(&is_free);
784
785     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
786             (long) in_use, (long) is_free);
787 }
788 #endif
789
790 struct record_cluster *show_single(struct session *s, int id)
791 {
792     struct record_cluster *r;
793
794     reclist_rewind(s->reclist);
795     while ((r = reclist_read_record(s->reclist)))
796         if (r->recid == id)
797             return r;
798     return 0;
799 }
800
801 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
802                              int start, int *num, int *total, int *sumhits, 
803                              NMEM nmem_show)
804 {
805     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
806                                        * sizeof(struct record_cluster *));
807     struct reclist_sortparms *spp;
808     int i;
809 #if USE_TIMING    
810     yaz_timing_t t = yaz_timing_create();
811 #endif
812
813     if (!s->relevance)
814     {
815         *num = 0;
816         *total = 0;
817         *sumhits = 0;
818         recs = 0;
819     }
820     else
821     {
822         for (spp = sp; spp; spp = spp->next)
823             if (spp->type == Metadata_sortkey_relevance)
824             {
825                 relevance_prepare_read(s->relevance, s->reclist);
826                 break;
827             }
828         reclist_sort(s->reclist, sp);
829         
830         *total = s->reclist->num_records;
831         *sumhits = s->total_hits;
832         
833         for (i = 0; i < start; i++)
834             if (!reclist_read_record(s->reclist))
835             {
836                 *num = 0;
837                 recs = 0;
838                 break;
839             }
840         
841         for (i = 0; i < *num; i++)
842         {
843             struct record_cluster *r = reclist_read_record(s->reclist);
844             if (!r)
845             {
846                 *num = i;
847                 break;
848             }
849             recs[i] = r;
850         }
851     }
852 #if USE_TIMING
853     yaz_timing_stop(t);
854     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
855             yaz_timing_get_real(t), yaz_timing_get_user(t),
856             yaz_timing_get_sys(t));
857     yaz_timing_destroy(&t);
858 #endif
859     return recs;
860 }
861
862 void statistics(struct session *se, struct statistics *stat)
863 {
864     struct client *cl;
865     int count = 0;
866
867     memset(stat, 0, sizeof(*stat));
868     for (cl = se->clients; cl; cl = client_next_in_session(cl))
869     {
870         if (!client_get_connection(cl))
871             stat->num_no_connection++;
872         switch (client_get_state(cl))
873         {
874             case Client_Connecting: stat->num_connecting++; break;
875             case Client_Initializing: stat->num_initializing++; break;
876             case Client_Searching: stat->num_searching++; break;
877             case Client_Presenting: stat->num_presenting++; break;
878             case Client_Idle: stat->num_idle++; break;
879             case Client_Failed: stat->num_failed++; break;
880             case Client_Error: stat->num_error++; break;
881             default: break;
882         }
883         count++;
884     }
885     stat->num_hits = se->total_hits;
886     stat->num_records = se->total_records;
887
888     stat->num_clients = count;
889 }
890
891 void start_http_listener(void)
892 {
893     char hp[128] = "";
894     struct conf_server *ser = global_parameters.server;
895
896     if (*global_parameters.listener_override)
897         strcpy(hp, global_parameters.listener_override);
898     else
899     {
900         strcpy(hp, ser->host ? ser->host : "");
901         if (ser->port)
902         {
903             if (*hp)
904                 strcat(hp, ":");
905             sprintf(hp + strlen(hp), "%d", ser->port);
906         }
907     }
908     http_init(hp);
909 }
910
911 void start_proxy(void)
912 {
913     char hp[128] = "";
914     struct conf_server *ser = global_parameters.server;
915
916     if (*global_parameters.proxy_override)
917         strcpy(hp, global_parameters.proxy_override);
918     else if (ser->proxy_host || ser->proxy_port)
919     {
920         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
921         if (ser->proxy_port)
922         {
923             if (*hp)
924                 strcat(hp, ":");
925             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
926         }
927     }
928     else
929         return;
930
931     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
932 }
933
934
935 // Master list of connections we're handling events to
936 static IOCHAN channel_list = 0; 
937 void pazpar2_add_channel(IOCHAN chan)
938 {
939     chan->next = channel_list;
940     channel_list = chan;
941 }
942
943 void pazpar2_event_loop()
944 {
945     event_loop(&channel_list);
946 }
947
948 static struct record_metadata *record_metadata_init(
949     NMEM nmem, char *value, enum conf_metadata_type type)
950 {
951     struct record_metadata *rec_md = record_metadata_create(nmem);
952     if (type == Metadata_type_generic)
953     {
954         char * p = value;
955         p = normalize7bit_generic(p, " ,/.:([");
956         
957         rec_md->data.text = nmem_strdup(nmem, p);
958     }
959     else if (type == Metadata_type_year)
960     {
961         int first, last;
962         if (extract7bit_years((char *) value, &first, &last) < 0)
963             return 0;
964         rec_md->data.number.min = first;
965         rec_md->data.number.max = last;
966     }
967     else
968         return 0;
969     return rec_md;
970 }
971
972 struct record *ingest_record(struct client *cl, Z_External *rec,
973                              int record_no)
974 {
975     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
976     xmlNode *root, *n;
977     struct record *record;
978     struct record_cluster *cluster;
979     struct session *se = client_get_session(cl);
980     xmlChar *mergekey, *mergekey_norm;
981     xmlChar *type = 0;
982     xmlChar *value = 0;
983     struct conf_service *service = global_parameters.server->service;
984
985     if (!xdoc)
986         return 0;
987
988     root = xmlDocGetRootElement(xdoc);
989     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
990     {
991         yaz_log(YLOG_WARN, "No mergekey found in record");
992         xmlFreeDoc(xdoc);
993         return 0;
994     }
995
996     record = record_create(se->nmem, 
997                            service->num_metadata, service->num_sortkeys, cl,
998                            record_no);
999
1000     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
1001     xmlFree(mergekey);
1002     normalize7bit_mergekey((char *) mergekey_norm, 0);
1003
1004     cluster = reclist_insert(se->reclist, 
1005                              global_parameters.server->service, 
1006                              record, (char *) mergekey_norm, 
1007                              &se->total_merged);
1008     if (global_parameters.dump_records)
1009         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
1010                 client_get_database(cl)->database->url, record_no);
1011     if (!cluster)
1012     {
1013         /* no room for record */
1014         xmlFreeDoc(xdoc);
1015         return 0;
1016     }
1017     relevance_newrec(se->relevance, cluster);
1018
1019
1020     // now parsing XML record and adding data to cluster or record metadata
1021     for (n = root->children; n; n = n->next)
1022     {
1023         if (type)
1024             xmlFree(type);
1025         if (value)
1026             xmlFree(value);
1027         type = value = 0;
1028
1029         if (n->type != XML_ELEMENT_NODE)
1030             continue;
1031         if (!strcmp((const char *) n->name, "metadata"))
1032         {
1033             struct conf_metadata *ser_md = 0;
1034             struct conf_sortkey *ser_sk = 0;
1035             struct record_metadata **wheretoput = 0;
1036             struct record_metadata *rec_md = 0;
1037             int md_field_id = -1;
1038             int sk_field_id = -1;
1039
1040             type = xmlGetProp(n, (xmlChar *) "type");
1041             value = xmlNodeListGetString(xdoc, n->children, 1);
1042
1043             if (!type || !value)
1044                 continue;
1045
1046             md_field_id 
1047                 = conf_service_metadata_field_id(service, (const char *) type);
1048             if (md_field_id < 0)
1049             {
1050                 yaz_log(YLOG_WARN, 
1051                         "Ignoring unknown metadata element: %s", type);
1052                 continue;
1053             }
1054
1055             ser_md = &service->metadata[md_field_id];
1056
1057             if (ser_md->sortkey_offset >= 0){
1058                 sk_field_id = ser_md->sortkey_offset;
1059                 ser_sk = &service->sortkeys[sk_field_id];
1060             }
1061
1062             // non-merged metadata
1063             rec_md = record_metadata_init(se->nmem, (char *) value,
1064                                           ser_md->type);
1065             if (!rec_md)
1066             {
1067                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1068                         value, type);
1069                 continue;
1070             }
1071             rec_md->next = record->metadata[md_field_id];
1072             record->metadata[md_field_id] = rec_md;
1073
1074             // merged metadata
1075             rec_md = record_metadata_init(se->nmem, (char *) value,
1076                                           ser_md->type);
1077             wheretoput = &cluster->metadata[md_field_id];
1078
1079             // and polulate with data:
1080             // assign cluster or record based on merge action
1081             if (ser_md->merge == Metadata_merge_unique)
1082             {
1083                 struct record_metadata *mnode;
1084                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1085                     if (!strcmp((const char *) mnode->data.text, 
1086                                 rec_md->data.text))
1087                         break;
1088                 if (!mnode)
1089                 {
1090                     rec_md->next = *wheretoput;
1091                     *wheretoput = rec_md;
1092                 }
1093             }
1094             else if (ser_md->merge == Metadata_merge_longest)
1095             {
1096                 if (!*wheretoput 
1097                     || strlen(rec_md->data.text) 
1098                        > strlen((*wheretoput)->data.text))
1099                 {
1100                     *wheretoput = rec_md;
1101                     if (ser_sk)
1102                     {
1103                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1104                         if (!cluster->sortkeys[sk_field_id])
1105                             cluster->sortkeys[sk_field_id] = 
1106                                 nmem_malloc(se->nmem, 
1107                                             sizeof(union data_types));
1108                         normalize7bit_mergekey(s,
1109                              (ser_sk->type == Metadata_sortkey_skiparticle));
1110                         cluster->sortkeys[sk_field_id]->text = s;
1111                     }
1112                 }
1113             }
1114             else if (ser_md->merge == Metadata_merge_all)
1115             {
1116                 rec_md->next = *wheretoput;
1117                 *wheretoput = rec_md;
1118             }
1119             else if (ser_md->merge == Metadata_merge_range)
1120             {
1121                 if (!*wheretoput)
1122                 {
1123                     *wheretoput = rec_md;
1124                     if (ser_sk)
1125                         cluster->sortkeys[sk_field_id] 
1126                             = &rec_md->data;
1127                 }
1128                 else
1129                 {
1130                     int this_min = rec_md->data.number.min;
1131                     int this_max = rec_md->data.number.max;
1132                     if (this_min < (*wheretoput)->data.number.min)
1133                         (*wheretoput)->data.number.min = this_min;
1134                     if (this_max > (*wheretoput)->data.number.max)
1135                         (*wheretoput)->data.number.max = this_max;
1136                 }
1137 #ifdef GAGA
1138                 if (ser_sk)
1139                 {
1140                     union data_types *sdata 
1141                         = cluster->sortkeys[sk_field_id];
1142                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1143                             sdata->number.min, sdata->number.max);
1144                 }
1145 #endif
1146             }
1147
1148
1149             // ranking of _all_ fields enabled ... 
1150             if (ser_md->rank)
1151                 relevance_countwords(se->relevance, cluster, 
1152                                      (char *) value, ser_md->rank);
1153
1154             // construct facets ... 
1155             if (ser_md->termlist)
1156             {
1157                 if (ser_md->type == Metadata_type_year)
1158                 {
1159                     char year[64];
1160                     sprintf(year, "%d", rec_md->data.number.max);
1161                     add_facet(se, (char *) type, year);
1162                     if (rec_md->data.number.max != rec_md->data.number.min)
1163                     {
1164                         sprintf(year, "%d", rec_md->data.number.min);
1165                         add_facet(se, (char *) type, year);
1166                     }
1167                 }
1168                 else
1169                     add_facet(se, (char *) type, (char *) value);
1170             }
1171
1172             // cleaning up
1173             xmlFree(type);
1174             xmlFree(value);
1175             type = value = 0;
1176         }
1177         else
1178             yaz_log(YLOG_WARN,
1179                     "Unexpected element %s in internal record", n->name);
1180     }
1181     if (type)
1182         xmlFree(type);
1183     if (value)
1184         xmlFree(value);
1185
1186     xmlFreeDoc(xdoc);
1187
1188     relevance_donerecord(se->relevance, cluster);
1189     se->total_records++;
1190
1191     return record;
1192 }
1193
1194
1195
1196 /*
1197  * Local variables:
1198  * c-basic-offset: 4
1199  * indent-tabs-mode: nil
1200  * End:
1201  * vim: shiftwidth=4 tabstop=8 expandtab
1202  */