Option -d dumps records to the current log file instead of stderr.
[pazpar2-moved-to-github.git] / src / logic.c
1 /* $Id: logic.c,v 1.52 2007-07-16 09:00:22 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     {
248         FILE *lf = yaz_log_file();
249         if (lf)
250         {
251             yaz_log(YLOG_LOG, "Normalized record from %s", db->url);
252 #if LIBXML_VERSION >= 20600
253             xmlDocFormatDump(lf, rdoc, 1);
254 #else
255             xmlDocDump(lf, rdoc);
256 #endif
257             fprintf(lf, "\n");
258         }
259     }
260     return rdoc;
261 }
262
263 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
264 {
265     struct database_retrievalmap *m;
266     xmlDoc *rdoc = record_to_xml(sdb, rec);
267     if (rdoc)
268     {
269         for (m = sdb->map; m; m = m->next){
270             xmlDoc *new = 0;
271             
272             {
273                 xmlNodePtr root = 0;
274                 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
275                 root= xmlDocGetRootElement(new);
276                 if (!new || !root || !(root->children))
277                 {
278                     yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
279                             sdb->database->url);
280                     xmlFreeDoc(new);
281                     xmlFreeDoc(rdoc);
282                     return 0;
283                 }
284             }
285             
286             xmlFreeDoc(rdoc);
287             rdoc = new;
288         }
289         if (global_parameters.dump_records)
290         {
291             fprintf(stderr, "Record from %s\n----------------\n", 
292                     sdb->database->url);
293 #if LIBXML_VERSION >= 20600
294             xmlDocFormatDump(stderr, rdoc, 1);
295 #else
296             xmlDocDump(stderr, rdoc);
297 #endif
298         }
299     }
300     return rdoc;
301 }
302
303 // Retrieve first defined value for 'name' for given database.
304 // Will be extended to take into account user associated with session
305 char *session_setting_oneval(struct session_database *db, int offset)
306 {
307     if (!db->settings[offset])
308         return "";
309     return db->settings[offset]->value;
310 }
311
312
313
314 // Initialize YAZ Map structures for MARC-based targets
315 static int prepare_yazmarc(struct session_database *sdb)
316 {
317     char *s;
318
319     if (!sdb->settings)
320     {
321         yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
322         return -1;
323     }
324     if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX)) 
325         && !strncmp(s, "iso2709", 7))
326     {
327         char *encoding = "marc-8s", *e;
328         yaz_iconv_t cm;
329
330         // See if a native encoding is specified
331         if ((e = strchr(s, ';')))
332             encoding = e + 1;
333
334         sdb->yaz_marc = yaz_marc_create();
335         yaz_marc_subfield_str(sdb->yaz_marc, "\t");
336         
337         cm = yaz_iconv_open("utf-8", encoding);
338         if (!cm)
339         {
340             yaz_log(YLOG_FATAL, 
341                     "Unable to map from %s to UTF-8 for target %s", 
342                     encoding, sdb->database->url);
343             return -1;
344         }
345         yaz_marc_iconv(sdb->yaz_marc, cm);
346     }
347     return 0;
348 }
349
350 // Prepare XSLT stylesheets for record normalization
351 // Structures are allocated on the session_wide nmem to avoid having
352 // to recompute this for every search. This would lead
353 // to leaking if a single session was to repeatedly change the PZ_XSLT
354 // setting. However, this is not a realistic use scenario.
355 static int prepare_map(struct session *se, struct session_database *sdb)
356 {
357    char *s;
358
359     if (!sdb->settings)
360     {
361         yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
362         return -1;
363     }
364     if ((s = session_setting_oneval(sdb, PZ_XSLT)))
365     {
366         char **stylesheets;
367         struct database_retrievalmap **m = &sdb->map;
368         int num, i;
369
370         nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
371         for (i = 0; i < num; i++)
372         {
373             (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
374             (*m)->next = 0;
375             if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
376             {
377                 yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
378                         stylesheets[i]);
379                 return -1;
380             }
381             m = &(*m)->next;
382         }
383     }
384     if (!sdb->map)
385         yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
386                 sdb->database->url);
387     return 0;
388 }
389
390 // This analyzes settings and recomputes any supporting data structures
391 // if necessary.
392 static int prepare_session_database(struct session *se, 
393                                     struct session_database *sdb)
394 {
395     if (!sdb->settings)
396     {
397         yaz_log(YLOG_WARN, 
398                 "No settings associated with %s", sdb->database->url);
399         return -1;
400     }
401     if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
402     {
403         if (prepare_yazmarc(sdb) < 0)
404             return -1;
405     }
406     if (sdb->settings[PZ_XSLT] && !sdb->map)
407     {
408         if (prepare_map(se, sdb) < 0)
409             return -1;
410     }
411     return 0;
412 }
413
414 // called if watch should be removed because http_channel is to be destroyed
415 static void session_watch_cancel(void *data, struct http_channel *c)
416 {
417     struct session_watchentry *ent = data;
418
419     ent->fun = 0;
420     ent->data = 0;
421     ent->obs = 0;
422 }
423
424 // set watch. Returns 0=OK, -1 if watch is already set
425 int session_set_watch(struct session *s, int what, 
426                       session_watchfun fun, void *data,
427                       struct http_channel *chan)
428 {
429     if (s->watchlist[what].fun)
430         return -1;
431     s->watchlist[what].fun = fun;
432     s->watchlist[what].data = data;
433     s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
434                                                session_watch_cancel);
435     return 0;
436 }
437
438 void session_alert_watch(struct session *s, int what)
439 {
440     if (!s->watchlist[what].fun)
441         return;
442     http_remove_observer(s->watchlist[what].obs);
443     (*s->watchlist[what].fun)(s->watchlist[what].data);
444     s->watchlist[what].fun = 0;
445     s->watchlist[what].data = 0;
446     s->watchlist[what].obs = 0;
447 }
448
449 //callback for grep_databases
450 static void select_targets_callback(void *context, struct session_database *db)
451 {
452     struct session *se = (struct session*) context;
453     struct client *cl = client_create();
454     client_set_database(cl, db);
455     client_set_session(cl, se);
456 }
457
458 // Associates a set of clients with a session;
459 // Note: Session-databases represent databases with per-session 
460 // setting overrides
461 int select_targets(struct session *se, struct database_criterion *crit)
462 {
463     while (se->clients)
464         client_destroy(se->clients);
465
466     return session_grep_databases(se, crit, select_targets_callback);
467 }
468
469 int session_active_clients(struct session *s)
470 {
471     struct client *c;
472     int res = 0;
473
474     for (c = s->clients; c; c = client_next_in_session(c))
475         if (client_is_active(c))
476             res++;
477
478     return res;
479 }
480
481 // parses crit1=val1,crit2=val2|val3,...
482 static struct database_criterion *parse_filter(NMEM m, const char *buf)
483 {
484     struct database_criterion *res = 0;
485     char **values;
486     int num;
487     int i;
488
489     if (!buf || !*buf)
490         return 0;
491     nmem_strsplit(m, ",", buf,  &values, &num);
492     for (i = 0; i < num; i++)
493     {
494         char **subvalues;
495         int subnum;
496         int subi;
497         struct database_criterion *new = nmem_malloc(m, sizeof(*new));
498         char *eq = strchr(values[i], '=');
499         if (!eq)
500         {
501             yaz_log(YLOG_WARN, "Missing equal-sign in filter");
502             return 0;
503         }
504         *(eq++) = '\0';
505         new->name = values[i];
506         nmem_strsplit(m, "|", eq, &subvalues, &subnum);
507         new->values = 0;
508         for (subi = 0; subi < subnum; subi++)
509         {
510             struct database_criterion_value *newv
511                 = nmem_malloc(m, sizeof(*newv));
512             newv->value = subvalues[subi];
513             newv->next = new->values;
514             new->values = newv;
515         }
516         new->next = res;
517         res = new;
518     }
519     return res;
520 }
521
522 enum pazpar2_error_code search(struct session *se,
523                                char *query, char *filter,
524                                const char **addinfo)
525 {
526     int live_channels = 0;
527     int no_working = 0;
528     int no_failed = 0;
529     struct client *cl;
530     struct database_criterion *criteria;
531
532     yaz_log(YLOG_DEBUG, "Search");
533
534     *addinfo = 0;
535     nmem_reset(se->nmem);
536     criteria = parse_filter(se->nmem, filter);
537     se->requestid++;
538     live_channels = select_targets(se, criteria);
539     if (live_channels)
540     {
541         int maxrecs = live_channels * global_parameters.toget;
542         se->num_termlists = 0;
543         se->reclist = reclist_create(se->nmem, maxrecs);
544         // This will be initialized in send_search()
545         se->total_records = se->total_hits = se->total_merged = 0;
546         se->expected_maxrecs = maxrecs;
547     }
548     else
549         return PAZPAR2_NO_TARGETS;
550
551     se->relevance = 0;
552
553     for (cl = se->clients; cl; cl = client_next_in_session(cl))
554     {
555         if (prepare_session_database(se, client_get_database(cl)) < 0)
556         {
557             *addinfo = client_get_database(cl)->database->url;
558             return PAZPAR2_CONFIG_TARGET;
559         }
560         // Parse query for target
561         if (client_parse_query(cl, query) < 0)
562             no_failed++;
563         else
564         {
565             no_working++;
566             client_prep_connection(cl);
567         }
568     }
569
570     // If no queries could be mapped, we signal an error
571     if (no_working == 0)
572     {
573         *addinfo = "query";
574         return PAZPAR2_MALFORMED_PARAMETER_VALUE;
575     }
576     return PAZPAR2_NO_ERROR;
577 }
578
579 // Creates a new session_database object for a database
580 static void session_init_databases_fun(void *context, struct database *db)
581 {
582     struct session *se = (struct session *) context;
583     struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
584     int num = settings_num();
585     int i;
586
587     new->database = db;
588     new->yaz_marc = 0;
589     
590 #ifdef HAVE_ICU
591     if (global_parameters.server && global_parameters.server->icu_chn)
592         new->pct = pp2_charset_create(global_parameters.server->icu_chn);
593     else
594         new->pct = pp2_charset_create(0);
595 #else // HAVE_ICU
596     new->pct = pp2_charset_create(0);
597 #endif // HAVE_ICU
598
599     new->map = 0;
600     new->settings 
601         = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
602     memset(new->settings, 0, sizeof(struct settings*) * num);
603
604     if (db->settings)
605     {
606         for (i = 0; i < num; i++)
607             new->settings[i] = db->settings[i];
608     }
609     new->next = se->databases;
610     se->databases = new;
611 }
612
613 // Doesn't free memory associated with sdb -- nmem takes care of that
614 static void session_database_destroy(struct session_database *sdb)
615 {
616     struct database_retrievalmap *m;
617
618     for (m = sdb->map; m; m = m->next)
619         xsltFreeStylesheet(m->stylesheet);
620     if (sdb->yaz_marc)
621         yaz_marc_destroy(sdb->yaz_marc);
622     if (sdb->pct)
623         pp2_charset_destroy(sdb->pct);
624 }
625
626 // Initialize session_database list -- this represents this session's view
627 // of the database list -- subject to modification by the settings ws command
628 void session_init_databases(struct session *se)
629 {
630     se->databases = 0;
631     predef_grep_databases(se, 0, session_init_databases_fun);
632 }
633
634 // Probably session_init_databases_fun should be refactored instead of
635 // called here.
636 static struct session_database *load_session_database(struct session *se, 
637                                                       char *id)
638 {
639     struct database *db = find_database(id, 0);
640
641     session_init_databases_fun((void*) se, db);
642     // New sdb is head of se->databases list
643     return se->databases;
644 }
645
646 // Find an existing session database. If not found, load it
647 static struct session_database *find_session_database(struct session *se, 
648                                                       char *id)
649 {
650     struct session_database *sdb;
651
652     for (sdb = se->databases; sdb; sdb = sdb->next)
653         if (!strcmp(sdb->database->url, id))
654             return sdb;
655     return load_session_database(se, id);
656 }
657
658 // Apply a session override to a database
659 void session_apply_setting(struct session *se, char *dbname, char *setting,
660                            char *value)
661 {
662     struct session_database *sdb = find_session_database(se, dbname);
663     struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
664     int offset = settings_offset_cprefix(setting);
665
666     if (offset < 0)
667     {
668         yaz_log(YLOG_WARN, "Unknown setting %s", setting);
669         return;
670     }
671     // Jakub: This breaks the filter setting.
672     /*if (offset == PZ_ID)
673     {
674         yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
675         return;
676     }*/
677     new->precedence = 0;
678     new->target = dbname;
679     new->name = setting;
680     new->value = value;
681     new->next = sdb->settings[offset];
682     sdb->settings[offset] = new;
683
684     // Force later recompute of settings-driven data structures
685     // (happens when a search starts and client connections are prepared)
686     switch (offset)
687     {
688         case PZ_NATIVESYNTAX:
689             if (sdb->yaz_marc)
690             {
691                 yaz_marc_destroy(sdb->yaz_marc);
692                 sdb->yaz_marc = 0;
693             }
694             break;
695         case PZ_XSLT:
696             if (sdb->map)
697             {
698                 struct database_retrievalmap *m;
699                 // We don't worry about the map structure -- it's in nmem
700                 for (m = sdb->map; m; m = m->next)
701                     xsltFreeStylesheet(m->stylesheet);
702                 sdb->map = 0;
703             }
704             break;
705     }
706 }
707
708 void destroy_session(struct session *s)
709 {
710     struct session_database *sdb;
711
712     while (s->clients)
713         client_destroy(s->clients);
714     for (sdb = s->databases; sdb; sdb = sdb->next)
715         session_database_destroy(sdb);
716     nmem_destroy(s->nmem);
717     wrbuf_destroy(s->wrbuf);
718 }
719
720 struct session *new_session(NMEM nmem) 
721 {
722     int i;
723     struct session *session = nmem_malloc(nmem, sizeof(*session));
724
725     yaz_log(YLOG_DEBUG, "New Pazpar2 session");
726     
727     session->relevance = 0;
728     session->total_hits = 0;
729     session->total_records = 0;
730     session->num_termlists = 0;
731     session->reclist = 0;
732     session->requestid = -1;
733     session->clients = 0;
734     session->expected_maxrecs = 0;
735     session->session_nmem = nmem;
736     session->nmem = nmem_create();
737     session->wrbuf = wrbuf_alloc();
738     session->databases = 0;
739     for (i = 0; i <= SESSION_WATCH_MAX; i++)
740     {
741         session->watchlist[i].data = 0;
742         session->watchlist[i].fun = 0;
743     }
744
745     return session;
746 }
747
748 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
749 {
750     static struct hitsbytarget res[1000]; // FIXME MM
751     struct client *cl;
752
753     *count = 0;
754     for (cl = se->clients; cl; cl = client_next_in_session(cl))
755     {
756         char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
757
758         res[*count].id = client_get_database(cl)->database->url;
759         res[*count].name = *name ? name : "Unknown";
760         res[*count].hits = client_get_hits(cl);
761         res[*count].records = client_get_num_records(cl);
762         res[*count].diagnostic = client_get_diagnostic(cl);
763         res[*count].state = client_get_state_str(cl);
764         res[*count].connected  = client_get_connection(cl) ? 1 : 0;
765         (*count)++;
766     }
767
768     return res;
769 }
770
771 struct termlist_score **termlist(struct session *s, const char *name, int *num)
772 {
773     int i;
774
775     for (i = 0; i < s->num_termlists; i++)
776         if (!strcmp((const char *) s->termlists[i].name, name))
777             return termlist_highscore(s->termlists[i].termlist, num);
778     return 0;
779 }
780
781 #ifdef MISSING_HEADERS
782 void report_nmem_stats(void)
783 {
784     size_t in_use, is_free;
785
786     nmem_get_memory_in_use(&in_use);
787     nmem_get_memory_free(&is_free);
788
789     yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld", 
790             (long) in_use, (long) is_free);
791 }
792 #endif
793
794 struct record_cluster *show_single(struct session *s, int id)
795 {
796     struct record_cluster *r;
797
798     reclist_rewind(s->reclist);
799     while ((r = reclist_read_record(s->reclist)))
800         if (r->recid == id)
801             return r;
802     return 0;
803 }
804
805 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp, 
806                              int start, int *num, int *total, int *sumhits, 
807                              NMEM nmem_show)
808 {
809     struct record_cluster **recs = nmem_malloc(nmem_show, *num 
810                                        * sizeof(struct record_cluster *));
811     struct reclist_sortparms *spp;
812     int i;
813 #if USE_TIMING    
814     yaz_timing_t t = yaz_timing_create();
815 #endif
816
817     if (!s->relevance)
818     {
819         *num = 0;
820         *total = 0;
821         *sumhits = 0;
822         recs = 0;
823     }
824     else
825     {
826         for (spp = sp; spp; spp = spp->next)
827             if (spp->type == Metadata_sortkey_relevance)
828             {
829                 relevance_prepare_read(s->relevance, s->reclist);
830                 break;
831             }
832         reclist_sort(s->reclist, sp);
833         
834         *total = s->reclist->num_records;
835         *sumhits = s->total_hits;
836         
837         for (i = 0; i < start; i++)
838             if (!reclist_read_record(s->reclist))
839             {
840                 *num = 0;
841                 recs = 0;
842                 break;
843             }
844         
845         for (i = 0; i < *num; i++)
846         {
847             struct record_cluster *r = reclist_read_record(s->reclist);
848             if (!r)
849             {
850                 *num = i;
851                 break;
852             }
853             recs[i] = r;
854         }
855     }
856 #if USE_TIMING
857     yaz_timing_stop(t);
858     yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f", 
859             yaz_timing_get_real(t), yaz_timing_get_user(t),
860             yaz_timing_get_sys(t));
861     yaz_timing_destroy(&t);
862 #endif
863     return recs;
864 }
865
866 void statistics(struct session *se, struct statistics *stat)
867 {
868     struct client *cl;
869     int count = 0;
870
871     memset(stat, 0, sizeof(*stat));
872     for (cl = se->clients; cl; cl = client_next_in_session(cl))
873     {
874         if (!client_get_connection(cl))
875             stat->num_no_connection++;
876         switch (client_get_state(cl))
877         {
878             case Client_Connecting: stat->num_connecting++; break;
879             case Client_Initializing: stat->num_initializing++; break;
880             case Client_Searching: stat->num_searching++; break;
881             case Client_Presenting: stat->num_presenting++; break;
882             case Client_Idle: stat->num_idle++; break;
883             case Client_Failed: stat->num_failed++; break;
884             case Client_Error: stat->num_error++; break;
885             default: break;
886         }
887         count++;
888     }
889     stat->num_hits = se->total_hits;
890     stat->num_records = se->total_records;
891
892     stat->num_clients = count;
893 }
894
895 void start_http_listener(void)
896 {
897     char hp[128] = "";
898     struct conf_server *ser = global_parameters.server;
899
900     if (*global_parameters.listener_override)
901         strcpy(hp, global_parameters.listener_override);
902     else
903     {
904         strcpy(hp, ser->host ? ser->host : "");
905         if (ser->port)
906         {
907             if (*hp)
908                 strcat(hp, ":");
909             sprintf(hp + strlen(hp), "%d", ser->port);
910         }
911     }
912     http_init(hp);
913 }
914
915 void start_proxy(void)
916 {
917     char hp[128] = "";
918     struct conf_server *ser = global_parameters.server;
919
920     if (*global_parameters.proxy_override)
921         strcpy(hp, global_parameters.proxy_override);
922     else if (ser->proxy_host || ser->proxy_port)
923     {
924         strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
925         if (ser->proxy_port)
926         {
927             if (*hp)
928                 strcat(hp, ":");
929             sprintf(hp + strlen(hp), "%d", ser->proxy_port);
930         }
931     }
932     else
933         return;
934
935     http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
936 }
937
938
939 // Master list of connections we're handling events to
940 static IOCHAN channel_list = 0; 
941 void pazpar2_add_channel(IOCHAN chan)
942 {
943     chan->next = channel_list;
944     channel_list = chan;
945 }
946
947 void pazpar2_event_loop()
948 {
949     event_loop(&channel_list);
950 }
951
952 static struct record_metadata *record_metadata_init(
953     NMEM nmem, char *value, enum conf_metadata_type type)
954 {
955     struct record_metadata *rec_md = record_metadata_create(nmem);
956     if (type == Metadata_type_generic)
957     {
958         char * p = value;
959         p = normalize7bit_generic(p, " ,/.:([");
960         
961         rec_md->data.text = nmem_strdup(nmem, p);
962     }
963     else if (type == Metadata_type_year)
964     {
965         int first, last;
966         if (extract7bit_years((char *) value, &first, &last) < 0)
967             return 0;
968         rec_md->data.number.min = first;
969         rec_md->data.number.max = last;
970     }
971     else
972         return 0;
973     return rec_md;
974 }
975
976 struct record *ingest_record(struct client *cl, Z_External *rec,
977                              int record_no)
978 {
979     xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
980     xmlNode *root, *n;
981     struct record *record;
982     struct record_cluster *cluster;
983     struct session *se = client_get_session(cl);
984     xmlChar *mergekey, *mergekey_norm;
985     xmlChar *type = 0;
986     xmlChar *value = 0;
987     struct conf_service *service = global_parameters.server->service;
988
989     if (!xdoc)
990         return 0;
991
992     root = xmlDocGetRootElement(xdoc);
993     if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
994     {
995         yaz_log(YLOG_WARN, "No mergekey found in record");
996         xmlFreeDoc(xdoc);
997         return 0;
998     }
999
1000     record = record_create(se->nmem, 
1001                            service->num_metadata, service->num_sortkeys, cl,
1002                            record_no);
1003
1004     mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
1005     xmlFree(mergekey);
1006     normalize7bit_mergekey((char *) mergekey_norm, 0);
1007
1008     cluster = reclist_insert(se->reclist, 
1009                              global_parameters.server->service, 
1010                              record, (char *) mergekey_norm, 
1011                              &se->total_merged);
1012     if (global_parameters.dump_records)
1013         yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
1014                 client_get_database(cl)->database->url, record_no);
1015     if (!cluster)
1016     {
1017         /* no room for record */
1018         xmlFreeDoc(xdoc);
1019         return 0;
1020     }
1021     relevance_newrec(se->relevance, cluster);
1022
1023
1024     // now parsing XML record and adding data to cluster or record metadata
1025     for (n = root->children; n; n = n->next)
1026     {
1027         if (type)
1028             xmlFree(type);
1029         if (value)
1030             xmlFree(value);
1031         type = value = 0;
1032
1033         if (n->type != XML_ELEMENT_NODE)
1034             continue;
1035         if (!strcmp((const char *) n->name, "metadata"))
1036         {
1037             struct conf_metadata *ser_md = 0;
1038             struct conf_sortkey *ser_sk = 0;
1039             struct record_metadata **wheretoput = 0;
1040             struct record_metadata *rec_md = 0;
1041             int md_field_id = -1;
1042             int sk_field_id = -1;
1043
1044             type = xmlGetProp(n, (xmlChar *) "type");
1045             value = xmlNodeListGetString(xdoc, n->children, 1);
1046
1047             if (!type || !value)
1048                 continue;
1049
1050             md_field_id 
1051                 = conf_service_metadata_field_id(service, (const char *) type);
1052             if (md_field_id < 0)
1053             {
1054                 yaz_log(YLOG_WARN, 
1055                         "Ignoring unknown metadata element: %s", type);
1056                 continue;
1057             }
1058
1059             ser_md = &service->metadata[md_field_id];
1060
1061             if (ser_md->sortkey_offset >= 0){
1062                 sk_field_id = ser_md->sortkey_offset;
1063                 ser_sk = &service->sortkeys[sk_field_id];
1064             }
1065
1066             // non-merged metadata
1067             rec_md = record_metadata_init(se->nmem, (char *) value,
1068                                           ser_md->type);
1069             if (!rec_md)
1070             {
1071                 yaz_log(YLOG_WARN, "bad metadata data '%s' for element '%s'",
1072                         value, type);
1073                 continue;
1074             }
1075             rec_md->next = record->metadata[md_field_id];
1076             record->metadata[md_field_id] = rec_md;
1077
1078             // merged metadata
1079             rec_md = record_metadata_init(se->nmem, (char *) value,
1080                                           ser_md->type);
1081             wheretoput = &cluster->metadata[md_field_id];
1082
1083             // and polulate with data:
1084             // assign cluster or record based on merge action
1085             if (ser_md->merge == Metadata_merge_unique)
1086             {
1087                 struct record_metadata *mnode;
1088                 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1089                     if (!strcmp((const char *) mnode->data.text, 
1090                                 rec_md->data.text))
1091                         break;
1092                 if (!mnode)
1093                 {
1094                     rec_md->next = *wheretoput;
1095                     *wheretoput = rec_md;
1096                 }
1097             }
1098             else if (ser_md->merge == Metadata_merge_longest)
1099             {
1100                 if (!*wheretoput 
1101                     || strlen(rec_md->data.text) 
1102                        > strlen((*wheretoput)->data.text))
1103                 {
1104                     *wheretoput = rec_md;
1105                     if (ser_sk)
1106                     {
1107                         char *s = nmem_strdup(se->nmem, rec_md->data.text);
1108                         if (!cluster->sortkeys[sk_field_id])
1109                             cluster->sortkeys[sk_field_id] = 
1110                                 nmem_malloc(se->nmem, 
1111                                             sizeof(union data_types));
1112                         normalize7bit_mergekey(s,
1113                              (ser_sk->type == Metadata_sortkey_skiparticle));
1114                         cluster->sortkeys[sk_field_id]->text = s;
1115                     }
1116                 }
1117             }
1118             else if (ser_md->merge == Metadata_merge_all)
1119             {
1120                 rec_md->next = *wheretoput;
1121                 *wheretoput = rec_md;
1122             }
1123             else if (ser_md->merge == Metadata_merge_range)
1124             {
1125                 if (!*wheretoput)
1126                 {
1127                     *wheretoput = rec_md;
1128                     if (ser_sk)
1129                         cluster->sortkeys[sk_field_id] 
1130                             = &rec_md->data;
1131                 }
1132                 else
1133                 {
1134                     int this_min = rec_md->data.number.min;
1135                     int this_max = rec_md->data.number.max;
1136                     if (this_min < (*wheretoput)->data.number.min)
1137                         (*wheretoput)->data.number.min = this_min;
1138                     if (this_max > (*wheretoput)->data.number.max)
1139                         (*wheretoput)->data.number.max = this_max;
1140                 }
1141 #ifdef GAGA
1142                 if (ser_sk)
1143                 {
1144                     union data_types *sdata 
1145                         = cluster->sortkeys[sk_field_id];
1146                     yaz_log(YLOG_LOG, "SK range: %d-%d",
1147                             sdata->number.min, sdata->number.max);
1148                 }
1149 #endif
1150             }
1151
1152
1153             // ranking of _all_ fields enabled ... 
1154             if (ser_md->rank)
1155                 relevance_countwords(se->relevance, cluster, 
1156                                      (char *) value, ser_md->rank);
1157
1158             // construct facets ... 
1159             if (ser_md->termlist)
1160             {
1161                 if (ser_md->type == Metadata_type_year)
1162                 {
1163                     char year[64];
1164                     sprintf(year, "%d", rec_md->data.number.max);
1165                     add_facet(se, (char *) type, year);
1166                     if (rec_md->data.number.max != rec_md->data.number.min)
1167                     {
1168                         sprintf(year, "%d", rec_md->data.number.min);
1169                         add_facet(se, (char *) type, year);
1170                     }
1171                 }
1172                 else
1173                     add_facet(se, (char *) type, (char *) value);
1174             }
1175
1176             // cleaning up
1177             xmlFree(type);
1178             xmlFree(value);
1179             type = value = 0;
1180         }
1181         else
1182             yaz_log(YLOG_WARN,
1183                     "Unexpected element %s in internal record", n->name);
1184     }
1185     if (type)
1186         xmlFree(type);
1187     if (value)
1188         xmlFree(value);
1189
1190     xmlFreeDoc(xdoc);
1191
1192     relevance_donerecord(se->relevance, cluster);
1193     se->total_records++;
1194
1195     return record;
1196 }
1197
1198
1199
1200 /*
1201  * Local variables:
1202  * c-basic-offset: 4
1203  * indent-tabs-mode: nil
1204  * End:
1205  * vim: shiftwidth=4 tabstop=8 expandtab
1206  */