1 /* This file is part of Pazpar2.
2 Copyright (C) 2006-2011 Index Data
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 \brief high-level logic; mostly user sessions and settings
46 #include <yaz/marcdisp.h>
47 #include <yaz/comstack.h>
48 #include <yaz/tcpip.h>
49 #include <yaz/proto.h>
50 #include <yaz/readconf.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/yaz-util.h>
55 #include <yaz/query-charset.h>
56 #include <yaz/querytowrbuf.h>
57 #include <yaz/oid_db.h>
58 #include <yaz/snprintf.h>
59 #include <yaz/gettimeofday.h>
63 #include <yaz/timing.h>
67 #include "parameters.h"
71 #include "termlists.h"
73 #include "relevance.h"
77 #include "normalize7bit.h"
79 #define TERMLIST_HIGH_SCORE 25
83 #define MAX(a,b) ((a)>(b)?(a):(b))
85 // Note: Some things in this structure will eventually move to configuration
86 struct parameters global_parameters =
93 struct client *client;
94 struct client_list *next;
97 /* session counting (1) , disable client counting (0) */
98 static YAZ_MUTEX g_session_mutex = 0;
99 static int no_sessions = 0;
101 static int session_use(int delta)
104 if (!g_session_mutex)
105 yaz_mutex_create(&g_session_mutex);
106 yaz_mutex_enter(g_session_mutex);
107 no_sessions += delta;
108 sessions = no_sessions;
109 yaz_mutex_leave(g_session_mutex);
110 yaz_log(YLOG_DEBUG, "%s sesions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
114 int sessions_count(void) {
115 return session_use(0);
118 static void log_xml_doc(xmlDoc *doc)
120 FILE *lf = yaz_log_file();
123 #if LIBXML_VERSION >= 20600
124 xmlDocDumpFormatMemory(doc, &result, &len, 1);
126 xmlDocDumpMemory(doc, &result, &len);
130 (void) fwrite(result, 1, len, lf);
136 static void session_enter(struct session *s)
138 yaz_mutex_enter(s->session_mutex);
141 static void session_leave(struct session *s)
143 yaz_mutex_leave(s->session_mutex);
146 // Recursively traverse query structure to extract terms.
147 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
159 pull_terms(nmem, n->u.p[0], termlist, num);
160 pull_terms(nmem, n->u.p[1], termlist, num);
163 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
164 for (i = 0; i < numwords; i++)
165 termlist[(*num)++] = words[i];
173 void add_facet(struct session *s, const char *type, const char *value, int count)
175 struct conf_service *service = s->service;
176 pp2_relevance_token_t prt;
177 const char *facet_component;
178 WRBUF facet_wrbuf = wrbuf_alloc();
179 prt = pp2_relevance_tokenize(service->facet_pct);
181 pp2_relevance_first(prt, value, 0);
182 while ((facet_component = pp2_relevance_token_next(prt)))
184 if (*facet_component)
186 if (wrbuf_len(facet_wrbuf))
187 wrbuf_puts(facet_wrbuf, " ");
188 wrbuf_puts(facet_wrbuf, facet_component);
191 pp2_relevance_token_destroy(prt);
193 if (wrbuf_len(facet_wrbuf))
196 for (i = 0; i < s->num_termlists; i++)
197 if (!strcmp(s->termlists[i].name, type))
199 if (i == s->num_termlists)
201 if (i == SESSION_MAX_TERMLISTS)
203 session_log(s, YLOG_FATAL, "Too many termlists");
204 wrbuf_destroy(facet_wrbuf);
208 s->termlists[i].name = nmem_strdup(s->nmem, type);
209 s->termlists[i].termlist
210 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
211 s->num_termlists = i + 1;
214 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)",
215 type, value, wrbuf_cstr(facet_wrbuf), count);
216 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(facet_wrbuf),
219 wrbuf_destroy(facet_wrbuf);
222 static xmlDoc *record_to_xml(struct session *se,
223 struct session_database *sdb, const char *rec)
225 struct database *db = sdb->database;
228 rdoc = xmlParseMemory(rec, strlen(rec));
232 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
237 if (global_parameters.dump_records)
239 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->url);
246 #define MAX_XSLT_ARGS 16
248 // Add static values from session database settings if applicable
249 static void insert_settings_parameters(struct session_database *sdb,
250 struct conf_service *service,
258 for (i = 0; i < service->num_metadata; i++)
260 struct conf_metadata *md = &service->metadata[i];
263 if (md->setting == Metadata_setting_parameter &&
264 (setting = settings_lookup_offset(service, md->name)) >= 0)
266 const char *val = session_setting_oneval(sdb, setting);
267 if (val && nparms < MAX_XSLT_ARGS)
270 int len = strlen(val);
271 buf = nmem_malloc(nmem, len + 3);
273 strcpy(buf + 1, val);
276 parms[offset++] = md->name;
277 parms[offset++] = buf;
285 // Add static values from session database settings if applicable
286 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
287 struct conf_service *service)
291 for (i = 0; i < service->num_metadata; i++)
293 struct conf_metadata *md = &service->metadata[i];
296 if (md->setting == Metadata_setting_postproc &&
297 (offset = settings_lookup_offset(service, md->name)) >= 0)
299 const char *val = session_setting_oneval(sdb, offset);
302 xmlNode *r = xmlDocGetRootElement(doc);
303 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
305 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
311 static xmlDoc *normalize_record(struct session *se,
312 struct session_database *sdb,
313 struct conf_service *service,
314 const char *rec, NMEM nmem)
316 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
320 char *parms[MAX_XSLT_ARGS*2+1];
322 insert_settings_parameters(sdb, service, parms, nmem);
324 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
326 session_log(se, YLOG_WARN, "Normalize failed from %s",
331 insert_settings_values(sdb, rdoc, service);
333 if (global_parameters.dump_records)
335 session_log(se, YLOG_LOG, "Normalized record from %s",
344 void session_settings_dump(struct session *se,
345 struct session_database *db,
350 int i, num = db->num_settings;
351 for (i = 0; i < num; i++)
353 struct setting *s = db->settings[i];
354 for (;s ; s = s->next)
356 wrbuf_puts(w, "<set name=\"");
357 wrbuf_xmlputs(w, s->name);
358 wrbuf_puts(w, "\" value=\"");
359 wrbuf_xmlputs(w, s->value);
360 wrbuf_puts(w, "\"/>");
368 // Retrieve first defined value for 'name' for given database.
369 // Will be extended to take into account user associated with session
370 const char *session_setting_oneval(struct session_database *db, int offset)
372 if (offset >= db->num_settings || !db->settings[offset])
374 return db->settings[offset]->value;
377 // Prepare XSLT stylesheets for record normalization
378 // Structures are allocated on the session_wide nmem to avoid having
379 // to recompute this for every search. This would lead
380 // to leaking if a single session was to repeatedly change the PZ_XSLT
381 // setting. However, this is not a realistic use scenario.
382 static int prepare_map(struct session *se, struct session_database *sdb)
388 session_log(se, YLOG_WARN, "No settings on %s", sdb->database->url);
391 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
393 char auto_stylesheet[256];
395 if (!strcmp(s, "auto"))
397 const char *request_syntax = session_setting_oneval(
398 sdb, PZ_REQUESTSYNTAX);
402 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
403 "%s.xsl", request_syntax);
404 for (cp = auto_stylesheet; *cp; cp++)
406 /* deliberately only consider ASCII */
407 if (*cp > 32 && *cp < 127)
414 session_log(se, YLOG_WARN,
415 "No pz:requestsyntax for auto stylesheet");
418 sdb->map = normalize_cache_get(se->normalize_cache,
419 se->service->server->config, s);
426 // This analyzes settings and recomputes any supporting data structures
428 static int prepare_session_database(struct session *se,
429 struct session_database *sdb)
433 session_log(se, YLOG_WARN,
434 "No settings associated with %s", sdb->database->url);
437 if (sdb->settings[PZ_XSLT] && !sdb->map)
439 if (prepare_map(se, sdb) < 0)
445 // called if watch should be removed because http_channel is to be destroyed
446 static void session_watch_cancel(void *data, struct http_channel *c,
449 struct session_watchentry *ent = data;
456 // set watch. Returns 0=OK, -1 if watch is already set
457 int session_set_watch(struct session *s, int what,
458 session_watchfun fun, void *data,
459 struct http_channel *chan)
463 if (s->watchlist[what].fun)
468 s->watchlist[what].fun = fun;
469 s->watchlist[what].data = data;
470 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
471 session_watch_cancel);
478 void session_alert_watch(struct session *s, int what)
482 if (s->watchlist[what].fun)
484 /* our watch is no longer associated with http_channel */
486 session_watchfun fun;
488 http_remove_observer(s->watchlist[what].obs);
489 fun = s->watchlist[what].fun;
490 data = s->watchlist[what].data;
492 /* reset watch before fun is invoked - in case fun wants to set
494 s->watchlist[what].fun = 0;
495 s->watchlist[what].data = 0;
496 s->watchlist[what].obs = 0;
499 session_log(s, YLOG_DEBUG,
500 "Alert Watch: %d calling function: %p", what, fun);
507 //callback for grep_databases
508 static void select_targets_callback(void *context, struct session_database *db)
510 struct session *se = (struct session*) context;
511 struct client *cl = client_create();
512 struct client_list *l;
513 client_set_database(cl, db);
515 client_set_session(cl, se);
517 l = xmalloc(sizeof(*l));
519 l->next = se->clients;
523 static void session_remove_clients(struct session *se)
525 struct client_list *l;
534 struct client_list *l_next = l->next;
535 client_lock(l->client);
536 client_set_session(l->client, 0);
537 client_set_database(l->client, 0);
538 client_unlock(l->client);
539 client_destroy(l->client);
545 // Associates a set of clients with a session;
546 // Note: Session-databases represent databases with per-session
548 static int select_targets(struct session *se, const char *filter)
550 return session_grep_databases(se, filter, select_targets_callback);
553 int session_active_clients(struct session *s)
555 struct client_list *l;
558 for (l = s->clients; l; l = l->next)
559 if (client_is_active(l->client))
565 int session_is_preferred_clients_ready(struct session *s)
567 struct client_list *l;
570 for (l = s->clients; l; l = l->next)
571 if (client_is_active_preferred(l->client))
573 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
579 enum pazpar2_error_code search(struct session *se,
581 const char *startrecs, const char *maxrecs,
583 const char **addinfo)
585 int live_channels = 0;
588 struct client_list *l;
591 session_log(se, YLOG_DEBUG, "Search");
595 session_remove_clients(se);
598 reclist_destroy(se->reclist);
600 relevance_destroy(&se->relevance);
601 nmem_reset(se->nmem);
602 se->total_records = se->total_hits = se->total_merged = 0;
603 se->num_termlists = 0;
604 live_channels = select_targets(se, filter);
608 return PAZPAR2_NO_TARGETS;
610 se->reclist = reclist_create(se->nmem);
612 yaz_gettimeofday(&tval);
616 for (l = se->clients; l; l = l->next)
618 struct client *cl = l->client;
621 client_set_maxrecs(cl, atoi(maxrecs));
623 client_set_startrecs(cl, atoi(startrecs));
624 if (prepare_session_database(se, client_get_database(cl)) < 0)
626 else if (client_parse_query(cl, query) < 0)
631 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
632 se->service->z3950_session_timeout,
633 se->service->server->iochan_man,
635 client_start_search(cl);
644 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
647 return PAZPAR2_NO_TARGETS;
649 return PAZPAR2_NO_ERROR;
652 // Creates a new session_database object for a database
653 static void session_init_databases_fun(void *context, struct database *db)
655 struct session *se = (struct session *) context;
656 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
662 assert(db->settings);
663 new->settings = nmem_malloc(se->session_nmem,
664 sizeof(struct settings *) * db->num_settings);
665 new->num_settings = db->num_settings;
666 for (i = 0; i < db->num_settings; i++)
668 struct setting *setting = db->settings[i];
669 new->settings[i] = setting;
671 new->next = se->databases;
675 // Doesn't free memory associated with sdb -- nmem takes care of that
676 static void session_database_destroy(struct session_database *sdb)
681 // Initialize session_database list -- this represents this session's view
682 // of the database list -- subject to modification by the settings ws command
683 void session_init_databases(struct session *se)
686 predef_grep_databases(se, se->service, session_init_databases_fun);
689 // Probably session_init_databases_fun should be refactored instead of
691 static struct session_database *load_session_database(struct session *se,
694 struct database *db = new_database(id, se->session_nmem);
696 resolve_database(se->service, db);
698 session_init_databases_fun((void*) se, db);
700 // New sdb is head of se->databases list
701 return se->databases;
704 // Find an existing session database. If not found, load it
705 static struct session_database *find_session_database(struct session *se,
708 struct session_database *sdb;
710 for (sdb = se->databases; sdb; sdb = sdb->next)
711 if (!strcmp(sdb->database->url, id))
713 return load_session_database(se, id);
716 // Apply a session override to a database
717 void session_apply_setting(struct session *se, char *dbname, char *setting,
720 struct session_database *sdb = find_session_database(se, dbname);
721 struct conf_service *service = se->service;
722 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
723 int offset = settings_create_offset(service, setting);
725 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
728 new->target = dbname;
731 new->next = sdb->settings[offset];
732 sdb->settings[offset] = new;
734 // Force later recompute of settings-driven data structures
735 // (happens when a search starts and client connections are prepared)
747 void destroy_session(struct session *se)
749 struct session_database *sdb;
750 session_log(se, YLOG_DEBUG, "Destroying");
752 session_remove_clients(se);
754 for (sdb = se->databases; sdb; sdb = sdb->next)
755 session_database_destroy(sdb);
756 normalize_cache_destroy(se->normalize_cache);
757 relevance_destroy(&se->relevance);
758 reclist_destroy(se->reclist);
759 nmem_destroy(se->nmem);
760 service_destroy(se->service);
761 yaz_mutex_destroy(&se->session_mutex);
762 wrbuf_destroy(se->wrbuf);
765 size_t session_get_memory_status(struct session *session) {
769 session_enter(session);
770 session_nmem = nmem_total(session->nmem);
771 session_leave(session);
776 struct session *new_session(NMEM nmem, struct conf_service *service,
780 struct session *session = nmem_malloc(nmem, sizeof(*session));
784 sprintf(tmp_str, "session#%u", session_id);
786 session->session_id = session_id;
787 session_log(session, YLOG_DEBUG, "New");
788 session->service = service;
789 session->relevance = 0;
790 session->total_hits = 0;
791 session->total_records = 0;
792 session->number_of_warnings_unknown_elements = 0;
793 session->number_of_warnings_unknown_metadata = 0;
794 session->num_termlists = 0;
795 session->reclist = 0;
796 session->clients = 0;
797 session->session_nmem = nmem;
798 session->nmem = nmem_create();
799 session->wrbuf = wrbuf_alloc();
800 session->databases = 0;
801 for (i = 0; i <= SESSION_WATCH_MAX; i++)
803 session->watchlist[i].data = 0;
804 session->watchlist[i].fun = 0;
806 session->normalize_cache = normalize_cache_create();
807 session->session_mutex = 0;
808 pazpar2_mutex_create(&session->session_mutex, tmp_str);
813 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
815 struct hitsbytarget *res = 0;
816 struct client_list *l;
820 for (l = se->clients; l; l = l->next)
823 res = nmem_malloc(nmem, sizeof(*res) * sz);
825 for (l = se->clients; l; l = l->next)
827 struct client *cl = l->client;
828 WRBUF w = wrbuf_alloc();
829 const char *name = session_setting_oneval(client_get_database(cl),
832 res[*count].id = client_get_database(cl)->database->url;
833 res[*count].name = *name ? name : "Unknown";
834 res[*count].hits = client_get_hits(cl);
835 res[*count].records = client_get_num_records(cl);
836 res[*count].diagnostic = client_get_diagnostic(cl);
837 res[*count].state = client_get_state_str(cl);
838 res[*count].connected = client_get_connection(cl) ? 1 : 0;
839 session_settings_dump(se, client_get_database(cl), w);
840 res[*count].settings_xml = w;
847 struct termlist_score **termlist(struct session *se, const char *name, int *num)
850 struct termlist_score **tl = 0;
853 for (i = 0; i < se->num_termlists; i++)
854 if (!strcmp((const char *) se->termlists[i].name, name))
856 tl = termlist_highscore(se->termlists[i].termlist, num);
863 #ifdef MISSING_HEADERS
864 void report_nmem_stats(void)
866 size_t in_use, is_free;
868 nmem_get_memory_in_use(&in_use);
869 nmem_get_memory_free(&is_free);
871 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
872 (long) in_use, (long) is_free);
876 struct record_cluster *show_single_start(struct session *se, const char *id,
877 struct record_cluster **prev_r,
878 struct record_cluster **next_r)
880 struct record_cluster *r = 0;
887 reclist_enter(se->reclist);
888 while ((r = reclist_read_record(se->reclist)))
890 if (!strcmp(r->recid, id))
892 *next_r = reclist_read_record(se->reclist);
897 reclist_leave(se->reclist);
904 void show_single_stop(struct session *se, struct record_cluster *rec)
909 struct record_cluster **show_range_start(struct session *se,
910 struct reclist_sortparms *sp,
911 int start, int *num, int *total, Odr_int *sumhits)
913 struct record_cluster **recs;
914 struct reclist_sortparms *spp;
917 yaz_timing_t t = yaz_timing_create();
920 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
930 for (spp = sp; spp; spp = spp->next)
931 if (spp->type == Metadata_sortkey_relevance)
933 relevance_prepare_read(se->relevance, se->reclist);
936 reclist_sort(se->reclist, sp);
938 reclist_enter(se->reclist);
939 *total = reclist_get_num_records(se->reclist);
940 *sumhits = se->total_hits;
942 for (i = 0; i < start; i++)
943 if (!reclist_read_record(se->reclist))
950 for (i = 0; i < *num; i++)
952 struct record_cluster *r = reclist_read_record(se->reclist);
960 reclist_leave(se->reclist);
964 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
965 yaz_timing_get_real(t), yaz_timing_get_user(t),
966 yaz_timing_get_sys(t));
967 yaz_timing_destroy(&t);
972 void show_range_stop(struct session *se, struct record_cluster **recs)
977 void statistics(struct session *se, struct statistics *stat)
979 struct client_list *l;
982 memset(stat, 0, sizeof(*stat));
983 for (l = se->clients; l; l = l->next)
985 struct client *cl = l->client;
986 if (!client_get_connection(cl))
987 stat->num_no_connection++;
988 switch (client_get_state(cl))
990 case Client_Connecting: stat->num_connecting++; break;
991 case Client_Working: stat->num_working++; break;
992 case Client_Idle: stat->num_idle++; break;
993 case Client_Failed: stat->num_failed++; break;
994 case Client_Error: stat->num_error++; break;
999 stat->num_hits = se->total_hits;
1000 stat->num_records = se->total_records;
1002 stat->num_clients = count;
1005 static struct record_metadata *record_metadata_init(
1006 NMEM nmem, const char *value, enum conf_metadata_type type,
1007 struct _xmlAttr *attr)
1009 struct record_metadata *rec_md = record_metadata_create(nmem);
1010 struct record_metadata_attr **attrp = &rec_md->attributes;
1012 for (; attr; attr = attr->next)
1014 if (attr->children && attr->children->content)
1016 if (strcmp((const char *) attr->name, "type"))
1017 { /* skip the "type" attribute.. Its value is already part of
1018 the element in output (md-%s) and so repeating it here
1020 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1022 nmem_strdup(nmem, (const char *) attr->name);
1024 nmem_strdup(nmem, (const char *) attr->children->content);
1025 attrp = &(*attrp)->next;
1031 if (type == Metadata_type_generic)
1033 char *p = nmem_strdup(nmem, value);
1035 p = normalize7bit_generic(p, " ,/.:([");
1037 rec_md->data.text.disp = p;
1038 rec_md->data.text.sort = 0;
1040 else if (type == Metadata_type_year || type == Metadata_type_date)
1045 if (type == Metadata_type_date)
1047 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1050 rec_md->data.number.min = first;
1051 rec_md->data.number.max = last;
1058 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1059 struct conf_service *service, WRBUF norm_wr)
1063 for (n = root->children; n; n = n->next)
1065 if (n->type != XML_ELEMENT_NODE)
1067 if (!strcmp((const char *) n->name, "metadata"))
1069 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1071 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1073 else if (!strcmp(name, (const char *) type))
1075 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1078 const char *norm_str;
1079 pp2_relevance_token_t prt =
1080 pp2_relevance_tokenize(service->mergekey_pct);
1082 pp2_relevance_first(prt, (const char *) value, 0);
1083 if (wrbuf_len(norm_wr) > 0)
1084 wrbuf_puts(norm_wr, " ");
1085 wrbuf_puts(norm_wr, name);
1087 pp2_relevance_token_next(prt)))
1091 wrbuf_puts(norm_wr, " ");
1092 wrbuf_puts(norm_wr, norm_str);
1096 pp2_relevance_token_destroy(prt);
1106 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1107 struct conf_service *service, NMEM nmem)
1109 char *mergekey_norm = 0;
1110 xmlNode *root = xmlDocGetRootElement(doc);
1111 WRBUF norm_wr = wrbuf_alloc();
1113 /* consider mergekey from XSL first */
1114 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1117 const char *norm_str;
1118 pp2_relevance_token_t prt =
1119 pp2_relevance_tokenize(service->mergekey_pct);
1121 pp2_relevance_first(prt, (const char *) mergekey, 0);
1122 while ((norm_str = pp2_relevance_token_next(prt)))
1126 if (wrbuf_len(norm_wr))
1127 wrbuf_puts(norm_wr, " ");
1128 wrbuf_puts(norm_wr, norm_str);
1131 pp2_relevance_token_destroy(prt);
1136 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1138 for (field_id = 0; field_id < service->num_metadata; field_id++)
1140 struct conf_metadata *ser_md = &service->metadata[field_id];
1141 if (ser_md->mergekey != Metadata_mergekey_no)
1143 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1145 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1147 /* no mergekey on this one and it is required..
1148 Generate unique key instead */
1149 wrbuf_rewind(norm_wr);
1156 /* generate unique key if none is not generated already or is empty */
1157 if (wrbuf_len(norm_wr) == 0)
1159 wrbuf_printf(norm_wr, "%s-%d",
1160 client_get_database(cl)->database->url, record_no);
1162 if (wrbuf_len(norm_wr) > 0)
1163 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1164 wrbuf_destroy(norm_wr);
1165 return mergekey_norm;
1168 /** \brief see if metadata for pz:recordfilter exists
1169 \param root xml root element of normalized record
1170 \param sdb session database for client
1171 \retval 0 if there is no metadata for pz:recordfilter
1172 \retval 1 if there is metadata for pz:recordfilter
1174 If there is no pz:recordfilter defined, this function returns 1
1178 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1183 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1188 for (n = root->children; n; n = n->next)
1190 if (n->type != XML_ELEMENT_NODE)
1192 if (!strcmp((const char *) n->name, "metadata"))
1194 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1201 if ((eq = strchr(s, '=')))
1203 else if ((eq = strchr(s, '~')))
1209 if (len == strlen((const char *)type) &&
1210 !memcmp((const char *) type, s, len))
1212 xmlChar *value = xmlNodeGetContent(n);
1213 if (value && *value)
1216 (substring && strstr((const char *) value, eq+1)) ||
1217 (!substring && !strcmp((const char *) value, eq + 1)))
1230 static int ingest_to_cluster(struct client *cl,
1234 const char *mergekey_norm);
1236 /** \brief ingest XML record
1237 \param cl client holds the result set for record
1238 \param rec record buffer (0 terminated)
1239 \param record_no record position (1, 2, ..)
1240 \param nmem working NMEM
1244 int ingest_record(struct client *cl, const char *rec,
1245 int record_no, NMEM nmem)
1247 struct session *se = client_get_session(cl);
1249 struct session_database *sdb = client_get_database(cl);
1250 struct conf_service *service = se->service;
1251 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1253 const char *mergekey_norm;
1258 root = xmlDocGetRootElement(xdoc);
1260 if (!check_record_filter(root, sdb))
1262 session_log(se, YLOG_WARN, "Filtered out record no %d from %s",
1263 record_no, sdb->database->url);
1268 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1271 session_log(se, YLOG_WARN, "Got no mergekey");
1276 if (client_get_session(cl) == se)
1277 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1284 static int ingest_to_cluster(struct client *cl,
1288 const char *mergekey_norm)
1293 struct session_database *sdb = client_get_database(cl);
1294 struct session *se = client_get_session(cl);
1295 struct conf_service *service = se->service;
1296 struct record *record = record_create(se->nmem,
1297 service->num_metadata,
1298 service->num_sortkeys, cl,
1300 struct record_cluster *cluster = reclist_insert(se->reclist,
1306 const char *use_term_factor_str = session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1307 // TODO: Work-around to default to use term factor, until other MK2 components supports it
1308 int use_term_factor = 1;
1309 int term_factor = 1;
1310 if (use_term_factor_str && use_term_factor_str[0] != 0)
1311 use_term_factor = atoi(use_term_factor_str);
1312 if (use_term_factor) {
1313 int maxrecs = client_get_maxrecs(cl);
1314 int hits = (int) client_get_hits(cl);
1315 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1316 assert(term_factor >= 1);
1317 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1322 if (global_parameters.dump_records)
1323 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1324 sdb->database->url, record_no);
1325 relevance_newrec(se->relevance, cluster);
1327 // now parsing XML record and adding data to cluster or record metadata
1328 for (n = root->children; n; n = n->next)
1330 pp2_relevance_token_t prt;
1337 if (n->type != XML_ELEMENT_NODE)
1339 if (!strcmp((const char *) n->name, "metadata"))
1341 struct conf_metadata *ser_md = 0;
1342 struct conf_sortkey *ser_sk = 0;
1343 struct record_metadata **wheretoput = 0;
1344 struct record_metadata *rec_md = 0;
1345 int md_field_id = -1;
1346 int sk_field_id = -1;
1348 type = xmlGetProp(n, (xmlChar *) "type");
1349 value = xmlNodeListGetString(xdoc, n->children, 1);
1351 if (!type || !value || !*value)
1355 = conf_service_metadata_field_id(service, (const char *) type);
1356 if (md_field_id < 0)
1358 if (se->number_of_warnings_unknown_metadata == 0)
1360 session_log(se, YLOG_WARN,
1361 "Ignoring unknown metadata element: %s", type);
1363 se->number_of_warnings_unknown_metadata++;
1367 ser_md = &service->metadata[md_field_id];
1369 if (ser_md->sortkey_offset >= 0){
1370 sk_field_id = ser_md->sortkey_offset;
1371 ser_sk = &service->sortkeys[sk_field_id];
1374 // non-merged metadata
1375 rec_md = record_metadata_init(se->nmem, (const char *) value,
1376 ser_md->type, n->properties);
1379 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1380 "for element '%s'", value, type);
1383 wheretoput = &record->metadata[md_field_id];
1385 wheretoput = &(*wheretoput)->next;
1386 *wheretoput = rec_md;
1389 rec_md = record_metadata_init(se->nmem, (const char *) value,
1391 wheretoput = &cluster->metadata[md_field_id];
1393 // and polulate with data:
1394 // assign cluster or record based on merge action
1395 if (ser_md->merge == Metadata_merge_unique)
1397 struct record_metadata *mnode;
1398 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1399 if (!strcmp((const char *) mnode->data.text.disp,
1400 rec_md->data.text.disp))
1404 rec_md->next = *wheretoput;
1405 *wheretoput = rec_md;
1408 else if (ser_md->merge == Metadata_merge_longest)
1411 || strlen(rec_md->data.text.disp)
1412 > strlen((*wheretoput)->data.text.disp))
1414 *wheretoput = rec_md;
1417 const char *sort_str = 0;
1419 ser_sk->type == Metadata_sortkey_skiparticle;
1421 if (!cluster->sortkeys[sk_field_id])
1422 cluster->sortkeys[sk_field_id] =
1423 nmem_malloc(se->nmem,
1424 sizeof(union data_types));
1426 prt = pp2_relevance_tokenize(service->sort_pct);
1428 pp2_relevance_first(prt, rec_md->data.text.disp,
1431 pp2_relevance_token_next(prt);
1433 sort_str = pp2_get_sort(prt);
1435 cluster->sortkeys[sk_field_id]->text.disp =
1436 rec_md->data.text.disp;
1439 sort_str = rec_md->data.text.disp;
1440 session_log(se, YLOG_WARN,
1441 "Could not make sortkey. Bug #1858");
1443 cluster->sortkeys[sk_field_id]->text.sort =
1444 nmem_strdup(se->nmem, sort_str);
1445 pp2_relevance_token_destroy(prt);
1449 else if (ser_md->merge == Metadata_merge_all)
1451 rec_md->next = *wheretoput;
1452 *wheretoput = rec_md;
1454 else if (ser_md->merge == Metadata_merge_range)
1458 *wheretoput = rec_md;
1460 cluster->sortkeys[sk_field_id]
1465 int this_min = rec_md->data.number.min;
1466 int this_max = rec_md->data.number.max;
1467 if (this_min < (*wheretoput)->data.number.min)
1468 (*wheretoput)->data.number.min = this_min;
1469 if (this_max > (*wheretoput)->data.number.max)
1470 (*wheretoput)->data.number.max = this_max;
1475 // ranking of _all_ fields enabled ...
1477 relevance_countwords(se->relevance, cluster,
1478 (char *) value, ser_md->rank,
1481 // construct facets ... unless the client already has reported them
1482 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1485 if (ser_md->type == Metadata_type_year)
1488 sprintf(year, "%d", rec_md->data.number.max);
1490 add_facet(se, (char *) type, year, term_factor);
1491 if (rec_md->data.number.max != rec_md->data.number.min)
1493 sprintf(year, "%d", rec_md->data.number.min);
1494 add_facet(se, (char *) type, year, term_factor);
1498 add_facet(se, (char *) type, (char *) value, term_factor);
1508 if (se->number_of_warnings_unknown_elements == 0)
1509 session_log(se, YLOG_WARN,
1510 "Unexpected element in internal record: %s", n->name);
1511 se->number_of_warnings_unknown_elements++;
1519 relevance_donerecord(se->relevance, cluster);
1520 se->total_records++;
1525 void session_log(struct session *s, int level, const char *fmt, ...)
1531 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1532 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1540 * c-file-style: "Stroustrup"
1541 * indent-tabs-mode: nil
1543 * vim: shiftwidth=4 tabstop=8 expandtab