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>
62 #include <yaz/timing.h>
66 #include "parameters.h"
70 #include "termlists.h"
72 #include "relevance.h"
76 #include "normalize7bit.h"
78 #include <libxml/tree.h>
82 #define MAX(a,b) ((a)>(b)?(a):(b))
84 // Note: Some things in this structure will eventually move to configuration
85 struct parameters global_parameters =
89 0, // predictable sessions
93 struct client *client;
94 struct client_list *next;
97 /* session counting (1) , disable client counting (0) */
98 static YAZ_MUTEX g_session_mutex = 0;
99 static int no_sessions = 0;
100 static int no_session_total = 0;
102 static int session_use(int delta)
105 if (!g_session_mutex)
106 yaz_mutex_create(&g_session_mutex);
107 yaz_mutex_enter(g_session_mutex);
108 no_sessions += delta;
110 no_session_total += delta;
111 sessions = no_sessions;
112 yaz_mutex_leave(g_session_mutex);
113 yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
117 int sessions_count(void)
119 return session_use(0);
122 int session_count_total(void)
125 if (!g_session_mutex)
127 yaz_mutex_enter(g_session_mutex);
128 total = no_session_total;
129 yaz_mutex_leave(g_session_mutex);
133 static void log_xml_doc(xmlDoc *doc)
135 FILE *lf = yaz_log_file();
138 #if LIBXML_VERSION >= 20600
139 xmlDocDumpFormatMemory(doc, &result, &len, 1);
141 xmlDocDumpMemory(doc, &result, &len);
145 (void) fwrite(result, 1, len, lf);
151 static void session_enter(struct session *s)
153 yaz_mutex_enter(s->session_mutex);
156 static void session_leave(struct session *s)
158 yaz_mutex_leave(s->session_mutex);
161 static void session_normalize_facet(struct session *s, const char *type,
166 struct conf_service *service = s->service;
167 pp2_charset_token_t prt;
168 const char *facet_component;
170 const char *icu_chain_id = 0;
172 for (i = 0; i < service->num_metadata; i++)
173 if (!strcmp((service->metadata + i)->name, type))
174 icu_chain_id = (service->metadata + i)->facetrule;
176 icu_chain_id = "facet";
177 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
180 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
182 wrbuf_destroy(facet_wrbuf);
183 wrbuf_destroy(display_wrbuf);
186 pp2_charset_token_first(prt, value, 0);
187 while ((facet_component = pp2_charset_token_next(prt)))
189 const char *display_component;
190 if (*facet_component)
192 if (wrbuf_len(facet_wrbuf))
193 wrbuf_puts(facet_wrbuf, " ");
194 wrbuf_puts(facet_wrbuf, facet_component);
196 display_component = pp2_get_display(prt);
197 if (display_component)
199 if (wrbuf_len(display_wrbuf))
200 wrbuf_puts(display_wrbuf, " ");
201 wrbuf_puts(display_wrbuf, display_component);
204 pp2_charset_token_destroy(prt);
207 void add_facet(struct session *s, const char *type, const char *value, int count)
209 WRBUF facet_wrbuf = wrbuf_alloc();
210 WRBUF display_wrbuf = wrbuf_alloc();
212 session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
214 if (wrbuf_len(facet_wrbuf))
217 for (i = 0; i < s->num_termlists; i++)
218 if (!strcmp(s->termlists[i].name, type))
220 if (i == s->num_termlists)
222 if (i == SESSION_MAX_TERMLISTS)
224 session_log(s, YLOG_FATAL, "Too many termlists");
225 wrbuf_destroy(facet_wrbuf);
226 wrbuf_destroy(display_wrbuf);
230 s->termlists[i].name = nmem_strdup(s->nmem, type);
231 s->termlists[i].termlist = termlist_create(s->nmem);
232 s->num_termlists = i + 1;
236 session_log(s, YLOG_LOG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
238 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
239 wrbuf_cstr(facet_wrbuf), count);
241 wrbuf_destroy(facet_wrbuf);
242 wrbuf_destroy(display_wrbuf);
245 static xmlDoc *record_to_xml(struct session *se,
246 struct session_database *sdb, const char *rec)
248 struct database *db = sdb->database;
251 rdoc = xmlParseMemory(rec, strlen(rec));
255 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
260 if (global_parameters.dump_records)
262 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
269 #define MAX_XSLT_ARGS 16
271 // Add static values from session database settings if applicable
272 static void insert_settings_parameters(struct session_database *sdb,
273 struct conf_service *service,
281 for (i = 0; i < service->num_metadata; i++)
283 struct conf_metadata *md = &service->metadata[i];
286 if (md->setting == Metadata_setting_parameter &&
287 (setting = settings_lookup_offset(service, md->name)) >= 0)
289 const char *val = session_setting_oneval(sdb, setting);
290 if (val && nparms < MAX_XSLT_ARGS)
293 int len = strlen(val);
294 buf = nmem_malloc(nmem, len + 3);
296 strcpy(buf + 1, val);
299 parms[offset++] = md->name;
300 parms[offset++] = buf;
308 // Add static values from session database settings if applicable
309 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
310 struct conf_service *service)
314 for (i = 0; i < service->num_metadata; i++)
316 struct conf_metadata *md = &service->metadata[i];
319 if (md->setting == Metadata_setting_postproc &&
320 (offset = settings_lookup_offset(service, md->name)) >= 0)
322 const char *val = session_setting_oneval(sdb, offset);
325 xmlNode *r = xmlDocGetRootElement(doc);
326 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
328 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
334 static xmlDoc *normalize_record(struct session *se,
335 struct session_database *sdb,
336 struct conf_service *service,
337 const char *rec, NMEM nmem)
339 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
343 char *parms[MAX_XSLT_ARGS*2+1];
345 insert_settings_parameters(sdb, service, parms, nmem);
347 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
349 session_log(se, YLOG_WARN, "Normalize failed from %s",
354 insert_settings_values(sdb, rdoc, service);
356 if (global_parameters.dump_records)
358 session_log(se, YLOG_LOG, "Normalized record from %s",
367 void session_settings_dump(struct session *se,
368 struct session_database *db,
373 int i, num = db->num_settings;
374 for (i = 0; i < num; i++)
376 struct setting *s = db->settings[i];
377 for (;s ; s = s->next)
379 wrbuf_puts(w, "<set name=\"");
380 wrbuf_xmlputs(w, s->name);
381 wrbuf_puts(w, "\" value=\"");
382 wrbuf_xmlputs(w, s->value);
383 wrbuf_puts(w, "\"/>");
391 // Retrieve first defined value for 'name' for given database.
392 // Will be extended to take into account user associated with session
393 const char *session_setting_oneval(struct session_database *db, int offset)
395 if (offset >= db->num_settings || !db->settings[offset])
397 return db->settings[offset]->value;
400 // Prepare XSLT stylesheets for record normalization
401 // Structures are allocated on the session_wide nmem to avoid having
402 // to recompute this for every search. This would lead
403 // to leaking if a single session was to repeatedly change the PZ_XSLT
404 // setting. However, this is not a realistic use scenario.
405 static int prepare_map(struct session *se, struct session_database *sdb)
407 if (sdb->settings && !sdb->map)
411 if (sdb->settings[PZ_XSLT] &&
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,
448 // called if watch should be removed because http_channel is to be destroyed
449 static void session_watch_cancel(void *data, struct http_channel *c,
452 struct session_watchentry *ent = data;
459 // set watch. Returns 0=OK, -1 if watch is already set
460 int session_set_watch(struct session *s, int what,
461 session_watchfun fun, void *data,
462 struct http_channel *chan)
466 if (s->watchlist[what].fun)
471 s->watchlist[what].fun = fun;
472 s->watchlist[what].data = data;
473 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
474 session_watch_cancel);
481 void session_alert_watch(struct session *s, int what)
485 if (s->watchlist[what].fun)
487 /* our watch is no longer associated with http_channel */
489 session_watchfun fun;
491 http_remove_observer(s->watchlist[what].obs);
492 fun = s->watchlist[what].fun;
493 data = s->watchlist[what].data;
495 /* reset watch before fun is invoked - in case fun wants to set
497 s->watchlist[what].fun = 0;
498 s->watchlist[what].data = 0;
499 s->watchlist[what].obs = 0;
502 session_log(s, YLOG_DEBUG,
503 "Alert Watch: %d calling function: %p", what, fun);
510 //callback for grep_databases
511 static void select_targets_callback(struct session *se,
512 struct session_database *db)
515 struct client_list *l;
517 for (l = se->clients_cached; l; l = l->next)
518 if (client_get_database(l->client) == db)
525 cl = client_create(db->database->id);
526 client_set_database(cl, db);
528 l = xmalloc(sizeof(*l));
530 l->next = se->clients_cached;
531 se->clients_cached = l;
533 /* set session always. If may be 0 if client is not active */
534 client_set_session(cl, se);
536 l = xmalloc(sizeof(*l));
538 l->next = se->clients_active;
539 se->clients_active = l;
542 static void session_reset_active_clients(struct session *se,
543 struct client_list *new_list)
545 struct client_list *l;
548 l = se->clients_active;
549 se->clients_active = new_list;
554 struct client_list *l_next = l->next;
556 client_lock(l->client);
557 client_set_session(l->client, 0); /* mark client inactive */
558 client_unlock(l->client);
565 static void session_remove_cached_clients(struct session *se)
567 struct client_list *l;
569 session_reset_active_clients(se, 0);
572 l = se->clients_cached;
573 se->clients_cached = 0;
578 struct client_list *l_next = l->next;
579 client_lock(l->client);
580 client_set_session(l->client, 0);
581 client_set_database(l->client, 0);
582 client_unlock(l->client);
583 client_destroy(l->client);
589 // Associates a set of clients with a session;
590 // Note: Session-databases represent databases with per-session
592 static int select_targets(struct session *se, const char *filter)
594 return session_grep_databases(se, filter, select_targets_callback);
597 int session_active_clients(struct session *s)
599 struct client_list *l;
602 for (l = s->clients_active; l; l = l->next)
603 if (client_is_active(l->client))
609 int session_is_preferred_clients_ready(struct session *s)
611 struct client_list *l;
614 for (l = s->clients_active; l; l = l->next)
615 if (client_is_active_preferred(l->client))
617 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
621 static void session_clear_set(struct session *se, struct reclist_sortparms *sp)
623 reclist_destroy(se->reclist);
625 if (nmem_total(se->nmem))
626 session_log(se, YLOG_DEBUG, "NMEN operation usage %zd",
627 nmem_total(se->nmem));
628 nmem_reset(se->nmem);
629 se->total_records = se->total_merged = 0;
630 se->num_termlists = 0;
632 /* reset list of sorted results and clear to relevance search */
633 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
634 se->sorted_results->name = nmem_strdup(se->nmem, sp->name);
635 se->sorted_results->increasing = sp->increasing;
636 se->sorted_results->type = sp->type;
637 se->sorted_results->next = 0;
639 session_log(se, YLOG_DEBUG, "clear_set session_sort: field=%s increasing=%d type=%d configured",
640 sp->name, sp->increasing, sp->type);
642 se->reclist = reclist_create(se->nmem);
645 void session_sort(struct session *se, struct reclist_sortparms *sp)
647 struct reclist_sortparms *sr;
648 struct client_list *l;
649 const char *field = sp->name;
650 int increasing = sp->increasing;
652 int clients_research = 0;
655 yaz_log(YLOG_LOG, "session_sort field=%s increasing=%d type=%d", field, increasing, type);
656 /* see if we already have sorted for this criteria */
657 for (sr = se->sorted_results; sr; sr = sr->next)
659 if (!reclist_sortparms_cmp(sr,sp))
664 session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d already fetched",
665 field, increasing, type);
669 session_log(se, YLOG_DEBUG, "search_sort: field=%s increasing=%d type=%d must fetch",
670 field, increasing, type);
672 // We need to reset reclist on every sort that changes the records, not just for position
673 // So if just one client requires new searching, we need to clear set.
674 // Ask each of the client if sorting requires re-search due to native sort
675 // If it does it will require us to
676 for (l = se->clients_active; l; l = l->next)
678 struct client *cl = l->client;
679 // Assume no re-search is required.
680 client_parse_init(cl, 1);
681 clients_research += client_parse_sort(cl, sp);
683 if (clients_research) {
684 yaz_log(YLOG_DEBUG, "Reset results due to %d clients researching", clients_research);
685 session_clear_set(se, sp);
688 // A new sorting based on same record set
689 sr = nmem_malloc(se->nmem, sizeof(*sr));
690 sr->name = nmem_strdup(se->nmem, field);
691 sr->increasing = increasing;
693 sr->next = se->sorted_results;
694 se->sorted_results = sr;
696 // yaz_log(YLOG_DEBUG, "Restarting search or re-ingesting for clients due to change in sort order");
698 for (l = se->clients_active; l; l = l->next)
700 struct client *cl = l->client;
701 if (client_get_state(cl) == Client_Connecting ||
702 client_get_state(cl) == Client_Idle ||
703 client_get_state(cl) == Client_Working) {
704 client_start_search(cl);
707 yaz_log(YLOG_DEBUG, "Client %s: Not re-start/ingest in show. Wrong client state: %d",
708 client_get_id(cl), client_get_state(cl));
715 enum pazpar2_error_code session_search(struct session *se,
717 const char *startrecs,
721 const char **addinfo,
722 struct reclist_sortparms *sp)
724 int live_channels = 0;
726 int no_failed_query = 0;
727 int no_failed_limit = 0;
728 struct client_list *l, *l0;
729 facet_limits_t facet_limits;
730 int same_sort_order = 0;
732 session_log(se, YLOG_DEBUG, "Search");
736 if (se->settings_modified)
737 session_remove_cached_clients(se);
739 session_reset_active_clients(se, 0);
742 se->settings_modified = 0;
744 if (se->sorted_results) {
745 if (!reclist_sortparms_cmp(se->sorted_results, sp))
748 session_clear_set(se, sp);
749 relevance_destroy(&se->relevance);
751 live_channels = select_targets(se, filter);
755 return PAZPAR2_NO_TARGETS;
758 facet_limits = facet_limits_create(limit);
763 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
766 l0 = se->clients_active;
767 se->clients_active = 0;
770 for (l = l0; l; l = l->next)
773 struct client *cl = l->client;
774 client_parse_init(cl, 1);
775 if (prepare_map(se, client_get_database(cl)) < 0)
778 parse_ret = client_parse_query(cl, query, facet_limits, se->service->ccl_bibset);
781 else if (parse_ret == -2)
783 else if (parse_ret < 0)
784 no_working++; /* other error, such as bad CCL map */
787 client_parse_range(cl, startrecs, maxrecs);
788 client_parse_sort(cl, sp);
789 client_start_search(cl);
793 facet_limits_destroy(facet_limits);
794 session_reset_active_clients(se, l0);
798 if (no_failed_query > 0)
801 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
803 else if (no_failed_limit > 0)
806 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
809 return PAZPAR2_NO_TARGETS;
811 session_log(se, YLOG_LOG, "session_start_search done");
812 return PAZPAR2_NO_ERROR;
815 // Creates a new session_database object for a database
816 static void session_init_databases_fun(void *context, struct database *db)
818 struct session *se = (struct session *) context;
819 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
825 assert(db->settings);
826 new->settings = nmem_malloc(se->session_nmem,
827 sizeof(struct settings *) * db->num_settings);
828 new->num_settings = db->num_settings;
829 for (i = 0; i < db->num_settings; i++)
831 struct setting *setting = db->settings[i];
832 new->settings[i] = setting;
834 new->next = se->databases;
838 // Doesn't free memory associated with sdb -- nmem takes care of that
839 static void session_database_destroy(struct session_database *sdb)
844 // Initialize session_database list -- this represents this session's view
845 // of the database list -- subject to modification by the settings ws command
846 void session_init_databases(struct session *se)
849 predef_grep_databases(se, se->service, session_init_databases_fun);
852 // Probably session_init_databases_fun should be refactored instead of
854 static struct session_database *load_session_database(struct session *se,
857 struct database *db = new_database_inherit_settings(id, se->session_nmem, se->service->settings);
858 session_init_databases_fun((void*) se, db);
860 // New sdb is head of se->databases list
861 return se->databases;
864 // Find an existing session database. If not found, load it
865 static struct session_database *find_session_database(struct session *se,
868 struct session_database *sdb;
870 for (sdb = se->databases; sdb; sdb = sdb->next)
871 if (!strcmp(sdb->database->id, id))
873 return load_session_database(se, id);
876 // Apply a session override to a database
877 void session_apply_setting(struct session *se, char *dbname, char *setting,
880 struct session_database *sdb = find_session_database(se, dbname);
881 struct conf_service *service = se->service;
882 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
883 int offset = settings_create_offset(service, setting);
885 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
888 new->target = dbname;
891 new->next = sdb->settings[offset];
892 sdb->settings[offset] = new;
894 se->settings_modified = 1;
896 // Force later recompute of settings-driven data structures
897 // (happens when a search starts and client connections are prepared)
909 void session_destroy(struct session *se)
911 struct session_database *sdb;
912 session_log(se, YLOG_DEBUG, "Destroying");
914 session_remove_cached_clients(se);
916 for (sdb = se->databases; sdb; sdb = sdb->next)
917 session_database_destroy(sdb);
918 normalize_cache_destroy(se->normalize_cache);
919 relevance_destroy(&se->relevance);
920 reclist_destroy(se->reclist);
921 if (nmem_total(se->nmem))
922 session_log(se, YLOG_DEBUG, "NMEN operation usage %zd", nmem_total(se->nmem));
923 if (nmem_total(se->session_nmem))
924 session_log(se, YLOG_DEBUG, "NMEN session usage %zd", nmem_total(se->session_nmem));
925 nmem_destroy(se->nmem);
926 service_destroy(se->service);
927 yaz_mutex_destroy(&se->session_mutex);
930 size_t session_get_memory_status(struct session *session) {
934 session_enter(session);
935 session_nmem = nmem_total(session->nmem);
936 session_leave(session);
941 struct session *new_session(NMEM nmem, struct conf_service *service,
945 struct session *session = nmem_malloc(nmem, sizeof(*session));
949 sprintf(tmp_str, "session#%u", session_id);
951 session->session_id = session_id;
952 session_log(session, YLOG_DEBUG, "New");
953 session->service = service;
954 session->relevance = 0;
955 session->total_records = 0;
956 session->number_of_warnings_unknown_elements = 0;
957 session->number_of_warnings_unknown_metadata = 0;
958 session->num_termlists = 0;
959 session->reclist = 0;
960 session->clients_active = 0;
961 session->clients_cached = 0;
962 session->settings_modified = 0;
963 session->session_nmem = nmem;
964 session->nmem = nmem_create();
965 session->databases = 0;
966 session->sorted_results = 0;
968 for (i = 0; i <= SESSION_WATCH_MAX; i++)
970 session->watchlist[i].data = 0;
971 session->watchlist[i].fun = 0;
973 session->normalize_cache = normalize_cache_create();
974 session->session_mutex = 0;
975 pazpar2_mutex_create(&session->session_mutex, tmp_str);
980 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
982 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
983 int *count, NMEM nmem)
985 struct hitsbytarget *res = 0;
986 struct client_list *l;
989 for (l = se->clients_active; l; l = l->next)
992 res = nmem_malloc(nmem, sizeof(*res) * sz);
994 for (l = se->clients_active; l; l = l->next)
996 struct client *cl = l->client;
997 WRBUF w = wrbuf_alloc();
998 const char *name = session_setting_oneval(client_get_database(cl),
1001 res[*count].id = client_get_id(cl);
1002 res[*count].name = *name ? name : "Unknown";
1003 res[*count].hits = client_get_hits(cl);
1004 res[*count].approximation = client_get_approximation(cl);
1005 res[*count].records = client_get_num_records(cl);
1006 res[*count].filtered = client_get_num_records_filtered(cl);
1007 res[*count].diagnostic =
1008 client_get_diagnostic(cl, &res[*count].addinfo);
1009 res[*count].state = client_get_state_str(cl);
1010 res[*count].connected = client_get_connection(cl) ? 1 : 0;
1011 session_settings_dump(se, client_get_database(cl), w);
1012 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1015 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1022 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1024 struct hitsbytarget *p;
1026 p = hitsbytarget_nb(se, count, nmem);
1031 // Compares two hitsbytarget nodes by hitcount
1032 static int cmp_ht(const void *p1, const void *p2)
1034 const struct hitsbytarget *h1 = p1;
1035 const struct hitsbytarget *h2 = p2;
1036 return h2->hits - h1->hits;
1039 // Compares two hitsbytarget nodes by hitcount
1040 static int cmp_ht_approx(const void *p1, const void *p2)
1042 const struct hitsbytarget *h1 = p1;
1043 const struct hitsbytarget *h2 = p2;
1044 return h2->approximation - h1->approximation;
1047 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1048 NMEM nmem, int version)
1050 struct hitsbytarget *ht;
1053 ht = hitsbytarget_nb(se, &count, nmem);
1055 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht_approx);
1057 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1058 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1061 // do only print terms which have display names
1063 wrbuf_puts(wrbuf, "<term>\n");
1065 wrbuf_puts(wrbuf, "<id>");
1066 wrbuf_xmlputs(wrbuf, ht[i].id);
1067 wrbuf_puts(wrbuf, "</id>\n");
1069 wrbuf_puts(wrbuf, "<name>");
1070 if (!ht[i].name || !ht[i].name[0])
1071 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1073 wrbuf_xmlputs(wrbuf, ht[i].name);
1074 wrbuf_puts(wrbuf, "</name>\n");
1076 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1080 // Should not print if we know it isn't a approximation.
1081 wrbuf_printf(wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
1082 wrbuf_printf(wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
1083 wrbuf_printf(wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
1086 wrbuf_puts(wrbuf, "<state>");
1087 wrbuf_xmlputs(wrbuf, ht[i].state);
1088 wrbuf_puts(wrbuf, "</state>\n");
1090 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1092 wrbuf_puts(wrbuf, "</term>\n");
1097 void perform_termlist(struct http_channel *c, struct session *se,
1098 const char *name, int num, int version)
1101 NMEM nmem_tmp = nmem_create();
1108 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1112 for (j = 0; j < num_names; j++)
1115 int must_generate_empty = 1; /* bug 5350 */
1117 for (i = 0; i < se->num_termlists; i++)
1119 tname = se->termlists[i].name;
1120 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1122 struct termlist_score **p = 0;
1125 wrbuf_puts(c->wrbuf, "<list name=\"");
1126 wrbuf_xmlputs(c->wrbuf, tname);
1127 wrbuf_puts(c->wrbuf, "\">\n");
1128 must_generate_empty = 0;
1130 p = termlist_highscore(se->termlists[i].termlist, &len,
1135 for (i = 0; i < len && i < num; i++)
1137 // prevent sending empty term elements
1138 if (!p[i]->display_term || !p[i]->display_term[0])
1141 wrbuf_puts(c->wrbuf, "<term>");
1142 wrbuf_puts(c->wrbuf, "<name>");
1143 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1144 wrbuf_puts(c->wrbuf, "</name>");
1146 wrbuf_printf(c->wrbuf,
1147 "<frequency>%d</frequency>",
1149 wrbuf_puts(c->wrbuf, "</term>\n");
1152 wrbuf_puts(c->wrbuf, "</list>\n");
1156 if (!strcmp(names[j], tname) || !strcmp(names[j], "*"))
1158 wrbuf_puts(c->wrbuf, "<list name=\"");
1159 wrbuf_xmlputs(c->wrbuf, tname);
1160 wrbuf_puts(c->wrbuf, "\">\n");
1162 targets_termlist_nb(c->wrbuf, se, num, c->nmem, version);
1163 wrbuf_puts(c->wrbuf, "</list>\n");
1164 must_generate_empty = 0;
1166 if (must_generate_empty)
1168 wrbuf_puts(c->wrbuf, "<list name=\"");
1169 wrbuf_xmlputs(c->wrbuf, names[j]);
1170 wrbuf_puts(c->wrbuf, "\"/>\n");
1174 nmem_destroy(nmem_tmp);
1177 #ifdef MISSING_HEADERS
1178 void report_nmem_stats(void)
1180 size_t in_use, is_free;
1182 nmem_get_memory_in_use(&in_use);
1183 nmem_get_memory_free(&is_free);
1185 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1186 (long) in_use, (long) is_free);
1190 struct record_cluster *show_single_start(struct session *se, const char *id,
1191 struct record_cluster **prev_r,
1192 struct record_cluster **next_r)
1194 struct record_cluster *r = 0;
1201 reclist_enter(se->reclist);
1202 while ((r = reclist_read_record(se->reclist)))
1204 if (!strcmp(r->recid, id))
1206 *next_r = reclist_read_record(se->reclist);
1211 reclist_leave(se->reclist);
1218 void show_single_stop(struct session *se, struct record_cluster *rec)
1223 struct record_cluster **show_range_start(struct session *se,
1224 struct reclist_sortparms *sp,
1225 int start, int *num, int *total, Odr_int *sumhits, Odr_int *approx_hits)
1227 struct record_cluster **recs;
1228 struct reclist_sortparms *spp;
1231 yaz_timing_t t = yaz_timing_create();
1234 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1245 struct client_list *l;
1247 for (spp = sp; spp; spp = spp->next)
1248 if (spp->type == Metadata_sortkey_relevance)
1250 relevance_prepare_read(se->relevance, se->reclist);
1253 reclist_sort(se->reclist, sp);
1255 reclist_enter(se->reclist);
1256 *total = reclist_get_num_records(se->reclist);
1260 for (l = se->clients_active; l; l = l->next) {
1261 *sumhits += client_get_hits(l->client);
1262 *approx_hits += client_get_approximation(l->client);
1264 for (i = 0; i < start; i++)
1265 if (!reclist_read_record(se->reclist))
1272 for (i = 0; i < *num; i++)
1274 struct record_cluster *r = reclist_read_record(se->reclist);
1282 reclist_leave(se->reclist);
1286 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1287 yaz_timing_get_real(t), yaz_timing_get_user(t),
1288 yaz_timing_get_sys(t));
1289 yaz_timing_destroy(&t);
1294 void show_range_stop(struct session *se, struct record_cluster **recs)
1299 void statistics(struct session *se, struct statistics *stat)
1301 struct client_list *l;
1304 memset(stat, 0, sizeof(*stat));
1306 for (l = se->clients_active; l; l = l->next)
1308 struct client *cl = l->client;
1309 if (!client_get_connection(cl))
1310 stat->num_no_connection++;
1311 stat->num_hits += client_get_hits(cl);
1312 switch (client_get_state(cl))
1314 case Client_Connecting: stat->num_connecting++; break;
1315 case Client_Working: stat->num_working++; break;
1316 case Client_Idle: stat->num_idle++; break;
1317 case Client_Failed: stat->num_failed++; break;
1318 case Client_Error: stat->num_error++; break;
1323 stat->num_records = se->total_records;
1325 stat->num_clients = count;
1328 static struct record_metadata *record_metadata_init(
1329 NMEM nmem, const char *value, enum conf_metadata_type type,
1330 struct _xmlAttr *attr)
1332 struct record_metadata *rec_md = record_metadata_create(nmem);
1333 struct record_metadata_attr **attrp = &rec_md->attributes;
1335 for (; attr; attr = attr->next)
1337 if (attr->children && attr->children->content)
1339 if (strcmp((const char *) attr->name, "type"))
1340 { /* skip the "type" attribute.. Its value is already part of
1341 the element in output (md-%s) and so repeating it here
1343 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1345 nmem_strdup(nmem, (const char *) attr->name);
1347 nmem_strdup(nmem, (const char *) attr->children->content);
1348 attrp = &(*attrp)->next;
1354 if (type == Metadata_type_generic)
1356 char *p = nmem_strdup(nmem, value);
1358 p = normalize7bit_generic(p, " ,/.:([");
1360 rec_md->data.text.disp = p;
1361 rec_md->data.text.sort = 0;
1363 else if (type == Metadata_type_year || type == Metadata_type_date)
1368 if (type == Metadata_type_date)
1370 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1373 rec_md->data.number.min = first;
1374 rec_md->data.number.max = last;
1381 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1382 struct conf_service *service, WRBUF norm_wr)
1386 for (n = root->children; n; n = n->next)
1388 if (n->type != XML_ELEMENT_NODE)
1390 if (!strcmp((const char *) n->name, "metadata"))
1392 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1394 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1396 else if (!strcmp(name, (const char *) type))
1398 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1401 const char *norm_str;
1402 pp2_charset_token_t prt =
1403 pp2_charset_token_create(service->charsets, "mergekey");
1405 pp2_charset_token_first(prt, (const char *) value, 0);
1406 if (wrbuf_len(norm_wr) > 0)
1407 wrbuf_puts(norm_wr, " ");
1408 wrbuf_puts(norm_wr, name);
1410 pp2_charset_token_next(prt)))
1414 wrbuf_puts(norm_wr, " ");
1415 wrbuf_puts(norm_wr, norm_str);
1419 pp2_charset_token_destroy(prt);
1429 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1430 struct conf_service *service, NMEM nmem)
1432 char *mergekey_norm = 0;
1433 xmlNode *root = xmlDocGetRootElement(doc);
1434 WRBUF norm_wr = wrbuf_alloc();
1436 /* consider mergekey from XSL first */
1437 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1440 const char *norm_str;
1441 pp2_charset_token_t prt =
1442 pp2_charset_token_create(service->charsets, "mergekey");
1444 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1445 while ((norm_str = pp2_charset_token_next(prt)))
1449 if (wrbuf_len(norm_wr))
1450 wrbuf_puts(norm_wr, " ");
1451 wrbuf_puts(norm_wr, norm_str);
1454 pp2_charset_token_destroy(prt);
1459 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1461 for (field_id = 0; field_id < service->num_metadata; field_id++)
1463 struct conf_metadata *ser_md = &service->metadata[field_id];
1464 if (ser_md->mergekey != Metadata_mergekey_no)
1466 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1468 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1470 /* no mergekey on this one and it is required..
1471 Generate unique key instead */
1472 wrbuf_rewind(norm_wr);
1479 /* generate unique key if none is not generated already or is empty */
1480 if (wrbuf_len(norm_wr) == 0)
1482 wrbuf_printf(norm_wr, "position: %s-%d",
1483 client_get_id(cl), record_no);
1487 const char *lead = "content: ";
1488 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1490 if (wrbuf_len(norm_wr) > 0)
1491 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1492 wrbuf_destroy(norm_wr);
1493 return mergekey_norm;
1496 /** \brief see if metadata for pz:recordfilter exists
1497 \param root xml root element of normalized record
1498 \param sdb session database for client
1499 \retval 0 if there is no metadata for pz:recordfilter
1500 \retval 1 if there is metadata for pz:recordfilter
1502 If there is no pz:recordfilter defined, this function returns 1
1506 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1511 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1516 for (n = root->children; n; n = n->next)
1518 if (n->type != XML_ELEMENT_NODE)
1520 if (!strcmp((const char *) n->name, "metadata"))
1522 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1529 if ((eq = strchr(s, '=')))
1531 else if ((eq = strchr(s, '~')))
1537 if (len == strlen((const char *)type) &&
1538 !memcmp((const char *) type, s, len))
1540 xmlChar *value = xmlNodeGetContent(n);
1541 if (value && *value)
1544 (substring && strstr((const char *) value, eq+1)) ||
1545 (!substring && !strcmp((const char *) value, eq + 1)))
1558 static int ingest_to_cluster(struct client *cl,
1562 const char *mergekey_norm);
1564 /** \brief ingest XML record
1565 \param cl client holds the result set for record
1566 \param rec record buffer (0 terminated)
1567 \param record_no record position (1, 2, ..)
1568 \param nmem working NMEM
1573 int ingest_record(struct client *cl, const char *rec,
1574 int record_no, NMEM nmem)
1576 struct session *se = client_get_session(cl);
1578 struct session_database *sdb = client_get_database(cl);
1579 struct conf_service *service = se->service;
1580 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1582 const char *mergekey_norm;
1587 root = xmlDocGetRootElement(xdoc);
1589 if (!check_record_filter(root, sdb))
1591 session_log(se, YLOG_LOG, "Filtered out record no %d from %s", record_no, sdb->database->id);
1596 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1599 session_log(se, YLOG_WARN, "Got no mergekey");
1604 if (client_get_session(cl) == se)
1605 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1612 // Skip record on non-zero
1613 static int check_limit_local(struct client *cl,
1614 struct record *record,
1617 int skip_record = 0;
1618 struct session *se = client_get_session(cl);
1619 struct conf_service *service = se->service;
1620 NMEM nmem_tmp = nmem_create();
1621 struct session_database *sdb = client_get_database(cl);
1623 while (!skip_record)
1625 struct conf_metadata *ser_md = 0;
1626 struct record_metadata *rec_md = 0;
1631 const char *name = client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v, &values);
1635 md_field_id = conf_service_metadata_field_id(service, name);
1636 if (md_field_id < 0)
1641 ser_md = &service->metadata[md_field_id];
1642 rec_md = record->metadata[md_field_id];
1643 yaz_log(YLOG_DEBUG, "check limit local %s", name);
1644 for (i = 0; i < num_v; )
1648 if (ser_md->type == Metadata_type_year
1649 || ser_md->type == Metadata_type_date)
1651 int y = atoi(values[i]);
1652 if (y >= rec_md->data.number.min
1653 && y <= rec_md->data.number.max)
1658 yaz_log(YLOG_DEBUG, "cmp: '%s' '%s'", rec_md->data.text.disp, values[i]);
1659 if (!strcmp(rec_md->data.text.disp, values[i]))
1661 // Value equals, should not be filtered.
1665 rec_md = rec_md->next;
1669 rec_md = record->metadata[md_field_id];
1673 // At end , not match
1680 nmem_destroy(nmem_tmp);
1684 static int ingest_to_cluster(struct client *cl,
1688 const char *mergekey_norm)
1693 struct session *se = client_get_session(cl);
1694 struct conf_service *service = se->service;
1695 int term_factor = 1;
1696 struct record_cluster *cluster;
1697 struct session_database *sdb = client_get_database(cl);
1698 struct record *record = record_create(se->nmem,
1699 service->num_metadata,
1700 service->num_sortkeys, cl,
1703 for (n = root->children; n; n = n->next)
1711 if (n->type != XML_ELEMENT_NODE)
1713 if (!strcmp((const char *) n->name, "metadata"))
1715 struct conf_metadata *ser_md = 0;
1716 struct record_metadata **wheretoput = 0;
1717 struct record_metadata *rec_md = 0;
1718 int md_field_id = -1;
1720 type = xmlGetProp(n, (xmlChar *) "type");
1721 value = xmlNodeListGetString(xdoc, n->children, 1);
1723 if (!type || !value || !*value)
1727 = conf_service_metadata_field_id(service, (const char *) type);
1728 if (md_field_id < 0)
1730 if (se->number_of_warnings_unknown_metadata == 0)
1732 session_log(se, YLOG_WARN,
1733 "Ignoring unknown metadata element: %s", type);
1735 se->number_of_warnings_unknown_metadata++;
1739 ser_md = &service->metadata[md_field_id];
1741 // non-merged metadata
1742 rec_md = record_metadata_init(se->nmem, (const char *) value,
1743 ser_md->type, n->properties);
1746 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1747 "for element '%s'", value, type);
1750 wheretoput = &record->metadata[md_field_id];
1752 wheretoput = &(*wheretoput)->next;
1753 *wheretoput = rec_md;
1757 if (check_limit_local(cl, record, record_no))
1759 session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1760 record_no, sdb->database->id);
1767 cluster = reclist_insert(se->reclist, service, record,
1768 mergekey_norm, &se->total_merged);
1773 const char *use_term_factor_str =
1774 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1775 if (use_term_factor_str && use_term_factor_str[0] == '1')
1777 int maxrecs = client_get_maxrecs(cl);
1778 int hits = (int) client_get_hits(cl);
1779 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1780 assert(term_factor >= 1);
1781 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1785 if (global_parameters.dump_records)
1786 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1787 sdb->database->id, record_no);
1790 relevance_newrec(se->relevance, cluster);
1792 // now parsing XML record and adding data to cluster or record metadata
1793 for (n = root->children; n; n = n->next)
1795 pp2_charset_token_t prt;
1802 if (n->type != XML_ELEMENT_NODE)
1804 if (!strcmp((const char *) n->name, "metadata"))
1806 struct conf_metadata *ser_md = 0;
1807 struct conf_sortkey *ser_sk = 0;
1808 struct record_metadata **wheretoput = 0;
1809 struct record_metadata *rec_md = 0;
1810 int md_field_id = -1;
1811 int sk_field_id = -1;
1815 type = xmlGetProp(n, (xmlChar *) "type");
1816 value = xmlNodeListGetString(xdoc, n->children, 1);
1818 if (!type || !value || !*value)
1822 = conf_service_metadata_field_id(service, (const char *) type);
1823 if (md_field_id < 0)
1826 ser_md = &service->metadata[md_field_id];
1828 if (ser_md->sortkey_offset >= 0)
1830 sk_field_id = ser_md->sortkey_offset;
1831 ser_sk = &service->sortkeys[sk_field_id];
1835 rec_md = record_metadata_init(se->nmem, (const char *) value,
1840 xml_rank = xmlGetProp(n, (xmlChar *) "rank");
1841 rank = xml_rank ? (const char *) xml_rank : ser_md->rank;
1843 wheretoput = &cluster->metadata[md_field_id];
1845 // and polulate with data:
1846 // assign cluster or record based on merge action
1847 if (ser_md->merge == Metadata_merge_unique)
1851 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1852 rec_md->data.text.disp))
1854 wheretoput = &(*wheretoput)->next;
1857 *wheretoput = rec_md;
1859 else if (ser_md->merge == Metadata_merge_longest)
1862 || strlen(rec_md->data.text.disp)
1863 > strlen((*wheretoput)->data.text.disp))
1865 *wheretoput = rec_md;
1868 const char *sort_str = 0;
1870 ser_sk->type == Metadata_sortkey_skiparticle;
1872 if (!cluster->sortkeys[sk_field_id])
1873 cluster->sortkeys[sk_field_id] =
1874 nmem_malloc(se->nmem,
1875 sizeof(union data_types));
1878 pp2_charset_token_create(service->charsets, "sort");
1880 pp2_charset_token_first(prt, rec_md->data.text.disp,
1883 pp2_charset_token_next(prt);
1885 sort_str = pp2_get_sort(prt);
1887 cluster->sortkeys[sk_field_id]->text.disp =
1888 rec_md->data.text.disp;
1891 sort_str = rec_md->data.text.disp;
1892 session_log(se, YLOG_WARN,
1893 "Could not make sortkey. Bug #1858");
1895 cluster->sortkeys[sk_field_id]->text.sort =
1896 nmem_strdup(se->nmem, sort_str);
1897 pp2_charset_token_destroy(prt);
1901 else if (ser_md->merge == Metadata_merge_all)
1904 wheretoput = &(*wheretoput)->next;
1905 *wheretoput = rec_md;
1907 else if (ser_md->merge == Metadata_merge_range)
1911 *wheretoput = rec_md;
1913 cluster->sortkeys[sk_field_id]
1918 int this_min = rec_md->data.number.min;
1919 int this_max = rec_md->data.number.max;
1920 if (this_min < (*wheretoput)->data.number.min)
1921 (*wheretoput)->data.number.min = this_min;
1922 if (this_max > (*wheretoput)->data.number.max)
1923 (*wheretoput)->data.number.max = this_max;
1927 // ranking of _all_ fields enabled ...
1930 relevance_countwords(se->relevance, cluster,
1931 (char *) value, rank, ser_md->name);
1934 // construct facets ... unless the client already has reported them
1935 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1937 if (ser_md->type == Metadata_type_year)
1940 sprintf(year, "%d", rec_md->data.number.max);
1942 add_facet(se, (char *) type, year, term_factor);
1943 if (rec_md->data.number.max != rec_md->data.number.min)
1945 sprintf(year, "%d", rec_md->data.number.min);
1946 add_facet(se, (char *) type, year, term_factor);
1950 add_facet(se, (char *) type, (char *) value, term_factor);
1962 if (se->number_of_warnings_unknown_elements == 0)
1963 session_log(se, YLOG_WARN,
1964 "Unexpected element in internal record: %s", n->name);
1965 se->number_of_warnings_unknown_elements++;
1973 relevance_donerecord(se->relevance, cluster);
1974 se->total_records++;
1979 void session_log(struct session *s, int level, const char *fmt, ...)
1985 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1986 yaz_log(level, "Session %u: %s", s->session_id, buf);
1994 * c-file-style: "Stroustrup"
1995 * indent-tabs-mode: nil
1997 * vim: shiftwidth=4 tabstop=8 expandtab