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)
410 session_log(se, YLOG_WARN, "No settings on %s", sdb->database->id);
413 if ((s = session_setting_oneval(sdb, PZ_XSLT)))
415 char auto_stylesheet[256];
417 if (!strcmp(s, "auto"))
419 const char *request_syntax = session_setting_oneval(
420 sdb, PZ_REQUESTSYNTAX);
424 yaz_snprintf(auto_stylesheet, sizeof(auto_stylesheet),
425 "%s.xsl", request_syntax);
426 for (cp = auto_stylesheet; *cp; cp++)
428 /* deliberately only consider ASCII */
429 if (*cp > 32 && *cp < 127)
436 session_log(se, YLOG_WARN,
437 "No pz:requestsyntax for auto stylesheet");
440 sdb->map = normalize_cache_get(se->normalize_cache,
441 se->service->server->config, s);
448 // This analyzes settings and recomputes any supporting data structures
450 static int prepare_session_database(struct session *se,
451 struct session_database *sdb)
455 session_log(se, YLOG_WARN,
456 "No settings associated with %s", sdb->database->id);
459 if (sdb->settings[PZ_XSLT] && !sdb->map)
461 if (prepare_map(se, sdb) < 0)
467 // called if watch should be removed because http_channel is to be destroyed
468 static void session_watch_cancel(void *data, struct http_channel *c,
471 struct session_watchentry *ent = data;
478 // set watch. Returns 0=OK, -1 if watch is already set
479 int session_set_watch(struct session *s, int what,
480 session_watchfun fun, void *data,
481 struct http_channel *chan)
485 if (s->watchlist[what].fun)
490 s->watchlist[what].fun = fun;
491 s->watchlist[what].data = data;
492 s->watchlist[what].obs = http_add_observer(chan, &s->watchlist[what],
493 session_watch_cancel);
500 void session_alert_watch(struct session *s, int what)
504 if (s->watchlist[what].fun)
506 /* our watch is no longer associated with http_channel */
508 session_watchfun fun;
510 http_remove_observer(s->watchlist[what].obs);
511 fun = s->watchlist[what].fun;
512 data = s->watchlist[what].data;
514 /* reset watch before fun is invoked - in case fun wants to set
516 s->watchlist[what].fun = 0;
517 s->watchlist[what].data = 0;
518 s->watchlist[what].obs = 0;
521 session_log(s, YLOG_DEBUG,
522 "Alert Watch: %d calling function: %p", what, fun);
529 //callback for grep_databases
530 static void select_targets_callback(struct session *se,
531 struct session_database *db)
533 struct client *cl = client_create(db->database->id);
534 struct client_list *l;
536 client_set_database(cl, db);
538 client_set_session(cl, se);
540 l = xmalloc(sizeof(*l));
542 l->next = se->clients;
546 static void session_remove_clients(struct session *se)
548 struct client_list *l;
557 struct client_list *l_next = l->next;
558 client_lock(l->client);
559 client_set_session(l->client, 0);
560 client_set_database(l->client, 0);
561 client_unlock(l->client);
562 client_destroy(l->client);
568 // Associates a set of clients with a session;
569 // Note: Session-databases represent databases with per-session
571 static int select_targets(struct session *se, const char *filter)
573 return session_grep_databases(se, filter, select_targets_callback);
576 int session_active_clients(struct session *s)
578 struct client_list *l;
581 for (l = s->clients; l; l = l->next)
582 if (client_is_active(l->client))
588 int session_is_preferred_clients_ready(struct session *s)
590 struct client_list *l;
593 for (l = s->clients; l; l = l->next)
594 if (client_is_active_preferred(l->client))
596 session_log(s, YLOG_DEBUG, "Has %d active preferred clients.", res);
600 static const char *get_strategy_plus_sort(struct client *l, const char *field)
602 struct session_database *sdb = client_get_database(l);
605 const char *strategy_plus_sort = 0;
607 for (s = sdb->settings[PZ_SORTMAP]; s; s = s->next)
609 char *p = strchr(s->name + 3, ':');
612 yaz_log(YLOG_WARN, "Malformed sortmap name: %s", s->name);
616 if (!strcmp(p, field))
618 strategy_plus_sort = s->value;
622 return strategy_plus_sort;
625 void session_sort(struct session *se, const char *field, int increasing)
627 struct session_sorted_results *sr;
628 struct client_list *l;
632 /* see if we already have sorted for this critieria */
633 for (sr = se->sorted_results; sr; sr = sr->next)
635 if (!strcmp(field, sr->field) && increasing == sr->increasing)
640 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d already fetched",
645 yaz_log(YLOG_LOG, "search_sort: field=%s increasing=%d must fetch",
647 sr = nmem_malloc(se->nmem, sizeof(*sr));
648 sr->field = nmem_strdup(se->nmem, field);
649 sr->increasing = increasing;
650 sr->next = se->sorted_results;
651 se->sorted_results = sr;
653 for (l = se->clients; l; l = l->next)
655 struct client *cl = l->client;
656 const char *strategy_plus_sort = get_strategy_plus_sort(cl, field);
657 if (strategy_plus_sort)
660 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
661 se->service->z3950_session_timeout,
662 se->service->server->iochan_man,
664 client_start_search(cl, strategy_plus_sort, increasing);
670 enum pazpar2_error_code session_search(struct session *se,
672 const char *startrecs,
676 const char **addinfo,
677 const char *sort_field, int increasing)
679 int live_channels = 0;
682 struct client_list *l;
684 facet_limits_t facet_limits;
686 session_log(se, YLOG_DEBUG, "Search");
690 session_remove_clients(se);
693 reclist_destroy(se->reclist);
695 relevance_destroy(&se->relevance);
696 nmem_reset(se->nmem);
697 se->total_records = se->total_merged = 0;
698 se->num_termlists = 0;
700 /* reset list of sorted results and clear to relevance search */
701 se->sorted_results = nmem_malloc(se->nmem, sizeof(*se->sorted_results));
702 se->sorted_results->field = nmem_strdup(se->nmem, sort_field);
703 se->sorted_results->increasing = increasing;
704 se->sorted_results->next = 0;
706 live_channels = select_targets(se, filter);
710 return PAZPAR2_NO_TARGETS;
712 se->reclist = reclist_create(se->nmem);
714 yaz_gettimeofday(&tval);
718 facet_limits = facet_limits_create(limit);
723 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
725 for (l = se->clients; l; l = l->next)
727 struct client *cl = l->client;
728 const char *strategy_plus_sort = get_strategy_plus_sort(cl, sort_field);
731 client_set_maxrecs(cl, atoi(maxrecs));
733 client_set_startrecs(cl, atoi(startrecs));
734 if (prepare_session_database(se, client_get_database(cl)) < 0)
736 else if (client_parse_query(cl, query, facet_limits) < 0)
741 if (client_prep_connection(cl, se->service->z3950_operation_timeout,
742 se->service->z3950_session_timeout,
743 se->service->server->iochan_man,
745 client_start_search(cl, strategy_plus_sort, increasing);
748 facet_limits_destroy(facet_limits);
755 return PAZPAR2_MALFORMED_PARAMETER_VALUE;
758 return PAZPAR2_NO_TARGETS;
760 return PAZPAR2_NO_ERROR;
763 // Creates a new session_database object for a database
764 static void session_init_databases_fun(void *context, struct database *db)
766 struct session *se = (struct session *) context;
767 struct session_database *new = nmem_malloc(se->session_nmem, sizeof(*new));
773 assert(db->settings);
774 new->settings = nmem_malloc(se->session_nmem,
775 sizeof(struct settings *) * db->num_settings);
776 new->num_settings = db->num_settings;
777 for (i = 0; i < db->num_settings; i++)
779 struct setting *setting = db->settings[i];
780 new->settings[i] = setting;
782 new->next = se->databases;
786 // Doesn't free memory associated with sdb -- nmem takes care of that
787 static void session_database_destroy(struct session_database *sdb)
792 // Initialize session_database list -- this represents this session's view
793 // of the database list -- subject to modification by the settings ws command
794 void session_init_databases(struct session *se)
797 predef_grep_databases(se, se->service, session_init_databases_fun);
800 // Probably session_init_databases_fun should be refactored instead of
802 static struct session_database *load_session_database(struct session *se,
805 struct database *db = new_database(id, se->session_nmem);
807 session_init_databases_fun((void*) se, db);
809 // New sdb is head of se->databases list
810 return se->databases;
813 // Find an existing session database. If not found, load it
814 static struct session_database *find_session_database(struct session *se,
817 struct session_database *sdb;
819 for (sdb = se->databases; sdb; sdb = sdb->next)
820 if (!strcmp(sdb->database->id, id))
822 return load_session_database(se, id);
825 // Apply a session override to a database
826 void session_apply_setting(struct session *se, char *dbname, char *setting,
829 struct session_database *sdb = find_session_database(se, dbname);
830 struct conf_service *service = se->service;
831 struct setting *new = nmem_malloc(se->session_nmem, sizeof(*new));
832 int offset = settings_create_offset(service, setting);
834 expand_settings_array(&sdb->settings, &sdb->num_settings, offset,
837 new->target = dbname;
840 new->next = sdb->settings[offset];
841 sdb->settings[offset] = new;
843 // Force later recompute of settings-driven data structures
844 // (happens when a search starts and client connections are prepared)
856 void session_destroy(struct session *se) {
857 struct session_database *sdb;
858 session_log(se, YLOG_DEBUG, "Destroying");
860 session_remove_clients(se);
862 for (sdb = se->databases; sdb; sdb = sdb->next)
863 session_database_destroy(sdb);
864 normalize_cache_destroy(se->normalize_cache);
865 relevance_destroy(&se->relevance);
866 reclist_destroy(se->reclist);
867 nmem_destroy(se->nmem);
868 service_destroy(se->service);
869 yaz_mutex_destroy(&se->session_mutex);
872 /* Depreciated: use session_destroy */
873 void destroy_session(struct session *se)
878 size_t session_get_memory_status(struct session *session) {
882 session_enter(session);
883 session_nmem = nmem_total(session->nmem);
884 session_leave(session);
889 struct session *new_session(NMEM nmem, struct conf_service *service,
893 struct session *session = nmem_malloc(nmem, sizeof(*session));
897 sprintf(tmp_str, "session#%u", session_id);
899 session->session_id = session_id;
900 session_log(session, YLOG_DEBUG, "New");
901 session->service = service;
902 session->relevance = 0;
903 session->total_records = 0;
904 session->number_of_warnings_unknown_elements = 0;
905 session->number_of_warnings_unknown_metadata = 0;
906 session->num_termlists = 0;
907 session->reclist = 0;
908 session->clients = 0;
909 session->session_nmem = nmem;
910 session->nmem = nmem_create();
911 session->databases = 0;
912 for (i = 0; i <= SESSION_WATCH_MAX; i++)
914 session->watchlist[i].data = 0;
915 session->watchlist[i].fun = 0;
917 session->normalize_cache = normalize_cache_create();
918 session->session_mutex = 0;
919 pazpar2_mutex_create(&session->session_mutex, tmp_str);
924 static struct hitsbytarget *hitsbytarget_nb(struct session *se,
925 int *count, NMEM nmem)
927 struct hitsbytarget *res = 0;
928 struct client_list *l;
931 for (l = se->clients; l; l = l->next)
934 res = nmem_malloc(nmem, sizeof(*res) * sz);
936 for (l = se->clients; l; l = l->next)
938 struct client *cl = l->client;
939 WRBUF w = wrbuf_alloc();
940 const char *name = session_setting_oneval(client_get_database(cl),
943 res[*count].id = client_get_id(cl);
944 res[*count].name = *name ? name : "Unknown";
945 res[*count].hits = client_get_hits(cl);
946 res[*count].records = client_get_num_records(cl);
947 res[*count].diagnostic = client_get_diagnostic(cl);
948 res[*count].state = client_get_state_str(cl);
949 res[*count].connected = client_get_connection(cl) ? 1 : 0;
950 session_settings_dump(se, client_get_database(cl), w);
951 res[*count].settings_xml = nmem_strdup(nmem, wrbuf_cstr(w));
958 struct hitsbytarget *get_hitsbytarget(struct session *se, int *count, NMEM nmem)
960 struct hitsbytarget *p;
962 p = hitsbytarget_nb(se, count, nmem);
967 struct termlist_score **get_termlist_score(struct session *se,
968 const char *name, int *num)
971 struct termlist_score **tl = 0;
974 for (i = 0; i < se->num_termlists; i++)
975 if (!strcmp((const char *) se->termlists[i].name, name))
977 tl = termlist_highscore(se->termlists[i].termlist, num);
984 // Compares two hitsbytarget nodes by hitcount
985 static int cmp_ht(const void *p1, const void *p2)
987 const struct hitsbytarget *h1 = p1;
988 const struct hitsbytarget *h2 = p2;
989 return h2->hits - h1->hits;
992 static int targets_termlist_nb(WRBUF wrbuf, struct session *se, int num,
995 struct hitsbytarget *ht;
998 ht = hitsbytarget_nb(se, &count, nmem);
999 qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
1000 for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
1003 // do only print terms which have display names
1005 wrbuf_puts(wrbuf, "<term>\n");
1007 wrbuf_puts(wrbuf, "<id>");
1008 wrbuf_xmlputs(wrbuf, ht[i].id);
1009 wrbuf_puts(wrbuf, "</id>\n");
1011 wrbuf_puts(wrbuf, "<name>");
1012 if (!ht[i].name || !ht[i].name[0])
1013 wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
1015 wrbuf_xmlputs(wrbuf, ht[i].name);
1016 wrbuf_puts(wrbuf, "</name>\n");
1018 wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
1021 wrbuf_puts(wrbuf, "<state>");
1022 wrbuf_xmlputs(wrbuf, ht[i].state);
1023 wrbuf_puts(wrbuf, "</state>\n");
1025 wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n",
1027 wrbuf_puts(wrbuf, "</term>\n");
1032 void perform_termlist(struct http_channel *c, struct session *se,
1033 const char *name, int num)
1036 NMEM nmem_tmp = nmem_create();
1041 nmem_strsplit(nmem_tmp, ",", name, &names, &num_names);
1045 for (j = 0; j < num_names; j++)
1048 for (i = 0; i < se->num_termlists; i++)
1050 tname = se->termlists[i].name;
1051 if (num_names > 0 && !strcmp(names[j], tname))
1053 struct termlist_score **p = 0;
1055 p = termlist_highscore(se->termlists[i].termlist, &len);
1059 wrbuf_puts(c->wrbuf, "<list name=\"");
1060 wrbuf_xmlputs(c->wrbuf, tname);
1061 wrbuf_puts(c->wrbuf, "\">\n");
1062 for (i = 0; i < len && i < num; i++)
1064 // prevent sending empty term elements
1065 if (!p[i]->display_term || !p[i]->display_term[0])
1068 wrbuf_puts(c->wrbuf, "<term>");
1069 wrbuf_puts(c->wrbuf, "<name>");
1070 wrbuf_xmlputs(c->wrbuf, p[i]->display_term);
1071 wrbuf_puts(c->wrbuf, "</name>");
1073 wrbuf_printf(c->wrbuf,
1074 "<frequency>%d</frequency>",
1076 wrbuf_puts(c->wrbuf, "</term>\n");
1078 wrbuf_puts(c->wrbuf, "</list>\n");
1083 if (num_names > 0 && !strcmp(names[j], tname))
1085 wrbuf_puts(c->wrbuf, "<list name=\"");
1086 wrbuf_xmlputs(c->wrbuf, tname);
1087 wrbuf_puts(c->wrbuf, "\">\n");
1088 targets_termlist_nb(c->wrbuf, se, num, c->nmem);
1089 wrbuf_puts(c->wrbuf, "</list>\n");
1093 nmem_destroy(nmem_tmp);
1096 #ifdef MISSING_HEADERS
1097 void report_nmem_stats(void)
1099 size_t in_use, is_free;
1101 nmem_get_memory_in_use(&in_use);
1102 nmem_get_memory_free(&is_free);
1104 yaz_log(YLOG_LOG, "nmem stat: use=%ld free=%ld",
1105 (long) in_use, (long) is_free);
1109 struct record_cluster *show_single_start(struct session *se, const char *id,
1110 struct record_cluster **prev_r,
1111 struct record_cluster **next_r)
1113 struct record_cluster *r = 0;
1120 reclist_enter(se->reclist);
1121 while ((r = reclist_read_record(se->reclist)))
1123 if (!strcmp(r->recid, id))
1125 *next_r = reclist_read_record(se->reclist);
1130 reclist_leave(se->reclist);
1137 void show_single_stop(struct session *se, struct record_cluster *rec)
1142 struct record_cluster **show_range_start(struct session *se,
1143 struct reclist_sortparms *sp,
1144 int start, int *num, int *total, Odr_int *sumhits)
1146 struct record_cluster **recs;
1147 struct reclist_sortparms *spp;
1150 yaz_timing_t t = yaz_timing_create();
1153 recs = nmem_malloc(se->nmem, *num * sizeof(struct record_cluster *));
1163 struct client_list *l;
1165 for (spp = sp; spp; spp = spp->next)
1166 if (spp->type == Metadata_sortkey_relevance)
1168 relevance_prepare_read(se->relevance, se->reclist);
1171 reclist_sort(se->reclist, sp);
1173 reclist_enter(se->reclist);
1174 *total = reclist_get_num_records(se->reclist);
1177 for (l = se->clients; l; l = l->next)
1178 *sumhits += client_get_hits(l->client);
1180 for (i = 0; i < start; i++)
1181 if (!reclist_read_record(se->reclist))
1188 for (i = 0; i < *num; i++)
1190 struct record_cluster *r = reclist_read_record(se->reclist);
1198 reclist_leave(se->reclist);
1202 yaz_log(YLOG_LOG, "show %6.5f %3.2f %3.2f",
1203 yaz_timing_get_real(t), yaz_timing_get_user(t),
1204 yaz_timing_get_sys(t));
1205 yaz_timing_destroy(&t);
1210 void show_range_stop(struct session *se, struct record_cluster **recs)
1215 void statistics(struct session *se, struct statistics *stat)
1217 struct client_list *l;
1220 memset(stat, 0, sizeof(*stat));
1222 for (l = se->clients; l; l = l->next)
1224 struct client *cl = l->client;
1225 if (!client_get_connection(cl))
1226 stat->num_no_connection++;
1227 stat->num_hits += client_get_hits(cl);
1228 switch (client_get_state(cl))
1230 case Client_Connecting: stat->num_connecting++; break;
1231 case Client_Working: stat->num_working++; break;
1232 case Client_Idle: stat->num_idle++; break;
1233 case Client_Failed: stat->num_failed++; break;
1234 case Client_Error: stat->num_error++; break;
1239 stat->num_records = se->total_records;
1241 stat->num_clients = count;
1244 static struct record_metadata *record_metadata_init(
1245 NMEM nmem, const char *value, enum conf_metadata_type type,
1246 struct _xmlAttr *attr)
1248 struct record_metadata *rec_md = record_metadata_create(nmem);
1249 struct record_metadata_attr **attrp = &rec_md->attributes;
1251 for (; attr; attr = attr->next)
1253 if (attr->children && attr->children->content)
1255 if (strcmp((const char *) attr->name, "type"))
1256 { /* skip the "type" attribute.. Its value is already part of
1257 the element in output (md-%s) and so repeating it here
1259 *attrp = nmem_malloc(nmem, sizeof(**attrp));
1261 nmem_strdup(nmem, (const char *) attr->name);
1263 nmem_strdup(nmem, (const char *) attr->children->content);
1264 attrp = &(*attrp)->next;
1270 if (type == Metadata_type_generic)
1272 char *p = nmem_strdup(nmem, value);
1274 p = normalize7bit_generic(p, " ,/.:([");
1276 rec_md->data.text.disp = p;
1277 rec_md->data.text.sort = 0;
1279 else if (type == Metadata_type_year || type == Metadata_type_date)
1284 if (type == Metadata_type_date)
1286 if (extract7bit_dates((char *) value, &first, &last, longdate) < 0)
1289 rec_md->data.number.min = first;
1290 rec_md->data.number.max = last;
1297 static int get_mergekey_from_doc(xmlDoc *doc, xmlNode *root, const char *name,
1298 struct conf_service *service, WRBUF norm_wr)
1302 for (n = root->children; n; n = n->next)
1304 if (n->type != XML_ELEMENT_NODE)
1306 if (!strcmp((const char *) n->name, "metadata"))
1308 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1310 yaz_log(YLOG_FATAL, "Missing type attribute on metadata element. Skipping!");
1312 else if (!strcmp(name, (const char *) type))
1314 xmlChar *value = xmlNodeListGetString(doc, n->children, 1);
1317 const char *norm_str;
1318 pp2_charset_token_t prt =
1319 pp2_charset_token_create(service->charsets, "mergekey");
1321 pp2_charset_token_first(prt, (const char *) value, 0);
1322 if (wrbuf_len(norm_wr) > 0)
1323 wrbuf_puts(norm_wr, " ");
1324 wrbuf_puts(norm_wr, name);
1326 pp2_charset_token_next(prt)))
1330 wrbuf_puts(norm_wr, " ");
1331 wrbuf_puts(norm_wr, norm_str);
1335 pp2_charset_token_destroy(prt);
1345 static const char *get_mergekey(xmlDoc *doc, struct client *cl, int record_no,
1346 struct conf_service *service, NMEM nmem)
1348 char *mergekey_norm = 0;
1349 xmlNode *root = xmlDocGetRootElement(doc);
1350 WRBUF norm_wr = wrbuf_alloc();
1352 /* consider mergekey from XSL first */
1353 xmlChar *mergekey = xmlGetProp(root, (xmlChar *) "mergekey");
1356 const char *norm_str;
1357 pp2_charset_token_t prt =
1358 pp2_charset_token_create(service->charsets, "mergekey");
1360 pp2_charset_token_first(prt, (const char *) mergekey, 0);
1361 while ((norm_str = pp2_charset_token_next(prt)))
1365 if (wrbuf_len(norm_wr))
1366 wrbuf_puts(norm_wr, " ");
1367 wrbuf_puts(norm_wr, norm_str);
1370 pp2_charset_token_destroy(prt);
1375 /* no mergekey defined in XSL. Look for mergekey metadata instead */
1377 for (field_id = 0; field_id < service->num_metadata; field_id++)
1379 struct conf_metadata *ser_md = &service->metadata[field_id];
1380 if (ser_md->mergekey != Metadata_mergekey_no)
1382 int r = get_mergekey_from_doc(doc, root, ser_md->name,
1384 if (r == 0 && ser_md->mergekey == Metadata_mergekey_required)
1386 /* no mergekey on this one and it is required..
1387 Generate unique key instead */
1388 wrbuf_rewind(norm_wr);
1395 /* generate unique key if none is not generated already or is empty */
1396 if (wrbuf_len(norm_wr) == 0)
1398 wrbuf_printf(norm_wr, "%s-%d",
1399 client_get_id(cl), record_no);
1401 if (wrbuf_len(norm_wr) > 0)
1402 mergekey_norm = nmem_strdup(nmem, wrbuf_cstr(norm_wr));
1403 wrbuf_destroy(norm_wr);
1404 return mergekey_norm;
1407 /** \brief see if metadata for pz:recordfilter exists
1408 \param root xml root element of normalized record
1409 \param sdb session database for client
1410 \retval 0 if there is no metadata for pz:recordfilter
1411 \retval 1 if there is metadata for pz:recordfilter
1413 If there is no pz:recordfilter defined, this function returns 1
1417 static int check_record_filter(xmlNode *root, struct session_database *sdb)
1422 s = session_setting_oneval(sdb, PZ_RECORDFILTER);
1427 for (n = root->children; n; n = n->next)
1429 if (n->type != XML_ELEMENT_NODE)
1431 if (!strcmp((const char *) n->name, "metadata"))
1433 xmlChar *type = xmlGetProp(n, (xmlChar *) "type");
1440 if ((eq = strchr(s, '=')))
1442 else if ((eq = strchr(s, '~')))
1448 if (len == strlen((const char *)type) &&
1449 !memcmp((const char *) type, s, len))
1451 xmlChar *value = xmlNodeGetContent(n);
1452 if (value && *value)
1455 (substring && strstr((const char *) value, eq+1)) ||
1456 (!substring && !strcmp((const char *) value, eq + 1)))
1469 static int ingest_to_cluster(struct client *cl,
1473 const char *mergekey_norm);
1475 /** \brief ingest XML record
1476 \param cl client holds the result set for record
1477 \param rec record buffer (0 terminated)
1478 \param record_no record position (1, 2, ..)
1479 \param nmem working NMEM
1484 int ingest_record(struct client *cl, const char *rec,
1485 int record_no, NMEM nmem)
1487 struct session *se = client_get_session(cl);
1489 struct session_database *sdb = client_get_database(cl);
1490 struct conf_service *service = se->service;
1491 xmlDoc *xdoc = normalize_record(se, sdb, service, rec, nmem);
1493 const char *mergekey_norm;
1498 root = xmlDocGetRootElement(xdoc);
1500 if (!check_record_filter(root, sdb))
1502 session_log(se, YLOG_LOG, "Filtered out record no %d from %s",
1503 record_no, sdb->database->id);
1508 mergekey_norm = get_mergekey(xdoc, cl, record_no, service, nmem);
1511 session_log(se, YLOG_WARN, "Got no mergekey");
1516 if (client_get_session(cl) == se)
1517 ingest_to_cluster(cl, xdoc, root, record_no, mergekey_norm);
1524 static int ingest_to_cluster(struct client *cl,
1528 const char *mergekey_norm)
1533 struct session *se = client_get_session(cl);
1534 struct conf_service *service = se->service;
1535 int term_factor = 1;
1536 struct record_cluster *cluster;
1537 struct session_database *sdb = client_get_database(cl);
1538 struct record *record = record_create(se->nmem,
1539 service->num_metadata,
1540 service->num_sortkeys, cl,
1543 for (n = root->children; n; n = n->next)
1551 if (n->type != XML_ELEMENT_NODE)
1553 if (!strcmp((const char *) n->name, "metadata"))
1555 struct conf_metadata *ser_md = 0;
1556 struct record_metadata **wheretoput = 0;
1557 struct record_metadata *rec_md = 0;
1558 int md_field_id = -1;
1560 type = xmlGetProp(n, (xmlChar *) "type");
1561 value = xmlNodeListGetString(xdoc, n->children, 1);
1563 if (!type || !value || !*value)
1567 = conf_service_metadata_field_id(service, (const char *) type);
1568 if (md_field_id < 0)
1570 if (se->number_of_warnings_unknown_metadata == 0)
1572 session_log(se, YLOG_WARN,
1573 "Ignoring unknown metadata element: %s", type);
1575 se->number_of_warnings_unknown_metadata++;
1579 ser_md = &service->metadata[md_field_id];
1581 // non-merged metadata
1582 rec_md = record_metadata_init(se->nmem, (const char *) value,
1583 ser_md->type, n->properties);
1586 session_log(se, YLOG_WARN, "bad metadata data '%s' "
1587 "for element '%s'", value, type);
1590 wheretoput = &record->metadata[md_field_id];
1592 wheretoput = &(*wheretoput)->next;
1593 *wheretoput = rec_md;
1597 cluster = reclist_insert(se->reclist, service, record,
1598 mergekey_norm, &se->total_merged);
1603 const char *use_term_factor_str =
1604 session_setting_oneval(sdb, PZ_TERMLIST_TERM_FACTOR);
1605 if (use_term_factor_str && use_term_factor_str[0] == '1')
1607 int maxrecs = client_get_maxrecs(cl);
1608 int hits = (int) client_get_hits(cl);
1609 term_factor = MAX(hits, maxrecs) / MAX(1, maxrecs);
1610 assert(term_factor >= 1);
1611 yaz_log(YLOG_DEBUG, "Using term factor: %d (%d / %d)", term_factor, MAX(hits, maxrecs), MAX(1, maxrecs));
1615 if (global_parameters.dump_records)
1616 session_log(se, YLOG_LOG, "Cluster id %s from %s (#%d)", cluster->recid,
1617 sdb->database->id, record_no);
1620 relevance_newrec(se->relevance, cluster);
1622 // now parsing XML record and adding data to cluster or record metadata
1623 for (n = root->children; n; n = n->next)
1625 pp2_charset_token_t prt;
1632 if (n->type != XML_ELEMENT_NODE)
1634 if (!strcmp((const char *) n->name, "metadata"))
1636 struct conf_metadata *ser_md = 0;
1637 struct conf_sortkey *ser_sk = 0;
1638 struct record_metadata **wheretoput = 0;
1639 struct record_metadata *rec_md = 0;
1640 int md_field_id = -1;
1641 int sk_field_id = -1;
1643 type = xmlGetProp(n, (xmlChar *) "type");
1644 value = xmlNodeListGetString(xdoc, n->children, 1);
1646 if (!type || !value || !*value)
1650 = conf_service_metadata_field_id(service, (const char *) type);
1651 if (md_field_id < 0)
1654 ser_md = &service->metadata[md_field_id];
1656 if (ser_md->sortkey_offset >= 0)
1658 sk_field_id = ser_md->sortkey_offset;
1659 ser_sk = &service->sortkeys[sk_field_id];
1663 rec_md = record_metadata_init(se->nmem, (const char *) value,
1665 wheretoput = &cluster->metadata[md_field_id];
1667 // and polulate with data:
1668 // assign cluster or record based on merge action
1669 if (ser_md->merge == Metadata_merge_unique)
1673 if (!strcmp((const char *) (*wheretoput)->data.text.disp,
1674 rec_md->data.text.disp))
1676 wheretoput = &(*wheretoput)->next;
1679 *wheretoput = rec_md;
1681 else if (ser_md->merge == Metadata_merge_longest)
1684 || strlen(rec_md->data.text.disp)
1685 > strlen((*wheretoput)->data.text.disp))
1687 *wheretoput = rec_md;
1690 const char *sort_str = 0;
1692 ser_sk->type == Metadata_sortkey_skiparticle;
1694 if (!cluster->sortkeys[sk_field_id])
1695 cluster->sortkeys[sk_field_id] =
1696 nmem_malloc(se->nmem,
1697 sizeof(union data_types));
1700 pp2_charset_token_create(service->charsets, "sort");
1702 pp2_charset_token_first(prt, rec_md->data.text.disp,
1705 pp2_charset_token_next(prt);
1707 sort_str = pp2_get_sort(prt);
1709 cluster->sortkeys[sk_field_id]->text.disp =
1710 rec_md->data.text.disp;
1713 sort_str = rec_md->data.text.disp;
1714 session_log(se, YLOG_WARN,
1715 "Could not make sortkey. Bug #1858");
1717 cluster->sortkeys[sk_field_id]->text.sort =
1718 nmem_strdup(se->nmem, sort_str);
1719 pp2_charset_token_destroy(prt);
1723 else if (ser_md->merge == Metadata_merge_all)
1726 wheretoput = &(*wheretoput)->next;
1727 *wheretoput = rec_md;
1729 else if (ser_md->merge == Metadata_merge_range)
1733 *wheretoput = rec_md;
1735 cluster->sortkeys[sk_field_id]
1740 int this_min = rec_md->data.number.min;
1741 int this_max = rec_md->data.number.max;
1742 if (this_min < (*wheretoput)->data.number.min)
1743 (*wheretoput)->data.number.min = this_min;
1744 if (this_max > (*wheretoput)->data.number.max)
1745 (*wheretoput)->data.number.max = this_max;
1750 // ranking of _all_ fields enabled ...
1752 relevance_countwords(se->relevance, cluster,
1753 (char *) value, ser_md->rank,
1756 // construct facets ... unless the client already has reported them
1757 if (ser_md->termlist && !client_has_facet(cl, (char *) type))
1759 if (ser_md->type == Metadata_type_year)
1762 sprintf(year, "%d", rec_md->data.number.max);
1764 add_facet(se, (char *) type, year, term_factor);
1765 if (rec_md->data.number.max != rec_md->data.number.min)
1767 sprintf(year, "%d", rec_md->data.number.min);
1768 add_facet(se, (char *) type, year, term_factor);
1772 add_facet(se, (char *) type, (char *) value, term_factor);
1782 if (se->number_of_warnings_unknown_elements == 0)
1783 session_log(se, YLOG_WARN,
1784 "Unexpected element in internal record: %s", n->name);
1785 se->number_of_warnings_unknown_elements++;
1793 relevance_donerecord(se->relevance, cluster);
1794 se->total_records++;
1799 void session_log(struct session *s, int level, const char *fmt, ...)
1805 yaz_vsnprintf(buf, sizeof(buf)-30, fmt, ap);
1806 yaz_log(level, "Session (%u): %s", s->session_id, buf);
1814 * c-file-style: "Stroustrup"
1815 * indent-tabs-mode: nil
1817 * vim: shiftwidth=4 tabstop=8 expandtab