1 /* This file is part of Pazpar2.
2 Copyright (C) 2006-2011 Index Data
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 \brief high-level logic; mostly user sessions and settings
46 #include <yaz/marcdisp.h>
47 #include <yaz/comstack.h>
48 #include <yaz/tcpip.h>
49 #include <yaz/proto.h>
50 #include <yaz/readconf.h>
51 #include <yaz/pquery.h>
52 #include <yaz/otherinfo.h>
53 #include <yaz/yaz-util.h>
55 #include <yaz/query-charset.h>
56 #include <yaz/querytowrbuf.h>
57 #include <yaz/oid_db.h>
58 #include <yaz/snprintf.h>
59 #include <yaz/gettimeofday.h>
63 #include <yaz/timing.h>
67 #include "parameters.h"
71 #include "termlists.h"
73 #include "relevance.h"
77 #include "normalize7bit.h"
79 #define TERMLIST_HIGH_SCORE 25
83 #define MAX(a,b) ((a)>(b)?(a):(b))
85 // Note: Some things in this structure will eventually move to configuration
86 struct parameters global_parameters =
90 0, // predictable sessions
94 struct client *client;
95 struct client_list *next;
98 /* session counting (1) , disable client counting (0) */
99 static YAZ_MUTEX g_session_mutex = 0;
100 static int no_sessions = 0;
101 static int no_session_total = 0;
103 static int session_use(int delta)
106 if (!g_session_mutex)
107 yaz_mutex_create(&g_session_mutex);
108 yaz_mutex_enter(g_session_mutex);
109 no_sessions += delta;
111 no_session_total += delta;
112 sessions = no_sessions;
113 yaz_mutex_leave(g_session_mutex);
114 yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
118 int sessions_count(void)
120 return session_use(0);
123 int session_count_total(void)
126 if (!g_session_mutex)
128 yaz_mutex_enter(g_session_mutex);
129 total = no_session_total;
130 yaz_mutex_leave(g_session_mutex);
134 static void log_xml_doc(xmlDoc *doc)
136 FILE *lf = yaz_log_file();
139 #if LIBXML_VERSION >= 20600
140 xmlDocDumpFormatMemory(doc, &result, &len, 1);
142 xmlDocDumpMemory(doc, &result, &len);
146 (void) fwrite(result, 1, len, lf);
152 static void session_enter(struct session *s)
154 yaz_mutex_enter(s->session_mutex);
157 static void session_leave(struct session *s)
159 yaz_mutex_leave(s->session_mutex);
162 void add_facet(struct session *s, const char *type, const char *value, int count)
164 struct conf_service *service = s->service;
165 pp2_charset_token_t prt;
166 const char *facet_component;
167 WRBUF facet_wrbuf = wrbuf_alloc();
168 WRBUF display_wrbuf = wrbuf_alloc();
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);
206 if (wrbuf_len(facet_wrbuf))
209 for (i = 0; i < s->num_termlists; i++)
210 if (!strcmp(s->termlists[i].name, type))
212 if (i == s->num_termlists)
214 if (i == SESSION_MAX_TERMLISTS)
216 session_log(s, YLOG_FATAL, "Too many termlists");
217 wrbuf_destroy(facet_wrbuf);
218 wrbuf_destroy(display_wrbuf);
222 s->termlists[i].name = nmem_strdup(s->nmem, type);
223 s->termlists[i].termlist
224 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
225 s->num_termlists = i + 1;
229 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
231 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
232 wrbuf_cstr(facet_wrbuf), count);
234 wrbuf_destroy(facet_wrbuf);
235 wrbuf_destroy(display_wrbuf);
238 static xmlDoc *record_to_xml(struct session *se,
239 struct session_database *sdb, const char *rec)
241 struct database *db = sdb->database;
244 rdoc = xmlParseMemory(rec, strlen(rec));
248 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
253 if (global_parameters.dump_records)
255 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
262 #define MAX_XSLT_ARGS 16
264 // Add static values from session database settings if applicable
265 static void insert_settings_parameters(struct session_database *sdb,
266 struct conf_service *service,
274 for (i = 0; i < service->num_metadata; i++)
276 struct conf_metadata *md = &service->metadata[i];
279 if (md->setting == Metadata_setting_parameter &&
280 (setting = settings_lookup_offset(service, md->name)) >= 0)
282 const char *val = session_setting_oneval(sdb, setting);
283 if (val && nparms < MAX_XSLT_ARGS)
286 int len = strlen(val);
287 buf = nmem_malloc(nmem, len + 3);
289 strcpy(buf + 1, val);
292 parms[offset++] = md->name;
293 parms[offset++] = buf;
301 // Add static values from session database settings if applicable
302 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
303 struct conf_service *service)
307 for (i = 0; i < service->num_metadata; i++)
309 struct conf_metadata *md = &service->metadata[i];
312 if (md->setting == Metadata_setting_postproc &&
313 (offset = settings_lookup_offset(service, md->name)) >= 0)
315 const char *val = session_setting_oneval(sdb, offset);
318 xmlNode *r = xmlDocGetRootElement(doc);
319 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
321 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
327 static xmlDoc *normalize_record(struct session *se,
328 struct session_database *sdb,
329 struct conf_service *service,
330 const char *rec, NMEM nmem)
332 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
336 char *parms[MAX_XSLT_ARGS*2+1];
338 insert_settings_parameters(sdb, service, parms, nmem);
340 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
342 session_log(se, YLOG_WARN, "Normalize failed from %s",
347 insert_settings_values(sdb, rdoc, service);
349 if (global_parameters.dump_records)
351 session_log(se, YLOG_LOG, "Normalized record from %s",
360 void session_settings_dump(struct session *se,
361 struct session_database *db,
366 int i, num = db->num_settings;
367 for (i = 0; i < num; i++)
369 struct setting *s = db->settings[i];
370 for (;s ; s = s->next)
372 wrbuf_puts(w, "<set name=\"");
373 wrbuf_xmlputs(w, s->name);
374 wrbuf_puts(w, "\" value=\"");
375 wrbuf_xmlputs(w, s->value);
376 wrbuf_puts(w, "\"/>");
384 // Retrieve first defined value for 'name' for given database.
385 // Will be extended to take into account user associated with session
386 const char *session_setting_oneval(struct session_database *db, int offset)
388 if (offset >= db->num_settings || !db->settings[offset])
390 return db->settings[offset]->value;
393 // Prepare XSLT stylesheets for record normalization
394 // Structures are allocated on the session_wide nmem to avoid having
395 // to recompute this for every search. This would lead
396 // to leaking if a single session was to repeatedly change the PZ_XSLT
397 // setting. However, this is not a realistic use scenario.
398 static int prepare_map(struct session *se, struct session_database *sdb)
404 session_log(se, YLOG_WARN, "No settings on %s", sdb->database->id);
407 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
409 char auto_stylesheet[256];
411 if (!strcmp(s, "auto"))
413 const char *request_syntax = session_setting_oneval(
414 sdb, PZ_REQUESTSYNTAX);
418 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
419 "%s.xsl", request_syntax);
420 for (cp = auto_stylesheet; *cp; cp++)
422 /* deliberately only consider ASCII */
423 if (*cp > 32 && *cp < 127)
430 session_log(se, YLOG_WARN,
431 "No pz:requestsyntax for auto stylesheet");
434 sdb->map = normalize_cache_get(se->normalize_cache,
435 se->service->server->config, s);
442 // This analyzes settings and recomputes any supporting data structures
444 static int prepare_session_database(struct session *se,
445 struct session_database *sdb)
449 session_log(se, YLOG_WARN,
450 "No settings associated with %s", sdb->database->id);
453 if (sdb->settings[PZ_XSLT] && !sdb->map)
455 if (prepare_map(se, sdb) < 0)
461 // called if watch should be removed because http_channel is to be destroyed
462 static void session_watch_cancel(void *data, struct http_channel *c,
465 struct session_watchentry *ent = data;
472 // set watch. Returns 0=OK, -1 if watch is already set
473 int session_set_watch(struct session *s, int what,
474 session_watchfun fun, void *data,
475 struct http_channel *chan)
479 if (s->watchlist[what].fun)
484 s->watchlist[what].fun = fun;
485 s->watchlist[what].data = data;
486 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
487 session_watch_cancel);
494 void session_alert_watch(struct session *s, int what)
498 if (s->watchlist[what].fun)
500 /* our watch is no longer associated with http_channel */
502 session_watchfun fun;
504 http_remove_observer(s->watchlist[what].obs);
505 fun = s->watchlist[what].fun;
506 data = s->watchlist[what].data;
508 /* reset watch before fun is invoked - in case fun wants to set
510 s->watchlist[what].fun = 0;
511 s->watchlist[what].data = 0;
512 s->watchlist[what].obs = 0;
515 session_log(s, YLOG_DEBUG,
516 "Alert Watch: %d calling function: %p", what, fun);
523 //callback for grep_databases
524 static void select_targets_callback(struct session *se,
525 struct session_database *db)
527 struct client *cl = client_create(db->database->id);
528 struct client_list *l;
530 client_set_database(cl, db);
532 client_set_session(cl, se);
534 l = xmalloc(sizeof(*l));
536 l->next = se->clients;
540 static void session_remove_clients(struct session *se)
542 struct client_list *l;
551 struct client_list *l_next = l->next;
552 client_lock(l->client);
553 client_set_session(l->client, 0);
554 client_set_database(l->client, 0);
555 client_unlock(l->client);
556 client_destroy(l->client);
562 // Associates a set of clients with a session;
563 // Note: Session-databases represent databases with per-session
565 static int select_targets(struct session *se, const char *filter)
567 return session_grep_databases(se, filter, select_targets_callback);
570 int session_active_clients(struct session *s)
572 struct client_list *l;
575 for (l = s->clients; l; l = l->next)
576 if (client_is_active(l->client))
582 int session_is_preferred_clients_ready(struct session *s)
584 struct client_list *l;
587 for (l = s->clients; l; l = l->next)
588 if (client_is_active_preferred(l->client))
590 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
594 void search_sort(struct session *se, const char *field, int increasing)
596 struct client_list *l;
600 for (l = se->clients; l; l = l->next)
602 struct client *cl = l->client;
603 struct session_database *sdb = client_get_database(cl);
605 const char *strategy_plus_sort = 0;
607 for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
609 char *p = strchr(s->name + 3, ':');
612 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
616 if (!strcmp(p, field))
618 strategy_plus_sort = s->value;
623 if (strategy_plus_sort)
625 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
626 se->service->z3950_session_timeout,
627 se->service->server->iochan_man,
632 nmem_strsplit(se->nmem, ":", strategy_plus_sort, &array, &num);
636 const char *sort_spec = array[1];
637 while (*sort_spec == ' ')
639 client_start_search(cl, array[0], sort_spec);
647 enum pazpar2_error_code search(struct session *se,
649 const char *startrecs, const char *maxrecs,
652 const char **addinfo)
654 int live_channels = 0;
657 struct client_list *l;
659 facet_limits_t facet_limits;
661 session_log(se, YLOG_DEBUG, "Search");
665 session_remove_clients(se);
668 reclist_destroy(se->reclist);
670 relevance_destroy(&se->relevance);
671 nmem_reset(se->nmem);
672 se->total_records = se->total_merged = 0;
673 se->num_termlists = 0;
674 live_channels = select_targets(se, filter);
678 return PAZPAR2_NO_TARGETS;
680 se->reclist = reclist_create(se->nmem);
682 yaz_gettimeofday(&tval);
686 facet_limits = facet_limits_create(limit);
691 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
693 for (l = se->clients; l; l = l->next)
695 struct client *cl = l->client;
698 client_set_maxrecs(cl, atoi(maxrecs));
700 client_set_startrecs(cl, atoi(startrecs));
701 if (prepare_session_database(se, client_get_database(cl)) < 0)
703 else if (client_parse_query(cl, query, facet_limits) < 0)
708 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
709 se->service->z3950_session_timeout,
710 se->service->server->iochan_man,
712 client_start_search(cl, 0, 0);
715 facet_limits_destroy(facet_limits);
722 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
725 return PAZPAR2_NO_TARGETS;
727 return PAZPAR2_NO_ERROR;
730 // Creates a new session_database object for a database
731 static void session_init_databases_fun(void *context, struct database *db)
733 struct session *se = (struct session *) context;
734 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
740 assert(db->settings);
741 new->settings = nmem_malloc(se->session_nmem,
742 sizeof(struct settings *) * db->num_settings);
743 new->num_settings = db->num_settings;
744 for (i = 0; i < db->num_settings; i++)
746 struct setting *setting = db->settings[i];
747 new->settings[i] = setting;
749 new->next = se->databases;
753 // Doesn't free memory associated with sdb -- nmem takes care of that
754 static void session_database_destroy(struct session_database *sdb)
759 // Initialize session_database list -- this represents this session's view
760 // of the database list -- subject to modification by the settings ws command
761 void session_init_databases(struct session *se)
764 predef_grep_databases(se, se->service, session_init_databases_fun);
767 // Probably session_init_databases_fun should be refactored instead of
769 static struct session_database *load_session_database(struct session *se,
772 struct database *db = new_database(id, se->session_nmem);
774 session_init_databases_fun((void*) se, db);
776 // New sdb is head of se->databases list
777 return se->databases;
780 // Find an existing session database. If not found, load it
781 static struct session_database *find_session_database(struct session *se,
784 struct session_database *sdb;
786 for (sdb = se->databases; sdb; sdb = sdb->next)
787 if (!strcmp(sdb->database->id, id))
789 return load_session_database(se, id);
792 // Apply a session override to a database
793 void session_apply_setting(struct session *se, char *dbname, char *setting,
796 struct session_database *sdb = find_session_database(se, dbname);
797 struct conf_service *service = se->service;
798 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
799 int offset = settings_create_offset(service, setting);
801 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
804 new->target = dbname;
807 new->next = sdb->settings[offset];
808 sdb->settings[offset] = new;
810 // Force later recompute of settings-driven data structures
811 // (happens when a search starts and client connections are prepared)
823 void session_destroy(struct session *se) {
824 struct session_database *sdb;
825 session_log(se, YLOG_DEBUG, "Destroying");
827 session_remove_clients(se);
829 for (sdb = se->databases; sdb; sdb = sdb->next)
830 session_database_destroy(sdb);
831 normalize_cache_destroy(se->normalize_cache);
832 relevance_destroy(&se->relevance);
833 reclist_destroy(se->reclist);
834 nmem_destroy(se->nmem);
835 service_destroy(se->service);
836 yaz_mutex_destroy(&se->session_mutex);
839 /* Depreciated: use session_destroy */
840 void destroy_session(struct session *se)
845 size_t session_get_memory_status(struct session *session) {
849 session_enter(session);
850 session_nmem = nmem_total(session->nmem);
851 session_leave(session);
856 struct session *new_session(NMEM nmem, struct conf_service *service,
860 struct session *session = nmem_malloc(nmem, sizeof(*session));
864 sprintf(tmp_str, "session#%u", session_id);
866 session->session_id = session_id;
867 session_log(session, YLOG_DEBUG, "New");
868 session->service = service;
869 session->relevance = 0;
870 session->total_records = 0;
871 session->number_of_warnings_unknown_elements = 0;
872 session->number_of_warnings_unknown_metadata = 0;
873 session->num_termlists = 0;
874 session->reclist = 0;
875 session->clients = 0;
876 session->session_nmem = nmem;
877 session->nmem = nmem_create();
878 session->databases = 0;
879 for (i = 0; i <= SESSION_WATCH_MAX; i++)
881 session->watchlist[i].data = 0;
882 session->watchlist[i].fun = 0;
884 session->normalize_cache = normalize_cache_create();
885 session->session_mutex = 0;
886 pazpar2_mutex_create(&session->session_mutex, tmp_str);
891 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
892 int *count, NMEM nmem)
894 struct hitsbytarget *res = 0;
895 struct client_list *l;
898 for (l = se->clients; l; l = l->next)
901 res = nmem_malloc(nmem, sizeof(*res) * sz);
903 for (l = se->clients; l; l = l->next)
905 struct client *cl = l->client;
906 WRBUF w = wrbuf_alloc();
907 const char *name = session_setting_oneval(client_get_database(cl),
910 res[*count].id = client_get_id(cl);
911 res[*count].name = *name ? name : "Unknown";
912 res[*count].hits = client_get_hits(cl);
913 res[*count].records = client_get_num_records(cl);
914 res[*count].diagnostic = client_get_diagnostic(cl);
915 res[*count].state = client_get_state_str(cl);
916 res[*count].connected = client_get_connection(cl) ? 1 : 0;
917 session_settings_dump(se, client_get_database(cl), w);
918 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
925 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
927 struct hitsbytarget *p;
929 p = hitsbytarget_nb(se, count, nmem);
934 struct termlist_score **get_termlist_score(struct session *se,
935 const char *name, int *num)
938 struct termlist_score **tl = 0;
941 for (i = 0; i < se->num_termlists; i++)
942 if (!strcmp((const char *) se->termlists[i].name, name))
944 tl = termlist_highscore(se->termlists[i].termlist, num);
951 // Compares two hitsbytarget nodes by hitcount
952 static int cmp_ht(const void *p1, const void *p2)
954 const struct hitsbytarget *h1 = p1;
955 const struct hitsbytarget *h2 = p2;
956 return h2->hits - h1->hits;
959 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
962 struct hitsbytarget *ht;
965 ht = hitsbytarget_nb(se, &count, nmem);
966 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
967 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
970 // do only print terms which have display names
972 wrbuf_puts(wrbuf, "<term>\n");
974 wrbuf_puts(wrbuf, "<id>");
975 wrbuf_xmlputs(wrbuf, ht[i].id);
976 wrbuf_puts(wrbuf, "</id>\n");
978 wrbuf_puts(wrbuf, "<name>");
979 if (!ht[i].name || !ht[i].name[0])
980 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
982 wrbuf_xmlputs(wrbuf, ht[i].name);
983 wrbuf_puts(wrbuf, "</name>\n");
985 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
988 wrbuf_puts(wrbuf, "<state>");
989 wrbuf_xmlputs(wrbuf, ht[i].state);
990 wrbuf_puts(wrbuf, "</state>\n");
992 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
994 wrbuf_puts(wrbuf, "</term>\n");
999 void perform_termlist(struct http_channel *c, struct session *se,
1000 const char *name, int num)
1003 NMEM nmem_tmp = nmem_create();
1008 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1012 for (j = 0; j < num_names; j++)
1015 for (i = 0; i < se->num_termlists; i++)
1017 tname = se->termlists[i].name;
1018 if (num_names > 0 && !strcmp(names[j], tname))
1020 struct termlist_score **p = 0;
1022 p = termlist_highscore(se->termlists[i].termlist, &len);
1026 wrbuf_puts(c->wrbuf, "<list name=\"");
1027 wrbuf_xmlputs(c->wrbuf, tname);
1028 wrbuf_puts(c->wrbuf, "\">\n");
1029 for (i = 0; i < len && i < num; i++)
1031 // prevent sending empty term elements
1032 if (!p[i]->display_term || !p[i]->display_term[0])
1035 wrbuf_puts(c->wrbuf, "<term>");
1036 wrbuf_puts(c->wrbuf, "<name>");
1037 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1038 wrbuf_puts(c->wrbuf, "</name>");
1040 wrbuf_printf(c->wrbuf,
1041 "<frequency>%d</frequency>",
1043 wrbuf_puts(c->wrbuf, "</term>\n");
1045 wrbuf_puts(c->wrbuf, "</list>\n");
1050 if (num_names > 0 && !strcmp(names[j], tname))
1052 wrbuf_puts(c->wrbuf, "<list name=\"");
1053 wrbuf_xmlputs(c->wrbuf, tname);
1054 wrbuf_puts(c->wrbuf, "\">\n");
1055 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1056 wrbuf_puts(c->wrbuf, "</list>\n");
1060 nmem_destroy(nmem_tmp);
1063 #ifdef MISSING_HEADERS
1064 void report_nmem_stats(void)
1066 size_t in_use, is_free;
1068 nmem_get_memory_in_use(&in_use);
1069 nmem_get_memory_free(&is_free);
1071 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1072 (long) in_use, (long) is_free);
1076 struct record_cluster *show_single_start(struct session *se, const char *id,
1077 struct record_cluster **prev_r,
1078 struct record_cluster **next_r)
1080 struct record_cluster *r = 0;
1087 reclist_enter(se->reclist);
1088 while ((r = reclist_read_record(se->reclist)))
1090 if (!strcmp(r->recid, id))
1092 *next_r = reclist_read_record(se->reclist);
1097 reclist_leave(se->reclist);
1104 void show_single_stop(struct session *se, struct record_cluster *rec)
1109 struct record_cluster **show_range_start(struct session *se,
1110 struct reclist_sortparms *sp,
1111 int start, int *num, int *total, Odr_int *sumhits)
1113 struct record_cluster **recs;
1114 struct reclist_sortparms *spp;
1117 yaz_timing_t t = yaz_timing_create();
1120 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1130 struct client_list *l;
1132 for (spp = sp; spp; spp = spp->next)
1133 if (spp->type == Metadata_sortkey_relevance)
1135 relevance_prepare_read(se->relevance, se->reclist);
1138 reclist_sort(se->reclist, sp);
1140 reclist_enter(se->reclist);
1141 *total = reclist_get_num_records(se->reclist);
1144 for (l = se->clients; l; l = l->next)
1145 *sumhits += client_get_hits(l->client);
1147 for (i = 0; i < start; i++)
1148 if (!reclist_read_record(se->reclist))
1155 for (i = 0; i < *num; i++)
1157 struct record_cluster *r = reclist_read_record(se->reclist);
1165 reclist_leave(se->reclist);
1169 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1170 yaz_timing_get_real(t), yaz_timing_get_user(t),
1171 yaz_timing_get_sys(t));
1172 yaz_timing_destroy(&t);
1177 void show_range_stop(struct session *se, struct record_cluster **recs)
1182 void statistics(struct session *se, struct statistics *stat)
1184 struct client_list *l;
1187 memset(stat, 0, sizeof(*stat));
1189 for (l = se->clients; l; l = l->next)
1191 struct client *cl = l->client;
1192 if (!client_get_connection(cl))
1193 stat->num_no_connection++;
1194 stat->num_hits += client_get_hits(cl);
1195 switch (client_get_state(cl))
1197 case Client_Connecting: stat->num_connecting++; break;
1198 case Client_Working: stat->num_working++; break;
1199 case Client_Idle: stat->num_idle++; break;
1200 case Client_Failed: stat->num_failed++; break;
1201 case Client_Error: stat->num_error++; break;
1206 stat->num_records = se->total_records;
1208 stat->num_clients = count;
1211 static struct record_metadata *record_metadata_init(
1212 NMEM nmem, const char *value, enum conf_metadata_type type,
1213 struct _xmlAttr *attr)
1215 struct record_metadata *rec_md = record_metadata_create(nmem);
1216 struct record_metadata_attr **attrp = &rec_md->attributes;
1218 for (; attr; attr = attr->next)
1220 if (attr->children && attr->children->content)
1222 if (strcmp((const char *) attr->name, "type"))
1223 { /* skip the "type" attribute.. Its value is already part of
1224 the element in output (md-%s) and so repeating it here
1226 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1228 nmem_strdup(nmem, (const char *) attr->name);
1230 nmem_strdup(nmem, (const char *) attr->children->content);
1231 attrp = &(*attrp)->next;
1237 if (type == Metadata_type_generic)
1239 char *p = nmem_strdup(nmem, value);
1241 p = normalize7bit_generic(p, " ,/.:([");
1243 rec_md->data.text.disp = p;
1244 rec_md->data.text.sort = 0;
1246 else if (type == Metadata_type_year || type == Metadata_type_date)
1251 if (type == Metadata_type_date)
1253 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1256 rec_md->data.number.min = first;
1257 rec_md->data.number.max = last;
1264 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1265 struct conf_service *service, WRBUF norm_wr)
1269 for (n = root->children; n; n = n->next)
1271 if (n->type != XML_ELEMENT_NODE)
1273 if (!strcmp((const char *) n->name, "metadata"))
1275 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1277 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1279 else if (!strcmp(name, (const char *) type))
1281 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1284 const char *norm_str;
1285 pp2_charset_token_t prt =
1286 pp2_charset_token_create(service->charsets, "mergekey");
1288 pp2_charset_token_first(prt, (const char *) value, 0);
1289 if (wrbuf_len(norm_wr) > 0)
1290 wrbuf_puts(norm_wr, " ");
1291 wrbuf_puts(norm_wr, name);
1293 pp2_charset_token_next(prt)))
1297 wrbuf_puts(norm_wr, " ");
1298 wrbuf_puts(norm_wr, norm_str);
1302 pp2_charset_token_destroy(prt);
1312 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1313 struct conf_service *service, NMEM nmem)
1315 char *mergekey_norm = 0;
1316 xmlNode *root = xmlDocGetRootElement(doc);
1317 WRBUF norm_wr = wrbuf_alloc();
1319 /* consider mergekey from XSL first */
1320 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1323 const char *norm_str;
1324 pp2_charset_token_t prt =
1325 pp2_charset_token_create(service->charsets, "mergekey");
1327 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1328 while ((norm_str = pp2_charset_token_next(prt)))
1332 if (wrbuf_len(norm_wr))
1333 wrbuf_puts(norm_wr, " ");
1334 wrbuf_puts(norm_wr, norm_str);
1337 pp2_charset_token_destroy(prt);
1342 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1344 for (field_id = 0; field_id < service->num_metadata; field_id++)
1346 struct conf_metadata *ser_md = &service->metadata[field_id];
1347 if (ser_md->mergekey != Metadata_mergekey_no)
1349 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1351 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1353 /* no mergekey on this one and it is required..
1354 Generate unique key instead */
1355 wrbuf_rewind(norm_wr);
1362 /* generate unique key if none is not generated already or is empty */
1363 if (wrbuf_len(norm_wr) == 0)
1365 wrbuf_printf(norm_wr, "%s-%d",
1366 client_get_id(cl), record_no);
1368 if (wrbuf_len(norm_wr) > 0)
1369 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1370 wrbuf_destroy(norm_wr);
1371 return mergekey_norm;
1374 /** \brief see if metadata for pz:recordfilter exists
1375 \param root xml root element of normalized record
1376 \param sdb session database for client
1377 \retval 0 if there is no metadata for pz:recordfilter
1378 \retval 1 if there is metadata for pz:recordfilter
1380 If there is no pz:recordfilter defined, this function returns 1
1384 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1389 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1394 for (n = root->children; n; n = n->next)
1396 if (n->type != XML_ELEMENT_NODE)
1398 if (!strcmp((const char *) n->name, "metadata"))
1400 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1407 if ((eq = strchr(s, '=')))
1409 else if ((eq = strchr(s, '~')))
1415 if (len == strlen((const char *)type) &&
1416 !memcmp((const char *) type, s, len))
1418 xmlChar *value = xmlNodeGetContent(n);
1419 if (value && *value)
1422 (substring && strstr((const char *) value, eq+1)) ||
1423 (!substring && !strcmp((const char *) value, eq + 1)))
1436 static int ingest_to_cluster(struct client *cl,
1440 const char *mergekey_norm);
1442 /** \brief ingest XML record
1443 \param cl client holds the result set for record
1444 \param rec record buffer (0 terminated)
1445 \param record_no record position (1, 2, ..)
1446 \param nmem working NMEM
1451 int ingest_record(struct client *cl, const char *rec,
1452 int record_no, NMEM nmem)
1454 struct session *se = client_get_session(cl);
1456 struct session_database *sdb = client_get_database(cl);
1457 struct conf_service *service = se->service;
1458 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1460 const char *mergekey_norm;
1465 root = xmlDocGetRootElement(xdoc);
1467 if (!check_record_filter(root, sdb))
1469 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1470 record_no, sdb->database->id);
1475 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1478 session_log(se, YLOG_WARN, "Got no mergekey");
1483 if (client_get_session(cl) == se)
1484 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1491 static int ingest_to_cluster(struct client *cl,
1495 const char *mergekey_norm)
1500 struct session_database *sdb = client_get_database(cl);
1501 struct session *se = client_get_session(cl);
1502 struct conf_service *service = se->service;
1503 struct record *record = record_create(se->nmem,
1504 service->num_metadata,
1505 service->num_sortkeys, cl,
1507 struct record_cluster *cluster = reclist_insert(se->reclist,
1513 const char *use_term_factor_str = session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1514 int use_term_factor = 0;
1515 int term_factor = 1;
1516 if (use_term_factor_str && use_term_factor_str[0] != 0)
1517 use_term_factor = atoi(use_term_factor_str);
1518 if (use_term_factor) {
1519 int maxrecs = client_get_maxrecs(cl);
1520 int hits = (int) client_get_hits(cl);
1521 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1522 assert(term_factor >= 1);
1523 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1528 if (global_parameters.dump_records)
1529 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1530 sdb->database->id, record_no);
1531 relevance_newrec(se->relevance, cluster);
1533 // now parsing XML record and adding data to cluster or record metadata
1534 for (n = root->children; n; n = n->next)
1536 pp2_charset_token_t prt;
1543 if (n->type != XML_ELEMENT_NODE)
1545 if (!strcmp((const char *) n->name, "metadata"))
1547 struct conf_metadata *ser_md = 0;
1548 struct conf_sortkey *ser_sk = 0;
1549 struct record_metadata **wheretoput = 0;
1550 struct record_metadata *rec_md = 0;
1551 int md_field_id = -1;
1552 int sk_field_id = -1;
1554 type = xmlGetProp(n, (xmlChar *) "type");
1555 value = xmlNodeListGetString(xdoc, n->children, 1);
1557 if (!type || !value || !*value)
1561 = conf_service_metadata_field_id(service, (const char *) type);
1562 if (md_field_id < 0)
1564 if (se->number_of_warnings_unknown_metadata == 0)
1566 session_log(se, YLOG_WARN,
1567 "Ignoring unknown metadata element: %s", type);
1569 se->number_of_warnings_unknown_metadata++;
1573 ser_md = &service->metadata[md_field_id];
1575 if (ser_md->sortkey_offset >= 0){
1576 sk_field_id = ser_md->sortkey_offset;
1577 ser_sk = &service->sortkeys[sk_field_id];
1580 // non-merged metadata
1581 rec_md = record_metadata_init(se->nmem, (const char *) value,
1582 ser_md->type, n->properties);
1585 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1586 "for element '%s'", value, type);
1589 wheretoput = &record->metadata[md_field_id];
1591 wheretoput = &(*wheretoput)->next;
1592 *wheretoput = rec_md;
1595 rec_md = record_metadata_init(se->nmem, (const char *) value,
1597 wheretoput = &cluster->metadata[md_field_id];
1599 // and polulate with data:
1600 // assign cluster or record based on merge action
1601 if (ser_md->merge == Metadata_merge_unique)
1605 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1606 rec_md->data.text.disp))
1608 wheretoput = &(*wheretoput)->next;
1611 *wheretoput = rec_md;
1613 else if (ser_md->merge == Metadata_merge_longest)
1616 || strlen(rec_md->data.text.disp)
1617 > strlen((*wheretoput)->data.text.disp))
1619 *wheretoput = rec_md;
1622 const char *sort_str = 0;
1624 ser_sk->type == Metadata_sortkey_skiparticle;
1626 if (!cluster->sortkeys[sk_field_id])
1627 cluster->sortkeys[sk_field_id] =
1628 nmem_malloc(se->nmem,
1629 sizeof(union data_types));
1632 pp2_charset_token_create(service->charsets, "sort");
1634 pp2_charset_token_first(prt, rec_md->data.text.disp,
1637 pp2_charset_token_next(prt);
1639 sort_str = pp2_get_sort(prt);
1641 cluster->sortkeys[sk_field_id]->text.disp =
1642 rec_md->data.text.disp;
1645 sort_str = rec_md->data.text.disp;
1646 session_log(se, YLOG_WARN,
1647 "Could not make sortkey. Bug #1858");
1649 cluster->sortkeys[sk_field_id]->text.sort =
1650 nmem_strdup(se->nmem, sort_str);
1651 pp2_charset_token_destroy(prt);
1655 else if (ser_md->merge == Metadata_merge_all)
1658 wheretoput = &(*wheretoput)->next;
1659 *wheretoput = rec_md;
1661 else if (ser_md->merge == Metadata_merge_range)
1665 *wheretoput = rec_md;
1667 cluster->sortkeys[sk_field_id]
1672 int this_min = rec_md->data.number.min;
1673 int this_max = rec_md->data.number.max;
1674 if (this_min < (*wheretoput)->data.number.min)
1675 (*wheretoput)->data.number.min = this_min;
1676 if (this_max > (*wheretoput)->data.number.max)
1677 (*wheretoput)->data.number.max = this_max;
1682 // ranking of _all_ fields enabled ...
1684 relevance_countwords(se->relevance, cluster,
1685 (char *) value, ser_md->rank,
1688 // construct facets ... unless the client already has reported them
1689 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1691 if (ser_md->type == Metadata_type_year)
1694 sprintf(year, "%d", rec_md->data.number.max);
1696 add_facet(se, (char *) type, year, term_factor);
1697 if (rec_md->data.number.max != rec_md->data.number.min)
1699 sprintf(year, "%d", rec_md->data.number.min);
1700 add_facet(se, (char *) type, year, term_factor);
1704 add_facet(se, (char *) type, (char *) value, term_factor);
1714 if (se->number_of_warnings_unknown_elements == 0)
1715 session_log(se, YLOG_WARN,
1716 "Unexpected element in internal record: %s", n->name);
1717 se->number_of_warnings_unknown_elements++;
1725 relevance_donerecord(se->relevance, cluster);
1726 se->total_records++;
1731 void session_log(struct session *s, int level, const char *fmt, ...)
1737 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1738 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1746 * c-file-style: "Stroustrup"
1747 * indent-tabs-mode: nil
1749 * vim: shiftwidth=4 tabstop=8 expandtab