1 /* This file is part of Pazpar2.
2 Copyright (C) 2006-2012 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 #include <libxml/tree.h>
81 #define TERMLIST_HIGH_SCORE 25
85 #define MAX(a,b) ((a)>(b)?(a):(b))
87 // Note: Some things in this structure will eventually move to configuration
88 struct parameters global_parameters =
92 0, // predictable sessions
96 struct client *client;
97 struct client_list *next;
100 /* session counting (1) , disable client counting (0) */
101 static YAZ_MUTEX g_session_mutex = 0;
102 static int no_sessions = 0;
103 static int no_session_total = 0;
105 static int session_use(int delta)
108 if (!g_session_mutex)
109 yaz_mutex_create(&g_session_mutex);
110 yaz_mutex_enter(g_session_mutex);
111 no_sessions += delta;
113 no_session_total += delta;
114 sessions = no_sessions;
115 yaz_mutex_leave(g_session_mutex);
116 yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
120 int sessions_count(void)
122 return session_use(0);
125 int session_count_total(void)
128 if (!g_session_mutex)
130 yaz_mutex_enter(g_session_mutex);
131 total = no_session_total;
132 yaz_mutex_leave(g_session_mutex);
136 static void log_xml_doc(xmlDoc *doc)
138 FILE *lf = yaz_log_file();
141 #if LIBXML_VERSION >= 20600
142 xmlDocDumpFormatMemory(doc, &result, &len, 1);
144 xmlDocDumpMemory(doc, &result, &len);
148 (void) fwrite(result, 1, len, lf);
154 static void session_enter(struct session *s)
156 yaz_mutex_enter(s->session_mutex);
159 static void session_leave(struct session *s)
161 yaz_mutex_leave(s->session_mutex);
164 static void session_normalize_facet(struct session *s, const char *type,
169 struct conf_service *service = s->service;
170 pp2_charset_token_t prt;
171 const char *facet_component;
173 const char *icu_chain_id = 0;
175 for (i = 0; i < service->num_metadata; i++)
176 if (!strcmp((service->metadata + i)->name, type))
177 icu_chain_id = (service->metadata + i)->facetrule;
179 icu_chain_id = "facet";
180 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
183 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
185 wrbuf_destroy(facet_wrbuf);
186 wrbuf_destroy(display_wrbuf);
189 pp2_charset_token_first(prt, value, 0);
190 while ((facet_component = pp2_charset_token_next(prt)))
192 const char *display_component;
193 if (*facet_component)
195 if (wrbuf_len(facet_wrbuf))
196 wrbuf_puts(facet_wrbuf, " ");
197 wrbuf_puts(facet_wrbuf, facet_component);
199 display_component = pp2_get_display(prt);
200 if (display_component)
202 if (wrbuf_len(display_wrbuf))
203 wrbuf_puts(display_wrbuf, " ");
204 wrbuf_puts(display_wrbuf, display_component);
207 pp2_charset_token_destroy(prt);
210 void add_facet(struct session *s, const char *type, const char *value, int count)
212 WRBUF facet_wrbuf = wrbuf_alloc();
213 WRBUF display_wrbuf = wrbuf_alloc();
215 session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
217 if (wrbuf_len(facet_wrbuf))
220 for (i = 0; i < s->num_termlists; i++)
221 if (!strcmp(s->termlists[i].name, type))
223 if (i == s->num_termlists)
225 if (i == SESSION_MAX_TERMLISTS)
227 session_log(s, YLOG_FATAL, "Too many termlists");
228 wrbuf_destroy(facet_wrbuf);
229 wrbuf_destroy(display_wrbuf);
233 s->termlists[i].name = nmem_strdup(s->nmem, type);
234 s->termlists[i].termlist
235 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
236 s->num_termlists = i + 1;
240 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
242 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
243 wrbuf_cstr(facet_wrbuf), count);
245 wrbuf_destroy(facet_wrbuf);
246 wrbuf_destroy(display_wrbuf);
249 static xmlDoc *record_to_xml(struct session *se,
250 struct session_database *sdb, const char *rec)
252 struct database *db = sdb->database;
255 rdoc = xmlParseMemory(rec, strlen(rec));
259 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
264 if (global_parameters.dump_records)
266 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
273 #define MAX_XSLT_ARGS 16
275 // Add static values from session database settings if applicable
276 static void insert_settings_parameters(struct session_database *sdb,
277 struct conf_service *service,
285 for (i = 0; i < service->num_metadata; i++)
287 struct conf_metadata *md = &service->metadata[i];
290 if (md->setting == Metadata_setting_parameter &&
291 (setting = settings_lookup_offset(service, md->name)) >= 0)
293 const char *val = session_setting_oneval(sdb, setting);
294 if (val && nparms < MAX_XSLT_ARGS)
297 int len = strlen(val);
298 buf = nmem_malloc(nmem, len + 3);
300 strcpy(buf + 1, val);
303 parms[offset++] = md->name;
304 parms[offset++] = buf;
312 // Add static values from session database settings if applicable
313 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
314 struct conf_service *service)
318 for (i = 0; i < service->num_metadata; i++)
320 struct conf_metadata *md = &service->metadata[i];
323 if (md->setting == Metadata_setting_postproc &&
324 (offset = settings_lookup_offset(service, md->name)) >= 0)
326 const char *val = session_setting_oneval(sdb, offset);
329 xmlNode *r = xmlDocGetRootElement(doc);
330 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
332 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
338 static xmlDoc *normalize_record(struct session *se,
339 struct session_database *sdb,
340 struct conf_service *service,
341 const char *rec, NMEM nmem)
343 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
347 char *parms[MAX_XSLT_ARGS*2+1];
349 insert_settings_parameters(sdb, service, parms, nmem);
351 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
353 session_log(se, YLOG_WARN, "Normalize failed from %s",
358 insert_settings_values(sdb, rdoc, service);
360 if (global_parameters.dump_records)
362 session_log(se, YLOG_LOG, "Normalized record from %s",
371 void session_settings_dump(struct session *se,
372 struct session_database *db,
377 int i, num = db->num_settings;
378 for (i = 0; i < num; i++)
380 struct setting *s = db->settings[i];
381 for (;s ; s = s->next)
383 wrbuf_puts(w, "<set name=\"");
384 wrbuf_xmlputs(w, s->name);
385 wrbuf_puts(w, "\" value=\"");
386 wrbuf_xmlputs(w, s->value);
387 wrbuf_puts(w, "\"/>");
395 // Retrieve first defined value for 'name' for given database.
396 // Will be extended to take into account user associated with session
397 const char *session_setting_oneval(struct session_database *db, int offset)
399 if (offset >= db->num_settings || !db->settings[offset])
401 return db->settings[offset]->value;
404 // Prepare XSLT stylesheets for record normalization
405 // Structures are allocated on the session_wide nmem to avoid having
406 // to recompute this for every search. This would lead
407 // to leaking if a single session was to repeatedly change the PZ_XSLT
408 // setting. However, this is not a realistic use scenario.
409 static int prepare_map(struct session *se, struct session_database *sdb)
413 if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
414 (s = session_setting_oneval(sdb, PZ_XSLT)))
416 char auto_stylesheet[256];
418 if (!strcmp(s, "auto"))
420 const char *request_syntax = session_setting_oneval(
421 sdb, PZ_REQUESTSYNTAX);
425 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
426 "%s.xsl", request_syntax);
427 for (cp = auto_stylesheet; *cp; cp++)
429 /* deliberately only consider ASCII */
430 if (*cp > 32 && *cp < 127)
437 session_log(se, YLOG_WARN,
438 "No pz:requestsyntax for auto stylesheet");
441 sdb->map = normalize_cache_get(se->normalize_cache,
449 // called if watch should be removed because http_channel is to be destroyed
450 static void session_watch_cancel(void *data, struct http_channel *c,
453 struct session_watchentry *ent = data;
460 // set watch. Returns 0=OK, -1 if watch is already set
461 int session_set_watch(struct session *s, int what,
462 session_watchfun fun, void *data,
463 struct http_channel *chan)
467 if (s->watchlist[what].fun)
472 s->watchlist[what].fun = fun;
473 s->watchlist[what].data = data;
474 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
475 session_watch_cancel);
482 void session_alert_watch(struct session *s, int what)
486 if (s->watchlist[what].fun)
488 /* our watch is no longer associated with http_channel */
490 session_watchfun fun;
492 http_remove_observer(s->watchlist[what].obs);
493 fun = s->watchlist[what].fun;
494 data = s->watchlist[what].data;
496 /* reset watch before fun is invoked - in case fun wants to set
498 s->watchlist[what].fun = 0;
499 s->watchlist[what].data = 0;
500 s->watchlist[what].obs = 0;
503 session_log(s, YLOG_DEBUG,
504 "Alert Watch: %d calling function: %p", what, fun);
511 //callback for grep_databases
512 static void select_targets_callback(struct session *se,
513 struct session_database *db)
516 struct client_list *l;
518 for (l = se->clients_cached; l; l = l->next)
519 if (client_get_database(l->client) == db)
526 cl = client_create(db->database->id);
527 client_set_database(cl, db);
529 l = xmalloc(sizeof(*l));
531 l->next = se->clients_cached;
532 se->clients_cached = l;
534 /* set session always. If may be 0 if client is not active */
535 client_set_session(cl, se);
537 l = xmalloc(sizeof(*l));
539 l->next = se->clients_active;
540 se->clients_active = l;
543 static void session_reset_active_clients(struct session *se,
544 struct client_list *new_list)
546 struct client_list *l;
549 l = se->clients_active;
550 se->clients_active = new_list;
555 struct client_list *l_next = l->next;
557 client_lock(l->client);
558 client_set_session(l->client, 0); /* mark client inactive */
559 client_unlock(l->client);
566 static void session_remove_cached_clients(struct session *se)
568 struct client_list *l;
570 session_reset_active_clients(se, 0);
573 l = se->clients_cached;
574 se->clients_cached = 0;
579 struct client_list *l_next = l->next;
580 client_lock(l->client);
581 client_set_session(l->client, 0);
582 client_set_database(l->client, 0);
583 client_unlock(l->client);
584 client_destroy(l->client);
590 // Associates a set of clients with a session;
591 // Note: Session-databases represent databases with per-session
593 static int select_targets(struct session *se, const char *filter)
595 return session_grep_databases(se, filter, select_targets_callback);
598 int session_active_clients(struct session *s)
600 struct client_list *l;
603 for (l = s->clients_active; l; l = l->next)
604 if (client_is_active(l->client))
610 int session_is_preferred_clients_ready(struct session *s)
612 struct client_list *l;
615 for (l = s->clients_active; l; l = l->next)
616 if (client_is_active_preferred(l->client))
618 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
622 void session_sort(struct session *se, const char *field, int increasing)
624 struct session_sorted_results *sr;
625 struct client_list *l;
629 /* see if we already have sorted for this critieria */
630 for (sr = se->sorted_results; sr; sr = sr->next)
632 if (!strcmp(field, sr->field) && increasing == sr->increasing)
637 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
642 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
644 sr = nmem_malloc(se->nmem, sizeof(*sr));
645 sr->field = nmem_strdup(se->nmem, field);
646 sr->increasing = increasing;
647 sr->next = se->sorted_results;
648 se->sorted_results = sr;
650 for (l = se->clients_active; l; l = l->next)
652 struct client *cl = l->client;
653 if (client_get_state(cl) == Client_Connecting ||
654 client_get_state(cl) == Client_Idle ||
655 client_get_state(cl) == Client_Working)
656 client_start_search(cl);
661 enum pazpar2_error_code session_search(struct session *se,
663 const char *startrecs,
667 const char **addinfo,
668 const char *sort_field, int increasing)
670 int live_channels = 0;
672 int no_failed_query = 0;
673 int no_failed_limit = 0;
674 struct client_list *l, *l0;
676 facet_limits_t facet_limits;
678 session_log(se, YLOG_DEBUG, "Search");
682 if (se->settings_modified)
683 session_remove_cached_clients(se);
685 session_reset_active_clients(se, 0);
688 reclist_destroy(se->reclist);
690 se->settings_modified = 0;
691 relevance_destroy(&se->relevance);
692 nmem_reset(se->nmem);
693 se->total_records = se->total_merged = 0;
694 se->num_termlists = 0;
696 /* reset list of sorted results and clear to relevance search */
697 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
698 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
699 se->sorted_results->increasing = increasing;
700 se->sorted_results->next = 0;
702 live_channels = select_targets(se, filter);
706 return PAZPAR2_NO_TARGETS;
708 se->reclist = reclist_create(se->nmem);
710 yaz_gettimeofday(&tval);
714 facet_limits = facet_limits_create(limit);
719 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
722 l0 = se->clients_active;
723 se->clients_active = 0;
726 for (l = l0; l; l = l->next)
729 struct client *cl = l->client;
731 if (prepare_map(se, client_get_database(cl)) < 0)
734 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
738 else if (parse_ret == -2)
743 client_prep_connection(cl, se->service->z3950_operation_timeout,
744 se->service->z3950_session_timeout,
745 se->service->server->iochan_man,
747 if (parse_ret == 1 && r == 2)
749 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
754 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
755 client_start_search(cl);
760 facet_limits_destroy(facet_limits);
761 session_reset_active_clients(se, l0);
765 if (no_failed_query > 0)
768 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
770 else if (no_failed_limit > 0)
773 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
776 return PAZPAR2_NO_TARGETS;
778 yaz_log(YLOG_LOG, "session_start_search done");
779 return PAZPAR2_NO_ERROR;
782 // Creates a new session_database object for a database
783 static void session_init_databases_fun(void *context, struct database *db)
785 struct session *se = (struct session *) context;
786 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
792 assert(db->settings);
793 new->settings = nmem_malloc(se->session_nmem,
794 sizeof(struct settings *) * db->num_settings);
795 new->num_settings = db->num_settings;
796 for (i = 0; i < db->num_settings; i++)
798 struct setting *setting = db->settings[i];
799 new->settings[i] = setting;
801 new->next = se->databases;
805 // Doesn't free memory associated with sdb -- nmem takes care of that
806 static void session_database_destroy(struct session_database *sdb)
811 // Initialize session_database list -- this represents this session's view
812 // of the database list -- subject to modification by the settings ws command
813 void session_init_databases(struct session *se)
816 predef_grep_databases(se, se->service, session_init_databases_fun);
819 // Probably session_init_databases_fun should be refactored instead of
821 static struct session_database *load_session_database(struct session *se,
824 struct database *db = new_database(id, se->session_nmem);
826 session_init_databases_fun((void*) se, db);
828 // New sdb is head of se->databases list
829 return se->databases;
832 // Find an existing session database. If not found, load it
833 static struct session_database *find_session_database(struct session *se,
836 struct session_database *sdb;
838 for (sdb = se->databases; sdb; sdb = sdb->next)
839 if (!strcmp(sdb->database->id, id))
841 return load_session_database(se, id);
844 // Apply a session override to a database
845 void session_apply_setting(struct session *se, char *dbname, char *setting,
848 struct session_database *sdb = find_session_database(se, dbname);
849 struct conf_service *service = se->service;
850 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
851 int offset = settings_create_offset(service, setting);
853 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
856 new->target = dbname;
859 new->next = sdb->settings[offset];
860 sdb->settings[offset] = new;
862 se->settings_modified = 1;
864 // Force later recompute of settings-driven data structures
865 // (happens when a search starts and client connections are prepared)
877 void session_destroy(struct session *se)
879 struct session_database *sdb;
880 session_log(se, YLOG_DEBUG, "Destroying");
882 session_remove_cached_clients(se);
884 for (sdb = se->databases; sdb; sdb = sdb->next)
885 session_database_destroy(sdb);
886 normalize_cache_destroy(se->normalize_cache);
887 relevance_destroy(&se->relevance);
888 reclist_destroy(se->reclist);
889 nmem_destroy(se->nmem);
890 service_destroy(se->service);
891 yaz_mutex_destroy(&se->session_mutex);
894 size_t session_get_memory_status(struct session *session) {
898 session_enter(session);
899 session_nmem = nmem_total(session->nmem);
900 session_leave(session);
905 struct session *new_session(NMEM nmem, struct conf_service *service,
909 struct session *session = nmem_malloc(nmem, sizeof(*session));
913 sprintf(tmp_str, "session#%u", session_id);
915 session->session_id = session_id;
916 session_log(session, YLOG_DEBUG, "New");
917 session->service = service;
918 session->relevance = 0;
919 session->total_records = 0;
920 session->number_of_warnings_unknown_elements = 0;
921 session->number_of_warnings_unknown_metadata = 0;
922 session->num_termlists = 0;
923 session->reclist = 0;
924 session->clients_active = 0;
925 session->clients_cached = 0;
926 session->settings_modified = 0;
927 session->session_nmem = nmem;
928 session->nmem = nmem_create();
929 session->databases = 0;
930 for (i = 0; i <= SESSION_WATCH_MAX; i++)
932 session->watchlist[i].data = 0;
933 session->watchlist[i].fun = 0;
935 session->normalize_cache = normalize_cache_create();
936 session->session_mutex = 0;
937 pazpar2_mutex_create(&session->session_mutex, tmp_str);
942 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
944 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
945 int *count, NMEM nmem)
947 struct hitsbytarget *res = 0;
948 struct client_list *l;
951 for (l = se->clients_active; l; l = l->next)
954 res = nmem_malloc(nmem, sizeof(*res) * sz);
956 for (l = se->clients_active; l; l = l->next)
958 struct client *cl = l->client;
959 WRBUF w = wrbuf_alloc();
960 const char *name = session_setting_oneval(client_get_database(cl),
963 res[*count].id = client_get_id(cl);
964 res[*count].name = *name ? name : "Unknown";
965 res[*count].hits = client_get_hits(cl);
966 res[*count].approximation = client_get_approximation(cl);
967 res[*count].records = client_get_num_records(cl);
968 res[*count].filtered = client_get_num_records_filtered(cl);
969 res[*count].diagnostic =
970 client_get_diagnostic(cl, &res[*count].addinfo);
971 res[*count].state = client_get_state_str(cl);
972 res[*count].connected = client_get_connection(cl) ? 1 : 0;
973 session_settings_dump(se, client_get_database(cl), w);
974 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
977 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
984 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
986 struct hitsbytarget *p;
988 p = hitsbytarget_nb(se, count, nmem);
993 struct termlist_score **get_termlist_score(struct session *se,
994 const char *name, int *num)
997 struct termlist_score **tl = 0;
1000 for (i = 0; i < se->num_termlists; i++)
1001 if (!strcmp((const char *) se->termlists[i].name, name))
1003 tl = termlist_highscore(se->termlists[i].termlist, num);
1010 // Compares two hitsbytarget nodes by hitcount
1011 static int cmp_ht(const void *p1, const void *p2)
1013 const struct hitsbytarget *h1 = p1;
1014 const struct hitsbytarget *h2 = p2;
1015 return h2->hits - h1->hits;
1018 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1019 NMEM nmem, int version)
1021 struct hitsbytarget *ht;
1024 ht = hitsbytarget_nb(se, &count, nmem);
1025 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1026 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1029 // do only print terms which have display names
1031 wrbuf_puts(wrbuf, "<term>\n");
1033 wrbuf_puts(wrbuf, "<id>");
1034 wrbuf_xmlputs(wrbuf, ht[i].id);
1035 wrbuf_puts(wrbuf, "</id>\n");
1037 wrbuf_puts(wrbuf, "<name>");
1038 if (!ht[i].name || !ht[i].name[0])
1039 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1041 wrbuf_xmlputs(wrbuf, ht[i].name);
1042 wrbuf_puts(wrbuf, "</name>\n");
1044 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1048 // Should not print if we know it isn't a approximation.
1049 wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1050 wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1051 wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1054 wrbuf_puts(wrbuf, "<state>");
1055 wrbuf_xmlputs(wrbuf, ht[i].state);
1056 wrbuf_puts(wrbuf, "</state>\n");
1058 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1060 wrbuf_puts(wrbuf, "</term>\n");
1065 void perform_termlist(struct http_channel *c, struct session *se,
1066 const char *name, int num, int version)
1069 NMEM nmem_tmp = nmem_create();
1076 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1080 for (j = 0; j < num_names; j++)
1083 int must_generate_empty = 1; /* bug 5350 */
1085 for (i = 0; i < se->num_termlists; i++)
1087 tname = se->termlists[i].name;
1088 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1090 struct termlist_score **p = 0;
1093 wrbuf_puts(c->wrbuf, "<list name=\"");
1094 wrbuf_xmlputs(c->wrbuf, tname);
1095 wrbuf_puts(c->wrbuf, "\">\n");
1096 must_generate_empty = 0;
1098 p = termlist_highscore(se->termlists[i].termlist, &len);
1102 for (i = 0; i < len && i < num; i++)
1104 // prevent sending empty term elements
1105 if (!p[i]->display_term || !p[i]->display_term[0])
1108 wrbuf_puts(c->wrbuf, "<term>");
1109 wrbuf_puts(c->wrbuf, "<name>");
1110 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1111 wrbuf_puts(c->wrbuf, "</name>");
1113 wrbuf_printf(c->wrbuf,
1114 "<frequency>%d</frequency>",
1116 wrbuf_puts(c->wrbuf, "</term>\n");
1119 wrbuf_puts(c->wrbuf, "</list>\n");
1123 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1125 wrbuf_puts(c->wrbuf, "<list name=\"");
1126 wrbuf_xmlputs(c->wrbuf, tname);
1127 wrbuf_puts(c->wrbuf, "\">\n");
1129 targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1130 wrbuf_puts(c->wrbuf, "</list>\n");
1131 must_generate_empty = 0;
1133 if (must_generate_empty)
1135 wrbuf_puts(c->wrbuf, "<list name=\"");
1136 wrbuf_xmlputs(c->wrbuf, names[j]);
1137 wrbuf_puts(c->wrbuf, "\"/>\n");
1141 nmem_destroy(nmem_tmp);
1144 #ifdef MISSING_HEADERS
1145 void report_nmem_stats(void)
1147 size_t in_use, is_free;
1149 nmem_get_memory_in_use(&in_use);
1150 nmem_get_memory_free(&is_free);
1152 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1153 (long) in_use, (long) is_free);
1157 struct record_cluster *show_single_start(struct session *se, const char *id,
1158 struct record_cluster **prev_r,
1159 struct record_cluster **next_r)
1161 struct record_cluster *r = 0;
1168 reclist_enter(se->reclist);
1169 while ((r = reclist_read_record(se->reclist)))
1171 if (!strcmp(r->recid, id))
1173 *next_r = reclist_read_record(se->reclist);
1178 reclist_leave(se->reclist);
1185 void show_single_stop(struct session *se, struct record_cluster *rec)
1190 struct record_cluster **show_range_start(struct session *se,
1191 struct reclist_sortparms *sp,
1192 int start, int *num, int *total, Odr_int *sumhits, Odr_int *approx_hits)
1194 struct record_cluster **recs;
1195 struct reclist_sortparms *spp;
1198 yaz_timing_t t = yaz_timing_create();
1201 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1211 struct client_list *l;
1213 for (spp = sp; spp; spp = spp->next)
1214 if (spp->type == Metadata_sortkey_relevance)
1216 relevance_prepare_read(se->relevance, se->reclist);
1219 reclist_sort(se->reclist, sp);
1221 reclist_enter(se->reclist);
1222 *total = reclist_get_num_records(se->reclist);
1225 for (l = se->clients_active; l; l = l->next) {
1226 *sumhits += client_get_hits(l->client);
1227 *approx_hits += client_get_approximation(l->client);
1229 for (i = 0; i < start; i++)
1230 if (!reclist_read_record(se->reclist))
1237 for (i = 0; i < *num; i++)
1239 struct record_cluster *r = reclist_read_record(se->reclist);
1247 reclist_leave(se->reclist);
1251 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1252 yaz_timing_get_real(t), yaz_timing_get_user(t),
1253 yaz_timing_get_sys(t));
1254 yaz_timing_destroy(&t);
1259 void show_range_stop(struct session *se, struct record_cluster **recs)
1264 void statistics(struct session *se, struct statistics *stat)
1266 struct client_list *l;
1269 memset(stat, 0, sizeof(*stat));
1271 for (l = se->clients_active; l; l = l->next)
1273 struct client *cl = l->client;
1274 if (!client_get_connection(cl))
1275 stat->num_no_connection++;
1276 stat->num_hits += client_get_hits(cl);
1277 switch (client_get_state(cl))
1279 case Client_Connecting: stat->num_connecting++; break;
1280 case Client_Working: stat->num_working++; break;
1281 case Client_Idle: stat->num_idle++; break;
1282 case Client_Failed: stat->num_failed++; break;
1283 case Client_Error: stat->num_error++; break;
1288 stat->num_records = se->total_records;
1290 stat->num_clients = count;
1293 static struct record_metadata *record_metadata_init(
1294 NMEM nmem, const char *value, enum conf_metadata_type type,
1295 struct _xmlAttr *attr)
1297 struct record_metadata *rec_md = record_metadata_create(nmem);
1298 struct record_metadata_attr **attrp = &rec_md->attributes;
1300 for (; attr; attr = attr->next)
1302 if (attr->children && attr->children->content)
1304 if (strcmp((const char *) attr->name, "type"))
1305 { /* skip the "type" attribute.. Its value is already part of
1306 the element in output (md-%s) and so repeating it here
1308 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1310 nmem_strdup(nmem, (const char *) attr->name);
1312 nmem_strdup(nmem, (const char *) attr->children->content);
1313 attrp = &(*attrp)->next;
1319 if (type == Metadata_type_generic)
1321 char *p = nmem_strdup(nmem, value);
1323 p = normalize7bit_generic(p, " ,/.:([");
1325 rec_md->data.text.disp = p;
1326 rec_md->data.text.sort = 0;
1328 else if (type == Metadata_type_year || type == Metadata_type_date)
1333 if (type == Metadata_type_date)
1335 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1338 rec_md->data.number.min = first;
1339 rec_md->data.number.max = last;
1346 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1347 struct conf_service *service, WRBUF norm_wr)
1351 for (n = root->children; n; n = n->next)
1353 if (n->type != XML_ELEMENT_NODE)
1355 if (!strcmp((const char *) n->name, "metadata"))
1357 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1359 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1361 else if (!strcmp(name, (const char *) type))
1363 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1366 const char *norm_str;
1367 pp2_charset_token_t prt =
1368 pp2_charset_token_create(service->charsets, "mergekey");
1370 pp2_charset_token_first(prt, (const char *) value, 0);
1371 if (wrbuf_len(norm_wr) > 0)
1372 wrbuf_puts(norm_wr, " ");
1373 wrbuf_puts(norm_wr, name);
1375 pp2_charset_token_next(prt)))
1379 wrbuf_puts(norm_wr, " ");
1380 wrbuf_puts(norm_wr, norm_str);
1384 pp2_charset_token_destroy(prt);
1394 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1395 struct conf_service *service, NMEM nmem)
1397 char *mergekey_norm = 0;
1398 xmlNode *root = xmlDocGetRootElement(doc);
1399 WRBUF norm_wr = wrbuf_alloc();
1401 /* consider mergekey from XSL first */
1402 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1405 const char *norm_str;
1406 pp2_charset_token_t prt =
1407 pp2_charset_token_create(service->charsets, "mergekey");
1409 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1410 while ((norm_str = pp2_charset_token_next(prt)))
1414 if (wrbuf_len(norm_wr))
1415 wrbuf_puts(norm_wr, " ");
1416 wrbuf_puts(norm_wr, norm_str);
1419 pp2_charset_token_destroy(prt);
1424 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1426 for (field_id = 0; field_id < service->num_metadata; field_id++)
1428 struct conf_metadata *ser_md = &service->metadata[field_id];
1429 if (ser_md->mergekey != Metadata_mergekey_no)
1431 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1433 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1435 /* no mergekey on this one and it is required..
1436 Generate unique key instead */
1437 wrbuf_rewind(norm_wr);
1444 /* generate unique key if none is not generated already or is empty */
1445 if (wrbuf_len(norm_wr) == 0)
1447 wrbuf_printf(norm_wr, "position: %s-%d",
1448 client_get_id(cl), record_no);
1452 const char *lead = "content: ";
1453 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1455 if (wrbuf_len(norm_wr) > 0)
1456 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1457 wrbuf_destroy(norm_wr);
1458 return mergekey_norm;
1461 /** \brief see if metadata for pz:recordfilter exists
1462 \param root xml root element of normalized record
1463 \param sdb session database for client
1464 \retval 0 if there is no metadata for pz:recordfilter
1465 \retval 1 if there is metadata for pz:recordfilter
1467 If there is no pz:recordfilter defined, this function returns 1
1471 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1476 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1481 for (n = root->children; n; n = n->next)
1483 if (n->type != XML_ELEMENT_NODE)
1485 if (!strcmp((const char *) n->name, "metadata"))
1487 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1494 if ((eq = strchr(s, '=')))
1496 else if ((eq = strchr(s, '~')))
1502 if (len == strlen((const char *)type) &&
1503 !memcmp((const char *) type, s, len))
1505 xmlChar *value = xmlNodeGetContent(n);
1506 if (value && *value)
1509 (substring && strstr((const char *) value, eq+1)) ||
1510 (!substring && !strcmp((const char *) value, eq + 1)))
1523 static int ingest_to_cluster(struct client *cl,
1527 const char *mergekey_norm);
1529 /** \brief ingest XML record
1530 \param cl client holds the result set for record
1531 \param rec record buffer (0 terminated)
1532 \param record_no record position (1, 2, ..)
1533 \param nmem working NMEM
1538 int ingest_record(struct client *cl, const char *rec,
1539 int record_no, NMEM nmem)
1541 struct session *se = client_get_session(cl);
1543 struct session_database *sdb = client_get_database(cl);
1544 struct conf_service *service = se->service;
1545 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1547 const char *mergekey_norm;
1552 root = xmlDocGetRootElement(xdoc);
1554 if (!check_record_filter(root, sdb))
1556 session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1561 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1564 session_log(se, YLOG_WARN, "Got no mergekey");
1569 if (client_get_session(cl) == se)
1570 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1577 static int check_limit_local(struct client *cl,
1578 struct record *record,
1581 int skip_record = 0;
1582 struct session *se = client_get_session(cl);
1583 struct conf_service *service = se->service;
1584 NMEM nmem_tmp = nmem_create();
1585 struct session_database *sdb = client_get_database(cl);
1587 while (!skip_record)
1589 struct conf_metadata *ser_md = 0;
1590 struct record_metadata *rec_md = 0;
1596 client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v,
1601 md_field_id = conf_service_metadata_field_id(service, name);
1602 if (md_field_id < 0)
1607 ser_md = &service->metadata[md_field_id];
1608 rec_md = record->metadata[md_field_id];
1609 yaz_log(YLOG_LOG, "check limit local %s", name);
1610 for (i = 0; i < num_v; )
1614 if (ser_md->type == Metadata_type_year
1615 || ser_md->type == Metadata_type_date)
1617 int y = atoi(values[i]);
1618 if (y >= rec_md->data.number.min
1619 && y <= rec_md->data.number.max)
1624 yaz_log(YLOG_LOG, "cmp: '%s' '%s'",
1625 rec_md->data.text.disp, values[i]);
1626 if (!strcmp(rec_md->data.text.disp, values[i]))
1631 rec_md = rec_md->next;
1635 rec_md = record->metadata[md_field_id];
1645 nmem_destroy(nmem_tmp);
1649 static int ingest_to_cluster(struct client *cl,
1653 const char *mergekey_norm)
1658 struct session *se = client_get_session(cl);
1659 struct conf_service *service = se->service;
1660 int term_factor = 1;
1661 struct record_cluster *cluster;
1662 struct session_database *sdb = client_get_database(cl);
1663 struct record *record = record_create(se->nmem,
1664 service->num_metadata,
1665 service->num_sortkeys, cl,
1668 for (n = root->children; n; n = n->next)
1676 if (n->type != XML_ELEMENT_NODE)
1678 if (!strcmp((const char *) n->name, "metadata"))
1680 struct conf_metadata *ser_md = 0;
1681 struct record_metadata **wheretoput = 0;
1682 struct record_metadata *rec_md = 0;
1683 int md_field_id = -1;
1685 type = xmlGetProp(n, (xmlChar *) "type");
1686 value = xmlNodeListGetString(xdoc, n->children, 1);
1688 if (!type || !value || !*value)
1692 = conf_service_metadata_field_id(service, (const char *) type);
1693 if (md_field_id < 0)
1695 if (se->number_of_warnings_unknown_metadata == 0)
1697 session_log(se, YLOG_WARN,
1698 "Ignoring unknown metadata element: %s", type);
1700 se->number_of_warnings_unknown_metadata++;
1704 ser_md = &service->metadata[md_field_id];
1706 // non-merged metadata
1707 rec_md = record_metadata_init(se->nmem, (const char *) value,
1708 ser_md->type, n->properties);
1711 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1712 "for element '%s'", value, type);
1715 wheretoput = &record->metadata[md_field_id];
1717 wheretoput = &(*wheretoput)->next;
1718 *wheretoput = rec_md;
1722 if (check_limit_local(cl, record, record_no))
1724 session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1725 record_no, sdb->database->id);
1732 cluster = reclist_insert(se->reclist, service, record,
1733 mergekey_norm, &se->total_merged);
1738 const char *use_term_factor_str =
1739 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1740 if (use_term_factor_str && use_term_factor_str[0] == '1')
1742 int maxrecs = client_get_maxrecs(cl);
1743 int hits = (int) client_get_hits(cl);
1744 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1745 assert(term_factor >= 1);
1746 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1750 if (global_parameters.dump_records)
1751 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1752 sdb->database->id, record_no);
1755 relevance_newrec(se->relevance, cluster);
1757 // now parsing XML record and adding data to cluster or record metadata
1758 for (n = root->children; n; n = n->next)
1760 pp2_charset_token_t prt;
1767 if (n->type != XML_ELEMENT_NODE)
1769 if (!strcmp((const char *) n->name, "metadata"))
1771 struct conf_metadata *ser_md = 0;
1772 struct conf_sortkey *ser_sk = 0;
1773 struct record_metadata **wheretoput = 0;
1774 struct record_metadata *rec_md = 0;
1775 int md_field_id = -1;
1776 int sk_field_id = -1;
1778 type = xmlGetProp(n, (xmlChar *) "type");
1779 value = xmlNodeListGetString(xdoc, n->children, 1);
1781 if (!type || !value || !*value)
1785 = conf_service_metadata_field_id(service, (const char *) type);
1786 if (md_field_id < 0)
1789 ser_md = &service->metadata[md_field_id];
1791 if (ser_md->sortkey_offset >= 0)
1793 sk_field_id = ser_md->sortkey_offset;
1794 ser_sk = &service->sortkeys[sk_field_id];
1798 rec_md = record_metadata_init(se->nmem, (const char *) value,
1803 wheretoput = &cluster->metadata[md_field_id];
1805 // and polulate with data:
1806 // assign cluster or record based on merge action
1807 if (ser_md->merge == Metadata_merge_unique)
1811 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1812 rec_md->data.text.disp))
1814 wheretoput = &(*wheretoput)->next;
1817 *wheretoput = rec_md;
1819 else if (ser_md->merge == Metadata_merge_longest)
1822 || strlen(rec_md->data.text.disp)
1823 > strlen((*wheretoput)->data.text.disp))
1825 *wheretoput = rec_md;
1828 const char *sort_str = 0;
1830 ser_sk->type == Metadata_sortkey_skiparticle;
1832 if (!cluster->sortkeys[sk_field_id])
1833 cluster->sortkeys[sk_field_id] =
1834 nmem_malloc(se->nmem,
1835 sizeof(union data_types));
1838 pp2_charset_token_create(service->charsets, "sort");
1840 pp2_charset_token_first(prt, rec_md->data.text.disp,
1843 pp2_charset_token_next(prt);
1845 sort_str = pp2_get_sort(prt);
1847 cluster->sortkeys[sk_field_id]->text.disp =
1848 rec_md->data.text.disp;
1851 sort_str = rec_md->data.text.disp;
1852 session_log(se, YLOG_WARN,
1853 "Could not make sortkey. Bug #1858");
1855 cluster->sortkeys[sk_field_id]->text.sort =
1856 nmem_strdup(se->nmem, sort_str);
1857 pp2_charset_token_destroy(prt);
1861 else if (ser_md->merge == Metadata_merge_all)
1864 wheretoput = &(*wheretoput)->next;
1865 *wheretoput = rec_md;
1867 else if (ser_md->merge == Metadata_merge_range)
1871 *wheretoput = rec_md;
1873 cluster->sortkeys[sk_field_id]
1878 int this_min = rec_md->data.number.min;
1879 int this_max = rec_md->data.number.max;
1880 if (this_min < (*wheretoput)->data.number.min)
1881 (*wheretoput)->data.number.min = this_min;
1882 if (this_max > (*wheretoput)->data.number.max)
1883 (*wheretoput)->data.number.max = this_max;
1888 // ranking of _all_ fields enabled ...
1890 relevance_countwords(se->relevance, cluster,
1891 (char *) value, ser_md->rank,
1894 // construct facets ... unless the client already has reported them
1895 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1897 if (ser_md->type == Metadata_type_year)
1900 sprintf(year, "%d", rec_md->data.number.max);
1902 add_facet(se, (char *) type, year, term_factor);
1903 if (rec_md->data.number.max != rec_md->data.number.min)
1905 sprintf(year, "%d", rec_md->data.number.min);
1906 add_facet(se, (char *) type, year, term_factor);
1910 add_facet(se, (char *) type, (char *) value, term_factor);
1920 if (se->number_of_warnings_unknown_elements == 0)
1921 session_log(se, YLOG_WARN,
1922 "Unexpected element in internal record: %s", n->name);
1923 se->number_of_warnings_unknown_elements++;
1931 relevance_donerecord(se->relevance, cluster);
1932 se->total_records++;
1937 void session_log(struct session *s, int level, const char *fmt, ...)
1943 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1944 yaz_log(level, "Session %u: %s", s->session_id, buf);
1952 * c-file-style: "Stroustrup"
1953 * indent-tabs-mode: nil
1955 * vim: shiftwidth=4 tabstop=8 expandtab