1 /* $Id: logic.c,v 1.28 2007-05-14 08:01:39 marc 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 =
99 // Recursively traverse query structure to extract terms.
100 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
112 pull_terms(nmem, n->u.p[0], termlist, num);
113 pull_terms(nmem, n->u.p[1], termlist, num);
116 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
117 for (i = 0; i < numwords; i++)
118 termlist[(*num)++] = words[i];
127 static void add_facet(struct session *s, const char *type, const char *value)
133 for (i = 0; i < s->num_termlists; i++)
134 if (!strcmp(s->termlists[i].name, type))
136 if (i == s->num_termlists)
138 if (i == SESSION_MAX_TERMLISTS)
140 yaz_log(YLOG_FATAL, "Too many termlists");
144 s->termlists[i].name = nmem_strdup(s->nmem, type);
145 s->termlists[i].termlist
146 = termlist_create(s->nmem, s->expected_maxrecs, 15);
147 s->num_termlists = i + 1;
149 termlist_insert(s->termlists[i].termlist, value);
152 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
154 struct database_retrievalmap *m;
155 struct database *db = sdb->database;
159 // First normalize to XML
164 if (rec->which != Z_External_octet)
166 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
170 buf = (char*) rec->u.octet_aligned->buf;
171 len = rec->u.octet_aligned->len;
172 if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
174 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
178 yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
179 if (yaz_marc_write_xml(sdb->yaz_marc, &res,
180 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
182 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
186 rdoc = xmlNewDoc((xmlChar *) "1.0");
187 xmlDocSetRootElement(rdoc, res);
193 "Unknown native_syntax in normalize_record from %s",
198 if (global_parameters.dump_records){
200 "Input Record (normalized) from %s\n----------------\n",
202 #if LIBXML_VERSION >= 20600
203 xmlDocFormatDump(stderr, rdoc, 1);
205 xmlDocDump(stderr, rdoc);
209 for (m = sdb->map; m; m = m->next){
214 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
215 root= xmlDocGetRootElement(new);
216 if (!new || !root || !(root->children))
218 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
229 if (global_parameters.dump_records)
231 fprintf(stderr, "Record from %s\n----------------\n",
233 #if LIBXML_VERSION >= 20600
234 xmlDocFormatDump(stderr, rdoc, 1);
236 xmlDocDump(stderr, rdoc);
242 // Retrieve first defined value for 'name' for given database.
243 // Will be extended to take into account user associated with session
244 char *session_setting_oneval(struct session_database *db, int offset)
246 if (!db->settings[offset])
248 return db->settings[offset]->value;
253 // Initialize YAZ Map structures for MARC-based targets
254 static int prepare_yazmarc(struct session_database *sdb)
260 yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
263 if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX))
264 && !strncmp(s, "iso2709", 7))
266 char *encoding = "marc-8s", *e;
269 // See if a native encoding is specified
270 if ((e = strchr(s, ';')))
273 sdb->yaz_marc = yaz_marc_create();
274 yaz_marc_subfield_str(sdb->yaz_marc, "\t");
276 cm = yaz_iconv_open("utf-8", encoding);
280 "Unable to map from %s to UTF-8 for target %s",
281 encoding, sdb->database->url);
284 yaz_marc_iconv(sdb->yaz_marc, cm);
289 // Prepare XSLT stylesheets for record normalization
290 // Structures are allocated on the session_wide nmem to avoid having
291 // to recompute this for every search. This would lead
292 // to leaking if a single session was to repeatedly change the PZ_XSLT
293 // setting. However, this is not a realistic use scenario.
294 static int prepare_map(struct session *se, struct session_database *sdb)
300 yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
303 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
306 struct database_retrievalmap **m = &sdb->map;
309 nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
310 for (i = 0; i < num; i++)
312 (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
314 if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
316 yaz_log(YLOG_FATAL, "Unable to load stylesheet: %s",
324 yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
329 // This analyzes settings and recomputes any supporting data structures
331 static int prepare_session_database(struct session *se,
332 struct session_database *sdb)
337 "No settings associated with %s", sdb->database->url);
340 if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
342 if (prepare_yazmarc(sdb) < 0)
345 if (sdb->settings[PZ_XSLT] && !sdb->map)
347 if (prepare_map(se, sdb) < 0)
354 void session_set_watch(struct session *s, int what,
355 session_watchfun fun, void *data)
357 s->watchlist[what].fun = fun;
358 s->watchlist[what].data = data;
361 void session_alert_watch(struct session *s, int what)
363 if (!s->watchlist[what].fun)
365 (*s->watchlist[what].fun)(s->watchlist[what].data);
366 s->watchlist[what].fun = 0;
367 s->watchlist[what].data = 0;
370 //callback for grep_databases
371 static void select_targets_callback(void *context, struct session_database *db)
373 struct session *se = (struct session*) context;
374 struct client *cl = client_create();
375 client_set_database(cl, db);
376 client_set_session(cl, se);
379 // Associates a set of clients with a session;
380 // Note: Session-databases represent databases with per-session
382 int select_targets(struct session *se, struct database_criterion *crit)
385 client_destroy(se->clients);
387 return session_grep_databases(se, crit, select_targets_callback);
390 int session_active_clients(struct session *s)
395 for (c = s->clients; c; c = client_next_in_session(c))
396 if (client_is_active(c))
402 // parses crit1=val1,crit2=val2|val3,...
403 static struct database_criterion *parse_filter(NMEM m, const char *buf)
405 struct database_criterion *res = 0;
412 nmem_strsplit(m, ",", buf, &values, &num);
413 for (i = 0; i < num; i++)
418 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
419 char *eq = strchr(values[i], '=');
422 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
426 new->name = values[i];
427 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
429 for (subi = 0; subi < subnum; subi++)
431 struct database_criterion_value *newv
432 = nmem_malloc(m, sizeof(*newv));
433 newv->value = subvalues[subi];
434 newv->next = new->values;
443 char *search(struct session *se, char *query, char *filter)
445 int live_channels = 0;
447 struct database_criterion *criteria;
449 yaz_log(YLOG_DEBUG, "Search");
451 nmem_reset(se->nmem);
452 criteria = parse_filter(se->nmem, filter);
454 live_channels = select_targets(se, criteria);
457 int maxrecs = live_channels * global_parameters.toget;
458 se->num_termlists = 0;
459 se->reclist = reclist_create(se->nmem, maxrecs);
460 // This will be initialized in send_search()
461 se->total_records = se->total_hits = se->total_merged = 0;
462 se->expected_maxrecs = maxrecs;
469 for (cl = se->clients; cl; cl = client_next_in_session(cl))
471 if (prepare_session_database(se, client_get_database(cl)) < 0)
472 return "CONFIG_ERROR";
473 // Query must parse for all targets
474 if (client_parse_query(cl, query) < 0)
478 for (cl = se->clients; cl; cl = client_next_in_session(cl))
480 client_prep_connection(cl);
486 // Creates a new session_database object for a database
487 static void session_init_databases_fun(void *context, struct database *db)
489 struct session *se = (struct session *) context;
490 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
491 int num = settings_num();
496 new->pct = pp2_charset_create();
499 = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
500 memset(new->settings, 0, sizeof(struct settings*) * num);
504 for (i = 0; i < num; i++)
505 new->settings[i] = db->settings[i];
507 new->next = se->databases;
511 // Doesn't free memory associated with sdb -- nmem takes care of that
512 static void session_database_destroy(struct session_database *sdb)
514 struct database_retrievalmap *m;
516 for (m = sdb->map; m; m = m->next)
517 xsltFreeStylesheet(m->stylesheet);
519 yaz_marc_destroy(sdb->yaz_marc);
521 pp2_charset_destroy(sdb->pct);
524 // Initialize session_database list -- this represents this session's view
525 // of the database list -- subject to modification by the settings ws command
526 void session_init_databases(struct session *se)
529 grep_databases(se, 0, session_init_databases_fun);
532 // Probably session_init_databases_fun should be refactored instead of
534 static struct session_database *load_session_database(struct session *se,
537 struct database *db = find_database(id, 0);
539 session_init_databases_fun((void*) se, db);
540 // New sdb is head of se->databases list
541 return se->databases;
544 // Find an existing session database. If not found, load it
545 static struct session_database *find_session_database(struct session *se,
548 struct session_database *sdb;
550 for (sdb = se->databases; sdb; sdb = sdb->next)
551 if (!strcmp(sdb->database->url, id))
553 return load_session_database(se, id);
556 // Apply a session override to a database
557 void session_apply_setting(struct session *se, char *dbname, char *setting,
560 struct session_database *sdb = find_session_database(se, dbname);
561 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
562 int offset = settings_offset(setting);
566 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
570 new->target = dbname;
573 new->next = sdb->settings[offset];
574 sdb->settings[offset] = new;
576 // Force later recompute of settings-driven data structures
577 // (happens when a search starts and client connections are prepared)
580 case PZ_NATIVESYNTAX:
583 yaz_marc_destroy(sdb->yaz_marc);
590 struct database_retrievalmap *m;
591 // We don't worry about the map structure -- it's in nmem
592 for (m = sdb->map; m; m = m->next)
593 xsltFreeStylesheet(m->stylesheet);
600 void destroy_session(struct session *s)
602 struct session_database *sdb;
604 yaz_log(YLOG_LOG, "Destroying session");
606 client_destroy(s->clients);
607 for (sdb = s->databases; sdb; sdb = sdb->next)
608 session_database_destroy(sdb);
609 nmem_destroy(s->nmem);
610 wrbuf_destroy(s->wrbuf);
613 struct session *new_session(NMEM nmem)
616 struct session *session = nmem_malloc(nmem, sizeof(*session));
618 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
620 session->total_hits = 0;
621 session->total_records = 0;
622 session->num_termlists = 0;
623 session->reclist = 0;
624 session->requestid = -1;
625 session->clients = 0;
626 session->expected_maxrecs = 0;
627 session->session_nmem = nmem;
628 session->nmem = nmem_create();
629 session->wrbuf = wrbuf_alloc();
630 session_init_databases(session);
631 for (i = 0; i <= SESSION_WATCH_MAX; i++)
633 session->watchlist[i].data = 0;
634 session->watchlist[i].fun = 0;
640 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
642 static struct hitsbytarget res[1000]; // FIXME MM
646 for (cl = se->clients; cl; cl = client_next_in_session(cl))
648 char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
650 res[*count].id = client_get_database(cl)->database->url;
651 res[*count].name = *name ? name : "Unknown";
652 res[*count].hits = client_get_hits(cl);
653 res[*count].records = client_get_num_records(cl);
654 res[*count].diagnostic = client_get_diagnostic(cl);
655 res[*count].state = client_get_state_str(cl);
656 res[*count].connected = client_get_connection(cl) ? 1 : 0;
663 struct termlist_score **termlist(struct session *s, const char *name, int *num)
667 for (i = 0; i < s->num_termlists; i++)
668 if (!strcmp((const char *) s->termlists[i].name, name))
669 return termlist_highscore(s->termlists[i].termlist, num);
673 #ifdef MISSING_HEADERS
674 void report_nmem_stats(void)
676 size_t in_use, is_free;
678 nmem_get_memory_in_use(&in_use);
679 nmem_get_memory_free(&is_free);
681 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
682 (long) in_use, (long) is_free);
686 struct record_cluster *show_single(struct session *s, int id)
688 struct record_cluster *r;
690 reclist_rewind(s->reclist);
691 while ((r = reclist_read_record(s->reclist)))
697 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp,
698 int start, int *num, int *total, int *sumhits,
701 struct record_cluster **recs = nmem_malloc(nmem_show, *num
702 * sizeof(struct record_cluster *));
703 struct reclist_sortparms *spp;
706 yaz_timing_t t = yaz_timing_create();
709 for (spp = sp; spp; spp = spp->next)
710 if (spp->type == Metadata_sortkey_relevance)
712 relevance_prepare_read(s->relevance, s->reclist);
715 reclist_sort(s->reclist, sp);
717 *total = s->reclist->num_records;
718 *sumhits = s->total_hits;
720 for (i = 0; i < start; i++)
721 if (!reclist_read_record(s->reclist))
728 for (i = 0; i < *num; i++)
730 struct record_cluster *r = reclist_read_record(s->reclist);
740 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
741 yaz_timing_get_real(t), yaz_timing_get_user(t),
742 yaz_timing_get_sys(t));
743 yaz_timing_destroy(&t);
748 void statistics(struct session *se, struct statistics *stat)
753 memset(stat, 0, sizeof(*stat));
754 for (cl = se->clients; cl; cl = client_next_in_session(cl))
756 if (!client_get_connection(cl))
757 stat->num_no_connection++;
758 switch (client_get_state(cl))
760 case Client_Connecting: stat->num_connecting++; break;
761 case Client_Initializing: stat->num_initializing++; break;
762 case Client_Searching: stat->num_searching++; break;
763 case Client_Presenting: stat->num_presenting++; break;
764 case Client_Idle: stat->num_idle++; break;
765 case Client_Failed: stat->num_failed++; break;
766 case Client_Error: stat->num_error++; break;
771 stat->num_hits = se->total_hits;
772 stat->num_records = se->total_records;
774 stat->num_clients = count;
777 void start_http_listener(void)
780 struct conf_server *ser = global_parameters.server;
782 if (*global_parameters.listener_override)
783 strcpy(hp, global_parameters.listener_override);
786 strcpy(hp, ser->host ? ser->host : "");
791 sprintf(hp + strlen(hp), "%d", ser->port);
797 void start_proxy(void)
800 struct conf_server *ser = global_parameters.server;
802 if (*global_parameters.proxy_override)
803 strcpy(hp, global_parameters.proxy_override);
804 else if (ser->proxy_host || ser->proxy_port)
806 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
811 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
817 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
820 void start_zproxy(void)
822 struct conf_server *ser = global_parameters.server;
824 if (*global_parameters.zproxy_override){
825 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
826 global_parameters.zproxy_override);
830 else if (ser->zproxy_host || ser->zproxy_port)
834 strcpy(hp, ser->zproxy_host ? ser->zproxy_host : "");
835 if (ser->zproxy_port)
842 sprintf(hp + strlen(hp), "%d", ser->zproxy_port);
844 strcpy(global_parameters.zproxy_override, hp);
845 yaz_log(YLOG_LOG, "Z39.50 proxy %s",
846 global_parameters.zproxy_override);
853 // Master list of connections we're handling events to
854 static IOCHAN channel_list = 0;
855 void pazpar2_add_channel(IOCHAN chan)
857 chan->next = channel_list;
861 void pazpar2_event_loop()
863 event_loop(&channel_list);
866 struct record *ingest_record(struct client *cl, Z_External *rec,
869 xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
871 struct record *record;
872 struct record_cluster *cluster;
873 struct session *se = client_get_session(cl);
874 xmlChar *mergekey, *mergekey_norm;
877 struct conf_service *service = global_parameters.server->service;
882 root = xmlDocGetRootElement(xdoc);
883 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
885 yaz_log(YLOG_WARN, "No mergekey found in record");
890 record = record_create(se->nmem,
891 service->num_metadata, service->num_sortkeys);
892 record_assign_client(record, cl);
894 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
896 normalize7bit_mergekey((char *) mergekey_norm, 0);
898 cluster = reclist_insert(se->reclist,
899 global_parameters.server->service,
900 record, (char *) mergekey_norm,
902 if (global_parameters.dump_records)
903 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
904 client_get_database(cl)->database->url, record_no);
907 /* no room for record */
911 relevance_newrec(se->relevance, cluster);
914 // now parsing XML record and adding data to cluster or record metadata
915 for (n = root->children; n; n = n->next)
923 if (n->type != XML_ELEMENT_NODE)
925 if (!strcmp((const char *) n->name, "metadata"))
927 struct conf_metadata *ser_md = 0;
928 struct conf_sortkey *ser_sk = 0;
929 struct record_metadata **wheretoput = 0;
930 struct record_metadata *rec_md = 0;
931 int md_field_id = -1;
932 int sk_field_id = -1;
935 type = xmlGetProp(n, (xmlChar *) "type");
936 value = xmlNodeListGetString(xdoc, n->children, 0);
942 = conf_service_metadata_field_id(service, (const char *) type);
946 "Ignoring unknown metadata element: %s", type);
950 ser_md = &service->metadata[md_field_id];
952 if (ser_md->sortkey_offset >= 0){
953 sk_field_id = ser_md->sortkey_offset;
954 ser_sk = &service->sortkeys[sk_field_id];
957 // Find out where we are putting it - based on merge or not
958 if (ser_md->merge == Metadata_merge_no)
959 wheretoput = &record->metadata[md_field_id];
961 wheretoput = &cluster->metadata[md_field_id];
963 // create new record_metadata
964 rec_md = record_metadata_create(se->nmem);
966 // and polulate with data:
967 // type based charmapping decisions follow here
968 if (ser_md->type == Metadata_type_generic)
971 char * p = (char *) value;
972 p = normalize7bit_generic(p, " ,/.:([");
974 rec_md->data.text = nmem_strdup(se->nmem, p);
977 else if (ser_md->type == Metadata_type_year)
979 if (extract7bit_years((char *) value, &first, &last) < 0)
985 "Unknown type in metadata element %s", type);
989 // and polulate with data:
990 // assign cluster or record based on merge action
991 if (ser_md->merge == Metadata_merge_unique)
993 struct record_metadata *mnode;
994 for (mnode = *wheretoput; mnode; mnode = mnode->next)
995 if (!strcmp((const char *) mnode->data.text,
1000 rec_md->next = *wheretoput;
1001 *wheretoput = rec_md;
1004 else if (ser_md->merge == Metadata_merge_longest)
1007 || strlen(rec_md->data.text)
1008 > strlen((*wheretoput)->data.text))
1010 *wheretoput = rec_md;
1013 char *s = nmem_strdup(se->nmem, rec_md->data.text);
1014 if (!cluster->sortkeys[sk_field_id])
1015 cluster->sortkeys[sk_field_id] =
1016 nmem_malloc(se->nmem,
1017 sizeof(union data_types));
1018 normalize7bit_mergekey(s,
1019 (ser_sk->type == Metadata_sortkey_skiparticle));
1020 cluster->sortkeys[sk_field_id]->text = s;
1024 else if (ser_md->merge == Metadata_merge_all
1025 || ser_md->merge == Metadata_merge_no)
1027 rec_md->next = *wheretoput;
1028 *wheretoput = rec_md;
1030 else if (ser_md->merge == Metadata_merge_range)
1034 *wheretoput = rec_md;
1035 (*wheretoput)->data.number.min = first;
1036 (*wheretoput)->data.number.max = last;
1038 cluster->sortkeys[sk_field_id]
1043 if (first < (*wheretoput)->data.number.min)
1044 (*wheretoput)->data.number.min = first;
1045 if (last > (*wheretoput)->data.number.max)
1046 (*wheretoput)->data.number.max = last;
1051 union data_types *sdata
1052 = cluster->sortkeys[sk_field_id];
1053 yaz_log(YLOG_LOG, "SK range: %d-%d",
1054 sdata->number.min, sdata->number.max);
1060 // ranking of _all_ fields enabled ...
1062 relevance_countwords(se->relevance, cluster,
1063 (char *) value, ser_md->rank);
1065 // construct facets ...
1066 if (ser_md->termlist)
1068 if (ser_md->type == Metadata_type_year)
1071 sprintf(year, "%d", last);
1072 add_facet(se, (char *) type, year);
1075 sprintf(year, "%d", first);
1076 add_facet(se, (char *) type, year);
1080 add_facet(se, (char *) type, (char *) value);
1090 "Unexpected element %s in internal record", n->name);
1099 relevance_donerecord(se->relevance, cluster);
1100 se->total_records++;
1110 * indent-tabs-mode: nil
1112 * vim: shiftwidth=4 tabstop=8 expandtab