1 /* $Id: logic.c,v 1.33 2007-05-24 10:57:38 adam Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
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
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
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
23 \brief high-level logic; mostly user sessions and settings
31 #include <sys/socket.h>
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>
46 #include <yaz/query-charset.h>
47 #include <yaz/querytowrbuf.h>
48 #if YAZ_VERSIONL >= 0x020163
49 #include <yaz/oid_db.h>
58 #include <yaz/timing.h>
61 #include <netinet/in.h>
66 #include "termlists.h"
68 #include "relevance.h"
73 #include "normalize7bit.h"
77 // Note: Some things in this structure will eventually move to configuration
78 struct parameters global_parameters =
100 // Recursively traverse query structure to extract terms.
101 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
113 pull_terms(nmem, n->u.p[0], termlist, num);
114 pull_terms(nmem, n->u.p[1], termlist, num);
117 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
118 for (i = 0; i < numwords; i++)
119 termlist[(*num)++] = words[i];
128 static void add_facet(struct session *s, const char *type, const char *value)
134 for (i = 0; i < s->num_termlists; i++)
135 if (!strcmp(s->termlists[i].name, type))
137 if (i == s->num_termlists)
139 if (i == SESSION_MAX_TERMLISTS)
141 yaz_log(YLOG_FATAL, "Too many termlists");
145 s->termlists[i].name = nmem_strdup(s->nmem, type);
146 s->termlists[i].termlist
147 = termlist_create(s->nmem, s->expected_maxrecs, 15);
148 s->num_termlists = i + 1;
150 termlist_insert(s->termlists[i].termlist, value);
153 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
155 struct database_retrievalmap *m;
156 struct database *db = sdb->database;
160 // First normalize to XML
165 if (rec->which != Z_External_octet)
167 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
171 buf = (char*) rec->u.octet_aligned->buf;
172 len = rec->u.octet_aligned->len;
173 if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
175 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
179 yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
180 if (yaz_marc_write_xml(sdb->yaz_marc, &res,
181 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
183 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
187 rdoc = xmlNewDoc((xmlChar *) "1.0");
188 xmlDocSetRootElement(rdoc, res);
194 "Unknown native_syntax in normalize_record from %s",
199 if (global_parameters.dump_records){
201 "Input Record (normalized) from %s\n----------------\n",
203 #if LIBXML_VERSION >= 20600
204 xmlDocFormatDump(stderr, rdoc, 1);
206 xmlDocDump(stderr, rdoc);
210 for (m = sdb->map; m; m = m->next){
215 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
216 root= xmlDocGetRootElement(new);
217 if (!new || !root || !(root->children))
219 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
230 if (global_parameters.dump_records)
232 fprintf(stderr, "Record from %s\n----------------\n",
234 #if LIBXML_VERSION >= 20600
235 xmlDocFormatDump(stderr, rdoc, 1);
237 xmlDocDump(stderr, rdoc);
243 // Retrieve first defined value for 'name' for given database.
244 // Will be extended to take into account user associated with session
245 char *session_setting_oneval(struct session_database *db, int offset)
247 if (!db->settings[offset])
249 return db->settings[offset]->value;
254 // Initialize YAZ Map structures for MARC-based targets
255 static int prepare_yazmarc(struct session_database *sdb)
261 yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
264 if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX))
265 && !strncmp(s, "iso2709", 7))
267 char *encoding = "marc-8s", *e;
270 // See if a native encoding is specified
271 if ((e = strchr(s, ';')))
274 sdb->yaz_marc = yaz_marc_create();
275 yaz_marc_subfield_str(sdb->yaz_marc, "\t");
277 cm = yaz_iconv_open("utf-8", encoding);
281 "Unable to map from %s to UTF-8 for target %s",
282 encoding, sdb->database->url);
285 yaz_marc_iconv(sdb->yaz_marc, cm);
290 // Prepare XSLT stylesheets for record normalization
291 // Structures are allocated on the session_wide nmem to avoid having
292 // to recompute this for every search. This would lead
293 // to leaking if a single session was to repeatedly change the PZ_XSLT
294 // setting. However, this is not a realistic use scenario.
295 static int prepare_map(struct session *se, struct session_database *sdb)
301 yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
304 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
307 struct database_retrievalmap **m = &sdb->map;
310 nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
311 for (i = 0; i < num; i++)
313 (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
315 if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
317 yaz_log(YLOG_FATAL, "Unable to load stylesheet: %s",
325 yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
330 // This analyzes settings and recomputes any supporting data structures
332 static int prepare_session_database(struct session *se,
333 struct session_database *sdb)
338 "No settings associated with %s", sdb->database->url);
341 if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
343 if (prepare_yazmarc(sdb) < 0)
346 if (sdb->settings[PZ_XSLT] && !sdb->map)
348 if (prepare_map(se, sdb) < 0)
355 void session_set_watch(struct session *s, int what,
356 session_watchfun fun, void *data)
358 s->watchlist[what].fun = fun;
359 s->watchlist[what].data = data;
362 void session_alert_watch(struct session *s, int what)
364 if (!s->watchlist[what].fun)
366 (*s->watchlist[what].fun)(s->watchlist[what].data);
367 s->watchlist[what].fun = 0;
368 s->watchlist[what].data = 0;
371 //callback for grep_databases
372 static void select_targets_callback(void *context, struct session_database *db)
374 struct session *se = (struct session*) context;
375 struct client *cl = client_create();
376 client_set_database(cl, db);
377 client_set_session(cl, se);
380 // Associates a set of clients with a session;
381 // Note: Session-databases represent databases with per-session
383 int select_targets(struct session *se, struct database_criterion *crit)
386 client_destroy(se->clients);
388 return session_grep_databases(se, crit, select_targets_callback);
391 int session_active_clients(struct session *s)
396 for (c = s->clients; c; c = client_next_in_session(c))
397 if (client_is_active(c))
403 // parses crit1=val1,crit2=val2|val3,...
404 static struct database_criterion *parse_filter(NMEM m, const char *buf)
406 struct database_criterion *res = 0;
413 nmem_strsplit(m, ",", buf, &values, &num);
414 for (i = 0; i < num; i++)
419 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
420 char *eq = strchr(values[i], '=');
423 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
427 new->name = values[i];
428 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
430 for (subi = 0; subi < subnum; subi++)
432 struct database_criterion_value *newv
433 = nmem_malloc(m, sizeof(*newv));
434 newv->value = subvalues[subi];
435 newv->next = new->values;
444 char *search(struct session *se, char *query, char *filter)
446 int live_channels = 0;
448 struct database_criterion *criteria;
450 yaz_log(YLOG_DEBUG, "Search");
452 nmem_reset(se->nmem);
453 criteria = parse_filter(se->nmem, filter);
455 live_channels = select_targets(se, criteria);
458 int maxrecs = live_channels * global_parameters.toget;
459 se->num_termlists = 0;
460 se->reclist = reclist_create(se->nmem, maxrecs);
461 // This will be initialized in send_search()
462 se->total_records = se->total_hits = se->total_merged = 0;
463 se->expected_maxrecs = maxrecs;
470 for (cl = se->clients; cl; cl = client_next_in_session(cl))
472 if (prepare_session_database(se, client_get_database(cl)) < 0)
473 return "CONFIG_ERROR";
474 // Query must parse for all targets
475 if (client_parse_query(cl, query) < 0)
479 for (cl = se->clients; cl; cl = client_next_in_session(cl))
481 client_prep_connection(cl);
487 // Creates a new session_database object for a database
488 static void session_init_databases_fun(void *context, struct database *db)
490 struct session *se = (struct session *) context;
491 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
492 int num = settings_num();
499 if (global_parameters.server && global_parameters.server->icu_chn)
500 new->pct = pp2_charset_create(global_parameters.server->icu_chn);
502 new->pct = pp2_charset_create(0);
504 new->pct = pp2_charset_create(0);
509 = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
510 memset(new->settings, 0, sizeof(struct settings*) * num);
514 for (i = 0; i < num; i++)
515 new->settings[i] = db->settings[i];
517 new->next = se->databases;
521 // Doesn't free memory associated with sdb -- nmem takes care of that
522 static void session_database_destroy(struct session_database *sdb)
524 struct database_retrievalmap *m;
526 for (m = sdb->map; m; m = m->next)
527 xsltFreeStylesheet(m->stylesheet);
529 yaz_marc_destroy(sdb->yaz_marc);
531 pp2_charset_destroy(sdb->pct);
534 // Initialize session_database list -- this represents this session's view
535 // of the database list -- subject to modification by the settings ws command
536 void session_init_databases(struct session *se)
539 grep_databases(se, 0, session_init_databases_fun);
542 // Probably session_init_databases_fun should be refactored instead of
544 static struct session_database *load_session_database(struct session *se,
547 struct database *db = find_database(id, 0);
549 session_init_databases_fun((void*) se, db);
550 // New sdb is head of se->databases list
551 return se->databases;
554 // Find an existing session database. If not found, load it
555 static struct session_database *find_session_database(struct session *se,
558 struct session_database *sdb;
560 for (sdb = se->databases; sdb; sdb = sdb->next)
561 if (!strcmp(sdb->database->url, id))
563 return load_session_database(se, id);
566 // Apply a session override to a database
567 void session_apply_setting(struct session *se, char *dbname, char *setting,
570 struct session_database *sdb = find_session_database(se, dbname);
571 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
572 int offset = settings_offset_cprefix(setting);
576 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
579 // Jakub: This breaks the filter setting.
580 /*if (offset == PZ_ID)
582 yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
586 new->target = dbname;
589 new->next = sdb->settings[offset];
590 sdb->settings[offset] = new;
592 // Force later recompute of settings-driven data structures
593 // (happens when a search starts and client connections are prepared)
596 case PZ_NATIVESYNTAX:
599 yaz_marc_destroy(sdb->yaz_marc);
606 struct database_retrievalmap *m;
607 // We don't worry about the map structure -- it's in nmem
608 for (m = sdb->map; m; m = m->next)
609 xsltFreeStylesheet(m->stylesheet);
616 void destroy_session(struct session *s)
618 struct session_database *sdb;
620 yaz_log(YLOG_LOG, "Destroying session");
622 client_destroy(s->clients);
623 for (sdb = s->databases; sdb; sdb = sdb->next)
624 session_database_destroy(sdb);
625 nmem_destroy(s->nmem);
626 wrbuf_destroy(s->wrbuf);
629 struct session *new_session(NMEM nmem)
632 struct session *session = nmem_malloc(nmem, sizeof(*session));
634 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
636 session->total_hits = 0;
637 session->total_records = 0;
638 session->num_termlists = 0;
639 session->reclist = 0;
640 session->requestid = -1;
641 session->clients = 0;
642 session->expected_maxrecs = 0;
643 session->session_nmem = nmem;
644 session->nmem = nmem_create();
645 session->wrbuf = wrbuf_alloc();
646 session_init_databases(session);
647 for (i = 0; i <= SESSION_WATCH_MAX; i++)
649 session->watchlist[i].data = 0;
650 session->watchlist[i].fun = 0;
656 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
658 static struct hitsbytarget res[1000]; // FIXME MM
662 for (cl = se->clients; cl; cl = client_next_in_session(cl))
664 char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
666 res[*count].id = client_get_database(cl)->database->url;
667 res[*count].name = *name ? name : "Unknown";
668 res[*count].hits = client_get_hits(cl);
669 res[*count].records = client_get_num_records(cl);
670 res[*count].diagnostic = client_get_diagnostic(cl);
671 res[*count].state = client_get_state_str(cl);
672 res[*count].connected = client_get_connection(cl) ? 1 : 0;
679 struct termlist_score **termlist(struct session *s, const char *name, int *num)
683 for (i = 0; i < s->num_termlists; i++)
684 if (!strcmp((const char *) s->termlists[i].name, name))
685 return termlist_highscore(s->termlists[i].termlist, num);
689 #ifdef MISSING_HEADERS
690 void report_nmem_stats(void)
692 size_t in_use, is_free;
694 nmem_get_memory_in_use(&in_use);
695 nmem_get_memory_free(&is_free);
697 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
698 (long) in_use, (long) is_free);
702 struct record_cluster *show_single(struct session *s, int id)
704 struct record_cluster *r;
706 reclist_rewind(s->reclist);
707 while ((r = reclist_read_record(s->reclist)))
713 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp,
714 int start, int *num, int *total, int *sumhits,
717 struct record_cluster **recs = nmem_malloc(nmem_show, *num
718 * sizeof(struct record_cluster *));
719 struct reclist_sortparms *spp;
722 yaz_timing_t t = yaz_timing_create();
725 for (spp = sp; spp; spp = spp->next)
726 if (spp->type == Metadata_sortkey_relevance)
728 relevance_prepare_read(s->relevance, s->reclist);
731 reclist_sort(s->reclist, sp);
733 *total = s->reclist->num_records;
734 *sumhits = s->total_hits;
736 for (i = 0; i < start; i++)
737 if (!reclist_read_record(s->reclist))
744 for (i = 0; i < *num; i++)
746 struct record_cluster *r = reclist_read_record(s->reclist);
756 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
757 yaz_timing_get_real(t), yaz_timing_get_user(t),
758 yaz_timing_get_sys(t));
759 yaz_timing_destroy(&t);
764 void statistics(struct session *se, struct statistics *stat)
769 memset(stat, 0, sizeof(*stat));
770 for (cl = se->clients; cl; cl = client_next_in_session(cl))
772 if (!client_get_connection(cl))
773 stat->num_no_connection++;
774 switch (client_get_state(cl))
776 case Client_Connecting: stat->num_connecting++; break;
777 case Client_Initializing: stat->num_initializing++; break;
778 case Client_Searching: stat->num_searching++; break;
779 case Client_Presenting: stat->num_presenting++; break;
780 case Client_Idle: stat->num_idle++; break;
781 case Client_Failed: stat->num_failed++; break;
782 case Client_Error: stat->num_error++; break;
787 stat->num_hits = se->total_hits;
788 stat->num_records = se->total_records;
790 stat->num_clients = count;
793 void start_http_listener(void)
796 struct conf_server *ser = global_parameters.server;
798 if (*global_parameters.listener_override)
799 strcpy(hp, global_parameters.listener_override);
802 strcpy(hp, ser->host ? ser->host : "");
807 sprintf(hp + strlen(hp), "%d", ser->port);
813 void start_proxy(void)
816 struct conf_server *ser = global_parameters.server;
818 if (*global_parameters.proxy_override)
819 strcpy(hp, global_parameters.proxy_override);
820 else if (ser->proxy_host || ser->proxy_port)
822 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
827 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
833 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
836 void start_zproxy(void)
838 struct conf_server *ser = global_parameters.server;
840 if (*global_parameters.zproxy_override){
841 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
842 global_parameters.zproxy_override);
846 else if (ser->zproxy_host || ser->zproxy_port)
850 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
851 if (ser->zproxy_port)
858 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
860 strcpy(global_parameters.zproxy_override, hp);
861 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
862 global_parameters.zproxy_override);
869 // Master list of connections we're handling events to
870 static IOCHAN channel_list = 0;
871 void pazpar2_add_channel(IOCHAN chan)
873 chan->next = channel_list;
877 void pazpar2_event_loop()
879 event_loop(&channel_list);
882 struct record *ingest_record(struct client *cl, Z_External *rec,
885 xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
887 struct record *record;
888 struct record_cluster *cluster;
889 struct session *se = client_get_session(cl);
890 xmlChar *mergekey, *mergekey_norm;
893 struct conf_service *service = global_parameters.server->service;
898 root = xmlDocGetRootElement(xdoc);
899 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
901 yaz_log(YLOG_WARN, "No mergekey found in record");
906 record = record_create(se->nmem,
907 service->num_metadata, service->num_sortkeys);
908 record_assign_client(record, cl);
910 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
912 normalize7bit_mergekey((char *) mergekey_norm, 0);
914 cluster = reclist_insert(se->reclist,
915 global_parameters.server->service,
916 record, (char *) mergekey_norm,
918 if (global_parameters.dump_records)
919 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
920 client_get_database(cl)->database->url, record_no);
923 /* no room for record */
927 relevance_newrec(se->relevance, cluster);
930 // now parsing XML record and adding data to cluster or record metadata
931 for (n = root->children; n; n = n->next)
939 if (n->type != XML_ELEMENT_NODE)
941 if (!strcmp((const char *) n->name, "metadata"))
943 struct conf_metadata *ser_md = 0;
944 struct conf_sortkey *ser_sk = 0;
945 struct record_metadata **wheretoput = 0;
946 struct record_metadata *rec_md = 0;
947 int md_field_id = -1;
948 int sk_field_id = -1;
951 type = xmlGetProp(n, (xmlChar *) "type");
952 value = xmlNodeListGetString(xdoc, n->children, 0);
958 = conf_service_metadata_field_id(service, (const char *) type);
962 "Ignoring unknown metadata element: %s", type);
966 ser_md = &service->metadata[md_field_id];
968 if (ser_md->sortkey_offset >= 0){
969 sk_field_id = ser_md->sortkey_offset;
970 ser_sk = &service->sortkeys[sk_field_id];
973 // Find out where we are putting it - based on merge or not
974 if (ser_md->merge == Metadata_merge_no)
975 wheretoput = &record->metadata[md_field_id];
977 wheretoput = &cluster->metadata[md_field_id];
979 // create new record_metadata
980 rec_md = record_metadata_create(se->nmem);
982 // and polulate with data:
983 // type based charmapping decisions follow here
984 if (ser_md->type == Metadata_type_generic)
987 char * p = (char *) value;
988 p = normalize7bit_generic(p, " ,/.:([");
990 rec_md->data.text = nmem_strdup(se->nmem, p);
993 else if (ser_md->type == Metadata_type_year)
995 if (extract7bit_years((char *) value, &first, &last) < 0)
1001 "Unknown type in metadata element %s", type);
1005 // and polulate with data:
1006 // assign cluster or record based on merge action
1007 if (ser_md->merge == Metadata_merge_unique)
1009 struct record_metadata *mnode;
1010 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1011 if (!strcmp((const char *) mnode->data.text,
1016 rec_md->next = *wheretoput;
1017 *wheretoput = rec_md;
1020 else if (ser_md->merge == Metadata_merge_longest)
1023 || strlen(rec_md->data.text)
1024 > strlen((*wheretoput)->data.text))
1026 *wheretoput = rec_md;
1029 char *s = nmem_strdup(se->nmem, rec_md->data.text);
1030 if (!cluster->sortkeys[sk_field_id])
1031 cluster->sortkeys[sk_field_id] =
1032 nmem_malloc(se->nmem,
1033 sizeof(union data_types));
1034 normalize7bit_mergekey(s,
1035 (ser_sk->type == Metadata_sortkey_skiparticle));
1036 cluster->sortkeys[sk_field_id]->text = s;
1040 else if (ser_md->merge == Metadata_merge_all
1041 || ser_md->merge == Metadata_merge_no)
1043 rec_md->next = *wheretoput;
1044 *wheretoput = rec_md;
1046 else if (ser_md->merge == Metadata_merge_range)
1050 *wheretoput = rec_md;
1051 (*wheretoput)->data.number.min = first;
1052 (*wheretoput)->data.number.max = last;
1054 cluster->sortkeys[sk_field_id]
1059 if (first < (*wheretoput)->data.number.min)
1060 (*wheretoput)->data.number.min = first;
1061 if (last > (*wheretoput)->data.number.max)
1062 (*wheretoput)->data.number.max = last;
1067 union data_types *sdata
1068 = cluster->sortkeys[sk_field_id];
1069 yaz_log(YLOG_LOG, "SK range: %d-%d",
1070 sdata->number.min, sdata->number.max);
1076 // ranking of _all_ fields enabled ...
1078 relevance_countwords(se->relevance, cluster,
1079 (char *) value, ser_md->rank);
1081 // construct facets ...
1082 if (ser_md->termlist)
1084 if (ser_md->type == Metadata_type_year)
1087 sprintf(year, "%d", last);
1088 add_facet(se, (char *) type, year);
1091 sprintf(year, "%d", first);
1092 add_facet(se, (char *) type, year);
1096 add_facet(se, (char *) type, (char *) value);
1106 "Unexpected element %s in internal record", n->name);
1115 relevance_donerecord(se->relevance, cluster);
1116 se->total_records++;
1126 * indent-tabs-mode: nil
1128 * vim: shiftwidth=4 tabstop=8 expandtab