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_charset_token_t prt;
192 const char *facet_component;
193 WRBUF facet_wrbuf = wrbuf_alloc();
194 WRBUF display_wrbuf = wrbuf_alloc();
196 const char *icu_chain_id = 0;
198 for (i = 0; i < service->num_metadata; i++)
199 if (!strcmp((service->metadata + i)->name, type))
200 icu_chain_id = (service->metadata + i)->icu_chain;
201 yaz_log(YLOG_LOG, "icu_chain id=%s", icu_chain_id ? icu_chain_id : "null");
204 icu_chain_id = "facet";
205 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
208 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
210 wrbuf_destroy(facet_wrbuf);
211 wrbuf_destroy(display_wrbuf);
214 pp2_charset_token_first(prt, value, 0);
215 while ((facet_component = pp2_charset_token_next(prt)))
217 const char *display_component;
218 if (*facet_component)
220 if (wrbuf_len(facet_wrbuf))
221 wrbuf_puts(facet_wrbuf, " ");
222 wrbuf_puts(facet_wrbuf, facet_component);
224 display_component = pp2_get_display(prt);
225 if (display_component)
227 if (wrbuf_len(display_wrbuf))
228 wrbuf_puts(display_wrbuf, " ");
229 wrbuf_puts(display_wrbuf, display_component);
232 pp2_charset_token_destroy(prt);
234 yaz_log(YLOG_LOG, "facet norm=%s", wrbuf_cstr(facet_wrbuf));
235 yaz_log(YLOG_LOG, "facet display=%s", wrbuf_cstr(display_wrbuf));
236 if (wrbuf_len(facet_wrbuf))
239 for (i = 0; i < s->num_termlists; i++)
240 if (!strcmp(s->termlists[i].name, type))
242 if (i == s->num_termlists)
244 if (i == SESSION_MAX_TERMLISTS)
246 session_log(s, YLOG_FATAL, "Too many termlists");
247 wrbuf_destroy(facet_wrbuf);
248 wrbuf_destroy(display_wrbuf);
252 s->termlists[i].name = nmem_strdup(s->nmem, type);
253 s->termlists[i].termlist
254 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
255 s->num_termlists = i + 1;
259 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
261 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
262 wrbuf_cstr(facet_wrbuf), count);
264 wrbuf_destroy(facet_wrbuf);
265 wrbuf_destroy(display_wrbuf);
268 static xmlDoc *record_to_xml(struct session *se,
269 struct session_database *sdb, const char *rec)
271 struct database *db = sdb->database;
274 rdoc = xmlParseMemory(rec, strlen(rec));
278 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
283 if (global_parameters.dump_records)
285 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->url);
292 #define MAX_XSLT_ARGS 16
294 // Add static values from session database settings if applicable
295 static void insert_settings_parameters(struct session_database *sdb,
296 struct conf_service *service,
304 for (i = 0; i < service->num_metadata; i++)
306 struct conf_metadata *md = &service->metadata[i];
309 if (md->setting == Metadata_setting_parameter &&
310 (setting = settings_lookup_offset(service, md->name)) >= 0)
312 const char *val = session_setting_oneval(sdb, setting);
313 if (val && nparms < MAX_XSLT_ARGS)
316 int len = strlen(val);
317 buf = nmem_malloc(nmem, len + 3);
319 strcpy(buf + 1, val);
322 parms[offset++] = md->name;
323 parms[offset++] = buf;
331 // Add static values from session database settings if applicable
332 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
333 struct conf_service *service)
337 for (i = 0; i < service->num_metadata; i++)
339 struct conf_metadata *md = &service->metadata[i];
342 if (md->setting == Metadata_setting_postproc &&
343 (offset = settings_lookup_offset(service, md->name)) >= 0)
345 const char *val = session_setting_oneval(sdb, offset);
348 xmlNode *r = xmlDocGetRootElement(doc);
349 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
351 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
357 static xmlDoc *normalize_record(struct session *se,
358 struct session_database *sdb,
359 struct conf_service *service,
360 const char *rec, NMEM nmem)
362 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
366 char *parms[MAX_XSLT_ARGS*2+1];
368 insert_settings_parameters(sdb, service, parms, nmem);
370 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
372 session_log(se, YLOG_WARN, "Normalize failed from %s",
377 insert_settings_values(sdb, rdoc, service);
379 if (global_parameters.dump_records)
381 session_log(se, YLOG_LOG, "Normalized record from %s",
390 void session_settings_dump(struct session *se,
391 struct session_database *db,
396 int i, num = db->num_settings;
397 for (i = 0; i < num; i++)
399 struct setting *s = db->settings[i];
400 for (;s ; s = s->next)
402 wrbuf_puts(w, "<set name=\"");
403 wrbuf_xmlputs(w, s->name);
404 wrbuf_puts(w, "\" value=\"");
405 wrbuf_xmlputs(w, s->value);
406 wrbuf_puts(w, "\"/>");
414 // Retrieve first defined value for 'name' for given database.
415 // Will be extended to take into account user associated with session
416 const char *session_setting_oneval(struct session_database *db, int offset)
418 if (offset >= db->num_settings || !db->settings[offset])
420 return db->settings[offset]->value;
423 // Prepare XSLT stylesheets for record normalization
424 // Structures are allocated on the session_wide nmem to avoid having
425 // to recompute this for every search. This would lead
426 // to leaking if a single session was to repeatedly change the PZ_XSLT
427 // setting. However, this is not a realistic use scenario.
428 static int prepare_map(struct session *se, struct session_database *sdb)
434 session_log(se, YLOG_WARN, "No settings on %s", sdb->database->url);
437 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
439 char auto_stylesheet[256];
441 if (!strcmp(s, "auto"))
443 const char *request_syntax = session_setting_oneval(
444 sdb, PZ_REQUESTSYNTAX);
448 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
449 "%s.xsl", request_syntax);
450 for (cp = auto_stylesheet; *cp; cp++)
452 /* deliberately only consider ASCII */
453 if (*cp > 32 && *cp < 127)
460 session_log(se, YLOG_WARN,
461 "No pz:requestsyntax for auto stylesheet");
464 sdb->map = normalize_cache_get(se->normalize_cache,
465 se->service->server->config, s);
472 // This analyzes settings and recomputes any supporting data structures
474 static int prepare_session_database(struct session *se,
475 struct session_database *sdb)
479 session_log(se, YLOG_WARN,
480 "No settings associated with %s", sdb->database->url);
483 if (sdb->settings[PZ_XSLT] && !sdb->map)
485 if (prepare_map(se, sdb) < 0)
491 // called if watch should be removed because http_channel is to be destroyed
492 static void session_watch_cancel(void *data, struct http_channel *c,
495 struct session_watchentry *ent = data;
502 // set watch. Returns 0=OK, -1 if watch is already set
503 int session_set_watch(struct session *s, int what,
504 session_watchfun fun, void *data,
505 struct http_channel *chan)
509 if (s->watchlist[what].fun)
514 s->watchlist[what].fun = fun;
515 s->watchlist[what].data = data;
516 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
517 session_watch_cancel);
524 void session_alert_watch(struct session *s, int what)
528 if (s->watchlist[what].fun)
530 /* our watch is no longer associated with http_channel */
532 session_watchfun fun;
534 http_remove_observer(s->watchlist[what].obs);
535 fun = s->watchlist[what].fun;
536 data = s->watchlist[what].data;
538 /* reset watch before fun is invoked - in case fun wants to set
540 s->watchlist[what].fun = 0;
541 s->watchlist[what].data = 0;
542 s->watchlist[what].obs = 0;
545 session_log(s, YLOG_DEBUG,
546 "Alert Watch: %d calling function: %p", what, fun);
553 //callback for grep_databases
554 static void select_targets_callback(void *context, struct session_database *db)
556 struct session *se = (struct session*) context;
557 struct client *cl = client_create();
558 struct client_list *l;
559 client_set_database(cl, db);
561 client_set_session(cl, se);
563 l = xmalloc(sizeof(*l));
565 l->next = se->clients;
569 static void session_remove_clients(struct session *se)
571 struct client_list *l;
580 struct client_list *l_next = l->next;
581 client_lock(l->client);
582 client_set_session(l->client, 0);
583 client_set_database(l->client, 0);
584 client_unlock(l->client);
585 client_destroy(l->client);
591 // Associates a set of clients with a session;
592 // Note: Session-databases represent databases with per-session
594 static int select_targets(struct session *se, const char *filter)
596 return session_grep_databases(se, filter, select_targets_callback);
599 int session_active_clients(struct session *s)
601 struct client_list *l;
604 for (l = s->clients; l; l = l->next)
605 if (client_is_active(l->client))
611 int session_is_preferred_clients_ready(struct session *s)
613 struct client_list *l;
616 for (l = s->clients; l; l = l->next)
617 if (client_is_active_preferred(l->client))
619 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
623 enum pazpar2_error_code search(struct session *se,
625 const char *startrecs, const char *maxrecs,
628 const char **addinfo)
630 int live_channels = 0;
633 struct client_list *l;
635 facet_limits_t facet_limits;
637 session_log(se, YLOG_DEBUG, "Search");
641 session_remove_clients(se);
644 reclist_destroy(se->reclist);
646 relevance_destroy(&se->relevance);
647 nmem_reset(se->nmem);
648 se->total_records = se->total_hits = se->total_merged = 0;
649 se->num_termlists = 0;
650 live_channels = select_targets(se, filter);
654 return PAZPAR2_NO_TARGETS;
656 se->reclist = reclist_create(se->nmem);
658 yaz_gettimeofday(&tval);
662 facet_limits = facet_limits_create(limit);
667 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
669 for (l = se->clients; l; l = l->next)
671 struct client *cl = l->client;
674 client_set_maxrecs(cl, atoi(maxrecs));
676 client_set_startrecs(cl, atoi(startrecs));
677 if (prepare_session_database(se, client_get_database(cl)) < 0)
679 else if (client_parse_query(cl, query, facet_limits) < 0)
684 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
685 se->service->z3950_session_timeout,
686 se->service->server->iochan_man,
688 client_start_search(cl);
691 facet_limits_destroy(facet_limits);
698 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
701 return PAZPAR2_NO_TARGETS;
703 return PAZPAR2_NO_ERROR;
706 // Creates a new session_database object for a database
707 static void session_init_databases_fun(void *context, struct database *db)
709 struct session *se = (struct session *) context;
710 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
716 assert(db->settings);
717 new->settings = nmem_malloc(se->session_nmem,
718 sizeof(struct settings *) * db->num_settings);
719 new->num_settings = db->num_settings;
720 for (i = 0; i < db->num_settings; i++)
722 struct setting *setting = db->settings[i];
723 new->settings[i] = setting;
725 new->next = se->databases;
729 // Doesn't free memory associated with sdb -- nmem takes care of that
730 static void session_database_destroy(struct session_database *sdb)
735 // Initialize session_database list -- this represents this session's view
736 // of the database list -- subject to modification by the settings ws command
737 void session_init_databases(struct session *se)
740 predef_grep_databases(se, se->service, session_init_databases_fun);
743 // Probably session_init_databases_fun should be refactored instead of
745 static struct session_database *load_session_database(struct session *se,
748 struct database *db = new_database(id, se->session_nmem);
750 resolve_database(se->service, db);
752 session_init_databases_fun((void*) se, db);
754 // New sdb is head of se->databases list
755 return se->databases;
758 // Find an existing session database. If not found, load it
759 static struct session_database *find_session_database(struct session *se,
762 struct session_database *sdb;
764 for (sdb = se->databases; sdb; sdb = sdb->next)
765 if (!strcmp(sdb->database->url, id))
767 return load_session_database(se, id);
770 // Apply a session override to a database
771 void session_apply_setting(struct session *se, char *dbname, char *setting,
774 struct session_database *sdb = find_session_database(se, dbname);
775 struct conf_service *service = se->service;
776 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
777 int offset = settings_create_offset(service, setting);
779 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
782 new->target = dbname;
785 new->next = sdb->settings[offset];
786 sdb->settings[offset] = new;
788 // Force later recompute of settings-driven data structures
789 // (happens when a search starts and client connections are prepared)
801 void session_destroy(struct session *se) {
802 struct session_database *sdb;
803 session_log(se, YLOG_DEBUG, "Destroying");
805 session_remove_clients(se);
807 for (sdb = se->databases; sdb; sdb = sdb->next)
808 session_database_destroy(sdb);
809 normalize_cache_destroy(se->normalize_cache);
810 relevance_destroy(&se->relevance);
811 reclist_destroy(se->reclist);
812 nmem_destroy(se->nmem);
813 service_destroy(se->service);
814 yaz_mutex_destroy(&se->session_mutex);
817 /* Depreciated: use session_destroy */
818 void destroy_session(struct session *se)
823 size_t session_get_memory_status(struct session *session) {
827 session_enter(session);
828 session_nmem = nmem_total(session->nmem);
829 session_leave(session);
834 struct session *new_session(NMEM nmem, struct conf_service *service,
838 struct session *session = nmem_malloc(nmem, sizeof(*session));
842 sprintf(tmp_str, "session#%u", session_id);
844 session->session_id = session_id;
845 session_log(session, YLOG_DEBUG, "New");
846 session->service = service;
847 session->relevance = 0;
848 session->total_hits = 0;
849 session->total_records = 0;
850 session->number_of_warnings_unknown_elements = 0;
851 session->number_of_warnings_unknown_metadata = 0;
852 session->num_termlists = 0;
853 session->reclist = 0;
854 session->clients = 0;
855 session->session_nmem = nmem;
856 session->nmem = nmem_create();
857 session->databases = 0;
858 for (i = 0; i <= SESSION_WATCH_MAX; i++)
860 session->watchlist[i].data = 0;
861 session->watchlist[i].fun = 0;
863 session->normalize_cache = normalize_cache_create();
864 session->session_mutex = 0;
865 pazpar2_mutex_create(&session->session_mutex, tmp_str);
870 struct hitsbytarget *hitsbytarget(struct session *se, int *count, NMEM nmem)
872 struct hitsbytarget *res = 0;
873 struct client_list *l;
877 for (l = se->clients; l; l = l->next)
880 res = nmem_malloc(nmem, sizeof(*res) * sz);
882 for (l = se->clients; l; l = l->next)
884 struct client *cl = l->client;
885 WRBUF w = wrbuf_alloc();
886 const char *name = session_setting_oneval(client_get_database(cl),
889 res[*count].id = client_get_database(cl)->database->url;
890 res[*count].name = *name ? name : "Unknown";
891 res[*count].hits = client_get_hits(cl);
892 res[*count].records = client_get_num_records(cl);
893 res[*count].diagnostic = client_get_diagnostic(cl);
894 res[*count].state = client_get_state_str(cl);
895 res[*count].connected = client_get_connection(cl) ? 1 : 0;
896 session_settings_dump(se, client_get_database(cl), w);
897 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
905 struct termlist_score **get_termlist_score(struct session *se,
906 const char *name, int *num)
909 struct termlist_score **tl = 0;
912 for (i = 0; i < se->num_termlists; i++)
913 if (!strcmp((const char *) se->termlists[i].name, name))
915 tl = termlist_highscore(se->termlists[i].termlist, num);
922 #ifdef MISSING_HEADERS
923 void report_nmem_stats(void)
925 size_t in_use, is_free;
927 nmem_get_memory_in_use(&in_use);
928 nmem_get_memory_free(&is_free);
930 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
931 (long) in_use, (long) is_free);
935 struct record_cluster *show_single_start(struct session *se, const char *id,
936 struct record_cluster **prev_r,
937 struct record_cluster **next_r)
939 struct record_cluster *r = 0;
946 reclist_enter(se->reclist);
947 while ((r = reclist_read_record(se->reclist)))
949 if (!strcmp(r->recid, id))
951 *next_r = reclist_read_record(se->reclist);
956 reclist_leave(se->reclist);
963 void show_single_stop(struct session *se, struct record_cluster *rec)
968 struct record_cluster **show_range_start(struct session *se,
969 struct reclist_sortparms *sp,
970 int start, int *num, int *total, Odr_int *sumhits)
972 struct record_cluster **recs;
973 struct reclist_sortparms *spp;
976 yaz_timing_t t = yaz_timing_create();
979 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
989 for (spp = sp; spp; spp = spp->next)
990 if (spp->type == Metadata_sortkey_relevance)
992 relevance_prepare_read(se->relevance, se->reclist);
995 reclist_sort(se->reclist, sp);
997 reclist_enter(se->reclist);
998 *total = reclist_get_num_records(se->reclist);
999 *sumhits = se->total_hits;
1001 for (i = 0; i < start; i++)
1002 if (!reclist_read_record(se->reclist))
1009 for (i = 0; i < *num; i++)
1011 struct record_cluster *r = reclist_read_record(se->reclist);
1019 reclist_leave(se->reclist);
1023 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1024 yaz_timing_get_real(t), yaz_timing_get_user(t),
1025 yaz_timing_get_sys(t));
1026 yaz_timing_destroy(&t);
1031 void show_range_stop(struct session *se, struct record_cluster **recs)
1036 void statistics(struct session *se, struct statistics *stat)
1038 struct client_list *l;
1041 memset(stat, 0, sizeof(*stat));
1042 for (l = se->clients; l; l = l->next)
1044 struct client *cl = l->client;
1045 if (!client_get_connection(cl))
1046 stat->num_no_connection++;
1047 switch (client_get_state(cl))
1049 case Client_Connecting: stat->num_connecting++; break;
1050 case Client_Working: stat->num_working++; break;
1051 case Client_Idle: stat->num_idle++; break;
1052 case Client_Failed: stat->num_failed++; break;
1053 case Client_Error: stat->num_error++; break;
1058 stat->num_hits = se->total_hits;
1059 stat->num_records = se->total_records;
1061 stat->num_clients = count;
1064 static struct record_metadata *record_metadata_init(
1065 NMEM nmem, const char *value, enum conf_metadata_type type,
1066 struct _xmlAttr *attr)
1068 struct record_metadata *rec_md = record_metadata_create(nmem);
1069 struct record_metadata_attr **attrp = &rec_md->attributes;
1071 for (; attr; attr = attr->next)
1073 if (attr->children && attr->children->content)
1075 if (strcmp((const char *) attr->name, "type"))
1076 { /* skip the "type" attribute.. Its value is already part of
1077 the element in output (md-%s) and so repeating it here
1079 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1081 nmem_strdup(nmem, (const char *) attr->name);
1083 nmem_strdup(nmem, (const char *) attr->children->content);
1084 attrp = &(*attrp)->next;
1090 if (type == Metadata_type_generic)
1092 char *p = nmem_strdup(nmem, value);
1094 p = normalize7bit_generic(p, " ,/.:([");
1096 rec_md->data.text.disp = p;
1097 rec_md->data.text.sort = 0;
1099 else if (type == Metadata_type_year || type == Metadata_type_date)
1104 if (type == Metadata_type_date)
1106 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1109 rec_md->data.number.min = first;
1110 rec_md->data.number.max = last;
1117 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1118 struct conf_service *service, WRBUF norm_wr)
1122 for (n = root->children; n; n = n->next)
1124 if (n->type != XML_ELEMENT_NODE)
1126 if (!strcmp((const char *) n->name, "metadata"))
1128 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1130 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1132 else if (!strcmp(name, (const char *) type))
1134 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1137 const char *norm_str;
1138 pp2_charset_token_t prt =
1139 pp2_charset_token_create(service->charsets, "mergekey");
1141 pp2_charset_token_first(prt, (const char *) value, 0);
1142 if (wrbuf_len(norm_wr) > 0)
1143 wrbuf_puts(norm_wr, " ");
1144 wrbuf_puts(norm_wr, name);
1146 pp2_charset_token_next(prt)))
1150 wrbuf_puts(norm_wr, " ");
1151 wrbuf_puts(norm_wr, norm_str);
1155 pp2_charset_token_destroy(prt);
1165 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1166 struct conf_service *service, NMEM nmem)
1168 char *mergekey_norm = 0;
1169 xmlNode *root = xmlDocGetRootElement(doc);
1170 WRBUF norm_wr = wrbuf_alloc();
1172 /* consider mergekey from XSL first */
1173 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1176 const char *norm_str;
1177 pp2_charset_token_t prt =
1178 pp2_charset_token_create(service->charsets, "mergekey");
1180 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1181 while ((norm_str = pp2_charset_token_next(prt)))
1185 if (wrbuf_len(norm_wr))
1186 wrbuf_puts(norm_wr, " ");
1187 wrbuf_puts(norm_wr, norm_str);
1190 pp2_charset_token_destroy(prt);
1195 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1197 for (field_id = 0; field_id < service->num_metadata; field_id++)
1199 struct conf_metadata *ser_md = &service->metadata[field_id];
1200 if (ser_md->mergekey != Metadata_mergekey_no)
1202 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1204 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1206 /* no mergekey on this one and it is required..
1207 Generate unique key instead */
1208 wrbuf_rewind(norm_wr);
1215 /* generate unique key if none is not generated already or is empty */
1216 if (wrbuf_len(norm_wr) == 0)
1218 wrbuf_printf(norm_wr, "%s-%d",
1219 client_get_database(cl)->database->url, record_no);
1221 if (wrbuf_len(norm_wr) > 0)
1222 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1223 wrbuf_destroy(norm_wr);
1224 return mergekey_norm;
1227 /** \brief see if metadata for pz:recordfilter exists
1228 \param root xml root element of normalized record
1229 \param sdb session database for client
1230 \retval 0 if there is no metadata for pz:recordfilter
1231 \retval 1 if there is metadata for pz:recordfilter
1233 If there is no pz:recordfilter defined, this function returns 1
1237 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1242 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1247 for (n = root->children; n; n = n->next)
1249 if (n->type != XML_ELEMENT_NODE)
1251 if (!strcmp((const char *) n->name, "metadata"))
1253 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1260 if ((eq = strchr(s, '=')))
1262 else if ((eq = strchr(s, '~')))
1268 if (len == strlen((const char *)type) &&
1269 !memcmp((const char *) type, s, len))
1271 xmlChar *value = xmlNodeGetContent(n);
1272 if (value && *value)
1275 (substring && strstr((const char *) value, eq+1)) ||
1276 (!substring && !strcmp((const char *) value, eq + 1)))
1289 static int ingest_to_cluster(struct client *cl,
1293 const char *mergekey_norm);
1295 /** \brief ingest XML record
1296 \param cl client holds the result set for record
1297 \param rec record buffer (0 terminated)
1298 \param record_no record position (1, 2, ..)
1299 \param nmem working NMEM
1304 int ingest_record(struct client *cl, const char *rec,
1305 int record_no, NMEM nmem)
1307 struct session *se = client_get_session(cl);
1309 struct session_database *sdb = client_get_database(cl);
1310 struct conf_service *service = se->service;
1311 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1313 const char *mergekey_norm;
1318 root = xmlDocGetRootElement(xdoc);
1320 if (!check_record_filter(root, sdb))
1322 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1323 record_no, sdb->database->url);
1328 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1331 session_log(se, YLOG_WARN, "Got no mergekey");
1336 if (client_get_session(cl) == se)
1337 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1344 static int ingest_to_cluster(struct client *cl,
1348 const char *mergekey_norm)
1353 struct session_database *sdb = client_get_database(cl);
1354 struct session *se = client_get_session(cl);
1355 struct conf_service *service = se->service;
1356 struct record *record = record_create(se->nmem,
1357 service->num_metadata,
1358 service->num_sortkeys, cl,
1360 struct record_cluster *cluster = reclist_insert(se->reclist,
1366 const char *use_term_factor_str = session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1367 int use_term_factor = 0;
1368 int term_factor = 1;
1369 if (use_term_factor_str && use_term_factor_str[0] != 0)
1370 use_term_factor = atoi(use_term_factor_str);
1371 if (use_term_factor) {
1372 int maxrecs = client_get_maxrecs(cl);
1373 int hits = (int) client_get_hits(cl);
1374 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1375 assert(term_factor >= 1);
1376 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1381 if (global_parameters.dump_records)
1382 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1383 sdb->database->url, record_no);
1384 relevance_newrec(se->relevance, cluster);
1386 // now parsing XML record and adding data to cluster or record metadata
1387 for (n = root->children; n; n = n->next)
1389 pp2_charset_token_t prt;
1396 if (n->type != XML_ELEMENT_NODE)
1398 if (!strcmp((const char *) n->name, "metadata"))
1400 struct conf_metadata *ser_md = 0;
1401 struct conf_sortkey *ser_sk = 0;
1402 struct record_metadata **wheretoput = 0;
1403 struct record_metadata *rec_md = 0;
1404 int md_field_id = -1;
1405 int sk_field_id = -1;
1407 type = xmlGetProp(n, (xmlChar *) "type");
1408 value = xmlNodeListGetString(xdoc, n->children, 1);
1410 if (!type || !value || !*value)
1414 = conf_service_metadata_field_id(service, (const char *) type);
1415 if (md_field_id < 0)
1417 if (se->number_of_warnings_unknown_metadata == 0)
1419 session_log(se, YLOG_WARN,
1420 "Ignoring unknown metadata element: %s", type);
1422 se->number_of_warnings_unknown_metadata++;
1426 ser_md = &service->metadata[md_field_id];
1428 if (ser_md->sortkey_offset >= 0){
1429 sk_field_id = ser_md->sortkey_offset;
1430 ser_sk = &service->sortkeys[sk_field_id];
1433 // non-merged metadata
1434 rec_md = record_metadata_init(se->nmem, (const char *) value,
1435 ser_md->type, n->properties);
1438 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1439 "for element '%s'", value, type);
1442 wheretoput = &record->metadata[md_field_id];
1444 wheretoput = &(*wheretoput)->next;
1445 *wheretoput = rec_md;
1448 rec_md = record_metadata_init(se->nmem, (const char *) value,
1450 wheretoput = &cluster->metadata[md_field_id];
1452 // and polulate with data:
1453 // assign cluster or record based on merge action
1454 if (ser_md->merge == Metadata_merge_unique)
1458 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1459 rec_md->data.text.disp))
1461 wheretoput = &(*wheretoput)->next;
1464 *wheretoput = rec_md;
1466 else if (ser_md->merge == Metadata_merge_longest)
1469 || strlen(rec_md->data.text.disp)
1470 > strlen((*wheretoput)->data.text.disp))
1472 *wheretoput = rec_md;
1475 const char *sort_str = 0;
1477 ser_sk->type == Metadata_sortkey_skiparticle;
1479 if (!cluster->sortkeys[sk_field_id])
1480 cluster->sortkeys[sk_field_id] =
1481 nmem_malloc(se->nmem,
1482 sizeof(union data_types));
1485 pp2_charset_token_create(service->charsets, "sort");
1487 pp2_charset_token_first(prt, rec_md->data.text.disp,
1490 pp2_charset_token_next(prt);
1492 sort_str = pp2_get_sort(prt);
1494 cluster->sortkeys[sk_field_id]->text.disp =
1495 rec_md->data.text.disp;
1498 sort_str = rec_md->data.text.disp;
1499 session_log(se, YLOG_WARN,
1500 "Could not make sortkey. Bug #1858");
1502 cluster->sortkeys[sk_field_id]->text.sort =
1503 nmem_strdup(se->nmem, sort_str);
1504 pp2_charset_token_destroy(prt);
1508 else if (ser_md->merge == Metadata_merge_all)
1511 wheretoput = &(*wheretoput)->next;
1512 *wheretoput = rec_md;
1514 else if (ser_md->merge == Metadata_merge_range)
1518 *wheretoput = rec_md;
1520 cluster->sortkeys[sk_field_id]
1525 int this_min = rec_md->data.number.min;
1526 int this_max = rec_md->data.number.max;
1527 if (this_min < (*wheretoput)->data.number.min)
1528 (*wheretoput)->data.number.min = this_min;
1529 if (this_max > (*wheretoput)->data.number.max)
1530 (*wheretoput)->data.number.max = this_max;
1535 // ranking of _all_ fields enabled ...
1537 relevance_countwords(se->relevance, cluster,
1538 (char *) value, ser_md->rank,
1541 // construct facets ... unless the client already has reported them
1542 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1544 if (ser_md->type == Metadata_type_year)
1547 sprintf(year, "%d", rec_md->data.number.max);
1549 add_facet(se, (char *) type, year, term_factor);
1550 if (rec_md->data.number.max != rec_md->data.number.min)
1552 sprintf(year, "%d", rec_md->data.number.min);
1553 add_facet(se, (char *) type, year, term_factor);
1557 add_facet(se, (char *) type, (char *) value, term_factor);
1567 if (se->number_of_warnings_unknown_elements == 0)
1568 session_log(se, YLOG_WARN,
1569 "Unexpected element in internal record: %s", n->name);
1570 se->number_of_warnings_unknown_elements++;
1578 relevance_donerecord(se->relevance, cluster);
1579 se->total_records++;
1584 void session_log(struct session *s, int level, const char *fmt, ...)
1590 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1591 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1599 * c-file-style: "Stroustrup"
1600 * indent-tabs-mode: nil
1602 * vim: shiftwidth=4 tabstop=8 expandtab