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 =
90 0, // predictable sessions
94 struct client *client;
95 struct client_list *next;
98 /* session counting (1) , disable client counting (0) */
99 static YAZ_MUTEX g_session_mutex = 0;
100 static int no_sessions = 0;
101 static int no_session_total = 0;
103 static int session_use(int delta)
106 if (!g_session_mutex)
107 yaz_mutex_create(&g_session_mutex);
108 yaz_mutex_enter(g_session_mutex);
109 no_sessions += delta;
111 no_session_total += delta;
112 sessions = no_sessions;
113 yaz_mutex_leave(g_session_mutex);
114 yaz_log(YLOG_DEBUG, "%s sesions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
118 int sessions_count(void) {
119 return session_use(0);
122 int session_count_total(void) {
124 if (!g_session_mutex)
126 yaz_mutex_enter(g_session_mutex);
127 total = no_session_total;
128 yaz_mutex_leave(g_session_mutex);
133 static void log_xml_doc(xmlDoc *doc)
135 FILE *lf = yaz_log_file();
138 #if LIBXML_VERSION >= 20600
139 xmlDocDumpFormatMemory(doc, &result, &len, 1);
141 xmlDocDumpMemory(doc, &result, &len);
145 (void) fwrite(result, 1, len, lf);
151 static void session_enter(struct session *s)
153 yaz_mutex_enter(s->session_mutex);
156 static void session_leave(struct session *s)
158 yaz_mutex_leave(s->session_mutex);
161 // Recursively traverse query structure to extract terms.
162 void pull_terms(NMEM nmem, struct ccl_rpn_node *n, char **termlist, int *num)
174 pull_terms(nmem, n->u.p[0], termlist, num);
175 pull_terms(nmem, n->u.p[1], termlist, num);
178 nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
179 for (i = 0; i < numwords; i++)
180 termlist[(*num)++] = words[i];
188 void add_facet(struct session *s, const char *type, const char *value, int count)
190 struct conf_service *service = s->service;
191 pp2_relevance_token_t prt;
192 const char *facet_component;
193 WRBUF facet_wrbuf = wrbuf_alloc();
194 prt = pp2_relevance_tokenize(service->facet_pct);
196 pp2_relevance_first(prt, value, 0);
197 while ((facet_component = pp2_relevance_token_next(prt)))
199 if (*facet_component)
201 if (wrbuf_len(facet_wrbuf))
202 wrbuf_puts(facet_wrbuf, " ");
203 wrbuf_puts(facet_wrbuf, facet_component);
206 pp2_relevance_token_destroy(prt);
208 if (wrbuf_len(facet_wrbuf))
211 for (i = 0; i < s->num_termlists; i++)
212 if (!strcmp(s->termlists[i].name, type))
214 if (i == s->num_termlists)
216 if (i == SESSION_MAX_TERMLISTS)
218 session_log(s, YLOG_FATAL, "Too many termlists");
219 wrbuf_destroy(facet_wrbuf);
223 s->termlists[i].name = nmem_strdup(s->nmem, type);
224 s->termlists[i].termlist
225 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
226 s->num_termlists = i + 1;
230 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
232 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(facet_wrbuf),
235 wrbuf_destroy(facet_wrbuf);
238 static xmlDoc *record_to_xml(struct session *se,
239 struct session_database *sdb, const char *rec)
241 struct database *db = sdb->database;
244 rdoc = xmlParseMemory(rec, strlen(rec));
248 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
253 if (global_parameters.dump_records)
255 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->url);
262 #define MAX_XSLT_ARGS 16
264 // Add static values from session database settings if applicable
265 static void insert_settings_parameters(struct session_database *sdb,
266 struct conf_service *service,
274 for (i = 0; i < service->num_metadata; i++)
276 struct conf_metadata *md = &service->metadata[i];
279 if (md->setting == Metadata_setting_parameter &&
280 (setting = settings_lookup_offset(service, md->name)) >= 0)
282 const char *val = session_setting_oneval(sdb, setting);
283 if (val && nparms < MAX_XSLT_ARGS)
286 int len = strlen(val);
287 buf = nmem_malloc(nmem, len + 3);
289 strcpy(buf + 1, val);
292 parms[offset++] = md->name;
293 parms[offset++] = buf;
301 // Add static values from session database settings if applicable
302 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
303 struct conf_service *service)
307 for (i = 0; i < service->num_metadata; i++)
309 struct conf_metadata *md = &service->metadata[i];
312 if (md->setting == Metadata_setting_postproc &&
313 (offset = settings_lookup_offset(service, md->name)) >= 0)
315 const char *val = session_setting_oneval(sdb, offset);
318 xmlNode *r = xmlDocGetRootElement(doc);
319 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
321 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
327 static xmlDoc *normalize_record(struct session *se,
328 struct session_database *sdb,
329 struct conf_service *service,
330 const char *rec, NMEM nmem)
332 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
336 char *parms[MAX_XSLT_ARGS*2+1];
338 insert_settings_parameters(sdb, service, parms, nmem);
340 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
342 session_log(se, YLOG_WARN, "Normalize failed from %s",
347 insert_settings_values(sdb, rdoc, service);
349 if (global_parameters.dump_records)
351 session_log(se, YLOG_LOG, "Normalized record from %s",
360 void session_settings_dump(struct session *se,
361 struct session_database *db,
366 int i, num = db->num_settings;
367 for (i = 0; i < num; i++)
369 struct setting *s = db->settings[i];
370 for (;s ; s = s->next)
372 wrbuf_puts(w, "<set name=\"");
373 wrbuf_xmlputs(w, s->name);
374 wrbuf_puts(w, "\" value=\"");
375 wrbuf_xmlputs(w, s->value);
376 wrbuf_puts(w, "\"/>");
384 // Retrieve first defined value for 'name' for given database.
385 // Will be extended to take into account user associated with session
386 const char *session_setting_oneval(struct session_database *db, int offset)
388 if (offset >= db->num_settings || !db->settings[offset])
390 return db->settings[offset]->value;
393 // Prepare XSLT stylesheets for record normalization
394 // Structures are allocated on the session_wide nmem to avoid having
395 // to recompute this for every search. This would lead
396 // to leaking if a single session was to repeatedly change the PZ_XSLT
397 // setting. However, this is not a realistic use scenario.
398 static int prepare_map(struct session *se, struct session_database *sdb)
404 session_log(se, YLOG_WARN, "No settings on %s", sdb->database->url);
407 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
409 char auto_stylesheet[256];
411 if (!strcmp(s, "auto"))
413 const char *request_syntax = session_setting_oneval(
414 sdb, PZ_REQUESTSYNTAX);
418 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
419 "%s.xsl", request_syntax);
420 for (cp = auto_stylesheet; *cp; cp++)
422 /* deliberately only consider ASCII */
423 if (*cp > 32 && *cp < 127)
430 session_log(se, YLOG_WARN,
431 "No pz:requestsyntax for auto stylesheet");
434 sdb->map = normalize_cache_get(se->normalize_cache,
435 se->service->server->config, s);
442 // This analyzes settings and recomputes any supporting data structures
444 static int prepare_session_database(struct session *se,
445 struct session_database *sdb)
449 session_log(se, YLOG_WARN,
450 "No settings associated with %s", sdb->database->url);
453 if (sdb->settings[PZ_XSLT] && !sdb->map)
455 if (prepare_map(se, sdb) < 0)
461 // called if watch should be removed because http_channel is to be destroyed
462 static void session_watch_cancel(void *data, struct http_channel *c,
465 struct session_watchentry *ent = data;
472 // set watch. Returns 0=OK, -1 if watch is already set
473 int session_set_watch(struct session *s, int what,
474 session_watchfun fun, void *data,
475 struct http_channel *chan)
479 if (s->watchlist[what].fun)
484 s->watchlist[what].fun = fun;
485 s->watchlist[what].data = data;
486 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
487 session_watch_cancel);
494 void session_alert_watch(struct session *s, int what)
498 if (s->watchlist[what].fun)
500 /* our watch is no longer associated with http_channel */
502 session_watchfun fun;
504 http_remove_observer(s->watchlist[what].obs);
505 fun = s->watchlist[what].fun;
506 data = s->watchlist[what].data;
508 /* reset watch before fun is invoked - in case fun wants to set
510 s->watchlist[what].fun = 0;
511 s->watchlist[what].data = 0;
512 s->watchlist[what].obs = 0;
515 session_log(s, YLOG_DEBUG,
516 "Alert Watch: %d calling function: %p", what, fun);
523 //callback for grep_databases
524 static void select_targets_callback(void *context, struct session_database *db)
526 struct session *se = (struct session*) context;
527 struct client *cl = client_create();
528 struct client_list *l;
529 client_set_database(cl, db);
531 client_set_session(cl, se);
533 l = xmalloc(sizeof(*l));
535 l->next = se->clients;
539 static void session_remove_clients(struct session *se)
541 struct client_list *l;
550 struct client_list *l_next = l->next;
551 client_lock(l->client);
552 client_set_session(l->client, 0);
553 client_set_database(l->client, 0);
554 client_unlock(l->client);
555 client_destroy(l->client);
561 // Associates a set of clients with a session;
562 // Note: Session-databases represent databases with per-session
564 static int select_targets(struct session *se, const char *filter)
566 return session_grep_databases(se, filter, select_targets_callback);
569 int session_active_clients(struct session *s)
571 struct client_list *l;
574 for (l = s->clients; l; l = l->next)
575 if (client_is_active(l->client))
581 int session_is_preferred_clients_ready(struct session *s)
583 struct client_list *l;
586 for (l = s->clients; l; l = l->next)
587 if (client_is_active_preferred(l->client))
589 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
593 enum pazpar2_error_code search(struct session *se,
595 const char *startrecs, const char *maxrecs,
598 const char **addinfo)
600 int live_channels = 0;
603 struct client_list *l;
605 facet_limits_t facet_limits;
607 session_log(se, YLOG_DEBUG, "Search");
611 session_remove_clients(se);
614 reclist_destroy(se->reclist);
616 relevance_destroy(&se->relevance);
617 nmem_reset(se->nmem);
618 se->total_records = se->total_hits = se->total_merged = 0;
619 se->num_termlists = 0;
620 live_channels = select_targets(se, filter);
624 return PAZPAR2_NO_TARGETS;
626 se->reclist = reclist_create(se->nmem);
628 yaz_gettimeofday(&tval);
632 facet_limits = facet_limits_create(limit);
636 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
638 for (l = se->clients; l; l = l->next)
640 struct client *cl = l->client;
643 client_set_maxrecs(cl, atoi(maxrecs));
645 client_set_startrecs(cl, atoi(startrecs));
646 if (prepare_session_database(se, client_get_database(cl)) < 0)
648 else if (client_parse_query(cl, query, facet_limits) < 0)
653 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
654 se->service->z3950_session_timeout,
655 se->service->server->iochan_man,
657 client_start_search(cl);
660 facet_limits_destroy(facet_limits);
667 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
670 return PAZPAR2_NO_TARGETS;
672 return PAZPAR2_NO_ERROR;
675 // Creates a new session_database object for a database
676 static void session_init_databases_fun(void *context, struct database *db)
678 struct session *se = (struct session *) context;
679 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
685 assert(db->settings);
686 new->settings = nmem_malloc(se->session_nmem,
687 sizeof(struct settings *) * db->num_settings);
688 new->num_settings = db->num_settings;
689 for (i = 0; i < db->num_settings; i++)
691 struct setting *setting = db->settings[i];
692 new->settings[i] = setting;
694 new->next = se->databases;
698 // Doesn't free memory associated with sdb -- nmem takes care of that
699 static void session_database_destroy(struct session_database *sdb)
704 // Initialize session_database list -- this represents this session's view
705 // of the database list -- subject to modification by the settings ws command
706 void session_init_databases(struct session *se)
709 predef_grep_databases(se, se->service, session_init_databases_fun);
712 // Probably session_init_databases_fun should be refactored instead of
714 static struct session_database *load_session_database(struct session *se,
717 struct database *db = new_database(id, se->session_nmem);
719 resolve_database(se->service, db);
721 session_init_databases_fun((void*) se, db);
723 // New sdb is head of se->databases list
724 return se->databases;
727 // Find an existing session database. If not found, load it
728 static struct session_database *find_session_database(struct session *se,
731 struct session_database *sdb;
733 for (sdb = se->databases; sdb; sdb = sdb->next)
734 if (!strcmp(sdb->database->url, id))
736 return load_session_database(se, id);
739 // Apply a session override to a database
740 void session_apply_setting(struct session *se, char *dbname, char *setting,
743 struct session_database *sdb = find_session_database(se, dbname);
744 struct conf_service *service = se->service;
745 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
746 int offset = settings_create_offset(service, setting);
748 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
751 new->target = dbname;
754 new->next = sdb->settings[offset];
755 sdb->settings[offset] = new;
757 // Force later recompute of settings-driven data structures
758 // (happens when a search starts and client connections are prepared)
770 void session_destroy(struct session *se) {
771 struct session_database *sdb;
772 session_log(se, YLOG_DEBUG, "Destroying");
774 session_remove_clients(se);
776 for (sdb = se->databases; sdb; sdb = sdb->next)
777 session_database_destroy(sdb);
778 normalize_cache_destroy(se->normalize_cache);
779 relevance_destroy(&se->relevance);
780 reclist_destroy(se->reclist);
781 nmem_destroy(se->nmem);
782 service_destroy(se->service);
783 yaz_mutex_destroy(&se->session_mutex);
784 wrbuf_destroy(se->wrbuf);
787 /* Depreciated: use session_destroy */
788 void destroy_session(struct session *se)
793 size_t session_get_memory_status(struct session *session) {
797 session_enter(session);
798 session_nmem = nmem_total(session->nmem);
799 session_leave(session);
804 struct session *new_session(NMEM nmem, struct conf_service *service,
808 struct session *session = nmem_malloc(nmem, sizeof(*session));
812 sprintf(tmp_str, "session#%u", session_id);
814 session->session_id = session_id;
815 session_log(session, YLOG_DEBUG, "New");
816 session->service = service;
817 session->relevance = 0;
818 session->total_hits = 0;
819 session->total_records = 0;
820 session->number_of_warnings_unknown_elements = 0;
821 session->number_of_warnings_unknown_metadata = 0;
822 session->num_termlists = 0;
823 session->reclist = 0;
824 session->clients = 0;
825 session->session_nmem = nmem;
826 session->nmem = nmem_create();
827 session->wrbuf = wrbuf_alloc();
828 session->databases = 0;
829 for (i = 0; i <= SESSION_WATCH_MAX; i++)
831 session->watchlist[i].data = 0;
832 session->watchlist[i].fun = 0;
834 session->normalize_cache = normalize_cache_create();
835 session->session_mutex = 0;
836 pazpar2_mutex_create(&session->session_mutex, tmp_str);
841 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
843 struct hitsbytarget *res = 0;
844 struct client_list *l;
848 for (l = se->clients; l; l = l->next)
851 res = nmem_malloc(nmem, sizeof(*res) * sz);
853 for (l = se->clients; l; l = l->next)
855 struct client *cl = l->client;
856 WRBUF w = wrbuf_alloc();
857 const char *name = session_setting_oneval(client_get_database(cl),
860 res[*count].id = client_get_database(cl)->database->url;
861 res[*count].name = *name ? name : "Unknown";
862 res[*count].hits = client_get_hits(cl);
863 res[*count].records = client_get_num_records(cl);
864 res[*count].diagnostic = client_get_diagnostic(cl);
865 res[*count].state = client_get_state_str(cl);
866 res[*count].connected = client_get_connection(cl) ? 1 : 0;
867 session_settings_dump(se, client_get_database(cl), w);
868 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
876 struct termlist_score **get_termlist_score(struct session *se,
877 const char *name, int *num)
880 struct termlist_score **tl = 0;
883 for (i = 0; i < se->num_termlists; i++)
884 if (!strcmp((const char *) se->termlists[i].name, name))
886 tl = termlist_highscore(se->termlists[i].termlist, num);
893 #ifdef MISSING_HEADERS
894 void report_nmem_stats(void)
896 size_t in_use, is_free;
898 nmem_get_memory_in_use(&in_use);
899 nmem_get_memory_free(&is_free);
901 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
902 (long) in_use, (long) is_free);
906 struct record_cluster *show_single_start(struct session *se, const char *id,
907 struct record_cluster **prev_r,
908 struct record_cluster **next_r)
910 struct record_cluster *r = 0;
917 reclist_enter(se->reclist);
918 while ((r = reclist_read_record(se->reclist)))
920 if (!strcmp(r->recid, id))
922 *next_r = reclist_read_record(se->reclist);
927 reclist_leave(se->reclist);
934 void show_single_stop(struct session *se, struct record_cluster *rec)
939 struct record_cluster **show_range_start(struct session *se,
940 struct reclist_sortparms *sp,
941 int start, int *num, int *total, Odr_int *sumhits)
943 struct record_cluster **recs;
944 struct reclist_sortparms *spp;
947 yaz_timing_t t = yaz_timing_create();
950 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
960 for (spp = sp; spp; spp = spp->next)
961 if (spp->type == Metadata_sortkey_relevance)
963 relevance_prepare_read(se->relevance, se->reclist);
966 reclist_sort(se->reclist, sp);
968 reclist_enter(se->reclist);
969 *total = reclist_get_num_records(se->reclist);
970 *sumhits = se->total_hits;
972 for (i = 0; i < start; i++)
973 if (!reclist_read_record(se->reclist))
980 for (i = 0; i < *num; i++)
982 struct record_cluster *r = reclist_read_record(se->reclist);
990 reclist_leave(se->reclist);
994 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
995 yaz_timing_get_real(t), yaz_timing_get_user(t),
996 yaz_timing_get_sys(t));
997 yaz_timing_destroy(&t);
1002 void show_range_stop(struct session *se, struct record_cluster **recs)
1007 void statistics(struct session *se, struct statistics *stat)
1009 struct client_list *l;
1012 memset(stat, 0, sizeof(*stat));
1013 for (l = se->clients; l; l = l->next)
1015 struct client *cl = l->client;
1016 if (!client_get_connection(cl))
1017 stat->num_no_connection++;
1018 switch (client_get_state(cl))
1020 case Client_Connecting: stat->num_connecting++; break;
1021 case Client_Working: stat->num_working++; break;
1022 case Client_Idle: stat->num_idle++; break;
1023 case Client_Failed: stat->num_failed++; break;
1024 case Client_Error: stat->num_error++; break;
1029 stat->num_hits = se->total_hits;
1030 stat->num_records = se->total_records;
1032 stat->num_clients = count;
1035 static struct record_metadata *record_metadata_init(
1036 NMEM nmem, const char *value, enum conf_metadata_type type,
1037 struct _xmlAttr *attr)
1039 struct record_metadata *rec_md = record_metadata_create(nmem);
1040 struct record_metadata_attr **attrp = &rec_md->attributes;
1042 for (; attr; attr = attr->next)
1044 if (attr->children && attr->children->content)
1046 if (strcmp((const char *) attr->name, "type"))
1047 { /* skip the "type" attribute.. Its value is already part of
1048 the element in output (md-%s) and so repeating it here
1050 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1052 nmem_strdup(nmem, (const char *) attr->name);
1054 nmem_strdup(nmem, (const char *) attr->children->content);
1055 attrp = &(*attrp)->next;
1061 if (type == Metadata_type_generic)
1063 char *p = nmem_strdup(nmem, value);
1065 p = normalize7bit_generic(p, " ,/.:([");
1067 rec_md->data.text.disp = p;
1068 rec_md->data.text.sort = 0;
1070 else if (type == Metadata_type_year || type == Metadata_type_date)
1075 if (type == Metadata_type_date)
1077 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1080 rec_md->data.number.min = first;
1081 rec_md->data.number.max = last;
1088 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1089 struct conf_service *service, WRBUF norm_wr)
1093 for (n = root->children; n; n = n->next)
1095 if (n->type != XML_ELEMENT_NODE)
1097 if (!strcmp((const char *) n->name, "metadata"))
1099 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1101 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1103 else if (!strcmp(name, (const char *) type))
1105 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1108 const char *norm_str;
1109 pp2_relevance_token_t prt =
1110 pp2_relevance_tokenize(service->mergekey_pct);
1112 pp2_relevance_first(prt, (const char *) value, 0);
1113 if (wrbuf_len(norm_wr) > 0)
1114 wrbuf_puts(norm_wr, " ");
1115 wrbuf_puts(norm_wr, name);
1117 pp2_relevance_token_next(prt)))
1121 wrbuf_puts(norm_wr, " ");
1122 wrbuf_puts(norm_wr, norm_str);
1126 pp2_relevance_token_destroy(prt);
1136 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1137 struct conf_service *service, NMEM nmem)
1139 char *mergekey_norm = 0;
1140 xmlNode *root = xmlDocGetRootElement(doc);
1141 WRBUF norm_wr = wrbuf_alloc();
1143 /* consider mergekey from XSL first */
1144 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1147 const char *norm_str;
1148 pp2_relevance_token_t prt =
1149 pp2_relevance_tokenize(service->mergekey_pct);
1151 pp2_relevance_first(prt, (const char *) mergekey, 0);
1152 while ((norm_str = pp2_relevance_token_next(prt)))
1156 if (wrbuf_len(norm_wr))
1157 wrbuf_puts(norm_wr, " ");
1158 wrbuf_puts(norm_wr, norm_str);
1161 pp2_relevance_token_destroy(prt);
1166 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1168 for (field_id = 0; field_id < service->num_metadata; field_id++)
1170 struct conf_metadata *ser_md = &service->metadata[field_id];
1171 if (ser_md->mergekey != Metadata_mergekey_no)
1173 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1175 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1177 /* no mergekey on this one and it is required..
1178 Generate unique key instead */
1179 wrbuf_rewind(norm_wr);
1186 /* generate unique key if none is not generated already or is empty */
1187 if (wrbuf_len(norm_wr) == 0)
1189 wrbuf_printf(norm_wr, "%s-%d",
1190 client_get_database(cl)->database->url, record_no);
1192 if (wrbuf_len(norm_wr) > 0)
1193 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1194 wrbuf_destroy(norm_wr);
1195 return mergekey_norm;
1198 /** \brief see if metadata for pz:recordfilter exists
1199 \param root xml root element of normalized record
1200 \param sdb session database for client
1201 \retval 0 if there is no metadata for pz:recordfilter
1202 \retval 1 if there is metadata for pz:recordfilter
1204 If there is no pz:recordfilter defined, this function returns 1
1208 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1213 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1218 for (n = root->children; n; n = n->next)
1220 if (n->type != XML_ELEMENT_NODE)
1222 if (!strcmp((const char *) n->name, "metadata"))
1224 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1231 if ((eq = strchr(s, '=')))
1233 else if ((eq = strchr(s, '~')))
1239 if (len == strlen((const char *)type) &&
1240 !memcmp((const char *) type, s, len))
1242 xmlChar *value = xmlNodeGetContent(n);
1243 if (value && *value)
1246 (substring && strstr((const char *) value, eq+1)) ||
1247 (!substring && !strcmp((const char *) value, eq + 1)))
1260 static int ingest_to_cluster(struct client *cl,
1264 const char *mergekey_norm);
1266 /** \brief ingest XML record
1267 \param cl client holds the result set for record
1268 \param rec record buffer (0 terminated)
1269 \param record_no record position (1, 2, ..)
1270 \param nmem working NMEM
1275 int ingest_record(struct client *cl, const char *rec,
1276 int record_no, NMEM nmem)
1278 struct session *se = client_get_session(cl);
1280 struct session_database *sdb = client_get_database(cl);
1281 struct conf_service *service = se->service;
1282 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1284 const char *mergekey_norm;
1289 root = xmlDocGetRootElement(xdoc);
1291 if (!check_record_filter(root, sdb))
1293 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1294 record_no, sdb->database->url);
1299 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1302 session_log(se, YLOG_WARN, "Got no mergekey");
1307 if (client_get_session(cl) == se)
1308 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1315 static int ingest_to_cluster(struct client *cl,
1319 const char *mergekey_norm)
1324 struct session_database *sdb = client_get_database(cl);
1325 struct session *se = client_get_session(cl);
1326 struct conf_service *service = se->service;
1327 struct record *record = record_create(se->nmem,
1328 service->num_metadata,
1329 service->num_sortkeys, cl,
1331 struct record_cluster *cluster = reclist_insert(se->reclist,
1337 const char *use_term_factor_str = session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1338 int use_term_factor = 0;
1339 int term_factor = 1;
1340 if (use_term_factor_str && use_term_factor_str[0] != 0)
1341 use_term_factor = atoi(use_term_factor_str);
1342 if (use_term_factor) {
1343 int maxrecs = client_get_maxrecs(cl);
1344 int hits = (int) client_get_hits(cl);
1345 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1346 assert(term_factor >= 1);
1347 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1352 if (global_parameters.dump_records)
1353 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1354 sdb->database->url, record_no);
1355 relevance_newrec(se->relevance, cluster);
1357 // now parsing XML record and adding data to cluster or record metadata
1358 for (n = root->children; n; n = n->next)
1360 pp2_relevance_token_t prt;
1367 if (n->type != XML_ELEMENT_NODE)
1369 if (!strcmp((const char *) n->name, "metadata"))
1371 struct conf_metadata *ser_md = 0;
1372 struct conf_sortkey *ser_sk = 0;
1373 struct record_metadata **wheretoput = 0;
1374 struct record_metadata *rec_md = 0;
1375 int md_field_id = -1;
1376 int sk_field_id = -1;
1378 type = xmlGetProp(n, (xmlChar *) "type");
1379 value = xmlNodeListGetString(xdoc, n->children, 1);
1381 if (!type || !value || !*value)
1385 = conf_service_metadata_field_id(service, (const char *) type);
1386 if (md_field_id < 0)
1388 if (se->number_of_warnings_unknown_metadata == 0)
1390 session_log(se, YLOG_WARN,
1391 "Ignoring unknown metadata element: %s", type);
1393 se->number_of_warnings_unknown_metadata++;
1397 ser_md = &service->metadata[md_field_id];
1399 if (ser_md->sortkey_offset >= 0){
1400 sk_field_id = ser_md->sortkey_offset;
1401 ser_sk = &service->sortkeys[sk_field_id];
1404 // non-merged metadata
1405 rec_md = record_metadata_init(se->nmem, (const char *) value,
1406 ser_md->type, n->properties);
1409 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1410 "for element '%s'", value, type);
1413 wheretoput = &record->metadata[md_field_id];
1415 wheretoput = &(*wheretoput)->next;
1416 *wheretoput = rec_md;
1419 rec_md = record_metadata_init(se->nmem, (const char *) value,
1421 wheretoput = &cluster->metadata[md_field_id];
1423 // and polulate with data:
1424 // assign cluster or record based on merge action
1425 if (ser_md->merge == Metadata_merge_unique)
1427 struct record_metadata *mnode;
1428 for (mnode = *wheretoput; mnode; mnode = mnode->next)
1429 if (!strcmp((const char *) mnode->data.text.disp,
1430 rec_md->data.text.disp))
1434 rec_md->next = *wheretoput;
1435 *wheretoput = rec_md;
1438 else if (ser_md->merge == Metadata_merge_longest)
1441 || strlen(rec_md->data.text.disp)
1442 > strlen((*wheretoput)->data.text.disp))
1444 *wheretoput = rec_md;
1447 const char *sort_str = 0;
1449 ser_sk->type == Metadata_sortkey_skiparticle;
1451 if (!cluster->sortkeys[sk_field_id])
1452 cluster->sortkeys[sk_field_id] =
1453 nmem_malloc(se->nmem,
1454 sizeof(union data_types));
1456 prt = pp2_relevance_tokenize(service->sort_pct);
1458 pp2_relevance_first(prt, rec_md->data.text.disp,
1461 pp2_relevance_token_next(prt);
1463 sort_str = pp2_get_sort(prt);
1465 cluster->sortkeys[sk_field_id]->text.disp =
1466 rec_md->data.text.disp;
1469 sort_str = rec_md->data.text.disp;
1470 session_log(se, YLOG_WARN,
1471 "Could not make sortkey. Bug #1858");
1473 cluster->sortkeys[sk_field_id]->text.sort =
1474 nmem_strdup(se->nmem, sort_str);
1475 pp2_relevance_token_destroy(prt);
1479 else if (ser_md->merge == Metadata_merge_all)
1481 rec_md->next = *wheretoput;
1482 *wheretoput = rec_md;
1484 else if (ser_md->merge == Metadata_merge_range)
1488 *wheretoput = rec_md;
1490 cluster->sortkeys[sk_field_id]
1495 int this_min = rec_md->data.number.min;
1496 int this_max = rec_md->data.number.max;
1497 if (this_min < (*wheretoput)->data.number.min)
1498 (*wheretoput)->data.number.min = this_min;
1499 if (this_max > (*wheretoput)->data.number.max)
1500 (*wheretoput)->data.number.max = this_max;
1505 // ranking of _all_ fields enabled ...
1507 relevance_countwords(se->relevance, cluster,
1508 (char *) value, ser_md->rank,
1511 // construct facets ... unless the client already has reported them
1512 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1514 if (ser_md->type == Metadata_type_year)
1517 sprintf(year, "%d", rec_md->data.number.max);
1519 add_facet(se, (char *) type, year, term_factor);
1520 if (rec_md->data.number.max != rec_md->data.number.min)
1522 sprintf(year, "%d", rec_md->data.number.min);
1523 add_facet(se, (char *) type, year, term_factor);
1527 add_facet(se, (char *) type, (char *) value, term_factor);
1537 if (se->number_of_warnings_unknown_elements == 0)
1538 session_log(se, YLOG_WARN,
1539 "Unexpected element in internal record: %s", n->name);
1540 se->number_of_warnings_unknown_elements++;
1548 relevance_donerecord(se->relevance, cluster);
1549 se->total_records++;
1554 void session_log(struct session *s, int level, const char *fmt, ...)
1560 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1561 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1569 * c-file-style: "Stroustrup"
1570 * indent-tabs-mode: nil
1572 * vim: shiftwidth=4 tabstop=8 expandtab