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 sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
118 int sessions_count(void)
120 return session_use(0);
123 int session_count_total(void)
126 if (!g_session_mutex)
128 yaz_mutex_enter(g_session_mutex);
129 total = no_session_total;
130 yaz_mutex_leave(g_session_mutex);
134 static void log_xml_doc(xmlDoc *doc)
136 FILE *lf = yaz_log_file();
139 #if LIBXML_VERSION >= 20600
140 xmlDocDumpFormatMemory(doc, &result, &len, 1);
142 xmlDocDumpMemory(doc, &result, &len);
146 (void) fwrite(result, 1, len, lf);
152 static void session_enter(struct session *s)
154 yaz_mutex_enter(s->session_mutex);
157 static void session_leave(struct session *s)
159 yaz_mutex_leave(s->session_mutex);
162 static void session_normalize_facet(struct session *s, const char *type,
167 struct conf_service *service = s->service;
168 pp2_charset_token_t prt;
169 const char *facet_component;
171 const char *icu_chain_id = 0;
173 for (i = 0; i < service->num_metadata; i++)
174 if (!strcmp((service->metadata + i)->name, type))
175 icu_chain_id = (service->metadata + i)->facetrule;
177 icu_chain_id = "facet";
178 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
181 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
183 wrbuf_destroy(facet_wrbuf);
184 wrbuf_destroy(display_wrbuf);
187 pp2_charset_token_first(prt, value, 0);
188 while ((facet_component = pp2_charset_token_next(prt)))
190 const char *display_component;
191 if (*facet_component)
193 if (wrbuf_len(facet_wrbuf))
194 wrbuf_puts(facet_wrbuf, " ");
195 wrbuf_puts(facet_wrbuf, facet_component);
197 display_component = pp2_get_display(prt);
198 if (display_component)
200 if (wrbuf_len(display_wrbuf))
201 wrbuf_puts(display_wrbuf, " ");
202 wrbuf_puts(display_wrbuf, display_component);
205 pp2_charset_token_destroy(prt);
208 void add_facet(struct session *s, const char *type, const char *value, int count)
210 WRBUF facet_wrbuf = wrbuf_alloc();
211 WRBUF display_wrbuf = wrbuf_alloc();
213 session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
215 if (wrbuf_len(facet_wrbuf))
218 for (i = 0; i < s->num_termlists; i++)
219 if (!strcmp(s->termlists[i].name, type))
221 if (i == s->num_termlists)
223 if (i == SESSION_MAX_TERMLISTS)
225 session_log(s, YLOG_FATAL, "Too many termlists");
226 wrbuf_destroy(facet_wrbuf);
227 wrbuf_destroy(display_wrbuf);
231 s->termlists[i].name = nmem_strdup(s->nmem, type);
232 s->termlists[i].termlist
233 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
234 s->num_termlists = i + 1;
238 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
240 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
241 wrbuf_cstr(facet_wrbuf), count);
243 wrbuf_destroy(facet_wrbuf);
244 wrbuf_destroy(display_wrbuf);
247 static xmlDoc *record_to_xml(struct session *se,
248 struct session_database *sdb, const char *rec)
250 struct database *db = sdb->database;
253 rdoc = xmlParseMemory(rec, strlen(rec));
257 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
262 if (global_parameters.dump_records)
264 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
271 #define MAX_XSLT_ARGS 16
273 // Add static values from session database settings if applicable
274 static void insert_settings_parameters(struct session_database *sdb,
275 struct conf_service *service,
283 for (i = 0; i < service->num_metadata; i++)
285 struct conf_metadata *md = &service->metadata[i];
288 if (md->setting == Metadata_setting_parameter &&
289 (setting = settings_lookup_offset(service, md->name)) >= 0)
291 const char *val = session_setting_oneval(sdb, setting);
292 if (val && nparms < MAX_XSLT_ARGS)
295 int len = strlen(val);
296 buf = nmem_malloc(nmem, len + 3);
298 strcpy(buf + 1, val);
301 parms[offset++] = md->name;
302 parms[offset++] = buf;
310 // Add static values from session database settings if applicable
311 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
312 struct conf_service *service)
316 for (i = 0; i < service->num_metadata; i++)
318 struct conf_metadata *md = &service->metadata[i];
321 if (md->setting == Metadata_setting_postproc &&
322 (offset = settings_lookup_offset(service, md->name)) >= 0)
324 const char *val = session_setting_oneval(sdb, offset);
327 xmlNode *r = xmlDocGetRootElement(doc);
328 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
330 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
336 static xmlDoc *normalize_record(struct session *se,
337 struct session_database *sdb,
338 struct conf_service *service,
339 const char *rec, NMEM nmem)
341 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
345 char *parms[MAX_XSLT_ARGS*2+1];
347 insert_settings_parameters(sdb, service, parms, nmem);
349 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
351 session_log(se, YLOG_WARN, "Normalize failed from %s",
356 insert_settings_values(sdb, rdoc, service);
358 if (global_parameters.dump_records)
360 session_log(se, YLOG_LOG, "Normalized record from %s",
369 void session_settings_dump(struct session *se,
370 struct session_database *db,
375 int i, num = db->num_settings;
376 for (i = 0; i < num; i++)
378 struct setting *s = db->settings[i];
379 for (;s ; s = s->next)
381 wrbuf_puts(w, "<set name=\"");
382 wrbuf_xmlputs(w, s->name);
383 wrbuf_puts(w, "\" value=\"");
384 wrbuf_xmlputs(w, s->value);
385 wrbuf_puts(w, "\"/>");
393 // Retrieve first defined value for 'name' for given database.
394 // Will be extended to take into account user associated with session
395 const char *session_setting_oneval(struct session_database *db, int offset)
397 if (offset >= db->num_settings || !db->settings[offset])
399 return db->settings[offset]->value;
402 // Prepare XSLT stylesheets for record normalization
403 // Structures are allocated on the session_wide nmem to avoid having
404 // to recompute this for every search. This would lead
405 // to leaking if a single session was to repeatedly change the PZ_XSLT
406 // setting. However, this is not a realistic use scenario.
407 static int prepare_map(struct session *se, struct session_database *sdb)
411 if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
412 (s = session_setting_oneval(sdb, PZ_XSLT)))
414 char auto_stylesheet[256];
416 if (!strcmp(s, "auto"))
418 const char *request_syntax = session_setting_oneval(
419 sdb, PZ_REQUESTSYNTAX);
423 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
424 "%s.xsl", request_syntax);
425 for (cp = auto_stylesheet; *cp; cp++)
427 /* deliberately only consider ASCII */
428 if (*cp > 32 && *cp < 127)
435 session_log(se, YLOG_WARN,
436 "No pz:requestsyntax for auto stylesheet");
439 sdb->map = normalize_cache_get(se->normalize_cache,
447 // called if watch should be removed because http_channel is to be destroyed
448 static void session_watch_cancel(void *data, struct http_channel *c,
451 struct session_watchentry *ent = data;
458 // set watch. Returns 0=OK, -1 if watch is already set
459 int session_set_watch(struct session *s, int what,
460 session_watchfun fun, void *data,
461 struct http_channel *chan)
465 if (s->watchlist[what].fun)
470 s->watchlist[what].fun = fun;
471 s->watchlist[what].data = data;
472 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
473 session_watch_cancel);
480 void session_alert_watch(struct session *s, int what)
484 if (s->watchlist[what].fun)
486 /* our watch is no longer associated with http_channel */
488 session_watchfun fun;
490 http_remove_observer(s->watchlist[what].obs);
491 fun = s->watchlist[what].fun;
492 data = s->watchlist[what].data;
494 /* reset watch before fun is invoked - in case fun wants to set
496 s->watchlist[what].fun = 0;
497 s->watchlist[what].data = 0;
498 s->watchlist[what].obs = 0;
501 session_log(s, YLOG_DEBUG,
502 "Alert Watch: %d calling function: %p", what, fun);
509 //callback for grep_databases
510 static void select_targets_callback(struct session *se,
511 struct session_database *db)
514 struct client_list *l;
516 for (l = se->clients_cached; l; l = l->next)
517 if (client_get_database(l->client) == db)
524 cl = client_create(db->database->id);
525 client_set_database(cl, db);
526 client_set_session(cl, se);
528 l = xmalloc(sizeof(*l));
530 l->next = se->clients_cached;
531 se->clients_cached = l;
534 l = xmalloc(sizeof(*l));
536 l->next = se->clients_active;
537 se->clients_active = l;
540 static void session_reset_active_clients(struct session *se,
541 struct client_list *new_list)
543 struct client_list *l;
546 l = se->clients_active;
547 se->clients_active = new_list;
552 struct client_list *l_next = l->next;
558 static void session_remove_cached_clients(struct session *se)
560 struct client_list *l;
562 session_reset_active_clients(se, 0);
565 l = se->clients_cached;
566 se->clients_cached = 0;
571 struct client_list *l_next = l->next;
572 client_lock(l->client);
573 client_set_session(l->client, 0);
574 client_set_database(l->client, 0);
575 client_unlock(l->client);
576 client_destroy(l->client);
582 // Associates a set of clients with a session;
583 // Note: Session-databases represent databases with per-session
585 static int select_targets(struct session *se, const char *filter)
587 return session_grep_databases(se, filter, select_targets_callback);
590 int session_active_clients(struct session *s)
592 struct client_list *l;
595 for (l = s->clients_active; l; l = l->next)
596 if (client_is_active(l->client))
602 int session_is_preferred_clients_ready(struct session *s)
604 struct client_list *l;
607 for (l = s->clients_active; l; l = l->next)
608 if (client_is_active_preferred(l->client))
610 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
614 void session_sort(struct session *se, const char *field, int increasing)
616 struct session_sorted_results *sr;
617 struct client_list *l;
621 /* see if we already have sorted for this critieria */
622 for (sr = se->sorted_results; sr; sr = sr->next)
624 if (!strcmp(field, sr->field) && increasing == sr->increasing)
629 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
634 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
636 sr = nmem_malloc(se->nmem, sizeof(*sr));
637 sr->field = nmem_strdup(se->nmem, field);
638 sr->increasing = increasing;
639 sr->next = se->sorted_results;
640 se->sorted_results = sr;
642 for (l = se->clients_active; l; l = l->next)
644 struct client *cl = l->client;
646 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
647 se->service->z3950_session_timeout,
648 se->service->server->iochan_man,
650 client_start_search(cl);
655 enum pazpar2_error_code session_search(struct session *se,
657 const char *startrecs,
661 const char **addinfo,
662 const char *sort_field, int increasing)
664 int live_channels = 0;
666 int no_failed_query = 0;
667 int no_failed_limit = 0;
668 struct client_list *l, *l0;
670 facet_limits_t facet_limits;
672 session_log(se, YLOG_DEBUG, "Search");
676 if (se->settings_modified)
677 session_remove_cached_clients(se);
679 session_reset_active_clients(se, 0);
682 reclist_destroy(se->reclist);
684 se->settings_modified = 0;
685 relevance_destroy(&se->relevance);
686 nmem_reset(se->nmem);
687 se->total_records = se->total_merged = 0;
688 se->num_termlists = 0;
690 /* reset list of sorted results and clear to relevance search */
691 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
692 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
693 se->sorted_results->increasing = increasing;
694 se->sorted_results->next = 0;
696 live_channels = select_targets(se, filter);
700 return PAZPAR2_NO_TARGETS;
702 se->reclist = reclist_create(se->nmem);
704 yaz_gettimeofday(&tval);
708 facet_limits = facet_limits_create(limit);
713 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
716 l0 = se->clients_active;
717 se->clients_active = 0;
720 for (l = l0; l; l = l->next)
723 struct client *cl = l->client;
725 if (prepare_map(se, client_get_database(cl)) < 0)
728 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
732 else if (parse_ret == -2)
737 client_prep_connection(cl, se->service->z3950_operation_timeout,
738 se->service->z3950_session_timeout,
739 se->service->server->iochan_man,
741 if (parse_ret == 1 && r == 2)
743 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
748 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
749 client_start_search(cl);
754 facet_limits_destroy(facet_limits);
755 session_reset_active_clients(se, l0);
759 if (no_failed_query > 0)
762 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
764 else if (no_failed_limit > 0)
767 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
770 return PAZPAR2_NO_TARGETS;
772 yaz_log(YLOG_LOG, "session_start_search done");
773 return PAZPAR2_NO_ERROR;
776 // Creates a new session_database object for a database
777 static void session_init_databases_fun(void *context, struct database *db)
779 struct session *se = (struct session *) context;
780 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
786 assert(db->settings);
787 new->settings = nmem_malloc(se->session_nmem,
788 sizeof(struct settings *) * db->num_settings);
789 new->num_settings = db->num_settings;
790 for (i = 0; i < db->num_settings; i++)
792 struct setting *setting = db->settings[i];
793 new->settings[i] = setting;
795 new->next = se->databases;
799 // Doesn't free memory associated with sdb -- nmem takes care of that
800 static void session_database_destroy(struct session_database *sdb)
805 // Initialize session_database list -- this represents this session's view
806 // of the database list -- subject to modification by the settings ws command
807 void session_init_databases(struct session *se)
810 predef_grep_databases(se, se->service, session_init_databases_fun);
813 // Probably session_init_databases_fun should be refactored instead of
815 static struct session_database *load_session_database(struct session *se,
818 struct database *db = new_database(id, se->session_nmem);
820 session_init_databases_fun((void*) se, db);
822 // New sdb is head of se->databases list
823 return se->databases;
826 // Find an existing session database. If not found, load it
827 static struct session_database *find_session_database(struct session *se,
830 struct session_database *sdb;
832 for (sdb = se->databases; sdb; sdb = sdb->next)
833 if (!strcmp(sdb->database->id, id))
835 return load_session_database(se, id);
838 // Apply a session override to a database
839 void session_apply_setting(struct session *se, char *dbname, char *setting,
842 struct session_database *sdb = find_session_database(se, dbname);
843 struct conf_service *service = se->service;
844 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
845 int offset = settings_create_offset(service, setting);
847 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
850 new->target = dbname;
853 new->next = sdb->settings[offset];
854 sdb->settings[offset] = new;
856 se->settings_modified = 1;
858 // Force later recompute of settings-driven data structures
859 // (happens when a search starts and client connections are prepared)
871 void session_destroy(struct session *se)
873 struct session_database *sdb;
874 session_log(se, YLOG_DEBUG, "Destroying");
876 session_remove_cached_clients(se);
878 for (sdb = se->databases; sdb; sdb = sdb->next)
879 session_database_destroy(sdb);
880 normalize_cache_destroy(se->normalize_cache);
881 relevance_destroy(&se->relevance);
882 reclist_destroy(se->reclist);
883 nmem_destroy(se->nmem);
884 service_destroy(se->service);
885 yaz_mutex_destroy(&se->session_mutex);
888 size_t session_get_memory_status(struct session *session) {
892 session_enter(session);
893 session_nmem = nmem_total(session->nmem);
894 session_leave(session);
899 struct session *new_session(NMEM nmem, struct conf_service *service,
903 struct session *session = nmem_malloc(nmem, sizeof(*session));
907 sprintf(tmp_str, "session#%u", session_id);
909 session->session_id = session_id;
910 session_log(session, YLOG_DEBUG, "New");
911 session->service = service;
912 session->relevance = 0;
913 session->total_records = 0;
914 session->number_of_warnings_unknown_elements = 0;
915 session->number_of_warnings_unknown_metadata = 0;
916 session->num_termlists = 0;
917 session->reclist = 0;
918 session->clients_active = 0;
919 session->clients_cached = 0;
920 session->settings_modified = 0;
921 session->session_nmem = nmem;
922 session->nmem = nmem_create();
923 session->databases = 0;
924 for (i = 0; i <= SESSION_WATCH_MAX; i++)
926 session->watchlist[i].data = 0;
927 session->watchlist[i].fun = 0;
929 session->normalize_cache = normalize_cache_create();
930 session->session_mutex = 0;
931 pazpar2_mutex_create(&session->session_mutex, tmp_str);
936 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
938 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
939 int *count, NMEM nmem)
941 struct hitsbytarget *res = 0;
942 struct client_list *l;
945 for (l = se->clients_active; l; l = l->next)
948 res = nmem_malloc(nmem, sizeof(*res) * sz);
950 for (l = se->clients_active; l; l = l->next)
952 struct client *cl = l->client;
953 WRBUF w = wrbuf_alloc();
954 const char *name = session_setting_oneval(client_get_database(cl),
957 res[*count].id = client_get_id(cl);
958 res[*count].name = *name ? name : "Unknown";
959 res[*count].hits = client_get_hits(cl);
960 res[*count].records = client_get_num_records(cl);
961 res[*count].diagnostic =
962 client_get_diagnostic(cl, &res[*count].addinfo);
963 res[*count].state = client_get_state_str(cl);
964 res[*count].connected = client_get_connection(cl) ? 1 : 0;
965 session_settings_dump(se, client_get_database(cl), w);
966 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
969 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
976 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
978 struct hitsbytarget *p;
980 p = hitsbytarget_nb(se, count, nmem);
985 struct termlist_score **get_termlist_score(struct session *se,
986 const char *name, int *num)
989 struct termlist_score **tl = 0;
992 for (i = 0; i < se->num_termlists; i++)
993 if (!strcmp((const char *) se->termlists[i].name, name))
995 tl = termlist_highscore(se->termlists[i].termlist, num);
1002 // Compares two hitsbytarget nodes by hitcount
1003 static int cmp_ht(const void *p1, const void *p2)
1005 const struct hitsbytarget *h1 = p1;
1006 const struct hitsbytarget *h2 = p2;
1007 return h2->hits - h1->hits;
1010 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1013 struct hitsbytarget *ht;
1016 ht = hitsbytarget_nb(se, &count, nmem);
1017 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1018 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1021 // do only print terms which have display names
1023 wrbuf_puts(wrbuf, "<term>\n");
1025 wrbuf_puts(wrbuf, "<id>");
1026 wrbuf_xmlputs(wrbuf, ht[i].id);
1027 wrbuf_puts(wrbuf, "</id>\n");
1029 wrbuf_puts(wrbuf, "<name>");
1030 if (!ht[i].name || !ht[i].name[0])
1031 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1033 wrbuf_xmlputs(wrbuf, ht[i].name);
1034 wrbuf_puts(wrbuf, "</name>\n");
1036 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1039 wrbuf_puts(wrbuf, "<state>");
1040 wrbuf_xmlputs(wrbuf, ht[i].state);
1041 wrbuf_puts(wrbuf, "</state>\n");
1043 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1045 wrbuf_puts(wrbuf, "</term>\n");
1050 void perform_termlist(struct http_channel *c, struct session *se,
1051 const char *name, int num)
1054 NMEM nmem_tmp = nmem_create();
1061 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1065 for (j = 0; j < num_names; j++)
1069 for (i = 0; i < se->num_termlists; i++)
1071 tname = se->termlists[i].name;
1072 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1074 struct termlist_score **p = 0;
1077 wrbuf_puts(c->wrbuf, "<list name=\"");
1078 wrbuf_xmlputs(c->wrbuf, tname);
1079 wrbuf_puts(c->wrbuf, "\">\n");
1081 p = termlist_highscore(se->termlists[i].termlist, &len);
1085 for (i = 0; i < len && i < num; i++)
1087 // prevent sending empty term elements
1088 if (!p[i]->display_term || !p[i]->display_term[0])
1091 wrbuf_puts(c->wrbuf, "<term>");
1092 wrbuf_puts(c->wrbuf, "<name>");
1093 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1094 wrbuf_puts(c->wrbuf, "</name>");
1096 wrbuf_printf(c->wrbuf,
1097 "<frequency>%d</frequency>",
1099 wrbuf_puts(c->wrbuf, "</term>\n");
1102 wrbuf_puts(c->wrbuf, "</list>\n");
1106 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1108 wrbuf_puts(c->wrbuf, "<list name=\"");
1109 wrbuf_xmlputs(c->wrbuf, tname);
1110 wrbuf_puts(c->wrbuf, "\">\n");
1112 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1113 wrbuf_puts(c->wrbuf, "</list>\n");
1117 nmem_destroy(nmem_tmp);
1120 #ifdef MISSING_HEADERS
1121 void report_nmem_stats(void)
1123 size_t in_use, is_free;
1125 nmem_get_memory_in_use(&in_use);
1126 nmem_get_memory_free(&is_free);
1128 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1129 (long) in_use, (long) is_free);
1133 struct record_cluster *show_single_start(struct session *se, const char *id,
1134 struct record_cluster **prev_r,
1135 struct record_cluster **next_r)
1137 struct record_cluster *r = 0;
1144 reclist_enter(se->reclist);
1145 while ((r = reclist_read_record(se->reclist)))
1147 if (!strcmp(r->recid, id))
1149 *next_r = reclist_read_record(se->reclist);
1154 reclist_leave(se->reclist);
1161 void show_single_stop(struct session *se, struct record_cluster *rec)
1166 struct record_cluster **show_range_start(struct session *se,
1167 struct reclist_sortparms *sp,
1168 int start, int *num, int *total, Odr_int *sumhits)
1170 struct record_cluster **recs;
1171 struct reclist_sortparms *spp;
1174 yaz_timing_t t = yaz_timing_create();
1177 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1187 struct client_list *l;
1189 for (spp = sp; spp; spp = spp->next)
1190 if (spp->type == Metadata_sortkey_relevance)
1192 relevance_prepare_read(se->relevance, se->reclist);
1195 reclist_sort(se->reclist, sp);
1197 reclist_enter(se->reclist);
1198 *total = reclist_get_num_records(se->reclist);
1201 for (l = se->clients_active; l; l = l->next)
1202 *sumhits += client_get_hits(l->client);
1204 for (i = 0; i < start; i++)
1205 if (!reclist_read_record(se->reclist))
1212 for (i = 0; i < *num; i++)
1214 struct record_cluster *r = reclist_read_record(se->reclist);
1222 reclist_leave(se->reclist);
1226 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1227 yaz_timing_get_real(t), yaz_timing_get_user(t),
1228 yaz_timing_get_sys(t));
1229 yaz_timing_destroy(&t);
1234 void show_range_stop(struct session *se, struct record_cluster **recs)
1239 void statistics(struct session *se, struct statistics *stat)
1241 struct client_list *l;
1244 memset(stat, 0, sizeof(*stat));
1246 for (l = se->clients_active; l; l = l->next)
1248 struct client *cl = l->client;
1249 if (!client_get_connection(cl))
1250 stat->num_no_connection++;
1251 stat->num_hits += client_get_hits(cl);
1252 switch (client_get_state(cl))
1254 case Client_Connecting: stat->num_connecting++; break;
1255 case Client_Working: stat->num_working++; break;
1256 case Client_Idle: stat->num_idle++; break;
1257 case Client_Failed: stat->num_failed++; break;
1258 case Client_Error: stat->num_error++; break;
1263 stat->num_records = se->total_records;
1265 stat->num_clients = count;
1268 static struct record_metadata *record_metadata_init(
1269 NMEM nmem, const char *value, enum conf_metadata_type type,
1270 struct _xmlAttr *attr)
1272 struct record_metadata *rec_md = record_metadata_create(nmem);
1273 struct record_metadata_attr **attrp = &rec_md->attributes;
1275 for (; attr; attr = attr->next)
1277 if (attr->children && attr->children->content)
1279 if (strcmp((const char *) attr->name, "type"))
1280 { /* skip the "type" attribute.. Its value is already part of
1281 the element in output (md-%s) and so repeating it here
1283 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1285 nmem_strdup(nmem, (const char *) attr->name);
1287 nmem_strdup(nmem, (const char *) attr->children->content);
1288 attrp = &(*attrp)->next;
1294 if (type == Metadata_type_generic)
1296 char *p = nmem_strdup(nmem, value);
1298 p = normalize7bit_generic(p, " ,/.:([");
1300 rec_md->data.text.disp = p;
1301 rec_md->data.text.sort = 0;
1303 else if (type == Metadata_type_year || type == Metadata_type_date)
1308 if (type == Metadata_type_date)
1310 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1313 rec_md->data.number.min = first;
1314 rec_md->data.number.max = last;
1321 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1322 struct conf_service *service, WRBUF norm_wr)
1326 for (n = root->children; n; n = n->next)
1328 if (n->type != XML_ELEMENT_NODE)
1330 if (!strcmp((const char *) n->name, "metadata"))
1332 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1334 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1336 else if (!strcmp(name, (const char *) type))
1338 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1341 const char *norm_str;
1342 pp2_charset_token_t prt =
1343 pp2_charset_token_create(service->charsets, "mergekey");
1345 pp2_charset_token_first(prt, (const char *) value, 0);
1346 if (wrbuf_len(norm_wr) > 0)
1347 wrbuf_puts(norm_wr, " ");
1348 wrbuf_puts(norm_wr, name);
1350 pp2_charset_token_next(prt)))
1354 wrbuf_puts(norm_wr, " ");
1355 wrbuf_puts(norm_wr, norm_str);
1359 pp2_charset_token_destroy(prt);
1369 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1370 struct conf_service *service, NMEM nmem)
1372 char *mergekey_norm = 0;
1373 xmlNode *root = xmlDocGetRootElement(doc);
1374 WRBUF norm_wr = wrbuf_alloc();
1376 /* consider mergekey from XSL first */
1377 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1380 const char *norm_str;
1381 pp2_charset_token_t prt =
1382 pp2_charset_token_create(service->charsets, "mergekey");
1384 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1385 while ((norm_str = pp2_charset_token_next(prt)))
1389 if (wrbuf_len(norm_wr))
1390 wrbuf_puts(norm_wr, " ");
1391 wrbuf_puts(norm_wr, norm_str);
1394 pp2_charset_token_destroy(prt);
1399 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1401 for (field_id = 0; field_id < service->num_metadata; field_id++)
1403 struct conf_metadata *ser_md = &service->metadata[field_id];
1404 if (ser_md->mergekey != Metadata_mergekey_no)
1406 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1408 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1410 /* no mergekey on this one and it is required..
1411 Generate unique key instead */
1412 wrbuf_rewind(norm_wr);
1419 /* generate unique key if none is not generated already or is empty */
1420 if (wrbuf_len(norm_wr) == 0)
1422 wrbuf_printf(norm_wr, "position: %s-%d",
1423 client_get_id(cl), record_no);
1427 const char *lead = "content: ";
1428 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1430 if (wrbuf_len(norm_wr) > 0)
1431 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1432 wrbuf_destroy(norm_wr);
1433 return mergekey_norm;
1436 /** \brief see if metadata for pz:recordfilter exists
1437 \param root xml root element of normalized record
1438 \param sdb session database for client
1439 \retval 0 if there is no metadata for pz:recordfilter
1440 \retval 1 if there is metadata for pz:recordfilter
1442 If there is no pz:recordfilter defined, this function returns 1
1446 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1451 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1456 for (n = root->children; n; n = n->next)
1458 if (n->type != XML_ELEMENT_NODE)
1460 if (!strcmp((const char *) n->name, "metadata"))
1462 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1469 if ((eq = strchr(s, '=')))
1471 else if ((eq = strchr(s, '~')))
1477 if (len == strlen((const char *)type) &&
1478 !memcmp((const char *) type, s, len))
1480 xmlChar *value = xmlNodeGetContent(n);
1481 if (value && *value)
1484 (substring && strstr((const char *) value, eq+1)) ||
1485 (!substring && !strcmp((const char *) value, eq + 1)))
1498 static int ingest_to_cluster(struct client *cl,
1502 const char *mergekey_norm);
1504 /** \brief ingest XML record
1505 \param cl client holds the result set for record
1506 \param rec record buffer (0 terminated)
1507 \param record_no record position (1, 2, ..)
1508 \param nmem working NMEM
1513 int ingest_record(struct client *cl, const char *rec,
1514 int record_no, NMEM nmem)
1516 struct session *se = client_get_session(cl);
1518 struct session_database *sdb = client_get_database(cl);
1519 struct conf_service *service = se->service;
1520 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1522 const char *mergekey_norm;
1527 root = xmlDocGetRootElement(xdoc);
1529 if (!check_record_filter(root, sdb))
1531 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1532 record_no, sdb->database->id);
1537 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1540 session_log(se, YLOG_WARN, "Got no mergekey");
1545 if (client_get_session(cl) == se)
1546 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1553 static int check_limit_local(struct client *cl,
1554 struct record *record,
1557 int skip_record = 0;
1558 struct session *se = client_get_session(cl);
1559 struct conf_service *service = se->service;
1560 NMEM nmem_tmp = nmem_create();
1561 struct session_database *sdb = client_get_database(cl);
1563 while (!skip_record)
1565 struct conf_metadata *ser_md = 0;
1566 struct record_metadata *rec_md = 0;
1572 client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v,
1577 md_field_id = conf_service_metadata_field_id(service, name);
1578 if (md_field_id < 0)
1583 ser_md = &service->metadata[md_field_id];
1584 rec_md = record->metadata[md_field_id];
1585 yaz_log(YLOG_LOG, "check limit local %s", name);
1586 for (i = 0; i < num_v; )
1590 if (ser_md->type == Metadata_type_year
1591 || ser_md->type == Metadata_type_date)
1593 int y = atoi(values[i]);
1594 if (y >= rec_md->data.number.min
1595 && y <= rec_md->data.number.max)
1600 yaz_log(YLOG_LOG, "cmp: '%s' '%s'",
1601 rec_md->data.text.disp, values[i]);
1602 if (!strcmp(rec_md->data.text.disp, values[i]))
1607 rec_md = rec_md->next;
1611 rec_md = record->metadata[md_field_id];
1621 nmem_destroy(nmem_tmp);
1625 static int ingest_to_cluster(struct client *cl,
1629 const char *mergekey_norm)
1634 struct session *se = client_get_session(cl);
1635 struct conf_service *service = se->service;
1636 int term_factor = 1;
1637 struct record_cluster *cluster;
1638 struct session_database *sdb = client_get_database(cl);
1639 struct record *record = record_create(se->nmem,
1640 service->num_metadata,
1641 service->num_sortkeys, cl,
1644 for (n = root->children; n; n = n->next)
1652 if (n->type != XML_ELEMENT_NODE)
1654 if (!strcmp((const char *) n->name, "metadata"))
1656 struct conf_metadata *ser_md = 0;
1657 struct record_metadata **wheretoput = 0;
1658 struct record_metadata *rec_md = 0;
1659 int md_field_id = -1;
1661 type = xmlGetProp(n, (xmlChar *) "type");
1662 value = xmlNodeListGetString(xdoc, n->children, 1);
1664 if (!type || !value || !*value)
1668 = conf_service_metadata_field_id(service, (const char *) type);
1669 if (md_field_id < 0)
1671 if (se->number_of_warnings_unknown_metadata == 0)
1673 session_log(se, YLOG_WARN,
1674 "Ignoring unknown metadata element: %s", type);
1676 se->number_of_warnings_unknown_metadata++;
1680 ser_md = &service->metadata[md_field_id];
1682 // non-merged metadata
1683 rec_md = record_metadata_init(se->nmem, (const char *) value,
1684 ser_md->type, n->properties);
1687 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1688 "for element '%s'", value, type);
1691 wheretoput = &record->metadata[md_field_id];
1693 wheretoput = &(*wheretoput)->next;
1694 *wheretoput = rec_md;
1698 if (check_limit_local(cl, record, record_no))
1700 session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1701 record_no, sdb->database->id);
1708 cluster = reclist_insert(se->reclist, service, record,
1709 mergekey_norm, &se->total_merged);
1714 const char *use_term_factor_str =
1715 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1716 if (use_term_factor_str && use_term_factor_str[0] == '1')
1718 int maxrecs = client_get_maxrecs(cl);
1719 int hits = (int) client_get_hits(cl);
1720 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1721 assert(term_factor >= 1);
1722 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1726 if (global_parameters.dump_records)
1727 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1728 sdb->database->id, record_no);
1731 relevance_newrec(se->relevance, cluster);
1733 // now parsing XML record and adding data to cluster or record metadata
1734 for (n = root->children; n; n = n->next)
1736 pp2_charset_token_t prt;
1743 if (n->type != XML_ELEMENT_NODE)
1745 if (!strcmp((const char *) n->name, "metadata"))
1747 struct conf_metadata *ser_md = 0;
1748 struct conf_sortkey *ser_sk = 0;
1749 struct record_metadata **wheretoput = 0;
1750 struct record_metadata *rec_md = 0;
1751 int md_field_id = -1;
1752 int sk_field_id = -1;
1754 type = xmlGetProp(n, (xmlChar *) "type");
1755 value = xmlNodeListGetString(xdoc, n->children, 1);
1757 if (!type || !value || !*value)
1761 = conf_service_metadata_field_id(service, (const char *) type);
1762 if (md_field_id < 0)
1765 ser_md = &service->metadata[md_field_id];
1767 if (ser_md->sortkey_offset >= 0)
1769 sk_field_id = ser_md->sortkey_offset;
1770 ser_sk = &service->sortkeys[sk_field_id];
1774 rec_md = record_metadata_init(se->nmem, (const char *) value,
1779 wheretoput = &cluster->metadata[md_field_id];
1781 // and polulate with data:
1782 // assign cluster or record based on merge action
1783 if (ser_md->merge == Metadata_merge_unique)
1787 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1788 rec_md->data.text.disp))
1790 wheretoput = &(*wheretoput)->next;
1793 *wheretoput = rec_md;
1795 else if (ser_md->merge == Metadata_merge_longest)
1798 || strlen(rec_md->data.text.disp)
1799 > strlen((*wheretoput)->data.text.disp))
1801 *wheretoput = rec_md;
1804 const char *sort_str = 0;
1806 ser_sk->type == Metadata_sortkey_skiparticle;
1808 if (!cluster->sortkeys[sk_field_id])
1809 cluster->sortkeys[sk_field_id] =
1810 nmem_malloc(se->nmem,
1811 sizeof(union data_types));
1814 pp2_charset_token_create(service->charsets, "sort");
1816 pp2_charset_token_first(prt, rec_md->data.text.disp,
1819 pp2_charset_token_next(prt);
1821 sort_str = pp2_get_sort(prt);
1823 cluster->sortkeys[sk_field_id]->text.disp =
1824 rec_md->data.text.disp;
1827 sort_str = rec_md->data.text.disp;
1828 session_log(se, YLOG_WARN,
1829 "Could not make sortkey. Bug #1858");
1831 cluster->sortkeys[sk_field_id]->text.sort =
1832 nmem_strdup(se->nmem, sort_str);
1833 pp2_charset_token_destroy(prt);
1837 else if (ser_md->merge == Metadata_merge_all)
1840 wheretoput = &(*wheretoput)->next;
1841 *wheretoput = rec_md;
1843 else if (ser_md->merge == Metadata_merge_range)
1847 *wheretoput = rec_md;
1849 cluster->sortkeys[sk_field_id]
1854 int this_min = rec_md->data.number.min;
1855 int this_max = rec_md->data.number.max;
1856 if (this_min < (*wheretoput)->data.number.min)
1857 (*wheretoput)->data.number.min = this_min;
1858 if (this_max > (*wheretoput)->data.number.max)
1859 (*wheretoput)->data.number.max = this_max;
1864 // ranking of _all_ fields enabled ...
1866 relevance_countwords(se->relevance, cluster,
1867 (char *) value, ser_md->rank,
1870 // construct facets ... unless the client already has reported them
1871 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1873 if (ser_md->type == Metadata_type_year)
1876 sprintf(year, "%d", rec_md->data.number.max);
1878 add_facet(se, (char *) type, year, term_factor);
1879 if (rec_md->data.number.max != rec_md->data.number.min)
1881 sprintf(year, "%d", rec_md->data.number.min);
1882 add_facet(se, (char *) type, year, term_factor);
1886 add_facet(se, (char *) type, (char *) value, term_factor);
1896 if (se->number_of_warnings_unknown_elements == 0)
1897 session_log(se, YLOG_WARN,
1898 "Unexpected element in internal record: %s", n->name);
1899 se->number_of_warnings_unknown_elements++;
1907 relevance_donerecord(se->relevance, cluster);
1908 se->total_records++;
1913 void session_log(struct session *s, int level, const char *fmt, ...)
1919 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1920 yaz_log(level, "Session %u: %s", s->session_id, buf);
1928 * c-file-style: "Stroustrup"
1929 * indent-tabs-mode: nil
1931 * vim: shiftwidth=4 tabstop=8 expandtab