1 /* $Id: logic.c,v 1.40 2007-06-11 12:08:23 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"
75 #define TERMLIST_HIGH_SCORE 25
79 // Note: Some things in this structure will eventually move to configuration
80 struct parameters global_parameters =
101 // Recursively traverse query structure to extract terms.
102 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
114 pull_terms(nmem, n->u.p[0], termlist, num);
115 pull_terms(nmem, n->u.p[1], termlist, num);
118 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
119 for (i = 0; i < numwords; i++)
120 termlist[(*num)++] = words[i];
129 static void add_facet(struct session *s, const char *type, const char *value)
135 for (i = 0; i < s->num_termlists; i++)
136 if (!strcmp(s->termlists[i].name, type))
138 if (i == s->num_termlists)
140 if (i == SESSION_MAX_TERMLISTS)
142 yaz_log(YLOG_FATAL, "Too many termlists");
146 s->termlists[i].name = nmem_strdup(s->nmem, type);
147 s->termlists[i].termlist
148 = termlist_create(s->nmem, s->expected_maxrecs,
149 TERMLIST_HIGH_SCORE);
150 s->num_termlists = i + 1;
152 termlist_insert(s->termlists[i].termlist, value);
155 xmlDoc *normalize_record(struct session_database *sdb, Z_External *rec)
157 struct database_retrievalmap *m;
158 struct database *db = sdb->database;
160 const Odr_oid *oid = rec->direct_reference;
162 /* convert response record to XML somehow */
163 if (rec->which == Z_External_octet && oid
164 && !oid_oidcmp(oid, yaz_oid_recsyn_xml))
167 rdoc = xmlParseMemory((char*) rec->u.octet_aligned->buf,
168 rec->u.octet_aligned->len);
171 yaz_log(YLOG_FATAL, "Non-wellformed XML received from %s",
176 else if (oid && yaz_oid_is_iso2709(oid))
178 /* ISO2709 gets converted to MARCXML */
181 yaz_log(YLOG_FATAL, "Unable to handle ISO2709 record");
190 if (rec->which != Z_External_octet)
192 yaz_log(YLOG_WARN, "Unexpected external branch, probably BER %s",
196 buf = (char*) rec->u.octet_aligned->buf;
197 len = rec->u.octet_aligned->len;
198 if (yaz_marc_read_iso2709(sdb->yaz_marc, buf, len) < 0)
200 yaz_log(YLOG_WARN, "Failed to decode MARC %s", db->url);
204 yaz_marc_write_using_libxml2(sdb->yaz_marc, 1);
205 if (yaz_marc_write_xml(sdb->yaz_marc, &res,
206 "http://www.loc.gov/MARC21/slim", 0, 0) < 0)
208 yaz_log(YLOG_WARN, "Failed to encode as XML %s",
212 rdoc = xmlNewDoc((xmlChar *) "1.0");
213 xmlDocSetRootElement(rdoc, res);
218 char oid_name_buf[OID_STR_MAX];
219 const char *oid_name = yaz_oid_to_string_buf(oid, 0, oid_name_buf);
221 "Unable to handle record of type %s from %s",
226 if (global_parameters.dump_records){
228 "Input Record (normalized) from %s\n----------------\n",
230 #if LIBXML_VERSION >= 20600
231 xmlDocFormatDump(stderr, rdoc, 1);
233 xmlDocDump(stderr, rdoc);
237 for (m = sdb->map; m; m = m->next){
242 new = xsltApplyStylesheet(m->stylesheet, rdoc, 0);
243 root= xmlDocGetRootElement(new);
244 if (!new || !root || !(root->children))
246 yaz_log(YLOG_WARN, "XSLT transformation failed from %s",
257 if (global_parameters.dump_records)
259 fprintf(stderr, "Record from %s\n----------------\n",
261 #if LIBXML_VERSION >= 20600
262 xmlDocFormatDump(stderr, rdoc, 1);
264 xmlDocDump(stderr, rdoc);
270 // Retrieve first defined value for 'name' for given database.
271 // Will be extended to take into account user associated with session
272 char *session_setting_oneval(struct session_database *db, int offset)
274 if (!db->settings[offset])
276 return db->settings[offset]->value;
281 // Initialize YAZ Map structures for MARC-based targets
282 static int prepare_yazmarc(struct session_database *sdb)
288 yaz_log(YLOG_WARN, "No settings for %s", sdb->database->url);
291 if ((s = session_setting_oneval(sdb, PZ_NATIVESYNTAX))
292 && !strncmp(s, "iso2709", 7))
294 char *encoding = "marc-8s", *e;
297 // See if a native encoding is specified
298 if ((e = strchr(s, ';')))
301 sdb->yaz_marc = yaz_marc_create();
302 yaz_marc_subfield_str(sdb->yaz_marc, "\t");
304 cm = yaz_iconv_open("utf-8", encoding);
308 "Unable to map from %s to UTF-8 for target %s",
309 encoding, sdb->database->url);
312 yaz_marc_iconv(sdb->yaz_marc, cm);
317 // Prepare XSLT stylesheets for record normalization
318 // Structures are allocated on the session_wide nmem to avoid having
319 // to recompute this for every search. This would lead
320 // to leaking if a single session was to repeatedly change the PZ_XSLT
321 // setting. However, this is not a realistic use scenario.
322 static int prepare_map(struct session *se, struct session_database *sdb)
328 yaz_log(YLOG_WARN, "No settings on %s", sdb->database->url);
331 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
334 struct database_retrievalmap **m = &sdb->map;
337 nmem_strsplit(se->session_nmem, ",", s, &stylesheets, &num);
338 for (i = 0; i < num; i++)
340 (*m) = nmem_malloc(se->session_nmem, sizeof(**m));
342 if (!((*m)->stylesheet = conf_load_stylesheet(stylesheets[i])))
344 yaz_log(YLOG_FATAL, "Unable to load stylesheet: %s",
352 yaz_log(YLOG_WARN, "No Normalization stylesheet for target %s",
357 // This analyzes settings and recomputes any supporting data structures
359 static int prepare_session_database(struct session *se,
360 struct session_database *sdb)
365 "No settings associated with %s", sdb->database->url);
368 if (sdb->settings[PZ_NATIVESYNTAX] && !sdb->yaz_marc)
370 if (prepare_yazmarc(sdb) < 0)
373 if (sdb->settings[PZ_XSLT] && !sdb->map)
375 if (prepare_map(se, sdb) < 0)
382 void session_set_watch(struct session *s, int what,
383 session_watchfun fun, void *data)
385 s->watchlist[what].fun = fun;
386 s->watchlist[what].data = data;
389 void session_alert_watch(struct session *s, int what)
391 if (!s->watchlist[what].fun)
393 (*s->watchlist[what].fun)(s->watchlist[what].data);
394 s->watchlist[what].fun = 0;
395 s->watchlist[what].data = 0;
398 //callback for grep_databases
399 static void select_targets_callback(void *context, struct session_database *db)
401 struct session *se = (struct session*) context;
402 struct client *cl = client_create();
403 client_set_database(cl, db);
404 client_set_session(cl, se);
407 // Associates a set of clients with a session;
408 // Note: Session-databases represent databases with per-session
410 int select_targets(struct session *se, struct database_criterion *crit)
413 client_destroy(se->clients);
415 return session_grep_databases(se, crit, select_targets_callback);
418 int session_active_clients(struct session *s)
423 for (c = s->clients; c; c = client_next_in_session(c))
424 if (client_is_active(c))
430 // parses crit1=val1,crit2=val2|val3,...
431 static struct database_criterion *parse_filter(NMEM m, const char *buf)
433 struct database_criterion *res = 0;
440 nmem_strsplit(m, ",", buf, &values, &num);
441 for (i = 0; i < num; i++)
446 struct database_criterion *new = nmem_malloc(m, sizeof(*new));
447 char *eq = strchr(values[i], '=');
450 yaz_log(YLOG_WARN, "Missing equal-sign in filter");
454 new->name = values[i];
455 nmem_strsplit(m, "|", eq, &subvalues, &subnum);
457 for (subi = 0; subi < subnum; subi++)
459 struct database_criterion_value *newv
460 = nmem_malloc(m, sizeof(*newv));
461 newv->value = subvalues[subi];
462 newv->next = new->values;
471 char *search(struct session *se, char *query, char *filter)
473 int live_channels = 0;
475 struct database_criterion *criteria;
477 yaz_log(YLOG_DEBUG, "Search");
479 nmem_reset(se->nmem);
480 criteria = parse_filter(se->nmem, filter);
482 live_channels = select_targets(se, criteria);
485 int maxrecs = live_channels * global_parameters.toget;
486 se->num_termlists = 0;
487 se->reclist = reclist_create(se->nmem, maxrecs);
488 // This will be initialized in send_search()
489 se->total_records = se->total_hits = se->total_merged = 0;
490 se->expected_maxrecs = maxrecs;
497 for (cl = se->clients; cl; cl = client_next_in_session(cl))
499 if (prepare_session_database(se, client_get_database(cl)) < 0)
500 return "CONFIG_ERROR";
501 // Query must parse for all targets
502 if (client_parse_query(cl, query) < 0)
506 for (cl = se->clients; cl; cl = client_next_in_session(cl))
507 client_prep_connection(cl);
512 // Creates a new session_database object for a database
513 static void session_init_databases_fun(void *context, struct database *db)
515 struct session *se = (struct session *) context;
516 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
517 int num = settings_num();
524 if (global_parameters.server && global_parameters.server->icu_chn)
525 new->pct = pp2_charset_create(global_parameters.server->icu_chn);
527 new->pct = pp2_charset_create(0);
529 new->pct = pp2_charset_create(0);
534 = nmem_malloc(se->session_nmem, sizeof(struct settings *) * num);
535 memset(new->settings, 0, sizeof(struct settings*) * num);
539 for (i = 0; i < num; i++)
540 new->settings[i] = db->settings[i];
542 new->next = se->databases;
546 // Doesn't free memory associated with sdb -- nmem takes care of that
547 static void session_database_destroy(struct session_database *sdb)
549 struct database_retrievalmap *m;
551 for (m = sdb->map; m; m = m->next)
552 xsltFreeStylesheet(m->stylesheet);
554 yaz_marc_destroy(sdb->yaz_marc);
556 pp2_charset_destroy(sdb->pct);
559 // Initialize session_database list -- this represents this session's view
560 // of the database list -- subject to modification by the settings ws command
561 void session_init_databases(struct session *se)
564 grep_databases(se, 0, session_init_databases_fun);
567 // Probably session_init_databases_fun should be refactored instead of
569 static struct session_database *load_session_database(struct session *se,
572 struct database *db = find_database(id, 0);
574 session_init_databases_fun((void*) se, db);
575 // New sdb is head of se->databases list
576 return se->databases;
579 // Find an existing session database. If not found, load it
580 static struct session_database *find_session_database(struct session *se,
583 struct session_database *sdb;
585 for (sdb = se->databases; sdb; sdb = sdb->next)
586 if (!strcmp(sdb->database->url, id))
588 return load_session_database(se, id);
591 // Apply a session override to a database
592 void session_apply_setting(struct session *se, char *dbname, char *setting,
595 struct session_database *sdb = find_session_database(se, dbname);
596 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
597 int offset = settings_offset_cprefix(setting);
601 yaz_log(YLOG_WARN, "Unknown setting %s", setting);
604 // Jakub: This breaks the filter setting.
605 /*if (offset == PZ_ID)
607 yaz_log(YLOG_WARN, "No need to set pz:id setting. Ignoring");
611 new->target = dbname;
614 new->next = sdb->settings[offset];
615 sdb->settings[offset] = new;
617 // Force later recompute of settings-driven data structures
618 // (happens when a search starts and client connections are prepared)
621 case PZ_NATIVESYNTAX:
624 yaz_marc_destroy(sdb->yaz_marc);
631 struct database_retrievalmap *m;
632 // We don't worry about the map structure -- it's in nmem
633 for (m = sdb->map; m; m = m->next)
634 xsltFreeStylesheet(m->stylesheet);
641 void destroy_session(struct session *s)
643 struct session_database *sdb;
645 yaz_log(YLOG_LOG, "Destroying session");
647 client_destroy(s->clients);
648 for (sdb = s->databases; sdb; sdb = sdb->next)
649 session_database_destroy(sdb);
650 nmem_destroy(s->nmem);
651 wrbuf_destroy(s->wrbuf);
654 struct session *new_session(NMEM nmem)
657 struct session *session = nmem_malloc(nmem, sizeof(*session));
659 yaz_log(YLOG_DEBUG, "New Pazpar2 session");
661 session->total_hits = 0;
662 session->total_records = 0;
663 session->num_termlists = 0;
664 session->reclist = 0;
665 session->requestid = -1;
666 session->clients = 0;
667 session->expected_maxrecs = 0;
668 session->session_nmem = nmem;
669 session->nmem = nmem_create();
670 session->wrbuf = wrbuf_alloc();
671 session_init_databases(session);
672 for (i = 0; i <= SESSION_WATCH_MAX; i++)
674 session->watchlist[i].data = 0;
675 session->watchlist[i].fun = 0;
681 struct hitsbytarget *hitsbytarget(struct session *se, int *count)
683 static struct hitsbytarget res[1000]; // FIXME MM
687 for (cl = se->clients; cl; cl = client_next_in_session(cl))
689 char *name = session_setting_oneval(client_get_database(cl), PZ_NAME);
691 res[*count].id = client_get_database(cl)->database->url;
692 res[*count].name = *name ? name : "Unknown";
693 res[*count].hits = client_get_hits(cl);
694 res[*count].records = client_get_num_records(cl);
695 res[*count].diagnostic = client_get_diagnostic(cl);
696 res[*count].state = client_get_state_str(cl);
697 res[*count].connected = client_get_connection(cl) ? 1 : 0;
704 struct termlist_score **termlist(struct session *s, const char *name, int *num)
708 for (i = 0; i < s->num_termlists; i++)
709 if (!strcmp((const char *) s->termlists[i].name, name))
710 return termlist_highscore(s->termlists[i].termlist, num);
714 #ifdef MISSING_HEADERS
715 void report_nmem_stats(void)
717 size_t in_use, is_free;
719 nmem_get_memory_in_use(&in_use);
720 nmem_get_memory_free(&is_free);
722 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
723 (long) in_use, (long) is_free);
727 struct record_cluster *show_single(struct session *s, int id)
729 struct record_cluster *r;
731 reclist_rewind(s->reclist);
732 while ((r = reclist_read_record(s->reclist)))
738 struct record_cluster **show(struct session *s, struct reclist_sortparms *sp,
739 int start, int *num, int *total, int *sumhits,
742 struct record_cluster **recs = nmem_malloc(nmem_show, *num
743 * sizeof(struct record_cluster *));
744 struct reclist_sortparms *spp;
747 yaz_timing_t t = yaz_timing_create();
750 for (spp = sp; spp; spp = spp->next)
751 if (spp->type == Metadata_sortkey_relevance)
753 relevance_prepare_read(s->relevance, s->reclist);
756 reclist_sort(s->reclist, sp);
758 *total = s->reclist->num_records;
759 *sumhits = s->total_hits;
761 for (i = 0; i < start; i++)
762 if (!reclist_read_record(s->reclist))
769 for (i = 0; i < *num; i++)
771 struct record_cluster *r = reclist_read_record(s->reclist);
781 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
782 yaz_timing_get_real(t), yaz_timing_get_user(t),
783 yaz_timing_get_sys(t));
784 yaz_timing_destroy(&t);
789 void statistics(struct session *se, struct statistics *stat)
794 memset(stat, 0, sizeof(*stat));
795 for (cl = se->clients; cl; cl = client_next_in_session(cl))
797 if (!client_get_connection(cl))
798 stat->num_no_connection++;
799 switch (client_get_state(cl))
801 case Client_Connecting: stat->num_connecting++; break;
802 case Client_Initializing: stat->num_initializing++; break;
803 case Client_Searching: stat->num_searching++; break;
804 case Client_Presenting: stat->num_presenting++; break;
805 case Client_Idle: stat->num_idle++; break;
806 case Client_Failed: stat->num_failed++; break;
807 case Client_Error: stat->num_error++; break;
812 stat->num_hits = se->total_hits;
813 stat->num_records = se->total_records;
815 stat->num_clients = count;
818 void start_http_listener(void)
821 struct conf_server *ser = global_parameters.server;
823 if (*global_parameters.listener_override)
824 strcpy(hp, global_parameters.listener_override);
827 strcpy(hp, ser->host ? ser->host : "");
832 sprintf(hp + strlen(hp), "%d", ser->port);
838 void start_proxy(void)
841 struct conf_server *ser = global_parameters.server;
843 if (*global_parameters.proxy_override)
844 strcpy(hp, global_parameters.proxy_override);
845 else if (ser->proxy_host || ser->proxy_port)
847 strcpy(hp, ser->proxy_host ? ser->proxy_host : "");
852 sprintf(hp + strlen(hp), "%d", ser->proxy_port);
858 http_set_proxyaddr(hp, ser->myurl ? ser->myurl : "");
862 // Master list of connections we're handling events to
863 static IOCHAN channel_list = 0;
864 void pazpar2_add_channel(IOCHAN chan)
866 chan->next = channel_list;
870 void pazpar2_event_loop()
872 event_loop(&channel_list);
875 struct record *ingest_record(struct client *cl, Z_External *rec,
878 xmlDoc *xdoc = normalize_record(client_get_database(cl), rec);
880 struct record *record;
881 struct record_cluster *cluster;
882 struct session *se = client_get_session(cl);
883 xmlChar *mergekey, *mergekey_norm;
886 struct conf_service *service = global_parameters.server->service;
891 root = xmlDocGetRootElement(xdoc);
892 if (!(mergekey = xmlGetProp(root, (xmlChar *) "mergekey")))
894 yaz_log(YLOG_WARN, "No mergekey found in record");
899 record = record_create(se->nmem,
900 service->num_metadata, service->num_sortkeys, cl);
902 mergekey_norm = (xmlChar *) nmem_strdup(se->nmem, (char*) mergekey);
904 normalize7bit_mergekey((char *) mergekey_norm, 0);
906 cluster = reclist_insert(se->reclist,
907 global_parameters.server->service,
908 record, (char *) mergekey_norm,
910 if (global_parameters.dump_records)
911 yaz_log(YLOG_LOG, "Cluster id %d from %s (#%d)", cluster->recid,
912 client_get_database(cl)->database->url, record_no);
915 /* no room for record */
919 relevance_newrec(se->relevance, cluster);
922 // now parsing XML record and adding data to cluster or record metadata
923 for (n = root->children; n; n = n->next)
931 if (n->type != XML_ELEMENT_NODE)
933 if (!strcmp((const char *) n->name, "metadata"))
935 struct conf_metadata *ser_md = 0;
936 struct conf_sortkey *ser_sk = 0;
937 struct record_metadata **wheretoput = 0;
938 struct record_metadata *rec_md = 0;
939 int md_field_id = -1;
940 int sk_field_id = -1;
943 type = xmlGetProp(n, (xmlChar *) "type");
944 value = xmlNodeListGetString(xdoc, n->children, 1);
950 = conf_service_metadata_field_id(service, (const char *) type);
954 "Ignoring unknown metadata element: %s", type);
958 ser_md = &service->metadata[md_field_id];
960 if (ser_md->sortkey_offset >= 0){
961 sk_field_id = ser_md->sortkey_offset;
962 ser_sk = &service->sortkeys[sk_field_id];
965 // Find out where we are putting it - based on merge or not
966 if (ser_md->merge == Metadata_merge_no)
967 wheretoput = &record->metadata[md_field_id];
969 wheretoput = &cluster->metadata[md_field_id];
971 // create new record_metadata
972 rec_md = record_metadata_create(se->nmem);
974 // and polulate with data:
975 // type based charmapping decisions follow here
976 if (ser_md->type == Metadata_type_generic)
979 char * p = (char *) value;
980 p = normalize7bit_generic(p, " ,/.:([");
982 rec_md->data.text = nmem_strdup(se->nmem, p);
985 else if (ser_md->type == Metadata_type_year)
987 if (extract7bit_years((char *) value, &first, &last) < 0)
993 "Unknown type in metadata element %s", type);
997 // and polulate with data:
998 // assign cluster or record based on merge action
999 if (ser_md->merge == Metadata_merge_unique)
1001 struct record_metadata *mnode;
1002 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1003 if (!strcmp((const char *) mnode->data.text,
1008 rec_md->next = *wheretoput;
1009 *wheretoput = rec_md;
1012 else if (ser_md->merge == Metadata_merge_longest)
1015 || strlen(rec_md->data.text)
1016 > strlen((*wheretoput)->data.text))
1018 *wheretoput = rec_md;
1021 char *s = nmem_strdup(se->nmem, rec_md->data.text);
1022 if (!cluster->sortkeys[sk_field_id])
1023 cluster->sortkeys[sk_field_id] =
1024 nmem_malloc(se->nmem,
1025 sizeof(union data_types));
1026 normalize7bit_mergekey(s,
1027 (ser_sk->type == Metadata_sortkey_skiparticle));
1028 cluster->sortkeys[sk_field_id]->text = s;
1032 else if (ser_md->merge == Metadata_merge_all
1033 || ser_md->merge == Metadata_merge_no)
1035 rec_md->next = *wheretoput;
1036 *wheretoput = rec_md;
1038 else if (ser_md->merge == Metadata_merge_range)
1042 *wheretoput = rec_md;
1043 (*wheretoput)->data.number.min = first;
1044 (*wheretoput)->data.number.max = last;
1046 cluster->sortkeys[sk_field_id]
1051 if (first < (*wheretoput)->data.number.min)
1052 (*wheretoput)->data.number.min = first;
1053 if (last > (*wheretoput)->data.number.max)
1054 (*wheretoput)->data.number.max = last;
1059 union data_types *sdata
1060 = cluster->sortkeys[sk_field_id];
1061 yaz_log(YLOG_LOG, "SK range: %d-%d",
1062 sdata->number.min, sdata->number.max);
1068 // ranking of _all_ fields enabled ...
1070 relevance_countwords(se->relevance, cluster,
1071 (char *) value, ser_md->rank);
1073 // construct facets ...
1074 if (ser_md->termlist)
1076 if (ser_md->type == Metadata_type_year)
1079 sprintf(year, "%d", last);
1080 add_facet(se, (char *) type, year);
1083 sprintf(year, "%d", first);
1084 add_facet(se, (char *) type, year);
1088 add_facet(se, (char *) type, (char *) value);
1098 "Unexpected element %s in internal record", n->name);
1107 relevance_donerecord(se->relevance, cluster);
1108 se->total_records++;
1118 * indent-tabs-mode: nil
1120 * vim: shiftwidth=4 tabstop=8 expandtab