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;
692 int no_failed_query = 0;
693 int no_failed_limit = 0;
694 struct client_list *l, *l0;
696 facet_limits_t facet_limits;
698 session_log(se, YLOG_DEBUG, "Search");
702 if (se->settings_modified)
703 session_remove_cached_clients(se);
705 session_reset_active_clients(se, 0);
708 reclist_destroy(se->reclist);
710 se->settings_modified = 0;
711 relevance_destroy(&se->relevance);
712 nmem_reset(se->nmem);
713 se->total_records = se->total_merged = 0;
714 se->num_termlists = 0;
716 /* reset list of sorted results and clear to relevance search */
717 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
718 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
719 se->sorted_results->increasing = increasing;
720 se->sorted_results->next = 0;
722 live_channels = select_targets(se, filter);
726 return PAZPAR2_NO_TARGETS;
728 se->reclist = reclist_create(se->nmem);
730 yaz_gettimeofday(&tval);
734 facet_limits = facet_limits_create(limit);
739 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
742 l0 = se->clients_active;
743 se->clients_active = 0;
746 for (l = l0; l; l = l->next)
749 struct client *cl = l->client;
750 const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
752 if (prepare_map(se, client_get_database(cl)) < 0)
755 parse_ret = client_parse_query(cl, query, facet_limits, startrecs,
759 else if (parse_ret == -2)
761 else if (parse_ret == 0)
763 session_log(se, YLOG_LOG, "client NEW %s", client_get_id(cl));
765 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
766 se->service->z3950_session_timeout,
767 se->service->server->iochan_man,
769 client_start_search(cl, strategy_plus_sort, increasing);
773 session_log(se, YLOG_LOG, "client REUSE %s", client_get_id(cl));
775 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
776 se->service->z3950_session_timeout,
777 se->service->server->iochan_man,
784 facet_limits_destroy(facet_limits);
785 session_reset_active_clients(se, l0);
789 if (no_failed_query > 0)
792 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
794 else if (no_failed_limit > 0)
797 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
800 return PAZPAR2_NO_TARGETS;
802 yaz_log(YLOG_LOG, "session_start_search done");
803 return PAZPAR2_NO_ERROR;
806 // Creates a new session_database object for a database
807 static void session_init_databases_fun(void *context, struct database *db)
809 struct session *se = (struct session *) context;
810 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
816 assert(db->settings);
817 new->settings = nmem_malloc(se->session_nmem,
818 sizeof(struct settings *) * db->num_settings);
819 new->num_settings = db->num_settings;
820 for (i = 0; i < db->num_settings; i++)
822 struct setting *setting = db->settings[i];
823 new->settings[i] = setting;
825 new->next = se->databases;
829 // Doesn't free memory associated with sdb -- nmem takes care of that
830 static void session_database_destroy(struct session_database *sdb)
835 // Initialize session_database list -- this represents this session's view
836 // of the database list -- subject to modification by the settings ws command
837 void session_init_databases(struct session *se)
840 predef_grep_databases(se, se->service, session_init_databases_fun);
843 // Probably session_init_databases_fun should be refactored instead of
845 static struct session_database *load_session_database(struct session *se,
848 struct database *db = new_database(id, se->session_nmem);
850 session_init_databases_fun((void*) se, db);
852 // New sdb is head of se->databases list
853 return se->databases;
856 // Find an existing session database. If not found, load it
857 static struct session_database *find_session_database(struct session *se,
860 struct session_database *sdb;
862 for (sdb = se->databases; sdb; sdb = sdb->next)
863 if (!strcmp(sdb->database->id, id))
865 return load_session_database(se, id);
868 // Apply a session override to a database
869 void session_apply_setting(struct session *se, char *dbname, char *setting,
872 struct session_database *sdb = find_session_database(se, dbname);
873 struct conf_service *service = se->service;
874 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
875 int offset = settings_create_offset(service, setting);
877 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
880 new->target = dbname;
883 new->next = sdb->settings[offset];
884 sdb->settings[offset] = new;
886 se->settings_modified = 1;
888 // Force later recompute of settings-driven data structures
889 // (happens when a search starts and client connections are prepared)
901 void session_destroy(struct session *se)
903 struct session_database *sdb;
904 session_log(se, YLOG_DEBUG, "Destroying");
906 session_remove_cached_clients(se);
908 for (sdb = se->databases; sdb; sdb = sdb->next)
909 session_database_destroy(sdb);
910 normalize_cache_destroy(se->normalize_cache);
911 relevance_destroy(&se->relevance);
912 reclist_destroy(se->reclist);
913 nmem_destroy(se->nmem);
914 service_destroy(se->service);
915 yaz_mutex_destroy(&se->session_mutex);
918 size_t session_get_memory_status(struct session *session) {
922 session_enter(session);
923 session_nmem = nmem_total(session->nmem);
924 session_leave(session);
929 struct session *new_session(NMEM nmem, struct conf_service *service,
933 struct session *session = nmem_malloc(nmem, sizeof(*session));
937 sprintf(tmp_str, "session#%u", session_id);
939 session->session_id = session_id;
940 session_log(session, YLOG_DEBUG, "New");
941 session->service = service;
942 session->relevance = 0;
943 session->total_records = 0;
944 session->number_of_warnings_unknown_elements = 0;
945 session->number_of_warnings_unknown_metadata = 0;
946 session->num_termlists = 0;
947 session->reclist = 0;
948 session->clients_active = 0;
949 session->clients_cached = 0;
950 session->settings_modified = 0;
951 session->session_nmem = nmem;
952 session->nmem = nmem_create();
953 session->databases = 0;
954 for (i = 0; i <= SESSION_WATCH_MAX; i++)
956 session->watchlist[i].data = 0;
957 session->watchlist[i].fun = 0;
959 session->normalize_cache = normalize_cache_create();
960 session->session_mutex = 0;
961 pazpar2_mutex_create(&session->session_mutex, tmp_str);
966 const char * client_get_suggestions_xml(struct client *cl, WRBUF wrbuf);
968 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
969 int *count, NMEM nmem)
971 struct hitsbytarget *res = 0;
972 struct client_list *l;
975 for (l = se->clients_active; l; l = l->next)
978 res = nmem_malloc(nmem, sizeof(*res) * sz);
980 for (l = se->clients_active; l; l = l->next)
982 struct client *cl = l->client;
983 WRBUF w = wrbuf_alloc();
984 const char *name = session_setting_oneval(client_get_database(cl),
987 res[*count].id = client_get_id(cl);
988 res[*count].name = *name ? name : "Unknown";
989 res[*count].hits = client_get_hits(cl);
990 res[*count].records = client_get_num_records(cl);
991 res[*count].diagnostic = client_get_diagnostic(cl);
992 res[*count].state = client_get_state_str(cl);
993 res[*count].connected = client_get_connection(cl) ? 1 : 0;
994 session_settings_dump(se, client_get_database(cl), w);
995 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
998 res[*count].suggestions_xml = nmem_strdup(nmem, client_get_suggestions_xml(cl, w));
1005 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
1007 struct hitsbytarget *p;
1009 p = hitsbytarget_nb(se, count, nmem);
1014 struct termlist_score **get_termlist_score(struct session *se,
1015 const char *name, int *num)
1018 struct termlist_score **tl = 0;
1021 for (i = 0; i < se->num_termlists; i++)
1022 if (!strcmp((const char *) se->termlists[i].name, name))
1024 tl = termlist_highscore(se->termlists[i].termlist, num);
1031 // Compares two hitsbytarget nodes by hitcount
1032 static int cmp_ht(const void *p1, const void *p2)
1034 const struct hitsbytarget *h1 = p1;
1035 const struct hitsbytarget *h2 = p2;
1036 return h2->hits - h1->hits;
1039 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
1042 struct hitsbytarget *ht;
1045 ht = hitsbytarget_nb(se, &count, nmem);
1046 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1047 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1050 // do only print terms which have display names
1052 wrbuf_puts(wrbuf, "<term>\n");
1054 wrbuf_puts(wrbuf, "<id>");
1055 wrbuf_xmlputs(wrbuf, ht[i].id);
1056 wrbuf_puts(wrbuf, "</id>\n");
1058 wrbuf_puts(wrbuf, "<name>");
1059 if (!ht[i].name || !ht[i].name[0])
1060 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1062 wrbuf_xmlputs(wrbuf, ht[i].name);
1063 wrbuf_puts(wrbuf, "</name>\n");
1065 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1068 wrbuf_puts(wrbuf, "<state>");
1069 wrbuf_xmlputs(wrbuf, ht[i].state);
1070 wrbuf_puts(wrbuf, "</state>\n");
1072 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1074 wrbuf_puts(wrbuf, "</term>\n");
1079 void perform_termlist(struct http_channel *c, struct session *se,
1080 const char *name, int num)
1083 NMEM nmem_tmp = nmem_create();
1088 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1092 for (j = 0; j < num_names; j++)
1096 wrbuf_puts(c->wrbuf, "<list name=\"");
1097 wrbuf_xmlputs(c->wrbuf, names[j]);
1098 wrbuf_puts(c->wrbuf, "\">\n");
1100 for (i = 0; i < se->num_termlists; i++)
1102 tname = se->termlists[i].name;
1103 if (num_names > 0 && !strcmp(names[j], tname))
1105 struct termlist_score **p = 0;
1107 p = termlist_highscore(se->termlists[i].termlist, &len);
1111 for (i = 0; i < len && i < num; i++)
1113 // prevent sending empty term elements
1114 if (!p[i]->display_term || !p[i]->display_term[0])
1117 wrbuf_puts(c->wrbuf, "<term>");
1118 wrbuf_puts(c->wrbuf, "<name>");
1119 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1120 wrbuf_puts(c->wrbuf, "</name>");
1122 wrbuf_printf(c->wrbuf,
1123 "<frequency>%d</frequency>",
1125 wrbuf_puts(c->wrbuf, "</term>\n");
1131 if (num_names > 0 && !strcmp(names[j], tname))
1133 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1135 wrbuf_puts(c->wrbuf, "</list>\n");
1138 nmem_destroy(nmem_tmp);
1141 #ifdef MISSING_HEADERS
1142 void report_nmem_stats(void)
1144 size_t in_use, is_free;
1146 nmem_get_memory_in_use(&in_use);
1147 nmem_get_memory_free(&is_free);
1149 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1150 (long) in_use, (long) is_free);
1154 struct record_cluster *show_single_start(struct session *se, const char *id,
1155 struct record_cluster **prev_r,
1156 struct record_cluster **next_r)
1158 struct record_cluster *r = 0;
1165 reclist_enter(se->reclist);
1166 while ((r = reclist_read_record(se->reclist)))
1168 if (!strcmp(r->recid, id))
1170 *next_r = reclist_read_record(se->reclist);
1175 reclist_leave(se->reclist);
1182 void show_single_stop(struct session *se, struct record_cluster *rec)
1187 struct record_cluster **show_range_start(struct session *se,
1188 struct reclist_sortparms *sp,
1189 int start, int *num, int *total, Odr_int *sumhits)
1191 struct record_cluster **recs;
1192 struct reclist_sortparms *spp;
1195 yaz_timing_t t = yaz_timing_create();
1198 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1208 struct client_list *l;
1210 for (spp = sp; spp; spp = spp->next)
1211 if (spp->type == Metadata_sortkey_relevance)
1213 relevance_prepare_read(se->relevance, se->reclist);
1216 reclist_sort(se->reclist, sp);
1218 reclist_enter(se->reclist);
1219 *total = reclist_get_num_records(se->reclist);
1222 for (l = se->clients_active; l; l = l->next)
1223 *sumhits += client_get_hits(l->client);
1225 for (i = 0; i < start; i++)
1226 if (!reclist_read_record(se->reclist))
1233 for (i = 0; i < *num; i++)
1235 struct record_cluster *r = reclist_read_record(se->reclist);
1243 reclist_leave(se->reclist);
1247 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1248 yaz_timing_get_real(t), yaz_timing_get_user(t),
1249 yaz_timing_get_sys(t));
1250 yaz_timing_destroy(&t);
1255 void show_range_stop(struct session *se, struct record_cluster **recs)
1260 void statistics(struct session *se, struct statistics *stat)
1262 struct client_list *l;
1265 memset(stat, 0, sizeof(*stat));
1267 for (l = se->clients_active; l; l = l->next)
1269 struct client *cl = l->client;
1270 if (!client_get_connection(cl))
1271 stat->num_no_connection++;
1272 stat->num_hits += client_get_hits(cl);
1273 switch (client_get_state(cl))
1275 case Client_Connecting: stat->num_connecting++; break;
1276 case Client_Working: stat->num_working++; break;
1277 case Client_Idle: stat->num_idle++; break;
1278 case Client_Failed: stat->num_failed++; break;
1279 case Client_Error: stat->num_error++; break;
1284 stat->num_records = se->total_records;
1286 stat->num_clients = count;
1289 static struct record_metadata *record_metadata_init(
1290 NMEM nmem, const char *value, enum conf_metadata_type type,
1291 struct _xmlAttr *attr)
1293 struct record_metadata *rec_md = record_metadata_create(nmem);
1294 struct record_metadata_attr **attrp = &rec_md->attributes;
1296 for (; attr; attr = attr->next)
1298 if (attr->children && attr->children->content)
1300 if (strcmp((const char *) attr->name, "type"))
1301 { /* skip the "type" attribute.. Its value is already part of
1302 the element in output (md-%s) and so repeating it here
1304 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1306 nmem_strdup(nmem, (const char *) attr->name);
1308 nmem_strdup(nmem, (const char *) attr->children->content);
1309 attrp = &(*attrp)->next;
1315 if (type == Metadata_type_generic)
1317 char *p = nmem_strdup(nmem, value);
1319 p = normalize7bit_generic(p, " ,/.:([");
1321 rec_md->data.text.disp = p;
1322 rec_md->data.text.sort = 0;
1324 else if (type == Metadata_type_year || type == Metadata_type_date)
1329 if (type == Metadata_type_date)
1331 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1334 rec_md->data.number.min = first;
1335 rec_md->data.number.max = last;
1342 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1343 struct conf_service *service, WRBUF norm_wr)
1347 for (n = root->children; n; n = n->next)
1349 if (n->type != XML_ELEMENT_NODE)
1351 if (!strcmp((const char *) n->name, "metadata"))
1353 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1355 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1357 else if (!strcmp(name, (const char *) type))
1359 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1362 const char *norm_str;
1363 pp2_charset_token_t prt =
1364 pp2_charset_token_create(service->charsets, "mergekey");
1366 pp2_charset_token_first(prt, (const char *) value, 0);
1367 if (wrbuf_len(norm_wr) > 0)
1368 wrbuf_puts(norm_wr, " ");
1369 wrbuf_puts(norm_wr, name);
1371 pp2_charset_token_next(prt)))
1375 wrbuf_puts(norm_wr, " ");
1376 wrbuf_puts(norm_wr, norm_str);
1380 pp2_charset_token_destroy(prt);
1390 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1391 struct conf_service *service, NMEM nmem)
1393 char *mergekey_norm = 0;
1394 xmlNode *root = xmlDocGetRootElement(doc);
1395 WRBUF norm_wr = wrbuf_alloc();
1397 /* consider mergekey from XSL first */
1398 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1401 const char *norm_str;
1402 pp2_charset_token_t prt =
1403 pp2_charset_token_create(service->charsets, "mergekey");
1405 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1406 while ((norm_str = pp2_charset_token_next(prt)))
1410 if (wrbuf_len(norm_wr))
1411 wrbuf_puts(norm_wr, " ");
1412 wrbuf_puts(norm_wr, norm_str);
1415 pp2_charset_token_destroy(prt);
1420 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1422 for (field_id = 0; field_id < service->num_metadata; field_id++)
1424 struct conf_metadata *ser_md = &service->metadata[field_id];
1425 if (ser_md->mergekey != Metadata_mergekey_no)
1427 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1429 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1431 /* no mergekey on this one and it is required..
1432 Generate unique key instead */
1433 wrbuf_rewind(norm_wr);
1440 /* generate unique key if none is not generated already or is empty */
1441 if (wrbuf_len(norm_wr) == 0)
1443 wrbuf_printf(norm_wr, "position: %s-%d",
1444 client_get_id(cl), record_no);
1448 const char *lead = "content: ";
1449 wrbuf_insert(norm_wr, 0, lead, strlen(lead));
1451 if (wrbuf_len(norm_wr) > 0)
1452 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1453 wrbuf_destroy(norm_wr);
1454 return mergekey_norm;
1457 /** \brief see if metadata for pz:recordfilter exists
1458 \param root xml root element of normalized record
1459 \param sdb session database for client
1460 \retval 0 if there is no metadata for pz:recordfilter
1461 \retval 1 if there is metadata for pz:recordfilter
1463 If there is no pz:recordfilter defined, this function returns 1
1467 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1472 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1477 for (n = root->children; n; n = n->next)
1479 if (n->type != XML_ELEMENT_NODE)
1481 if (!strcmp((const char *) n->name, "metadata"))
1483 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1490 if ((eq = strchr(s, '=')))
1492 else if ((eq = strchr(s, '~')))
1498 if (len == strlen((const char *)type) &&
1499 !memcmp((const char *) type, s, len))
1501 xmlChar *value = xmlNodeGetContent(n);
1502 if (value && *value)
1505 (substring && strstr((const char *) value, eq+1)) ||
1506 (!substring && !strcmp((const char *) value, eq + 1)))
1519 static int ingest_to_cluster(struct client *cl,
1523 const char *mergekey_norm);
1525 /** \brief ingest XML record
1526 \param cl client holds the result set for record
1527 \param rec record buffer (0 terminated)
1528 \param record_no record position (1, 2, ..)
1529 \param nmem working NMEM
1534 int ingest_record(struct client *cl, const char *rec,
1535 int record_no, NMEM nmem)
1537 struct session *se = client_get_session(cl);
1539 struct session_database *sdb = client_get_database(cl);
1540 struct conf_service *service = se->service;
1541 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1543 const char *mergekey_norm;
1548 root = xmlDocGetRootElement(xdoc);
1550 if (!check_record_filter(root, sdb))
1552 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1553 record_no, sdb->database->id);
1558 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1561 session_log(se, YLOG_WARN, "Got no mergekey");
1566 if (client_get_session(cl) == se)
1567 ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1574 static int ingest_to_cluster(struct client *cl,
1578 const char *mergekey_norm)
1583 struct session *se = client_get_session(cl);
1584 struct conf_service *service = se->service;
1585 int term_factor = 1;
1586 struct record_cluster *cluster;
1587 struct session_database *sdb = client_get_database(cl);
1588 struct record *record = record_create(se->nmem,
1589 service->num_metadata,
1590 service->num_sortkeys, cl,
1593 for (n = root->children; n; n = n->next)
1601 if (n->type != XML_ELEMENT_NODE)
1603 if (!strcmp((const char *) n->name, "metadata"))
1605 struct conf_metadata *ser_md = 0;
1606 struct record_metadata **wheretoput = 0;
1607 struct record_metadata *rec_md = 0;
1608 int md_field_id = -1;
1610 type = xmlGetProp(n, (xmlChar *) "type");
1611 value = xmlNodeListGetString(xdoc, n->children, 1);
1613 if (!type || !value || !*value)
1617 = conf_service_metadata_field_id(service, (const char *) type);
1618 if (md_field_id < 0)
1620 if (se->number_of_warnings_unknown_metadata == 0)
1622 session_log(se, YLOG_WARN,
1623 "Ignoring unknown metadata element: %s", type);
1625 se->number_of_warnings_unknown_metadata++;
1629 ser_md = &service->metadata[md_field_id];
1631 // non-merged metadata
1632 rec_md = record_metadata_init(se->nmem, (const char *) value,
1633 ser_md->type, n->properties);
1636 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1637 "for element '%s'", value, type);
1640 wheretoput = &record->metadata[md_field_id];
1642 wheretoput = &(*wheretoput)->next;
1643 *wheretoput = rec_md;
1647 cluster = reclist_insert(se->reclist, service, record,
1648 mergekey_norm, &se->total_merged);
1653 const char *use_term_factor_str =
1654 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1655 if (use_term_factor_str && use_term_factor_str[0] == '1')
1657 int maxrecs = client_get_maxrecs(cl);
1658 int hits = (int) client_get_hits(cl);
1659 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1660 assert(term_factor >= 1);
1661 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1665 if (global_parameters.dump_records)
1666 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1667 sdb->database->id, record_no);
1670 relevance_newrec(se->relevance, cluster);
1672 // now parsing XML record and adding data to cluster or record metadata
1673 for (n = root->children; n; n = n->next)
1675 pp2_charset_token_t prt;
1682 if (n->type != XML_ELEMENT_NODE)
1684 if (!strcmp((const char *) n->name, "metadata"))
1686 struct conf_metadata *ser_md = 0;
1687 struct conf_sortkey *ser_sk = 0;
1688 struct record_metadata **wheretoput = 0;
1689 struct record_metadata *rec_md = 0;
1690 int md_field_id = -1;
1691 int sk_field_id = -1;
1693 type = xmlGetProp(n, (xmlChar *) "type");
1694 value = xmlNodeListGetString(xdoc, n->children, 1);
1696 if (!type || !value || !*value)
1700 = conf_service_metadata_field_id(service, (const char *) type);
1701 if (md_field_id < 0)
1704 ser_md = &service->metadata[md_field_id];
1706 if (ser_md->sortkey_offset >= 0)
1708 sk_field_id = ser_md->sortkey_offset;
1709 ser_sk = &service->sortkeys[sk_field_id];
1713 rec_md = record_metadata_init(se->nmem, (const char *) value,
1718 wheretoput = &cluster->metadata[md_field_id];
1720 // and polulate with data:
1721 // assign cluster or record based on merge action
1722 if (ser_md->merge == Metadata_merge_unique)
1726 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1727 rec_md->data.text.disp))
1729 wheretoput = &(*wheretoput)->next;
1732 *wheretoput = rec_md;
1734 else if (ser_md->merge == Metadata_merge_longest)
1737 || strlen(rec_md->data.text.disp)
1738 > strlen((*wheretoput)->data.text.disp))
1740 *wheretoput = rec_md;
1743 const char *sort_str = 0;
1745 ser_sk->type == Metadata_sortkey_skiparticle;
1747 if (!cluster->sortkeys[sk_field_id])
1748 cluster->sortkeys[sk_field_id] =
1749 nmem_malloc(se->nmem,
1750 sizeof(union data_types));
1753 pp2_charset_token_create(service->charsets, "sort");
1755 pp2_charset_token_first(prt, rec_md->data.text.disp,
1758 pp2_charset_token_next(prt);
1760 sort_str = pp2_get_sort(prt);
1762 cluster->sortkeys[sk_field_id]->text.disp =
1763 rec_md->data.text.disp;
1766 sort_str = rec_md->data.text.disp;
1767 session_log(se, YLOG_WARN,
1768 "Could not make sortkey. Bug #1858");
1770 cluster->sortkeys[sk_field_id]->text.sort =
1771 nmem_strdup(se->nmem, sort_str);
1772 pp2_charset_token_destroy(prt);
1776 else if (ser_md->merge == Metadata_merge_all)
1779 wheretoput = &(*wheretoput)->next;
1780 *wheretoput = rec_md;
1782 else if (ser_md->merge == Metadata_merge_range)
1786 *wheretoput = rec_md;
1788 cluster->sortkeys[sk_field_id]
1793 int this_min = rec_md->data.number.min;
1794 int this_max = rec_md->data.number.max;
1795 if (this_min < (*wheretoput)->data.number.min)
1796 (*wheretoput)->data.number.min = this_min;
1797 if (this_max > (*wheretoput)->data.number.max)
1798 (*wheretoput)->data.number.max = this_max;
1803 // ranking of _all_ fields enabled ...
1805 relevance_countwords(se->relevance, cluster,
1806 (char *) value, ser_md->rank,
1809 // construct facets ... unless the client already has reported them
1810 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1812 if (ser_md->type == Metadata_type_year)
1815 sprintf(year, "%d", rec_md->data.number.max);
1817 add_facet(se, (char *) type, year, term_factor);
1818 if (rec_md->data.number.max != rec_md->data.number.min)
1820 sprintf(year, "%d", rec_md->data.number.min);
1821 add_facet(se, (char *) type, year, term_factor);
1825 add_facet(se, (char *) type, (char *) value, term_factor);
1835 if (se->number_of_warnings_unknown_elements == 0)
1836 session_log(se, YLOG_WARN,
1837 "Unexpected element in internal record: %s", n->name);
1838 se->number_of_warnings_unknown_elements++;
1846 relevance_donerecord(se->relevance, cluster);
1847 se->total_records++;
1852 void session_log(struct session *s, int level, const char *fmt, ...)
1858 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1859 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1867 * c-file-style: "Stroustrup"
1868 * indent-tabs-mode: nil
1870 * vim: shiftwidth=4 tabstop=8 expandtab