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 struct session_sorted_results {
101 struct session_sorted_results *next;
104 /* session counting (1) , disable client counting (0) */
105 static YAZ_MUTEX g_session_mutex = 0;
106 static int no_sessions = 0;
107 static int no_session_total = 0;
109 static int session_use(int delta)
112 if (!g_session_mutex)
113 yaz_mutex_create(&g_session_mutex);
114 yaz_mutex_enter(g_session_mutex);
115 no_sessions += delta;
117 no_session_total += delta;
118 sessions = no_sessions;
119 yaz_mutex_leave(g_session_mutex);
120 yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), no_sessions);
124 int sessions_count(void)
126 return session_use(0);
129 int session_count_total(void)
132 if (!g_session_mutex)
134 yaz_mutex_enter(g_session_mutex);
135 total = no_session_total;
136 yaz_mutex_leave(g_session_mutex);
140 static void log_xml_doc(xmlDoc *doc)
142 FILE *lf = yaz_log_file();
145 #if LIBXML_VERSION >= 20600
146 xmlDocDumpFormatMemory(doc, &result, &len, 1);
148 xmlDocDumpMemory(doc, &result, &len);
152 (void) fwrite(result, 1, len, lf);
158 static void session_enter(struct session *s)
160 yaz_mutex_enter(s->session_mutex);
163 static void session_leave(struct session *s)
165 yaz_mutex_leave(s->session_mutex);
168 void add_facet(struct session *s, const char *type, const char *value, int count)
170 struct conf_service *service = s->service;
171 pp2_charset_token_t prt;
172 const char *facet_component;
173 WRBUF facet_wrbuf = wrbuf_alloc();
174 WRBUF display_wrbuf = wrbuf_alloc();
176 const char *icu_chain_id = 0;
178 for (i = 0; i < service->num_metadata; i++)
179 if (!strcmp((service->metadata + i)->name, type))
180 icu_chain_id = (service->metadata + i)->facetrule;
182 icu_chain_id = "facet";
183 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
186 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
188 wrbuf_destroy(facet_wrbuf);
189 wrbuf_destroy(display_wrbuf);
192 pp2_charset_token_first(prt, value, 0);
193 while ((facet_component = pp2_charset_token_next(prt)))
195 const char *display_component;
196 if (*facet_component)
198 if (wrbuf_len(facet_wrbuf))
199 wrbuf_puts(facet_wrbuf, " ");
200 wrbuf_puts(facet_wrbuf, facet_component);
202 display_component = pp2_get_display(prt);
203 if (display_component)
205 if (wrbuf_len(display_wrbuf))
206 wrbuf_puts(display_wrbuf, " ");
207 wrbuf_puts(display_wrbuf, display_component);
210 pp2_charset_token_destroy(prt);
212 if (wrbuf_len(facet_wrbuf))
215 for (i = 0; i < s->num_termlists; i++)
216 if (!strcmp(s->termlists[i].name, type))
218 if (i == s->num_termlists)
220 if (i == SESSION_MAX_TERMLISTS)
222 session_log(s, YLOG_FATAL, "Too many termlists");
223 wrbuf_destroy(facet_wrbuf);
224 wrbuf_destroy(display_wrbuf);
228 s->termlists[i].name = nmem_strdup(s->nmem, type);
229 s->termlists[i].termlist
230 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
231 s->num_termlists = i + 1;
235 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
237 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
238 wrbuf_cstr(facet_wrbuf), count);
240 wrbuf_destroy(facet_wrbuf);
241 wrbuf_destroy(display_wrbuf);
244 static xmlDoc *record_to_xml(struct session *se,
245 struct session_database *sdb, const char *rec)
247 struct database *db = sdb->database;
250 rdoc = xmlParseMemory(rec, strlen(rec));
254 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
259 if (global_parameters.dump_records)
261 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
268 #define MAX_XSLT_ARGS 16
270 // Add static values from session database settings if applicable
271 static void insert_settings_parameters(struct session_database *sdb,
272 struct conf_service *service,
280 for (i = 0; i < service->num_metadata; i++)
282 struct conf_metadata *md = &service->metadata[i];
285 if (md->setting == Metadata_setting_parameter &&
286 (setting = settings_lookup_offset(service, md->name)) >= 0)
288 const char *val = session_setting_oneval(sdb, setting);
289 if (val && nparms < MAX_XSLT_ARGS)
292 int len = strlen(val);
293 buf = nmem_malloc(nmem, len + 3);
295 strcpy(buf + 1, val);
298 parms[offset++] = md->name;
299 parms[offset++] = buf;
307 // Add static values from session database settings if applicable
308 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
309 struct conf_service *service)
313 for (i = 0; i < service->num_metadata; i++)
315 struct conf_metadata *md = &service->metadata[i];
318 if (md->setting == Metadata_setting_postproc &&
319 (offset = settings_lookup_offset(service, md->name)) >= 0)
321 const char *val = session_setting_oneval(sdb, offset);
324 xmlNode *r = xmlDocGetRootElement(doc);
325 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
327 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
333 static xmlDoc *normalize_record(struct session *se,
334 struct session_database *sdb,
335 struct conf_service *service,
336 const char *rec, NMEM nmem)
338 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
342 char *parms[MAX_XSLT_ARGS*2+1];
344 insert_settings_parameters(sdb, service, parms, nmem);
346 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
348 session_log(se, YLOG_WARN, "Normalize failed from %s",
353 insert_settings_values(sdb, rdoc, service);
355 if (global_parameters.dump_records)
357 session_log(se, YLOG_LOG, "Normalized record from %s",
366 void session_settings_dump(struct session *se,
367 struct session_database *db,
372 int i, num = db->num_settings;
373 for (i = 0; i < num; i++)
375 struct setting *s = db->settings[i];
376 for (;s ; s = s->next)
378 wrbuf_puts(w, "<set name=\"");
379 wrbuf_xmlputs(w, s->name);
380 wrbuf_puts(w, "\" value=\"");
381 wrbuf_xmlputs(w, s->value);
382 wrbuf_puts(w, "\"/>");
390 // Retrieve first defined value for 'name' for given database.
391 // Will be extended to take into account user associated with session
392 const char *session_setting_oneval(struct session_database *db, int offset)
394 if (offset >= db->num_settings || !db->settings[offset])
396 return db->settings[offset]->value;
399 // Prepare XSLT stylesheets for record normalization
400 // Structures are allocated on the session_wide nmem to avoid having
401 // to recompute this for every search. This would lead
402 // to leaking if a single session was to repeatedly change the PZ_XSLT
403 // setting. However, this is not a realistic use scenario.
404 static int prepare_map(struct session *se, struct session_database *sdb)
408 if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
409 (s = session_setting_oneval(sdb, PZ_XSLT)))
411 char auto_stylesheet[256];
413 if (!strcmp(s, "auto"))
415 const char *request_syntax = session_setting_oneval(
416 sdb, PZ_REQUESTSYNTAX);
420 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
421 "%s.xsl", request_syntax);
422 for (cp = auto_stylesheet; *cp; cp++)
424 /* deliberately only consider ASCII */
425 if (*cp > 32 && *cp < 127)
432 session_log(se, YLOG_WARN,
433 "No pz:requestsyntax for auto stylesheet");
436 sdb->map = normalize_cache_get(se->normalize_cache,
444 // called if watch should be removed because http_channel is to be destroyed
445 static void session_watch_cancel(void *data, struct http_channel *c,
448 struct session_watchentry *ent = data;
455 // set watch. Returns 0=OK, -1 if watch is already set
456 int session_set_watch(struct session *s, int what,
457 session_watchfun fun, void *data,
458 struct http_channel *chan)
462 if (s->watchlist[what].fun)
467 s->watchlist[what].fun = fun;
468 s->watchlist[what].data = data;
469 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
470 session_watch_cancel);
477 void session_alert_watch(struct session *s, int what)
481 if (s->watchlist[what].fun)
483 /* our watch is no longer associated with http_channel */
485 session_watchfun fun;
487 http_remove_observer(s->watchlist[what].obs);
488 fun = s->watchlist[what].fun;
489 data = s->watchlist[what].data;
491 /* reset watch before fun is invoked - in case fun wants to set
493 s->watchlist[what].fun = 0;
494 s->watchlist[what].data = 0;
495 s->watchlist[what].obs = 0;
498 session_log(s, YLOG_DEBUG,
499 "Alert Watch: %d calling function: %p", what, fun);
506 //callback for grep_databases
507 static void select_targets_callback(struct session *se,
508 struct session_database *db)
511 struct client_list *l;
513 for (l = se->clients_cached; l; l = l->next)
514 if (client_get_database(l->client) == db)
521 cl = client_create(db->database->id);
522 client_set_database(cl, db);
523 client_set_session(cl, se);
525 l = xmalloc(sizeof(*l));
527 l->next = se->clients_cached;
528 se->clients_cached = l;
531 l = xmalloc(sizeof(*l));
533 l->next = se->clients_active;
534 se->clients_active = l;
537 static void session_reset_active_clients(struct session *se,
538 struct client_list *new_list)
540 struct client_list *l;
543 l = se->clients_active;
544 se->clients_active = new_list;
549 struct client_list *l_next = l->next;
555 static void session_remove_cached_clients(struct session *se)
557 struct client_list *l;
559 session_reset_active_clients(se, 0);
562 l = se->clients_cached;
563 se->clients_cached = 0;
568 struct client_list *l_next = l->next;
569 client_lock(l->client);
570 client_set_session(l->client, 0);
571 client_set_database(l->client, 0);
572 client_unlock(l->client);
573 client_destroy(l->client);
579 // Associates a set of clients with a session;
580 // Note: Session-databases represent databases with per-session
582 static int select_targets(struct session *se, const char *filter)
584 return session_grep_databases(se, filter, select_targets_callback);
587 int session_active_clients(struct session *s)
589 struct client_list *l;
592 for (l = s->clients_active; l; l = l->next)
593 if (client_is_active(l->client))
599 int session_is_preferred_clients_ready(struct session *s)
601 struct client_list *l;
604 for (l = s->clients_active; l; l = l->next)
605 if (client_is_active_preferred(l->client))
607 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
611 static const char *get_strategy_plus_sort(struct client *l, const char *field)
613 struct session_database *sdb = client_get_database(l);
616 const char *strategy_plus_sort = 0;
618 for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
620 char *p = strchr(s->name + 3, ':');
623 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
627 if (!strcmp(p, field))
629 strategy_plus_sort = s->value;
633 return strategy_plus_sort;
636 void session_sort(struct session *se, const char *field, int increasing)
638 struct session_sorted_results *sr;
639 struct client_list *l;
643 /* see if we already have sorted for this critieria */
644 for (sr = se->sorted_results; sr; sr = sr->next)
646 if (!strcmp(field, sr->field) && increasing == sr->increasing)
651 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
656 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
658 sr = nmem_malloc(se->nmem, sizeof(*sr));
659 sr->field = nmem_strdup(se->nmem, field);
660 sr->increasing = increasing;
661 sr->next = se->sorted_results;
662 se->sorted_results = sr;
664 for (l = se->clients_active; l; l = l->next)
666 struct client *cl = l->client;
667 const char *strategy_plus_sort = get_strategy_plus_sort(cl, field);
668 if (strategy_plus_sort)
671 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
672 se->service->z3950_session_timeout,
673 se->service->server->iochan_man,
675 client_start_search(cl, strategy_plus_sort, increasing);
681 enum pazpar2_error_code session_search(struct session *se,
683 const char *startrecs,
687 const char **addinfo,
688 const char *sort_field, int increasing)
690 int live_channels = 0;
693 struct client_list *l, *l0;
695 facet_limits_t facet_limits;
697 session_log(se, YLOG_DEBUG, "Search");
701 if (se->settings_modified)
702 session_remove_cached_clients(se);
704 session_reset_active_clients(se, 0);
707 reclist_destroy(se->reclist);
709 se->settings_modified = 0;
710 relevance_destroy(&se->relevance);
711 nmem_reset(se->nmem);
712 se->total_records = se->total_merged = 0;
713 se->num_termlists = 0;
715 /* reset list of sorted results and clear to relevance search */
716 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
717 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
718 se->sorted_results->increasing = increasing;
719 se->sorted_results->next = 0;
721 live_channels = select_targets(se, filter);
725 return PAZPAR2_NO_TARGETS;
727 se->reclist = reclist_create(se->nmem);
729 yaz_gettimeofday(&tval);
733 facet_limits = facet_limits_create(limit);
738 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
741 l0 = se->clients_active;
742 se->clients_active = 0;
745 for (l = l0; l; l = l->next)
748 struct client *cl = l->client;
749 const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
751 if (prepare_map(se, client_get_database(cl)) < 0)
754 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
758 else if (parse_ret == 0)
760 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
762 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
763 se->service->z3950_session_timeout,
764 se->service->server->iochan_man,
766 client_start_search(cl, strategy_plus_sort, increasing);
770 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
772 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
773 se->service->z3950_session_timeout,
774 se->service->server->iochan_man,
781 facet_limits_destroy(facet_limits);
782 session_reset_active_clients(se, l0);
789 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
792 return PAZPAR2_NO_TARGETS;
794 yaz_log(YLOG_LOG, "session_start_search done");
795 return PAZPAR2_NO_ERROR;
798 // Creates a new session_database object for a database
799 static void session_init_databases_fun(void *context, struct database *db)
801 struct session *se = (struct session *) context;
802 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
808 assert(db->settings);
809 new->settings = nmem_malloc(se->session_nmem,
810 sizeof(struct settings *) * db->num_settings);
811 new->num_settings = db->num_settings;
812 for (i = 0; i < db->num_settings; i++)
814 struct setting *setting = db->settings[i];
815 new->settings[i] = setting;
817 new->next = se->databases;
821 // Doesn't free memory associated with sdb -- nmem takes care of that
822 static void session_database_destroy(struct session_database *sdb)
827 // Initialize session_database list -- this represents this session's view
828 // of the database list -- subject to modification by the settings ws command
829 void session_init_databases(struct session *se)
832 predef_grep_databases(se, se->service, session_init_databases_fun);
835 // Probably session_init_databases_fun should be refactored instead of
837 static struct session_database *load_session_database(struct session *se,
840 struct database *db = new_database(id, se->session_nmem);
842 session_init_databases_fun((void*) se, db);
844 // New sdb is head of se->databases list
845 return se->databases;
848 // Find an existing session database. If not found, load it
849 static struct session_database *find_session_database(struct session *se,
852 struct session_database *sdb;
854 for (sdb = se->databases; sdb; sdb = sdb->next)
855 if (!strcmp(sdb->database->id, id))
857 return load_session_database(se, id);
860 // Apply a session override to a database
861 void session_apply_setting(struct session *se, char *dbname, char *setting,
864 struct session_database *sdb = find_session_database(se, dbname);
865 struct conf_service *service = se->service;
866 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
867 int offset = settings_create_offset(service, setting);
869 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
872 new->target = dbname;
875 new->next = sdb->settings[offset];
876 sdb->settings[offset] = new;
878 se->settings_modified = 1;
880 // Force later recompute of settings-driven data structures
881 // (happens when a search starts and client connections are prepared)
893 void session_destroy(struct session *se)
895 struct session_database *sdb;
896 session_log(se, YLOG_DEBUG, "Destroying");
898 session_remove_cached_clients(se);
900 for (sdb = se->databases; sdb; sdb = sdb->next)
901 session_database_destroy(sdb);
902 normalize_cache_destroy(se->normalize_cache);
903 relevance_destroy(&se->relevance);
904 reclist_destroy(se->reclist);
905 nmem_destroy(se->nmem);
906 service_destroy(se->service);
907 yaz_mutex_destroy(&se->session_mutex);
910 size_t session_get_memory_status(struct session *session) {
914 session_enter(session);
915 session_nmem = nmem_total(session->nmem);
916 session_leave(session);
921 struct session *new_session(NMEM nmem, struct conf_service *service,
925 struct session *session = nmem_malloc(nmem, sizeof(*session));
929 sprintf(tmp_str, "session#%u", session_id);
931 session->session_id = session_id;
932 session_log(session, YLOG_DEBUG, "New");
933 session->service = service;
934 session->relevance = 0;
935 session->total_records = 0;
936 session->number_of_warnings_unknown_elements = 0;
937 session->number_of_warnings_unknown_metadata = 0;
938 session->num_termlists = 0;
939 session->reclist = 0;
940 session->clients_active = 0;
941 session->clients_cached = 0;
942 session->settings_modified = 0;
943 session->session_nmem = nmem;
944 session->nmem = nmem_create();
945 session->databases = 0;
946 for (i = 0; i <= SESSION_WATCH_MAX; i++)
948 session->watchlist[i].data = 0;
949 session->watchlist[i].fun = 0;
951 session->normalize_cache = normalize_cache_create();
952 session->session_mutex = 0;
953 pazpar2_mutex_create(&session->session_mutex, tmp_str);
958 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
960 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
961 int *count, NMEM nmem)
963 struct hitsbytarget *res = 0;
964 struct client_list *l;
967 for (l = se->clients_active; l; l = l->next)
970 res = nmem_malloc(nmem, sizeof(*res) * sz);
972 for (l = se->clients_active; l; l = l->next)
974 struct client *cl = l->client;
975 WRBUF w = wrbuf_alloc();
976 const char *name = session_setting_oneval(client_get_database(cl),
979 res[*count].id = client_get_id(cl);
980 res[*count].name = *name ? name : "Unknown";
981 res[*count].hits = client_get_hits(cl);
982 res[*count].records = client_get_num_records(cl);
983 res[*count].diagnostic = client_get_diagnostic(cl);
984 res[*count].state = client_get_state_str(cl);
985 res[*count].connected = client_get_connection(cl) ? 1 : 0;
986 session_settings_dump(se, client_get_database(cl), w);
987 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
990 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
997 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
999 struct hitsbytarget *p;
1001 p = hitsbytarget_nb(se, count, nmem);
1006 struct termlist_score **get_termlist_score(struct session *se,
1007 const char *name, int *num)
1010 struct termlist_score **tl = 0;
1013 for (i = 0; i < se->num_termlists; i++)
1014 if (!strcmp((const char *) se->termlists[i].name, name))
1016 tl = termlist_highscore(se->termlists[i].termlist, num);
1023 // Compares two hitsbytarget nodes by hitcount
1024 static int cmp_ht(const void *p1, const void *p2)
1026 const struct hitsbytarget *h1 = p1;
1027 const struct hitsbytarget *h2 = p2;
1028 return h2->hits - h1->hits;
1031 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1034 struct hitsbytarget *ht;
1037 ht = hitsbytarget_nb(se, &count, nmem);
1038 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1039 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1042 // do only print terms which have display names
1044 wrbuf_puts(wrbuf, "<term>\n");
1046 wrbuf_puts(wrbuf, "<id>");
1047 wrbuf_xmlputs(wrbuf, ht[i].id);
1048 wrbuf_puts(wrbuf, "</id>\n");
1050 wrbuf_puts(wrbuf, "<name>");
1051 if (!ht[i].name || !ht[i].name[0])
1052 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1054 wrbuf_xmlputs(wrbuf, ht[i].name);
1055 wrbuf_puts(wrbuf, "</name>\n");
1057 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1060 wrbuf_puts(wrbuf, "<state>");
1061 wrbuf_xmlputs(wrbuf, ht[i].state);
1062 wrbuf_puts(wrbuf, "</state>\n");
1064 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1066 wrbuf_puts(wrbuf, "</term>\n");
1071 void perform_termlist(struct http_channel *c, struct session *se,
1072 const char *name, int num)
1075 NMEM nmem_tmp = nmem_create();
1080 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1084 for (j = 0; j < num_names; j++)
1088 wrbuf_puts(c->wrbuf, "<list name=\"");
1089 wrbuf_xmlputs(c->wrbuf, names[j]);
1090 wrbuf_puts(c->wrbuf, "\">\n");
1092 for (i = 0; i < se->num_termlists; i++)
1094 tname = se->termlists[i].name;
1095 if (num_names > 0 && !strcmp(names[j], tname))
1097 struct termlist_score **p = 0;
1099 p = termlist_highscore(se->termlists[i].termlist, &len);
1103 for (i = 0; i < len && i < num; i++)
1105 // prevent sending empty term elements
1106 if (!p[i]->display_term || !p[i]->display_term[0])
1109 wrbuf_puts(c->wrbuf, "<term>");
1110 wrbuf_puts(c->wrbuf, "<name>");
1111 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1112 wrbuf_puts(c->wrbuf, "</name>");
1114 wrbuf_printf(c->wrbuf,
1115 "<frequency>%d</frequency>",
1117 wrbuf_puts(c->wrbuf, "</term>\n");
1123 if (num_names > 0 && !strcmp(names[j], tname))
1125 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1127 wrbuf_puts(c->wrbuf, "</list>\n");
1130 nmem_destroy(nmem_tmp);
1133 #ifdef MISSING_HEADERS
1134 void report_nmem_stats(void)
1136 size_t in_use, is_free;
1138 nmem_get_memory_in_use(&in_use);
1139 nmem_get_memory_free(&is_free);
1141 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1142 (long) in_use, (long) is_free);
1146 struct record_cluster *show_single_start(struct session *se, const char *id,
1147 struct record_cluster **prev_r,
1148 struct record_cluster **next_r)
1150 struct record_cluster *r = 0;
1157 reclist_enter(se->reclist);
1158 while ((r = reclist_read_record(se->reclist)))
1160 if (!strcmp(r->recid, id))
1162 *next_r = reclist_read_record(se->reclist);
1167 reclist_leave(se->reclist);
1174 void show_single_stop(struct session *se, struct record_cluster *rec)
1179 struct record_cluster **show_range_start(struct session *se,
1180 struct reclist_sortparms *sp,
1181 int start, int *num, int *total, Odr_int *sumhits)
1183 struct record_cluster **recs;
1184 struct reclist_sortparms *spp;
1187 yaz_timing_t t = yaz_timing_create();
1190 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1200 struct client_list *l;
1202 for (spp = sp; spp; spp = spp->next)
1203 if (spp->type == Metadata_sortkey_relevance)
1205 relevance_prepare_read(se->relevance, se->reclist);
1208 reclist_sort(se->reclist, sp);
1210 reclist_enter(se->reclist);
1211 *total = reclist_get_num_records(se->reclist);
1214 for (l = se->clients_active; l; l = l->next)
1215 *sumhits += client_get_hits(l->client);
1217 for (i = 0; i < start; i++)
1218 if (!reclist_read_record(se->reclist))
1225 for (i = 0; i < *num; i++)
1227 struct record_cluster *r = reclist_read_record(se->reclist);
1235 reclist_leave(se->reclist);
1239 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1240 yaz_timing_get_real(t), yaz_timing_get_user(t),
1241 yaz_timing_get_sys(t));
1242 yaz_timing_destroy(&t);
1247 void show_range_stop(struct session *se, struct record_cluster **recs)
1252 void statistics(struct session *se, struct statistics *stat)
1254 struct client_list *l;
1257 memset(stat, 0, sizeof(*stat));
1259 for (l = se->clients_active; l; l = l->next)
1261 struct client *cl = l->client;
1262 if (!client_get_connection(cl))
1263 stat->num_no_connection++;
1264 stat->num_hits += client_get_hits(cl);
1265 switch (client_get_state(cl))
1267 case Client_Connecting: stat->num_connecting++; break;
1268 case Client_Working: stat->num_working++; break;
1269 case Client_Idle: stat->num_idle++; break;
1270 case Client_Failed: stat->num_failed++; break;
1271 case Client_Error: stat->num_error++; break;
1276 stat->num_records = se->total_records;
1278 stat->num_clients = count;
1281 static struct record_metadata *record_metadata_init(
1282 NMEM nmem, const char *value, enum conf_metadata_type type,
1283 struct _xmlAttr *attr)
1285 struct record_metadata *rec_md = record_metadata_create(nmem);
1286 struct record_metadata_attr **attrp = &rec_md->attributes;
1288 for (; attr; attr = attr->next)
1290 if (attr->children && attr->children->content)
1292 if (strcmp((const char *) attr->name, "type"))
1293 { /* skip the "type" attribute.. Its value is already part of
1294 the element in output (md-%s) and so repeating it here
1296 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1298 nmem_strdup(nmem, (const char *) attr->name);
1300 nmem_strdup(nmem, (const char *) attr->children->content);
1301 attrp = &(*attrp)->next;
1307 if (type == Metadata_type_generic)
1309 char *p = nmem_strdup(nmem, value);
1311 p = normalize7bit_generic(p, " ,/.:([");
1313 rec_md->data.text.disp = p;
1314 rec_md->data.text.sort = 0;
1316 else if (type == Metadata_type_year || type == Metadata_type_date)
1321 if (type == Metadata_type_date)
1323 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1326 rec_md->data.number.min = first;
1327 rec_md->data.number.max = last;
1334 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1335 struct conf_service *service, WRBUF norm_wr)
1339 for (n = root->children; n; n = n->next)
1341 if (n->type != XML_ELEMENT_NODE)
1343 if (!strcmp((const char *) n->name, "metadata"))
1345 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1347 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1349 else if (!strcmp(name, (const char *) type))
1351 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1354 const char *norm_str;
1355 pp2_charset_token_t prt =
1356 pp2_charset_token_create(service->charsets, "mergekey");
1358 pp2_charset_token_first(prt, (const char *) value, 0);
1359 if (wrbuf_len(norm_wr) > 0)
1360 wrbuf_puts(norm_wr, " ");
1361 wrbuf_puts(norm_wr, name);
1363 pp2_charset_token_next(prt)))
1367 wrbuf_puts(norm_wr, " ");
1368 wrbuf_puts(norm_wr, norm_str);
1372 pp2_charset_token_destroy(prt);
1382 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1383 struct conf_service *service, NMEM nmem)
1385 char *mergekey_norm = 0;
1386 xmlNode *root = xmlDocGetRootElement(doc);
1387 WRBUF norm_wr = wrbuf_alloc();
1389 /* consider mergekey from XSL first */
1390 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1393 const char *norm_str;
1394 pp2_charset_token_t prt =
1395 pp2_charset_token_create(service->charsets, "mergekey");
1397 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1398 while ((norm_str = pp2_charset_token_next(prt)))
1402 if (wrbuf_len(norm_wr))
1403 wrbuf_puts(norm_wr, " ");
1404 wrbuf_puts(norm_wr, norm_str);
1407 pp2_charset_token_destroy(prt);
1412 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1414 for (field_id = 0; field_id < service->num_metadata; field_id++)
1416 struct conf_metadata *ser_md = &service->metadata[field_id];
1417 if (ser_md->mergekey != Metadata_mergekey_no)
1419 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1421 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1423 /* no mergekey on this one and it is required..
1424 Generate unique key instead */
1425 wrbuf_rewind(norm_wr);
1432 /* generate unique key if none is not generated already or is empty */
1433 if (wrbuf_len(norm_wr) == 0)
1435 wrbuf_printf(norm_wr, "position: %s-%d",
1436 client_get_id(cl), record_no);
1440 const char *lead = "content: ";
1441 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1443 if (wrbuf_len(norm_wr) > 0)
1444 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1445 wrbuf_destroy(norm_wr);
1446 return mergekey_norm;
1449 /** \brief see if metadata for pz:recordfilter exists
1450 \param root xml root element of normalized record
1451 \param sdb session database for client
1452 \retval 0 if there is no metadata for pz:recordfilter
1453 \retval 1 if there is metadata for pz:recordfilter
1455 If there is no pz:recordfilter defined, this function returns 1
1459 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1464 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1469 for (n = root->children; n; n = n->next)
1471 if (n->type != XML_ELEMENT_NODE)
1473 if (!strcmp((const char *) n->name, "metadata"))
1475 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1482 if ((eq = strchr(s, '=')))
1484 else if ((eq = strchr(s, '~')))
1490 if (len == strlen((const char *)type) &&
1491 !memcmp((const char *) type, s, len))
1493 xmlChar *value = xmlNodeGetContent(n);
1494 if (value && *value)
1497 (substring && strstr((const char *) value, eq+1)) ||
1498 (!substring && !strcmp((const char *) value, eq + 1)))
1511 static int ingest_to_cluster(struct client *cl,
1515 const char *mergekey_norm);
1517 /** \brief ingest XML record
1518 \param cl client holds the result set for record
1519 \param rec record buffer (0 terminated)
1520 \param record_no record position (1, 2, ..)
1521 \param nmem working NMEM
1526 int ingest_record(struct client *cl, const char *rec,
1527 int record_no, NMEM nmem)
1529 struct session *se = client_get_session(cl);
1531 struct session_database *sdb = client_get_database(cl);
1532 struct conf_service *service = se->service;
1533 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1535 const char *mergekey_norm;
1540 root = xmlDocGetRootElement(xdoc);
1542 if (!check_record_filter(root, sdb))
1544 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1545 record_no, sdb->database->id);
1550 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1553 session_log(se, YLOG_WARN, "Got no mergekey");
1558 if (client_get_session(cl) == se)
1559 ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1566 static int ingest_to_cluster(struct client *cl,
1570 const char *mergekey_norm)
1575 struct session *se = client_get_session(cl);
1576 struct conf_service *service = se->service;
1577 int term_factor = 1;
1578 struct record_cluster *cluster;
1579 struct session_database *sdb = client_get_database(cl);
1580 struct record *record = record_create(se->nmem,
1581 service->num_metadata,
1582 service->num_sortkeys, cl,
1585 for (n = root->children; n; n = n->next)
1593 if (n->type != XML_ELEMENT_NODE)
1595 if (!strcmp((const char *) n->name, "metadata"))
1597 struct conf_metadata *ser_md = 0;
1598 struct record_metadata **wheretoput = 0;
1599 struct record_metadata *rec_md = 0;
1600 int md_field_id = -1;
1602 type = xmlGetProp(n, (xmlChar *) "type");
1603 value = xmlNodeListGetString(xdoc, n->children, 1);
1605 if (!type || !value || !*value)
1609 = conf_service_metadata_field_id(service, (const char *) type);
1610 if (md_field_id < 0)
1612 if (se->number_of_warnings_unknown_metadata == 0)
1614 session_log(se, YLOG_WARN,
1615 "Ignoring unknown metadata element: %s", type);
1617 se->number_of_warnings_unknown_metadata++;
1621 ser_md = &service->metadata[md_field_id];
1623 // non-merged metadata
1624 rec_md = record_metadata_init(se->nmem, (const char *) value,
1625 ser_md->type, n->properties);
1628 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1629 "for element '%s'", value, type);
1632 wheretoput = &record->metadata[md_field_id];
1634 wheretoput = &(*wheretoput)->next;
1635 *wheretoput = rec_md;
1639 cluster = reclist_insert(se->reclist, service, record,
1640 mergekey_norm, &se->total_merged);
1645 const char *use_term_factor_str =
1646 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1647 if (use_term_factor_str && use_term_factor_str[0] == '1')
1649 int maxrecs = client_get_maxrecs(cl);
1650 int hits = (int) client_get_hits(cl);
1651 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1652 assert(term_factor >= 1);
1653 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1657 if (global_parameters.dump_records)
1658 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1659 sdb->database->id, record_no);
1662 relevance_newrec(se->relevance, cluster);
1664 // now parsing XML record and adding data to cluster or record metadata
1665 for (n = root->children; n; n = n->next)
1667 pp2_charset_token_t prt;
1674 if (n->type != XML_ELEMENT_NODE)
1676 if (!strcmp((const char *) n->name, "metadata"))
1678 struct conf_metadata *ser_md = 0;
1679 struct conf_sortkey *ser_sk = 0;
1680 struct record_metadata **wheretoput = 0;
1681 struct record_metadata *rec_md = 0;
1682 int md_field_id = -1;
1683 int sk_field_id = -1;
1685 type = xmlGetProp(n, (xmlChar *) "type");
1686 value = xmlNodeListGetString(xdoc, n->children, 1);
1688 if (!type || !value || !*value)
1692 = conf_service_metadata_field_id(service, (const char *) type);
1693 if (md_field_id < 0)
1696 ser_md = &service->metadata[md_field_id];
1698 if (ser_md->sortkey_offset >= 0)
1700 sk_field_id = ser_md->sortkey_offset;
1701 ser_sk = &service->sortkeys[sk_field_id];
1705 rec_md = record_metadata_init(se->nmem, (const char *) value,
1710 wheretoput = &cluster->metadata[md_field_id];
1712 // and polulate with data:
1713 // assign cluster or record based on merge action
1714 if (ser_md->merge == Metadata_merge_unique)
1718 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1719 rec_md->data.text.disp))
1721 wheretoput = &(*wheretoput)->next;
1724 *wheretoput = rec_md;
1726 else if (ser_md->merge == Metadata_merge_longest)
1729 || strlen(rec_md->data.text.disp)
1730 > strlen((*wheretoput)->data.text.disp))
1732 *wheretoput = rec_md;
1735 const char *sort_str = 0;
1737 ser_sk->type == Metadata_sortkey_skiparticle;
1739 if (!cluster->sortkeys[sk_field_id])
1740 cluster->sortkeys[sk_field_id] =
1741 nmem_malloc(se->nmem,
1742 sizeof(union data_types));
1745 pp2_charset_token_create(service->charsets, "sort");
1747 pp2_charset_token_first(prt, rec_md->data.text.disp,
1750 pp2_charset_token_next(prt);
1752 sort_str = pp2_get_sort(prt);
1754 cluster->sortkeys[sk_field_id]->text.disp =
1755 rec_md->data.text.disp;
1758 sort_str = rec_md->data.text.disp;
1759 session_log(se, YLOG_WARN,
1760 "Could not make sortkey. Bug #1858");
1762 cluster->sortkeys[sk_field_id]->text.sort =
1763 nmem_strdup(se->nmem, sort_str);
1764 pp2_charset_token_destroy(prt);
1768 else if (ser_md->merge == Metadata_merge_all)
1771 wheretoput = &(*wheretoput)->next;
1772 *wheretoput = rec_md;
1774 else if (ser_md->merge == Metadata_merge_range)
1778 *wheretoput = rec_md;
1780 cluster->sortkeys[sk_field_id]
1785 int this_min = rec_md->data.number.min;
1786 int this_max = rec_md->data.number.max;
1787 if (this_min < (*wheretoput)->data.number.min)
1788 (*wheretoput)->data.number.min = this_min;
1789 if (this_max > (*wheretoput)->data.number.max)
1790 (*wheretoput)->data.number.max = this_max;
1795 // ranking of _all_ fields enabled ...
1797 relevance_countwords(se->relevance, cluster,
1798 (char *) value, ser_md->rank,
1801 // construct facets ... unless the client already has reported them
1802 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1804 if (ser_md->type == Metadata_type_year)
1807 sprintf(year, "%d", rec_md->data.number.max);
1809 add_facet(se, (char *) type, year, term_factor);
1810 if (rec_md->data.number.max != rec_md->data.number.min)
1812 sprintf(year, "%d", rec_md->data.number.min);
1813 add_facet(se, (char *) type, year, term_factor);
1817 add_facet(se, (char *) type, (char *) value, term_factor);
1827 if (se->number_of_warnings_unknown_elements == 0)
1828 session_log(se, YLOG_WARN,
1829 "Unexpected element in internal record: %s", n->name);
1830 se->number_of_warnings_unknown_elements++;
1838 relevance_donerecord(se->relevance, cluster);
1839 se->total_records++;
1844 void session_log(struct session *s, int level, const char *fmt, ...)
1850 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1851 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1859 * c-file-style: "Stroustrup"
1860 * indent-tabs-mode: nil
1862 * vim: shiftwidth=4 tabstop=8 expandtab