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 static void session_normalize_facet(struct session *s, const char *type,
173 struct conf_service *service = s->service;
174 pp2_charset_token_t prt;
175 const char *facet_component;
177 const char *icu_chain_id = 0;
179 for (i = 0; i < service->num_metadata; i++)
180 if (!strcmp((service->metadata + i)->name, type))
181 icu_chain_id = (service->metadata + i)->facetrule;
183 icu_chain_id = "facet";
184 prt = pp2_charset_token_create(service->charsets, icu_chain_id);
187 yaz_log(YLOG_FATAL, "Unknown ICU chain '%s' for facet of type '%s'",
189 wrbuf_destroy(facet_wrbuf);
190 wrbuf_destroy(display_wrbuf);
193 pp2_charset_token_first(prt, value, 0);
194 while ((facet_component = pp2_charset_token_next(prt)))
196 const char *display_component;
197 if (*facet_component)
199 if (wrbuf_len(facet_wrbuf))
200 wrbuf_puts(facet_wrbuf, " ");
201 wrbuf_puts(facet_wrbuf, facet_component);
203 display_component = pp2_get_display(prt);
204 if (display_component)
206 if (wrbuf_len(display_wrbuf))
207 wrbuf_puts(display_wrbuf, " ");
208 wrbuf_puts(display_wrbuf, display_component);
211 pp2_charset_token_destroy(prt);
214 void add_facet(struct session *s, const char *type, const char *value, int count)
216 WRBUF facet_wrbuf = wrbuf_alloc();
217 WRBUF display_wrbuf = wrbuf_alloc();
219 session_normalize_facet(s, type, value, display_wrbuf, facet_wrbuf);
221 if (wrbuf_len(facet_wrbuf))
224 for (i = 0; i < s->num_termlists; i++)
225 if (!strcmp(s->termlists[i].name, type))
227 if (i == s->num_termlists)
229 if (i == SESSION_MAX_TERMLISTS)
231 session_log(s, YLOG_FATAL, "Too many termlists");
232 wrbuf_destroy(facet_wrbuf);
233 wrbuf_destroy(display_wrbuf);
237 s->termlists[i].name = nmem_strdup(s->nmem, type);
238 s->termlists[i].termlist
239 = termlist_create(s->nmem, TERMLIST_HIGH_SCORE);
240 s->num_termlists = i + 1;
244 session_log(s, YLOG_DEBUG, "Facets for %s: %s norm:%s (%d)", type, value, wrbuf_cstr(facet_wrbuf), count);
246 termlist_insert(s->termlists[i].termlist, wrbuf_cstr(display_wrbuf),
247 wrbuf_cstr(facet_wrbuf), count);
249 wrbuf_destroy(facet_wrbuf);
250 wrbuf_destroy(display_wrbuf);
253 static xmlDoc *record_to_xml(struct session *se,
254 struct session_database *sdb, const char *rec)
256 struct database *db = sdb->database;
259 rdoc = xmlParseMemory(rec, strlen(rec));
263 session_log(se, YLOG_FATAL, "Non-wellformed XML received from %s",
268 if (global_parameters.dump_records)
270 session_log(se, YLOG_LOG, "Un-normalized record from %s", db->id);
277 #define MAX_XSLT_ARGS 16
279 // Add static values from session database settings if applicable
280 static void insert_settings_parameters(struct session_database *sdb,
281 struct conf_service *service,
289 for (i = 0; i < service->num_metadata; i++)
291 struct conf_metadata *md = &service->metadata[i];
294 if (md->setting == Metadata_setting_parameter &&
295 (setting = settings_lookup_offset(service, md->name)) >= 0)
297 const char *val = session_setting_oneval(sdb, setting);
298 if (val && nparms < MAX_XSLT_ARGS)
301 int len = strlen(val);
302 buf = nmem_malloc(nmem, len + 3);
304 strcpy(buf + 1, val);
307 parms[offset++] = md->name;
308 parms[offset++] = buf;
316 // Add static values from session database settings if applicable
317 static void insert_settings_values(struct session_database *sdb, xmlDoc *doc,
318 struct conf_service *service)
322 for (i = 0; i < service->num_metadata; i++)
324 struct conf_metadata *md = &service->metadata[i];
327 if (md->setting == Metadata_setting_postproc &&
328 (offset = settings_lookup_offset(service, md->name)) >= 0)
330 const char *val = session_setting_oneval(sdb, offset);
333 xmlNode *r = xmlDocGetRootElement(doc);
334 xmlNode *n = xmlNewTextChild(r, 0, (xmlChar *) "metadata",
336 xmlSetProp(n, (xmlChar *) "type", (xmlChar *) md->name);
342 static xmlDoc *normalize_record(struct session *se,
343 struct session_database *sdb,
344 struct conf_service *service,
345 const char *rec, NMEM nmem)
347 xmlDoc *rdoc = record_to_xml(se, sdb, rec);
351 char *parms[MAX_XSLT_ARGS*2+1];
353 insert_settings_parameters(sdb, service, parms, nmem);
355 if (normalize_record_transform(sdb->map, &rdoc, (const char **)parms))
357 session_log(se, YLOG_WARN, "Normalize failed from %s",
362 insert_settings_values(sdb, rdoc, service);
364 if (global_parameters.dump_records)
366 session_log(se, YLOG_LOG, "Normalized record from %s",
375 void session_settings_dump(struct session *se,
376 struct session_database *db,
381 int i, num = db->num_settings;
382 for (i = 0; i < num; i++)
384 struct setting *s = db->settings[i];
385 for (;s ; s = s->next)
387 wrbuf_puts(w, "<set name=\"");
388 wrbuf_xmlputs(w, s->name);
389 wrbuf_puts(w, "\" value=\"");
390 wrbuf_xmlputs(w, s->value);
391 wrbuf_puts(w, "\"/>");
399 // Retrieve first defined value for 'name' for given database.
400 // Will be extended to take into account user associated with session
401 const char *session_setting_oneval(struct session_database *db, int offset)
403 if (offset >= db->num_settings || !db->settings[offset])
405 return db->settings[offset]->value;
408 // Prepare XSLT stylesheets for record normalization
409 // Structures are allocated on the session_wide nmem to avoid having
410 // to recompute this for every search. This would lead
411 // to leaking if a single session was to repeatedly change the PZ_XSLT
412 // setting. However, this is not a realistic use scenario.
413 static int prepare_map(struct session *se, struct session_database *sdb)
417 if (sdb->settings && sdb->settings[PZ_XSLT] && !sdb->map &&
418 (s = session_setting_oneval(sdb, PZ_XSLT)))
420 char auto_stylesheet[256];
422 if (!strcmp(s, "auto"))
424 const char *request_syntax = session_setting_oneval(
425 sdb, PZ_REQUESTSYNTAX);
429 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
430 "%s.xsl", request_syntax);
431 for (cp = auto_stylesheet; *cp; cp++)
433 /* deliberately only consider ASCII */
434 if (*cp > 32 && *cp < 127)
441 session_log(se, YLOG_WARN,
442 "No pz:requestsyntax for auto stylesheet");
445 sdb->map = normalize_cache_get(se->normalize_cache,
453 // called if watch should be removed because http_channel is to be destroyed
454 static void session_watch_cancel(void *data, struct http_channel *c,
457 struct session_watchentry *ent = data;
464 // set watch. Returns 0=OK, -1 if watch is already set
465 int session_set_watch(struct session *s, int what,
466 session_watchfun fun, void *data,
467 struct http_channel *chan)
471 if (s->watchlist[what].fun)
476 s->watchlist[what].fun = fun;
477 s->watchlist[what].data = data;
478 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
479 session_watch_cancel);
486 void session_alert_watch(struct session *s, int what)
490 if (s->watchlist[what].fun)
492 /* our watch is no longer associated with http_channel */
494 session_watchfun fun;
496 http_remove_observer(s->watchlist[what].obs);
497 fun = s->watchlist[what].fun;
498 data = s->watchlist[what].data;
500 /* reset watch before fun is invoked - in case fun wants to set
502 s->watchlist[what].fun = 0;
503 s->watchlist[what].data = 0;
504 s->watchlist[what].obs = 0;
507 session_log(s, YLOG_DEBUG,
508 "Alert Watch: %d calling function: %p", what, fun);
515 //callback for grep_databases
516 static void select_targets_callback(struct session *se,
517 struct session_database *db)
520 struct client_list *l;
522 for (l = se->clients_cached; l; l = l->next)
523 if (client_get_database(l->client) == db)
530 cl = client_create(db->database->id);
531 client_set_database(cl, db);
532 client_set_session(cl, se);
534 l = xmalloc(sizeof(*l));
536 l->next = se->clients_cached;
537 se->clients_cached = l;
540 l = xmalloc(sizeof(*l));
542 l->next = se->clients_active;
543 se->clients_active = l;
546 static void session_reset_active_clients(struct session *se,
547 struct client_list *new_list)
549 struct client_list *l;
552 l = se->clients_active;
553 se->clients_active = new_list;
558 struct client_list *l_next = l->next;
564 static void session_remove_cached_clients(struct session *se)
566 struct client_list *l;
568 session_reset_active_clients(se, 0);
571 l = se->clients_cached;
572 se->clients_cached = 0;
577 struct client_list *l_next = l->next;
578 client_lock(l->client);
579 client_set_session(l->client, 0);
580 client_set_database(l->client, 0);
581 client_unlock(l->client);
582 client_destroy(l->client);
588 // Associates a set of clients with a session;
589 // Note: Session-databases represent databases with per-session
591 static int select_targets(struct session *se, const char *filter)
593 return session_grep_databases(se, filter, select_targets_callback);
596 int session_active_clients(struct session *s)
598 struct client_list *l;
601 for (l = s->clients_active; l; l = l->next)
602 if (client_is_active(l->client))
608 int session_is_preferred_clients_ready(struct session *s)
610 struct client_list *l;
613 for (l = s->clients_active; l; l = l->next)
614 if (client_is_active_preferred(l->client))
616 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
620 static const char *get_strategy_plus_sort(struct client *l, const char *field)
622 struct session_database *sdb = client_get_database(l);
625 const char *strategy_plus_sort = 0;
627 for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
629 char *p = strchr(s->name + 3, ':');
632 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
636 if (!strcmp(p, field))
638 strategy_plus_sort = s->value;
642 return strategy_plus_sort;
645 void session_sort(struct session *se, const char *field, int increasing)
647 struct session_sorted_results *sr;
648 struct client_list *l;
652 /* see if we already have sorted for this critieria */
653 for (sr = se->sorted_results; sr; sr = sr->next)
655 if (!strcmp(field, sr->field) && increasing == sr->increasing)
660 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
665 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
667 sr = nmem_malloc(se->nmem, sizeof(*sr));
668 sr->field = nmem_strdup(se->nmem, field);
669 sr->increasing = increasing;
670 sr->next = se->sorted_results;
671 se->sorted_results = sr;
673 for (l = se->clients_active; l; l = l->next)
675 struct client *cl = l->client;
676 const char *strategy_plus_sort = get_strategy_plus_sort(cl, field);
677 if (strategy_plus_sort)
680 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
681 se->service->z3950_session_timeout,
682 se->service->server->iochan_man,
684 client_start_search(cl, strategy_plus_sort, increasing);
690 enum pazpar2_error_code session_search(struct session *se,
692 const char *startrecs,
696 const char **addinfo,
697 const char *sort_field, int increasing)
699 int live_channels = 0;
701 int no_failed_query = 0;
702 int no_failed_limit = 0;
703 struct client_list *l, *l0;
705 facet_limits_t facet_limits;
707 session_log(se, YLOG_DEBUG, "Search");
711 if (se->settings_modified)
712 session_remove_cached_clients(se);
714 session_reset_active_clients(se, 0);
717 reclist_destroy(se->reclist);
719 se->settings_modified = 0;
720 relevance_destroy(&se->relevance);
721 nmem_reset(se->nmem);
722 se->total_records = se->total_merged = 0;
723 se->num_termlists = 0;
725 /* reset list of sorted results and clear to relevance search */
726 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
727 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
728 se->sorted_results->increasing = increasing;
729 se->sorted_results->next = 0;
731 live_channels = select_targets(se, filter);
735 return PAZPAR2_NO_TARGETS;
737 se->reclist = reclist_create(se->nmem);
739 yaz_gettimeofday(&tval);
743 facet_limits = facet_limits_create(limit);
748 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
751 l0 = se->clients_active;
752 se->clients_active = 0;
755 for (l = l0; l; l = l->next)
758 struct client *cl = l->client;
759 const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
761 if (prepare_map(se, client_get_database(cl)) < 0)
764 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
768 else if (parse_ret == -2)
770 else if (parse_ret == 0)
772 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
774 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
775 se->service->z3950_session_timeout,
776 se->service->server->iochan_man,
778 client_start_search(cl, strategy_plus_sort, increasing);
782 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
784 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
785 se->service->z3950_session_timeout,
786 se->service->server->iochan_man,
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 yaz_log(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(id, se->session_nmem);
859 session_init_databases_fun((void*) se, db);
861 // New sdb is head of se->databases list
862 return se->databases;
865 // Find an existing session database. If not found, load it
866 static struct session_database *find_session_database(struct session *se,
869 struct session_database *sdb;
871 for (sdb = se->databases; sdb; sdb = sdb->next)
872 if (!strcmp(sdb->database->id, id))
874 return load_session_database(se, id);
877 // Apply a session override to a database
878 void session_apply_setting(struct session *se, char *dbname, char *setting,
881 struct session_database *sdb = find_session_database(se, dbname);
882 struct conf_service *service = se->service;
883 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
884 int offset = settings_create_offset(service, setting);
886 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
889 new->target = dbname;
892 new->next = sdb->settings[offset];
893 sdb->settings[offset] = new;
895 se->settings_modified = 1;
897 // Force later recompute of settings-driven data structures
898 // (happens when a search starts and client connections are prepared)
910 void session_destroy(struct session *se)
912 struct session_database *sdb;
913 session_log(se, YLOG_DEBUG, "Destroying");
915 session_remove_cached_clients(se);
917 for (sdb = se->databases; sdb; sdb = sdb->next)
918 session_database_destroy(sdb);
919 normalize_cache_destroy(se->normalize_cache);
920 relevance_destroy(&se->relevance);
921 reclist_destroy(se->reclist);
922 nmem_destroy(se->nmem);
923 service_destroy(se->service);
924 yaz_mutex_destroy(&se->session_mutex);
927 size_t session_get_memory_status(struct session *session) {
931 session_enter(session);
932 session_nmem = nmem_total(session->nmem);
933 session_leave(session);
938 struct session *new_session(NMEM nmem, struct conf_service *service,
942 struct session *session = nmem_malloc(nmem, sizeof(*session));
946 sprintf(tmp_str, "session#%u", session_id);
948 session->session_id = session_id;
949 session_log(session, YLOG_DEBUG, "New");
950 session->service = service;
951 session->relevance = 0;
952 session->total_records = 0;
953 session->number_of_warnings_unknown_elements = 0;
954 session->number_of_warnings_unknown_metadata = 0;
955 session->num_termlists = 0;
956 session->reclist = 0;
957 session->clients_active = 0;
958 session->clients_cached = 0;
959 session->settings_modified = 0;
960 session->session_nmem = nmem;
961 session->nmem = nmem_create();
962 session->databases = 0;
963 for (i = 0; i <= SESSION_WATCH_MAX; i++)
965 session->watchlist[i].data = 0;
966 session->watchlist[i].fun = 0;
968 session->normalize_cache = normalize_cache_create();
969 session->session_mutex = 0;
970 pazpar2_mutex_create(&session->session_mutex, tmp_str);
975 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
977 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
978 int *count, NMEM nmem)
980 struct hitsbytarget *res = 0;
981 struct client_list *l;
984 for (l = se->clients_active; l; l = l->next)
987 res = nmem_malloc(nmem, sizeof(*res) * sz);
989 for (l = se->clients_active; l; l = l->next)
991 struct client *cl = l->client;
992 WRBUF w = wrbuf_alloc();
993 const char *name = session_setting_oneval(client_get_database(cl),
996 res[*count].id = client_get_id(cl);
997 res[*count].name = *name ? name : "Unknown";
998 res[*count].hits = client_get_hits(cl);
999 res[*count].records = client_get_num_records(cl);
1000 res[*count].diagnostic = client_get_diagnostic(cl);
1001 res[*count].state = client_get_state_str(cl);
1002 res[*count].connected = client_get_connection(cl) ? 1 : 0;
1003 session_settings_dump(se, client_get_database(cl), w);
1004 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
1007 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1014 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1016 struct hitsbytarget *p;
1018 p = hitsbytarget_nb(se, count, nmem);
1023 struct termlist_score **get_termlist_score(struct session *se,
1024 const char *name, int *num)
1027 struct termlist_score **tl = 0;
1030 for (i = 0; i < se->num_termlists; i++)
1031 if (!strcmp((const char *) se->termlists[i].name, name))
1033 tl = termlist_highscore(se->termlists[i].termlist, num);
1040 // Compares two hitsbytarget nodes by hitcount
1041 static int cmp_ht(const void *p1, const void *p2)
1043 const struct hitsbytarget *h1 = p1;
1044 const struct hitsbytarget *h2 = p2;
1045 return h2->hits - h1->hits;
1048 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1051 struct hitsbytarget *ht;
1054 ht = hitsbytarget_nb(se, &count, nmem);
1055 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1056 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1059 // do only print terms which have display names
1061 wrbuf_puts(wrbuf, "<term>\n");
1063 wrbuf_puts(wrbuf, "<id>");
1064 wrbuf_xmlputs(wrbuf, ht[i].id);
1065 wrbuf_puts(wrbuf, "</id>\n");
1067 wrbuf_puts(wrbuf, "<name>");
1068 if (!ht[i].name || !ht[i].name[0])
1069 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1071 wrbuf_xmlputs(wrbuf, ht[i].name);
1072 wrbuf_puts(wrbuf, "</name>\n");
1074 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1077 wrbuf_puts(wrbuf, "<state>");
1078 wrbuf_xmlputs(wrbuf, ht[i].state);
1079 wrbuf_puts(wrbuf, "</state>\n");
1081 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1083 wrbuf_puts(wrbuf, "</term>\n");
1088 void perform_termlist(struct http_channel *c, struct session *se,
1089 const char *name, int num)
1092 NMEM nmem_tmp = nmem_create();
1097 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1101 for (j = 0; j < num_names; j++)
1105 wrbuf_puts(c->wrbuf, "<list name=\"");
1106 wrbuf_xmlputs(c->wrbuf, names[j]);
1107 wrbuf_puts(c->wrbuf, "\">\n");
1109 for (i = 0; i < se->num_termlists; i++)
1111 tname = se->termlists[i].name;
1112 if (num_names > 0 && !strcmp(names[j], tname))
1114 struct termlist_score **p = 0;
1116 p = termlist_highscore(se->termlists[i].termlist, &len);
1120 for (i = 0; i < len && i < num; i++)
1122 // prevent sending empty term elements
1123 if (!p[i]->display_term || !p[i]->display_term[0])
1126 wrbuf_puts(c->wrbuf, "<term>");
1127 wrbuf_puts(c->wrbuf, "<name>");
1128 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1129 wrbuf_puts(c->wrbuf, "</name>");
1131 wrbuf_printf(c->wrbuf,
1132 "<frequency>%d</frequency>",
1134 wrbuf_puts(c->wrbuf, "</term>\n");
1140 if (num_names > 0 && !strcmp(names[j], tname))
1142 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1144 wrbuf_puts(c->wrbuf, "</list>\n");
1147 nmem_destroy(nmem_tmp);
1150 #ifdef MISSING_HEADERS
1151 void report_nmem_stats(void)
1153 size_t in_use, is_free;
1155 nmem_get_memory_in_use(&in_use);
1156 nmem_get_memory_free(&is_free);
1158 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1159 (long) in_use, (long) is_free);
1163 struct record_cluster *show_single_start(struct session *se, const char *id,
1164 struct record_cluster **prev_r,
1165 struct record_cluster **next_r)
1167 struct record_cluster *r = 0;
1174 reclist_enter(se->reclist);
1175 while ((r = reclist_read_record(se->reclist)))
1177 if (!strcmp(r->recid, id))
1179 *next_r = reclist_read_record(se->reclist);
1184 reclist_leave(se->reclist);
1191 void show_single_stop(struct session *se, struct record_cluster *rec)
1196 struct record_cluster **show_range_start(struct session *se,
1197 struct reclist_sortparms *sp,
1198 int start, int *num, int *total, Odr_int *sumhits)
1200 struct record_cluster **recs;
1201 struct reclist_sortparms *spp;
1204 yaz_timing_t t = yaz_timing_create();
1207 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1217 struct client_list *l;
1219 for (spp = sp; spp; spp = spp->next)
1220 if (spp->type == Metadata_sortkey_relevance)
1222 relevance_prepare_read(se->relevance, se->reclist);
1225 reclist_sort(se->reclist, sp);
1227 reclist_enter(se->reclist);
1228 *total = reclist_get_num_records(se->reclist);
1231 for (l = se->clients_active; l; l = l->next)
1232 *sumhits += client_get_hits(l->client);
1234 for (i = 0; i < start; i++)
1235 if (!reclist_read_record(se->reclist))
1242 for (i = 0; i < *num; i++)
1244 struct record_cluster *r = reclist_read_record(se->reclist);
1252 reclist_leave(se->reclist);
1256 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1257 yaz_timing_get_real(t), yaz_timing_get_user(t),
1258 yaz_timing_get_sys(t));
1259 yaz_timing_destroy(&t);
1264 void show_range_stop(struct session *se, struct record_cluster **recs)
1269 void statistics(struct session *se, struct statistics *stat)
1271 struct client_list *l;
1274 memset(stat, 0, sizeof(*stat));
1276 for (l = se->clients_active; l; l = l->next)
1278 struct client *cl = l->client;
1279 if (!client_get_connection(cl))
1280 stat->num_no_connection++;
1281 stat->num_hits += client_get_hits(cl);
1282 switch (client_get_state(cl))
1284 case Client_Connecting: stat->num_connecting++; break;
1285 case Client_Working: stat->num_working++; break;
1286 case Client_Idle: stat->num_idle++; break;
1287 case Client_Failed: stat->num_failed++; break;
1288 case Client_Error: stat->num_error++; break;
1293 stat->num_records = se->total_records;
1295 stat->num_clients = count;
1298 static struct record_metadata *record_metadata_init(
1299 NMEM nmem, const char *value, enum conf_metadata_type type,
1300 struct _xmlAttr *attr)
1302 struct record_metadata *rec_md = record_metadata_create(nmem);
1303 struct record_metadata_attr **attrp = &rec_md->attributes;
1305 for (; attr; attr = attr->next)
1307 if (attr->children && attr->children->content)
1309 if (strcmp((const char *) attr->name, "type"))
1310 { /* skip the "type" attribute.. Its value is already part of
1311 the element in output (md-%s) and so repeating it here
1313 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1315 nmem_strdup(nmem, (const char *) attr->name);
1317 nmem_strdup(nmem, (const char *) attr->children->content);
1318 attrp = &(*attrp)->next;
1324 if (type == Metadata_type_generic)
1326 char *p = nmem_strdup(nmem, value);
1328 p = normalize7bit_generic(p, " ,/.:([");
1330 rec_md->data.text.disp = p;
1331 rec_md->data.text.sort = 0;
1333 else if (type == Metadata_type_year || type == Metadata_type_date)
1338 if (type == Metadata_type_date)
1340 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1343 rec_md->data.number.min = first;
1344 rec_md->data.number.max = last;
1351 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1352 struct conf_service *service, WRBUF norm_wr)
1356 for (n = root->children; n; n = n->next)
1358 if (n->type != XML_ELEMENT_NODE)
1360 if (!strcmp((const char *) n->name, "metadata"))
1362 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1364 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1366 else if (!strcmp(name, (const char *) type))
1368 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1371 const char *norm_str;
1372 pp2_charset_token_t prt =
1373 pp2_charset_token_create(service->charsets, "mergekey");
1375 pp2_charset_token_first(prt, (const char *) value, 0);
1376 if (wrbuf_len(norm_wr) > 0)
1377 wrbuf_puts(norm_wr, " ");
1378 wrbuf_puts(norm_wr, name);
1380 pp2_charset_token_next(prt)))
1384 wrbuf_puts(norm_wr, " ");
1385 wrbuf_puts(norm_wr, norm_str);
1389 pp2_charset_token_destroy(prt);
1399 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1400 struct conf_service *service, NMEM nmem)
1402 char *mergekey_norm = 0;
1403 xmlNode *root = xmlDocGetRootElement(doc);
1404 WRBUF norm_wr = wrbuf_alloc();
1406 /* consider mergekey from XSL first */
1407 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1410 const char *norm_str;
1411 pp2_charset_token_t prt =
1412 pp2_charset_token_create(service->charsets, "mergekey");
1414 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1415 while ((norm_str = pp2_charset_token_next(prt)))
1419 if (wrbuf_len(norm_wr))
1420 wrbuf_puts(norm_wr, " ");
1421 wrbuf_puts(norm_wr, norm_str);
1424 pp2_charset_token_destroy(prt);
1429 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1431 for (field_id = 0; field_id < service->num_metadata; field_id++)
1433 struct conf_metadata *ser_md = &service->metadata[field_id];
1434 if (ser_md->mergekey != Metadata_mergekey_no)
1436 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1438 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1440 /* no mergekey on this one and it is required..
1441 Generate unique key instead */
1442 wrbuf_rewind(norm_wr);
1449 /* generate unique key if none is not generated already or is empty */
1450 if (wrbuf_len(norm_wr) == 0)
1452 wrbuf_printf(norm_wr, "position: %s-%d",
1453 client_get_id(cl), record_no);
1457 const char *lead = "content: ";
1458 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1460 if (wrbuf_len(norm_wr) > 0)
1461 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1462 wrbuf_destroy(norm_wr);
1463 return mergekey_norm;
1466 /** \brief see if metadata for pz:recordfilter exists
1467 \param root xml root element of normalized record
1468 \param sdb session database for client
1469 \retval 0 if there is no metadata for pz:recordfilter
1470 \retval 1 if there is metadata for pz:recordfilter
1472 If there is no pz:recordfilter defined, this function returns 1
1476 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1481 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1486 for (n = root->children; n; n = n->next)
1488 if (n->type != XML_ELEMENT_NODE)
1490 if (!strcmp((const char *) n->name, "metadata"))
1492 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1499 if ((eq = strchr(s, '=')))
1501 else if ((eq = strchr(s, '~')))
1507 if (len == strlen((const char *)type) &&
1508 !memcmp((const char *) type, s, len))
1510 xmlChar *value = xmlNodeGetContent(n);
1511 if (value && *value)
1514 (substring && strstr((const char *) value, eq+1)) ||
1515 (!substring && !strcmp((const char *) value, eq + 1)))
1528 static int ingest_to_cluster(struct client *cl,
1532 const char *mergekey_norm);
1534 /** \brief ingest XML record
1535 \param cl client holds the result set for record
1536 \param rec record buffer (0 terminated)
1537 \param record_no record position (1, 2, ..)
1538 \param nmem working NMEM
1543 int ingest_record(struct client *cl, const char *rec,
1544 int record_no, NMEM nmem)
1546 struct session *se = client_get_session(cl);
1548 struct session_database *sdb = client_get_database(cl);
1549 struct conf_service *service = se->service;
1550 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1552 const char *mergekey_norm;
1557 root = xmlDocGetRootElement(xdoc);
1559 if (!check_record_filter(root, sdb))
1561 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1562 record_no, sdb->database->id);
1567 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1570 session_log(se, YLOG_WARN, "Got no mergekey");
1575 if (client_get_session(cl) == se)
1576 ret = ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1583 static int check_limit_local(struct client *cl,
1584 struct record *record,
1587 int skip_record = 0;
1588 struct session *se = client_get_session(cl);
1589 struct conf_service *service = se->service;
1590 NMEM nmem_tmp = nmem_create();
1591 struct session_database *sdb = client_get_database(cl);
1593 while (!skip_record)
1595 struct conf_metadata *ser_md = 0;
1596 struct record_metadata *rec_md = 0;
1602 client_get_facet_limit_local(cl, sdb, &l, nmem_tmp, &num_v,
1607 md_field_id = conf_service_metadata_field_id(service, name);
1608 if (md_field_id < 0)
1613 ser_md = &service->metadata[md_field_id];
1614 rec_md = record->metadata[md_field_id];
1615 yaz_log(YLOG_LOG, "check limit local %s", name);
1616 for (i = 0; i < num_v; )
1620 if (ser_md->type == Metadata_type_year
1621 || ser_md->type == Metadata_type_date)
1623 int y = atoi(values[i]);
1624 if (y >= rec_md->data.number.min
1625 && y <= rec_md->data.number.max)
1630 yaz_log(YLOG_LOG, "cmp: '%s' '%s'",
1631 rec_md->data.text.disp, values[i]);
1632 if (!strcmp(rec_md->data.text.disp, values[i]))
1637 rec_md = rec_md->next;
1641 rec_md = record->metadata[md_field_id];
1651 nmem_destroy(nmem_tmp);
1655 static int ingest_to_cluster(struct client *cl,
1659 const char *mergekey_norm)
1664 struct session *se = client_get_session(cl);
1665 struct conf_service *service = se->service;
1666 int term_factor = 1;
1667 struct record_cluster *cluster;
1668 struct session_database *sdb = client_get_database(cl);
1669 struct record *record = record_create(se->nmem,
1670 service->num_metadata,
1671 service->num_sortkeys, cl,
1674 for (n = root->children; n; n = n->next)
1682 if (n->type != XML_ELEMENT_NODE)
1684 if (!strcmp((const char *) n->name, "metadata"))
1686 struct conf_metadata *ser_md = 0;
1687 struct record_metadata **wheretoput = 0;
1688 struct record_metadata *rec_md = 0;
1689 int md_field_id = -1;
1691 type = xmlGetProp(n, (xmlChar *) "type");
1692 value = xmlNodeListGetString(xdoc, n->children, 1);
1694 if (!type || !value || !*value)
1698 = conf_service_metadata_field_id(service, (const char *) type);
1699 if (md_field_id < 0)
1701 if (se->number_of_warnings_unknown_metadata == 0)
1703 session_log(se, YLOG_WARN,
1704 "Ignoring unknown metadata element: %s", type);
1706 se->number_of_warnings_unknown_metadata++;
1710 ser_md = &service->metadata[md_field_id];
1712 // non-merged metadata
1713 rec_md = record_metadata_init(se->nmem, (const char *) value,
1714 ser_md->type, n->properties);
1717 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1718 "for element '%s'", value, type);
1721 wheretoput = &record->metadata[md_field_id];
1723 wheretoput = &(*wheretoput)->next;
1724 *wheretoput = rec_md;
1728 if (check_limit_local(cl, record, record_no))
1730 session_log(se, YLOG_LOG, "Facet filtered out record no %d from %s",
1731 record_no, sdb->database->id);
1738 cluster = reclist_insert(se->reclist, service, record,
1739 mergekey_norm, &se->total_merged);
1744 const char *use_term_factor_str =
1745 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1746 if (use_term_factor_str && use_term_factor_str[0] == '1')
1748 int maxrecs = client_get_maxrecs(cl);
1749 int hits = (int) client_get_hits(cl);
1750 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1751 assert(term_factor >= 1);
1752 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1756 if (global_parameters.dump_records)
1757 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1758 sdb->database->id, record_no);
1761 relevance_newrec(se->relevance, cluster);
1763 // now parsing XML record and adding data to cluster or record metadata
1764 for (n = root->children; n; n = n->next)
1766 pp2_charset_token_t prt;
1773 if (n->type != XML_ELEMENT_NODE)
1775 if (!strcmp((const char *) n->name, "metadata"))
1777 struct conf_metadata *ser_md = 0;
1778 struct conf_sortkey *ser_sk = 0;
1779 struct record_metadata **wheretoput = 0;
1780 struct record_metadata *rec_md = 0;
1781 int md_field_id = -1;
1782 int sk_field_id = -1;
1784 type = xmlGetProp(n, (xmlChar *) "type");
1785 value = xmlNodeListGetString(xdoc, n->children, 1);
1787 if (!type || !value || !*value)
1791 = conf_service_metadata_field_id(service, (const char *) type);
1792 if (md_field_id < 0)
1795 ser_md = &service->metadata[md_field_id];
1797 if (ser_md->sortkey_offset >= 0)
1799 sk_field_id = ser_md->sortkey_offset;
1800 ser_sk = &service->sortkeys[sk_field_id];
1804 rec_md = record_metadata_init(se->nmem, (const char *) value,
1809 wheretoput = &cluster->metadata[md_field_id];
1811 // and polulate with data:
1812 // assign cluster or record based on merge action
1813 if (ser_md->merge == Metadata_merge_unique)
1817 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1818 rec_md->data.text.disp))
1820 wheretoput = &(*wheretoput)->next;
1823 *wheretoput = rec_md;
1825 else if (ser_md->merge == Metadata_merge_longest)
1828 || strlen(rec_md->data.text.disp)
1829 > strlen((*wheretoput)->data.text.disp))
1831 *wheretoput = rec_md;
1834 const char *sort_str = 0;
1836 ser_sk->type == Metadata_sortkey_skiparticle;
1838 if (!cluster->sortkeys[sk_field_id])
1839 cluster->sortkeys[sk_field_id] =
1840 nmem_malloc(se->nmem,
1841 sizeof(union data_types));
1844 pp2_charset_token_create(service->charsets, "sort");
1846 pp2_charset_token_first(prt, rec_md->data.text.disp,
1849 pp2_charset_token_next(prt);
1851 sort_str = pp2_get_sort(prt);
1853 cluster->sortkeys[sk_field_id]->text.disp =
1854 rec_md->data.text.disp;
1857 sort_str = rec_md->data.text.disp;
1858 session_log(se, YLOG_WARN,
1859 "Could not make sortkey. Bug #1858");
1861 cluster->sortkeys[sk_field_id]->text.sort =
1862 nmem_strdup(se->nmem, sort_str);
1863 pp2_charset_token_destroy(prt);
1867 else if (ser_md->merge == Metadata_merge_all)
1870 wheretoput = &(*wheretoput)->next;
1871 *wheretoput = rec_md;
1873 else if (ser_md->merge == Metadata_merge_range)
1877 *wheretoput = rec_md;
1879 cluster->sortkeys[sk_field_id]
1884 int this_min = rec_md->data.number.min;
1885 int this_max = rec_md->data.number.max;
1886 if (this_min < (*wheretoput)->data.number.min)
1887 (*wheretoput)->data.number.min = this_min;
1888 if (this_max > (*wheretoput)->data.number.max)
1889 (*wheretoput)->data.number.max = this_max;
1894 // ranking of _all_ fields enabled ...
1896 relevance_countwords(se->relevance, cluster,
1897 (char *) value, ser_md->rank,
1900 // construct facets ... unless the client already has reported them
1901 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1903 if (ser_md->type == Metadata_type_year)
1906 sprintf(year, "%d", rec_md->data.number.max);
1908 add_facet(se, (char *) type, year, term_factor);
1909 if (rec_md->data.number.max != rec_md->data.number.min)
1911 sprintf(year, "%d", rec_md->data.number.min);
1912 add_facet(se, (char *) type, year, term_factor);
1916 add_facet(se, (char *) type, (char *) value, term_factor);
1926 if (se->number_of_warnings_unknown_elements == 0)
1927 session_log(se, YLOG_WARN,
1928 "Unexpected element in internal record: %s", n->name);
1929 se->number_of_warnings_unknown_elements++;
1937 relevance_donerecord(se->relevance, cluster);
1938 se->total_records++;
1943 void session_log(struct session *s, int level, const char *fmt, ...)
1949 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1950 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1958 * c-file-style: "Stroustrup"
1959 * indent-tabs-mode: nil
1961 * vim: shiftwidth=4 tabstop=8 expandtab