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>
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 = termlist_create(s->nmem);
233 s->num_termlists = i + 1;
237 session_log(s, YLOG_LOG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
239 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
240 wrbuf_cstr(facet_wrbuf), count);
242 wrbuf_destroy(facet_wrbuf);
243 wrbuf_destroy(display_wrbuf);
246 static xmlDoc *record_to_xml(struct session *se,
247 struct session_database *sdb, const char *rec)
249 struct database *db = sdb->database;
252 rdoc = xmlParseMemory(rec, strlen(rec));
256 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
261 if (global_parameters.dump_records)
263 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
270 #define MAX_XSLT_ARGS 16
272 // Add static values from session database settings if applicable
273 static void insert_settings_parameters(struct session_database *sdb,
274 struct conf_service *service,
282 for (i = 0; i < service->num_metadata; i++)
284 struct conf_metadata *md = &service->metadata[i];
287 if (md->setting == Metadata_setting_parameter &&
288 (setting = settings_lookup_offset(service, md->name)) >= 0)
290 const char *val = session_setting_oneval(sdb, setting);
291 if (val && nparms < MAX_XSLT_ARGS)
294 int len = strlen(val);
295 buf = nmem_malloc(nmem, len + 3);
297 strcpy(buf + 1, val);
300 parms[offset++] = md->name;
301 parms[offset++] = buf;
309 // Add static values from session database settings if applicable
310 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
311 struct conf_service *service)
315 for (i = 0; i < service->num_metadata; i++)
317 struct conf_metadata *md = &service->metadata[i];
320 if (md->setting == Metadata_setting_postproc &&
321 (offset = settings_lookup_offset(service, md->name)) >= 0)
323 const char *val = session_setting_oneval(sdb, offset);
326 xmlNode *r = xmlDocGetRootElement(doc);
327 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
329 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
335 static xmlDoc *normalize_record(struct session *se,
336 struct session_database *sdb,
337 struct conf_service *service,
338 const char *rec, NMEM nmem)
340 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
344 char *parms[MAX_XSLT_ARGS*2+1];
346 insert_settings_parameters(sdb, service, parms, nmem);
348 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
350 session_log(se, YLOG_WARN, "Normalize failed from %s",
355 insert_settings_values(sdb, rdoc, service);
357 if (global_parameters.dump_records)
359 session_log(se, YLOG_LOG, "Normalized record from %s",
368 void session_settings_dump(struct session *se,
369 struct session_database *db,
374 int i, num = db->num_settings;
375 for (i = 0; i < num; i++)
377 struct setting *s = db->settings[i];
378 for (;s ; s = s->next)
380 wrbuf_puts(w, "<set name=\"");
381 wrbuf_xmlputs(w, s->name);
382 wrbuf_puts(w, "\" value=\"");
383 wrbuf_xmlputs(w, s->value);
384 wrbuf_puts(w, "\"/>");
392 // Retrieve first defined value for 'name' for given database.
393 // Will be extended to take into account user associated with session
394 const char *session_setting_oneval(struct session_database *db, int offset)
396 if (offset >= db->num_settings || !db->settings[offset])
398 return db->settings[offset]->value;
401 // Prepare XSLT stylesheets for record normalization
402 // Structures are allocated on the session_wide nmem to avoid having
403 // to recompute this for every search. This would lead
404 // to leaking if a single session was to repeatedly change the PZ_XSLT
405 // setting. However, this is not a realistic use scenario.
406 static int prepare_map(struct session *se, struct session_database *sdb)
408 if (sdb->settings && !sdb->map)
412 if (sdb->settings[PZ_XSLT] &&
413 (s = session_setting_oneval(sdb, PZ_XSLT)))
415 char auto_stylesheet[256];
417 if (!strcmp(s, "auto"))
419 const char *request_syntax = session_setting_oneval(
420 sdb, PZ_REQUESTSYNTAX);
424 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
425 "%s.xsl", request_syntax);
426 for (cp = auto_stylesheet; *cp; cp++)
428 /* deliberately only consider ASCII */
429 if (*cp > 32 && *cp < 127)
436 session_log(se, YLOG_WARN,
437 "No pz:requestsyntax for auto stylesheet");
440 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 static void session_clear_set(struct session *se,
623 const char *sort_field, int increasing, int position)
625 reclist_destroy(se->reclist);
627 if (nmem_total(se->nmem))
628 session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
629 nmem_total(se->nmem));
630 nmem_reset(se->nmem);
631 se->total_records = se->total_merged = 0;
632 se->num_termlists = 0;
634 /* reset list of sorted results and clear to relevance search */
635 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
636 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
637 se->sorted_results->increasing = increasing;
638 se->sorted_results->position = position;
639 se->sorted_results->next = 0;
641 session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d position=%d configured",
642 sort_field, increasing, position);
644 se->reclist = reclist_create(se->nmem);
647 void session_sort(struct session *se, const char *field, int increasing,
650 struct session_sorted_results *sr;
651 struct client_list *l;
655 yaz_log(YLOG_LOG, "session_sort field=%s increasing=%d position=%d", field, increasing, position);
656 /* see if we already have sorted for this critieria */
657 for (sr = se->sorted_results; sr; sr = sr->next)
659 if (!strcmp(field, sr->field) && increasing == sr->increasing && sr->position == position)
664 session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d position=%d already fetched",
665 field, increasing, position);
669 session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d position=%d must fetch",
670 field, increasing, position);
673 yaz_log(YLOG_DEBUG, "Reset results due to position");
674 session_clear_set(se, field, increasing, position);
677 sr = nmem_malloc(se->nmem, sizeof(*sr));
678 sr->field = nmem_strdup(se->nmem, field);
679 sr->increasing = increasing;
680 sr->position = position;
681 sr->next = se->sorted_results;
682 se->sorted_results = sr;
684 yaz_log(YLOG_DEBUG, "Restarting search for clients due to change in sort order");
686 for (l = se->clients_active; l; l = l->next)
688 struct client *cl = l->client;
689 if (client_get_state(cl) == Client_Connecting ||
690 client_get_state(cl) == Client_Idle ||
691 client_get_state(cl) == Client_Working) {
692 yaz_log(YLOG_DEBUG, "Client %s: Restarting search due to change in sort order", client_get_id(cl));
693 client_start_search(cl);
699 enum pazpar2_error_code session_search(struct session *se,
701 const char *startrecs,
705 const char **addinfo,
706 struct reclist_sortparms *sp)
708 int live_channels = 0;
710 int no_failed_query = 0;
711 int no_failed_limit = 0;
712 struct client_list *l, *l0;
714 facet_limits_t facet_limits;
716 session_log(se, YLOG_DEBUG, "Search");
720 if (se->settings_modified)
721 session_remove_cached_clients(se);
723 session_reset_active_clients(se, 0);
726 se->settings_modified = 0;
727 session_clear_set(se, sp->name, sp->increasing, sp->type == Metadata_sortkey_position);
728 relevance_destroy(&se->relevance);
730 live_channels = select_targets(se, filter);
734 return PAZPAR2_NO_TARGETS;
737 yaz_gettimeofday(&tval);
741 facet_limits = facet_limits_create(limit);
746 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
749 l0 = se->clients_active;
750 se->clients_active = 0;
753 for (l = l0; l; l = l->next)
756 struct client *cl = l->client;
758 if (prepare_map(se, client_get_database(cl)) < 0)
761 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
762 maxrecs, se->service->ccl_bibset);
765 else if (parse_ret == -2)
768 no_working++; /* other error, such as bad CCL map */
772 client_prep_connection(cl, se->service->z3950_operation_timeout,
773 se->service->z3950_session_timeout,
774 se->service->server->iochan_man,
776 if (parse_ret == 1 && r == 2)
778 session_log(se, YLOG_LOG, "client %s REUSE result", client_get_id(cl));
783 session_log(se, YLOG_LOG, "client %s NEW search", client_get_id(cl));
784 client_start_search(cl);
789 facet_limits_destroy(facet_limits);
790 session_reset_active_clients(se, l0);
794 if (no_failed_query > 0)
797 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
799 else if (no_failed_limit > 0)
802 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
805 return PAZPAR2_NO_TARGETS;
807 session_log(se, YLOG_LOG, "session_start_search done");
808 return PAZPAR2_NO_ERROR;
811 // Creates a new session_database object for a database
812 static void session_init_databases_fun(void *context, struct database *db)
814 struct session *se = (struct session *) context;
815 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
821 assert(db->settings);
822 new->settings = nmem_malloc(se->session_nmem,
823 sizeof(struct settings *) * db->num_settings);
824 new->num_settings = db->num_settings;
825 for (i = 0; i < db->num_settings; i++)
827 struct setting *setting = db->settings[i];
828 new->settings[i] = setting;
830 new->next = se->databases;
834 // Doesn't free memory associated with sdb -- nmem takes care of that
835 static void session_database_destroy(struct session_database *sdb)
840 // Initialize session_database list -- this represents this session's view
841 // of the database list -- subject to modification by the settings ws command
842 void session_init_databases(struct session *se)
845 predef_grep_databases(se, se->service, session_init_databases_fun);
848 // Probably session_init_databases_fun should be refactored instead of
850 static struct session_database *load_session_database(struct session *se,
853 struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
854 session_init_databases_fun((void*) se, db);
856 // New sdb is head of se->databases list
857 return se->databases;
860 // Find an existing session database. If not found, load it
861 static struct session_database *find_session_database(struct session *se,
864 struct session_database *sdb;
866 for (sdb = se->databases; sdb; sdb = sdb->next)
867 if (!strcmp(sdb->database->id, id))
869 return load_session_database(se, id);
872 // Apply a session override to a database
873 void session_apply_setting(struct session *se, char *dbname, char *setting,
876 struct session_database *sdb = find_session_database(se, dbname);
877 struct conf_service *service = se->service;
878 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
879 int offset = settings_create_offset(service, setting);
881 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
884 new->target = dbname;
887 new->next = sdb->settings[offset];
888 sdb->settings[offset] = new;
890 se->settings_modified = 1;
892 // Force later recompute of settings-driven data structures
893 // (happens when a search starts and client connections are prepared)
905 void session_destroy(struct session *se)
907 struct session_database *sdb;
908 session_log(se, YLOG_DEBUG, "Destroying");
910 session_remove_cached_clients(se);
912 for (sdb = se->databases; sdb; sdb = sdb->next)
913 session_database_destroy(sdb);
914 normalize_cache_destroy(se->normalize_cache);
915 relevance_destroy(&se->relevance);
916 reclist_destroy(se->reclist);
917 if (nmem_total(se->nmem))
918 session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
919 if (nmem_total(se->session_nmem))
920 session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
921 nmem_destroy(se->nmem);
922 service_destroy(se->service);
923 yaz_mutex_destroy(&se->session_mutex);
926 size_t session_get_memory_status(struct session *session) {
930 session_enter(session);
931 session_nmem = nmem_total(session->nmem);
932 session_leave(session);
937 struct session *new_session(NMEM nmem, struct conf_service *service,
941 struct session *session = nmem_malloc(nmem, sizeof(*session));
945 sprintf(tmp_str, "session#%u", session_id);
947 session->session_id = session_id;
948 session_log(session, YLOG_DEBUG, "New");
949 session->service = service;
950 session->relevance = 0;
951 session->total_records = 0;
952 session->number_of_warnings_unknown_elements = 0;
953 session->number_of_warnings_unknown_metadata = 0;
954 session->num_termlists = 0;
955 session->reclist = 0;
956 session->clients_active = 0;
957 session->clients_cached = 0;
958 session->settings_modified = 0;
959 session->session_nmem = nmem;
960 session->nmem = nmem_create();
961 session->databases = 0;
962 for (i = 0; i <= SESSION_WATCH_MAX; i++)
964 session->watchlist[i].data = 0;
965 session->watchlist[i].fun = 0;
967 session->normalize_cache = normalize_cache_create();
968 session->session_mutex = 0;
969 pazpar2_mutex_create(&session->session_mutex, tmp_str);
974 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
976 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
977 int *count, NMEM nmem)
979 struct hitsbytarget *res = 0;
980 struct client_list *l;
983 for (l = se->clients_active; l; l = l->next)
986 res = nmem_malloc(nmem, sizeof(*res) * sz);
988 for (l = se->clients_active; l; l = l->next)
990 struct client *cl = l->client;
991 WRBUF w = wrbuf_alloc();
992 const char *name = session_setting_oneval(client_get_database(cl),
995 res[*count].id = client_get_id(cl);
996 res[*count].name = *name ? name : "Unknown";
997 res[*count].hits = client_get_hits(cl);
998 res[*count].approximation = client_get_approximation(cl);
999 res[*count].records = client_get_num_records(cl);
1000 res[*count].filtered = client_get_num_records_filtered(cl);
1001 res[*count].diagnostic =
1002 client_get_diagnostic(cl, &res[*count].addinfo);
1003 res[*count].state = client_get_state_str(cl);
1004 res[*count].connected = client_get_connection(cl) ? 1 : 0;
1005 session_settings_dump(se, client_get_database(cl), w);
1006 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1009 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1016 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1018 struct hitsbytarget *p;
1020 p = hitsbytarget_nb(se, count, nmem);
1025 // Compares two hitsbytarget nodes by hitcount
1026 static int cmp_ht(const void *p1, const void *p2)
1028 const struct hitsbytarget *h1 = p1;
1029 const struct hitsbytarget *h2 = p2;
1030 return h2->hits - h1->hits;
1033 // Compares two hitsbytarget nodes by hitcount
1034 static int cmp_ht_approx(const void *p1, const void *p2)
1036 const struct hitsbytarget *h1 = p1;
1037 const struct hitsbytarget *h2 = p2;
1038 return h2->approximation - h1->approximation;
1041 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1042 NMEM nmem, int version)
1044 struct hitsbytarget *ht;
1047 ht = hitsbytarget_nb(se, &count, nmem);
1049 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1051 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1052 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1055 // do only print terms which have display names
1057 wrbuf_puts(wrbuf, "<term>\n");
1059 wrbuf_puts(wrbuf, "<id>");
1060 wrbuf_xmlputs(wrbuf, ht[i].id);
1061 wrbuf_puts(wrbuf, "</id>\n");
1063 wrbuf_puts(wrbuf, "<name>");
1064 if (!ht[i].name || !ht[i].name[0])
1065 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1067 wrbuf_xmlputs(wrbuf, ht[i].name);
1068 wrbuf_puts(wrbuf, "</name>\n");
1070 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1074 // Should not print if we know it isn't a approximation.
1075 wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1076 wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1077 wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1080 wrbuf_puts(wrbuf, "<state>");
1081 wrbuf_xmlputs(wrbuf, ht[i].state);
1082 wrbuf_puts(wrbuf, "</state>\n");
1084 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1086 wrbuf_puts(wrbuf, "</term>\n");
1091 void perform_termlist(struct http_channel *c, struct session *se,
1092 const char *name, int num, int version)
1095 NMEM nmem_tmp = nmem_create();
1102 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1106 for (j = 0; j < num_names; j++)
1109 int must_generate_empty = 1; /* bug 5350 */
1111 for (i = 0; i < se->num_termlists; i++)
1113 tname = se->termlists[i].name;
1114 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1116 struct termlist_score **p = 0;
1119 wrbuf_puts(c->wrbuf, "<list name=\"");
1120 wrbuf_xmlputs(c->wrbuf, tname);
1121 wrbuf_puts(c->wrbuf, "\">\n");
1122 must_generate_empty = 0;
1124 p = termlist_highscore(se->termlists[i].termlist, &len,
1129 for (i = 0; i < len && i < num; i++)
1131 // prevent sending empty term elements
1132 if (!p[i]->display_term || !p[i]->display_term[0])
1135 wrbuf_puts(c->wrbuf, "<term>");
1136 wrbuf_puts(c->wrbuf, "<name>");
1137 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1138 wrbuf_puts(c->wrbuf, "</name>");
1140 wrbuf_printf(c->wrbuf,
1141 "<frequency>%d</frequency>",
1143 wrbuf_puts(c->wrbuf, "</term>\n");
1146 wrbuf_puts(c->wrbuf, "</list>\n");
1150 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1152 wrbuf_puts(c->wrbuf, "<list name=\"");
1153 wrbuf_xmlputs(c->wrbuf, tname);
1154 wrbuf_puts(c->wrbuf, "\">\n");
1156 targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1157 wrbuf_puts(c->wrbuf, "</list>\n");
1158 must_generate_empty = 0;
1160 if (must_generate_empty)
1162 wrbuf_puts(c->wrbuf, "<list name=\"");
1163 wrbuf_xmlputs(c->wrbuf, names[j]);
1164 wrbuf_puts(c->wrbuf, "\"/>\n");
1168 nmem_destroy(nmem_tmp);
1171 #ifdef MISSING_HEADERS
1172 void report_nmem_stats(void)
1174 size_t in_use, is_free;
1176 nmem_get_memory_in_use(&in_use);
1177 nmem_get_memory_free(&is_free);
1179 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1180 (long) in_use, (long) is_free);
1184 struct record_cluster *show_single_start(struct session *se, const char *id,
1185 struct record_cluster **prev_r,
1186 struct record_cluster **next_r)
1188 struct record_cluster *r = 0;
1195 reclist_enter(se->reclist);
1196 while ((r = reclist_read_record(se->reclist)))
1198 if (!strcmp(r->recid, id))
1200 *next_r = reclist_read_record(se->reclist);
1205 reclist_leave(se->reclist);
1212 void show_single_stop(struct session *se, struct record_cluster *rec)
1217 struct record_cluster **show_range_start(struct session *se,
1218 struct reclist_sortparms *sp,
1219 int start, int *num, int *total, Odr_int *sumhits, Odr_int *approx_hits)
1221 struct record_cluster **recs;
1222 struct reclist_sortparms *spp;
1225 yaz_timing_t t = yaz_timing_create();
1228 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1239 struct client_list *l;
1241 for (spp = sp; spp; spp = spp->next)
1242 if (spp->type == Metadata_sortkey_relevance)
1244 relevance_prepare_read(se->relevance, se->reclist);
1247 reclist_sort(se->reclist, sp);
1249 reclist_enter(se->reclist);
1250 *total = reclist_get_num_records(se->reclist);
1254 for (l = se->clients_active; l; l = l->next) {
1255 *sumhits += client_get_hits(l->client);
1256 *approx_hits += client_get_approximation(l->client);
1258 for (i = 0; i < start; i++)
1259 if (!reclist_read_record(se->reclist))
1266 for (i = 0; i < *num; i++)
1268 struct record_cluster *r = reclist_read_record(se->reclist);
1276 reclist_leave(se->reclist);
1280 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1281 yaz_timing_get_real(t), yaz_timing_get_user(t),
1282 yaz_timing_get_sys(t));
1283 yaz_timing_destroy(&t);
1288 void show_range_stop(struct session *se, struct record_cluster **recs)
1293 void statistics(struct session *se, struct statistics *stat)
1295 struct client_list *l;
1298 memset(stat, 0, sizeof(*stat));
1300 for (l = se->clients_active; l; l = l->next)
1302 struct client *cl = l->client;
1303 if (!client_get_connection(cl))
1304 stat->num_no_connection++;
1305 stat->num_hits += client_get_hits(cl);
1306 switch (client_get_state(cl))
1308 case Client_Connecting: stat->num_connecting++; break;
1309 case Client_Working: stat->num_working++; break;
1310 case Client_Idle: stat->num_idle++; break;
1311 case Client_Failed: stat->num_failed++; break;
1312 case Client_Error: stat->num_error++; break;
1317 stat->num_records = se->total_records;
1319 stat->num_clients = count;
1322 static struct record_metadata *record_metadata_init(
1323 NMEM nmem, const char *value, enum conf_metadata_type type,
1324 struct _xmlAttr *attr)
1326 struct record_metadata *rec_md = record_metadata_create(nmem);
1327 struct record_metadata_attr **attrp = &rec_md->attributes;
1329 for (; attr; attr = attr->next)
1331 if (attr->children && attr->children->content)
1333 if (strcmp((const char *) attr->name, "type"))
1334 { /* skip the "type" attribute.. Its value is already part of
1335 the element in output (md-%s) and so repeating it here
1337 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1339 nmem_strdup(nmem, (const char *) attr->name);
1341 nmem_strdup(nmem, (const char *) attr->children->content);
1342 attrp = &(*attrp)->next;
1348 if (type == Metadata_type_generic)
1350 char *p = nmem_strdup(nmem, value);
1352 p = normalize7bit_generic(p, " ,/.:([");
1354 rec_md->data.text.disp = p;
1355 rec_md->data.text.sort = 0;
1357 else if (type == Metadata_type_year || type == Metadata_type_date)
1362 if (type == Metadata_type_date)
1364 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1367 rec_md->data.number.min = first;
1368 rec_md->data.number.max = last;
1375 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1376 struct conf_service *service, WRBUF norm_wr)
1380 for (n = root->children; n; n = n->next)
1382 if (n->type != XML_ELEMENT_NODE)
1384 if (!strcmp((const char *) n->name, "metadata"))
1386 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1388 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1390 else if (!strcmp(name, (const char *) type))
1392 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1395 const char *norm_str;
1396 pp2_charset_token_t prt =
1397 pp2_charset_token_create(service->charsets, "mergekey");
1399 pp2_charset_token_first(prt, (const char *) value, 0);
1400 if (wrbuf_len(norm_wr) > 0)
1401 wrbuf_puts(norm_wr, " ");
1402 wrbuf_puts(norm_wr, name);
1404 pp2_charset_token_next(prt)))
1408 wrbuf_puts(norm_wr, " ");
1409 wrbuf_puts(norm_wr, norm_str);
1413 pp2_charset_token_destroy(prt);
1423 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1424 struct conf_service *service, NMEM nmem)
1426 char *mergekey_norm = 0;
1427 xmlNode *root = xmlDocGetRootElement(doc);
1428 WRBUF norm_wr = wrbuf_alloc();
1430 /* consider mergekey from XSL first */
1431 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1434 const char *norm_str;
1435 pp2_charset_token_t prt =
1436 pp2_charset_token_create(service->charsets, "mergekey");
1438 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1439 while ((norm_str = pp2_charset_token_next(prt)))
1443 if (wrbuf_len(norm_wr))
1444 wrbuf_puts(norm_wr, " ");
1445 wrbuf_puts(norm_wr, norm_str);
1448 pp2_charset_token_destroy(prt);
1453 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1455 for (field_id = 0; field_id < service->num_metadata; field_id++)
1457 struct conf_metadata *ser_md = &service->metadata[field_id];
1458 if (ser_md->mergekey != Metadata_mergekey_no)
1460 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1462 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1464 /* no mergekey on this one and it is required..
1465 Generate unique key instead */
1466 wrbuf_rewind(norm_wr);
1473 /* generate unique key if none is not generated already or is empty */
1474 if (wrbuf_len(norm_wr) == 0)
1476 wrbuf_printf(norm_wr, "position: %s-%d",
1477 client_get_id(cl), record_no);
1481 const char *lead = "content: ";
1482 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1484 if (wrbuf_len(norm_wr) > 0)
1485 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1486 wrbuf_destroy(norm_wr);
1487 return mergekey_norm;
1490 /** \brief see if metadata for pz:recordfilter exists
1491 \param root xml root element of normalized record
1492 \param sdb session database for client
1493 \retval 0 if there is no metadata for pz:recordfilter
1494 \retval 1 if there is metadata for pz:recordfilter
1496 If there is no pz:recordfilter defined, this function returns 1
1500 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1505 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1510 for (n = root->children; n; n = n->next)
1512 if (n->type != XML_ELEMENT_NODE)
1514 if (!strcmp((const char *) n->name, "metadata"))
1516 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1523 if ((eq = strchr(s, '=')))
1525 else if ((eq = strchr(s, '~')))
1531 if (len == strlen((const char *)type) &&
1532 !memcmp((const char *) type, s, len))
1534 xmlChar *value = xmlNodeGetContent(n);
1535 if (value && *value)
1538 (substring && strstr((const char *) value, eq+1)) ||
1539 (!substring && !strcmp((const char *) value, eq + 1)))
1552 static int ingest_to_cluster(struct client *cl,
1556 const char *mergekey_norm);
1558 /** \brief ingest XML record
1559 \param cl client holds the result set for record
1560 \param rec record buffer (0 terminated)
1561 \param record_no record position (1, 2, ..)
1562 \param nmem working NMEM
1567 int ingest_record(struct client *cl, const char *rec,
1568 int record_no, NMEM nmem)
1570 struct session *se = client_get_session(cl);
1572 struct session_database *sdb = client_get_database(cl);
1573 struct conf_service *service = se->service;
1574 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1576 const char *mergekey_norm;
1581 root = xmlDocGetRootElement(xdoc);
1583 if (!check_record_filter(root, sdb))
1585 session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1590 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1593 session_log(se, YLOG_WARN, "Got no mergekey");
1598 if (client_get_session(cl) == se)
1599 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1606 // Skip record on non-zero
1607 static int check_limit_local(struct client *cl,
1608 struct record *record,
1611 int skip_record = 0;
1612 struct session *se = client_get_session(cl);
1613 struct conf_service *service = se->service;
1614 NMEM nmem_tmp = nmem_create();
1615 struct session_database *sdb = client_get_database(cl);
1617 while (!skip_record)
1619 struct conf_metadata *ser_md = 0;
1620 struct record_metadata *rec_md = 0;
1625 const char *name = client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v, &values);
1629 md_field_id = conf_service_metadata_field_id(service, name);
1630 if (md_field_id < 0)
1635 ser_md = &service->metadata[md_field_id];
1636 rec_md = record->metadata[md_field_id];
1637 yaz_log(YLOG_DEBUG, "check limit local %s", name);
1638 for (i = 0; i < num_v; )
1642 if (ser_md->type == Metadata_type_year
1643 || ser_md->type == Metadata_type_date)
1645 int y = atoi(values[i]);
1646 if (y >= rec_md->data.number.min
1647 && y <= rec_md->data.number.max)
1652 yaz_log(YLOG_DEBUG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1653 if (!strcmp(rec_md->data.text.disp, values[i]))
1655 // Value equals, should not be filtered.
1659 rec_md = rec_md->next;
1663 rec_md = record->metadata[md_field_id];
1667 // At end , not match
1674 nmem_destroy(nmem_tmp);
1678 static int ingest_to_cluster(struct client *cl,
1682 const char *mergekey_norm)
1687 struct session *se = client_get_session(cl);
1688 struct conf_service *service = se->service;
1689 int term_factor = 1;
1690 struct record_cluster *cluster;
1691 struct session_database *sdb = client_get_database(cl);
1692 struct record *record = record_create(se->nmem,
1693 service->num_metadata,
1694 service->num_sortkeys, cl,
1697 for (n = root->children; n; n = n->next)
1705 if (n->type != XML_ELEMENT_NODE)
1707 if (!strcmp((const char *) n->name, "metadata"))
1709 struct conf_metadata *ser_md = 0;
1710 struct record_metadata **wheretoput = 0;
1711 struct record_metadata *rec_md = 0;
1712 int md_field_id = -1;
1714 type = xmlGetProp(n, (xmlChar *) "type");
1715 value = xmlNodeListGetString(xdoc, n->children, 1);
1717 if (!type || !value || !*value)
1721 = conf_service_metadata_field_id(service, (const char *) type);
1722 if (md_field_id < 0)
1724 if (se->number_of_warnings_unknown_metadata == 0)
1726 session_log(se, YLOG_WARN,
1727 "Ignoring unknown metadata element: %s", type);
1729 se->number_of_warnings_unknown_metadata++;
1733 ser_md = &service->metadata[md_field_id];
1735 // non-merged metadata
1736 rec_md = record_metadata_init(se->nmem, (const char *) value,
1737 ser_md->type, n->properties);
1740 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1741 "for element '%s'", value, type);
1744 wheretoput = &record->metadata[md_field_id];
1746 wheretoput = &(*wheretoput)->next;
1747 *wheretoput = rec_md;
1751 if (check_limit_local(cl, record, record_no))
1753 session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1754 record_no, sdb->database->id);
1761 cluster = reclist_insert(se->reclist, service, record,
1762 mergekey_norm, &se->total_merged);
1767 const char *use_term_factor_str =
1768 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1769 if (use_term_factor_str && use_term_factor_str[0] == '1')
1771 int maxrecs = client_get_maxrecs(cl);
1772 int hits = (int) client_get_hits(cl);
1773 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1774 assert(term_factor >= 1);
1775 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1779 if (global_parameters.dump_records)
1780 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1781 sdb->database->id, record_no);
1784 relevance_newrec(se->relevance, cluster);
1786 // now parsing XML record and adding data to cluster or record metadata
1787 for (n = root->children; n; n = n->next)
1789 pp2_charset_token_t prt;
1796 if (n->type != XML_ELEMENT_NODE)
1798 if (!strcmp((const char *) n->name, "metadata"))
1800 struct conf_metadata *ser_md = 0;
1801 struct conf_sortkey *ser_sk = 0;
1802 struct record_metadata **wheretoput = 0;
1803 struct record_metadata *rec_md = 0;
1804 int md_field_id = -1;
1805 int sk_field_id = -1;
1809 type = xmlGetProp(n, (xmlChar *) "type");
1810 value = xmlNodeListGetString(xdoc, n->children, 1);
1812 if (!type || !value || !*value)
1816 = conf_service_metadata_field_id(service, (const char *) type);
1817 if (md_field_id < 0)
1820 ser_md = &service->metadata[md_field_id];
1822 if (ser_md->sortkey_offset >= 0)
1824 sk_field_id = ser_md->sortkey_offset;
1825 ser_sk = &service->sortkeys[sk_field_id];
1829 rec_md = record_metadata_init(se->nmem, (const char *) value,
1834 xml_rank = xmlGetProp(n, (xmlChar *) "rank");
1835 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
1837 wheretoput = &cluster->metadata[md_field_id];
1839 // and polulate with data:
1840 // assign cluster or record based on merge action
1841 if (ser_md->merge == Metadata_merge_unique)
1845 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1846 rec_md->data.text.disp))
1848 wheretoput = &(*wheretoput)->next;
1851 *wheretoput = rec_md;
1853 else if (ser_md->merge == Metadata_merge_longest)
1856 || strlen(rec_md->data.text.disp)
1857 > strlen((*wheretoput)->data.text.disp))
1859 *wheretoput = rec_md;
1862 const char *sort_str = 0;
1864 ser_sk->type == Metadata_sortkey_skiparticle;
1866 if (!cluster->sortkeys[sk_field_id])
1867 cluster->sortkeys[sk_field_id] =
1868 nmem_malloc(se->nmem,
1869 sizeof(union data_types));
1872 pp2_charset_token_create(service->charsets, "sort");
1874 pp2_charset_token_first(prt, rec_md->data.text.disp,
1877 pp2_charset_token_next(prt);
1879 sort_str = pp2_get_sort(prt);
1881 cluster->sortkeys[sk_field_id]->text.disp =
1882 rec_md->data.text.disp;
1885 sort_str = rec_md->data.text.disp;
1886 session_log(se, YLOG_WARN,
1887 "Could not make sortkey. Bug #1858");
1889 cluster->sortkeys[sk_field_id]->text.sort =
1890 nmem_strdup(se->nmem, sort_str);
1891 pp2_charset_token_destroy(prt);
1895 else if (ser_md->merge == Metadata_merge_all)
1898 wheretoput = &(*wheretoput)->next;
1899 *wheretoput = rec_md;
1901 else if (ser_md->merge == Metadata_merge_range)
1905 *wheretoput = rec_md;
1907 cluster->sortkeys[sk_field_id]
1912 int this_min = rec_md->data.number.min;
1913 int this_max = rec_md->data.number.max;
1914 if (this_min < (*wheretoput)->data.number.min)
1915 (*wheretoput)->data.number.min = this_min;
1916 if (this_max > (*wheretoput)->data.number.max)
1917 (*wheretoput)->data.number.max = this_max;
1921 // ranking of _all_ fields enabled ...
1924 relevance_countwords(se->relevance, cluster,
1925 (char *) value, rank, ser_md->name);
1928 // construct facets ... unless the client already has reported them
1929 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1931 if (ser_md->type == Metadata_type_year)
1934 sprintf(year, "%d", rec_md->data.number.max);
1936 add_facet(se, (char *) type, year, term_factor);
1937 if (rec_md->data.number.max != rec_md->data.number.min)
1939 sprintf(year, "%d", rec_md->data.number.min);
1940 add_facet(se, (char *) type, year, term_factor);
1944 add_facet(se, (char *) type, (char *) value, term_factor);
1956 if (se->number_of_warnings_unknown_elements == 0)
1957 session_log(se, YLOG_WARN,
1958 "Unexpected element in internal record: %s", n->name);
1959 se->number_of_warnings_unknown_elements++;
1967 relevance_donerecord(se->relevance, cluster);
1968 se->total_records++;
1973 void session_log(struct session *s, int level, const char *fmt, ...)
1979 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1980 yaz_log(level, "Session %u: %s", s->session_id, buf);
1988 * c-file-style: "Stroustrup"
1989 * indent-tabs-mode: nil
1991 * vim: shiftwidth=4 tabstop=8 expandtab