1 /* This file is part of Metaproxy.
2 Copyright (C) Index Data
4 Metaproxy 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 Metaproxy 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
19 #include <metaproxy/package.hpp>
20 #include <metaproxy/util.hpp>
23 #include <yaz/diagbib1.h>
24 #include <yaz/match_glob.h>
25 #include <boost/scoped_ptr.hpp>
26 #include <boost/thread/mutex.hpp>
27 #include <boost/thread/condition.hpp>
32 namespace mp = metaproxy_1;
33 namespace yf = mp::filter;
35 namespace metaproxy_1 {
37 class SPARQL : public Base {
44 typedef boost::shared_ptr<Session> SessionPtr;
45 typedef boost::shared_ptr<Conf> ConfPtr;
47 typedef boost::shared_ptr<FrontendSet> FrontendSetPtr;
48 typedef std::map<std::string,FrontendSetPtr> FrontendSets;
52 void process(metaproxy_1::Package & package) const;
53 void configure(const xmlNode * ptr, bool test_only,
55 SessionPtr get_session(Package &package, Z_APDU **apdu) const;
56 void release_session(Package &package) const;
57 boost::scoped_ptr<Rep> m_p;
58 std::list<ConfPtr> db_conf;
70 boost::condition m_cond_session_ready;
72 std::map<mp::Session,SessionPtr> m_clients;
74 class SPARQL::Result {
79 friend class FrontendSet;
84 class SPARQL::FrontendSet {
89 std::list<Result> results;
91 class SPARQL::Session {
93 Session(const SPARQL *);
95 void handle_z(Package &package, Z_APDU *apdu);
96 Z_APDU *search(mp::Package &package,
99 const char *sparql_query,
100 ConfPtr conf, FrontendSetPtr fset);
101 int invoke_sparql(mp::Package &package,
102 const char *sparql_query,
109 ODR odr, Odr_oid *preferredRecordSyntax,
110 Z_ElementSetNames *esn,
111 int start, int number, int &error_code, std::string &addinfo,
112 int *number_returned, int *next_position);
115 bool m_support_named_result_sets;
116 FrontendSets m_frontend_sets;
117 const SPARQL *m_sparql;
122 yf::SPARQL::Result::~Result()
128 yf::SPARQL::Result::Result()
133 yf::SPARQL::SPARQL() : m_p(new Rep)
137 yf::SPARQL::~SPARQL()
141 void yf::SPARQL::configure(const xmlNode *xmlnode, bool test_only,
144 const xmlNode *ptr = xmlnode->children;
147 for (; ptr; ptr = ptr->next)
149 if (ptr->type != XML_ELEMENT_NODE)
151 if (!strcmp((const char *) ptr->name, "defaults"))
153 const struct _xmlAttr *attr;
154 for (attr = ptr->properties; attr; attr = attr->next)
156 if (!strcmp((const char *) attr->name, "uri"))
157 uri = mp::xml::get_text(attr->children);
159 throw mp::filter::FilterException(
160 "Bad attribute " + std::string((const char *)
164 else if (!strcmp((const char *) ptr->name, "db"))
166 yaz_sparql_t s = yaz_sparql_create();
167 ConfPtr conf(new Conf);
171 const struct _xmlAttr *attr;
172 for (attr = ptr->properties; attr; attr = attr->next)
174 if (!strcmp((const char *) attr->name, "path"))
175 conf->db = mp::xml::get_text(attr->children);
176 else if (!strcmp((const char *) attr->name, "uri"))
177 conf->uri = mp::xml::get_text(attr->children);
178 else if (!strcmp((const char *) attr->name, "schema"))
179 conf->schema = mp::xml::get_text(attr->children);
180 else if (!strcmp((const char *) attr->name, "include"))
182 std::string name = mp::xml::get_text(attr->children);
183 std::list<ConfPtr>::const_iterator it = db_conf.begin();
185 if (it == db_conf.end())
187 throw mp::filter::FilterException(
188 "include db not found: " + name);
190 else if (name.compare((*it)->db) == 0)
192 yaz_sparql_include(s, (*it)->s);
199 throw mp::filter::FilterException(
200 "Bad attribute " + std::string((const char *)
203 xmlNode *p = ptr->children;
204 for (; p; p = p->next)
206 if (p->type != XML_ELEMENT_NODE)
208 std::string name = (const char *) p->name;
209 const struct _xmlAttr *attr;
210 for (attr = p->properties; attr; attr = attr->next)
212 if (!strcmp((const char *) attr->name, "type"))
215 name.append(mp::xml::get_text(attr->children));
218 throw mp::filter::FilterException(
219 "Bad attribute " + std::string((const char *)
222 std::string value = mp::xml::get_text(p);
223 if (yaz_sparql_add_pattern(s, name.c_str(), value.c_str()))
225 throw mp::filter::FilterException(
226 "Bad SPARQL config " + name);
229 if (!conf->uri.length())
231 throw mp::filter::FilterException("Missing uri");
233 if (!conf->db.length())
235 throw mp::filter::FilterException("Missing path");
237 db_conf.push_back(conf);
241 throw mp::filter::FilterException
243 + std::string((const char *) ptr->name)
244 + " in sparql filter");
249 yf::SPARQL::Conf::~Conf()
251 yaz_sparql_destroy(s);
254 yf::SPARQL::Session::Session(const SPARQL *sparql) :
256 m_support_named_result_sets(false),
261 yf::SPARQL::Session::~Session()
265 yf::SPARQL::SessionPtr yf::SPARQL::get_session(Package & package,
270 Z_GDU *gdu = package.request().get();
272 boost::mutex::scoped_lock lock(m_p->m_mutex);
274 std::map<mp::Session,SPARQL::SessionPtr>::iterator it;
276 if (gdu && gdu->which == Z_GDU_Z3950)
277 *apdu = gdu->u.z3950;
283 it = m_p->m_clients.find(package.session());
284 if (it == m_p->m_clients.end())
286 if (!it->second->m_in_use)
288 it->second->m_in_use = true;
291 m_p->m_cond_session_ready.wait(lock);
296 // new Z39.50 session ..
297 SessionPtr p(new Session(this));
298 m_p->m_clients[package.session()] = p;
302 void yf::SPARQL::release_session(Package &package) const
304 boost::mutex::scoped_lock lock(m_p->m_mutex);
305 std::map<mp::Session,SessionPtr>::iterator it;
307 it = m_p->m_clients.find(package.session());
308 if (it != m_p->m_clients.end())
310 it->second->m_in_use = false;
312 if (package.session().is_closed())
313 m_p->m_clients.erase(it);
314 m_p->m_cond_session_ready.notify_all();
318 static bool get_result(xmlDoc *doc, Odr_int *sz, Odr_int pos, xmlDoc **ndoc)
320 xmlNode *ptr = xmlDocGetRootElement(doc);
325 *ndoc = xmlNewDoc(BAD_CAST "1.0");
327 if (ptr->type == XML_ELEMENT_NODE &&
328 !strcmp((const char *) ptr->name, "RDF"))
332 q0 = xmlCopyNode(ptr, 2);
333 xmlDocSetRootElement(*ndoc, q0);
337 while (ptr && ptr->type != XML_ELEMENT_NODE)
339 if (ptr && ptr->type == XML_ELEMENT_NODE &&
340 !strcmp((const char *) ptr->name, "Description"))
342 xmlNode *p = ptr->children;
344 while (p && p->type != XML_ELEMENT_NODE)
346 if (p && p->type == XML_ELEMENT_NODE &&
347 !strcmp((const char *) p->name, "type"))
348 { /* SELECT RESULT */
349 for (ptr = ptr->children; ptr; ptr = ptr->next)
350 if (ptr->type == XML_ELEMENT_NODE &&
351 !strcmp((const char *) ptr->name, "solution"))
357 xmlNode *q1 = xmlCopyNode(ptr, 1);
365 { /* CONSTRUCT result */
366 for (; ptr; ptr = ptr->next)
367 if (ptr->type == XML_ELEMENT_NODE &&
368 !strcmp((const char *) ptr->name, "Description"))
374 xmlNode *q1 = xmlCopyNode(ptr, 1);
385 for (; ptr; ptr = ptr->next)
386 if (ptr->type == XML_ELEMENT_NODE &&
387 !strcmp((const char *) ptr->name, "sparql"))
393 q0 = xmlCopyNode(ptr, 2);
394 xmlDocSetRootElement(*ndoc, q0);
396 for (ptr = ptr->children; ptr; ptr = ptr->next)
397 if (ptr->type == XML_ELEMENT_NODE &&
398 !strcmp((const char *) ptr->name, "results"))
406 q1 = xmlCopyNode(ptr, 0);
409 for (ptr = ptr->children; ptr; ptr = ptr->next)
410 if (ptr->type == XML_ELEMENT_NODE &&
411 !strcmp((const char *) ptr->name, "result"))
417 xmlNode *q2 = xmlCopyNode(ptr, 1);
430 Z_Records *yf::SPARQL::Session::fetch(
433 ODR odr, Odr_oid *preferredRecordSyntax,
434 Z_ElementSetNames *esn,
435 int start, int number, int &error_code, std::string &addinfo,
436 int *number_returned, int *next_position)
438 Z_Records *rec = (Z_Records *) odr_malloc(odr, sizeof(Z_Records));
439 std::list<Result>::iterator it = fset->results.begin();
440 const char *schema = 0;
441 bool uri_lookup = false;
442 if (esn && esn->which == Z_ElementSetNames_generic)
443 schema = esn->u.generic;
445 for (; it != fset->results.end(); it++)
447 if (yaz_sparql_lookup_schema(it->conf->s, schema))
452 if (!schema || !strcmp(esn->u.generic, it->conf->schema.c_str()))
455 if (it == fset->results.end())
457 rec->which = Z_Records_NSD;
458 rec->u.nonSurrogateDiagnostic =
459 zget_DefaultDiagFormat(
461 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
465 rec->which = Z_Records_DBOSD;
466 rec->u.databaseOrSurDiagnostics = (Z_NamePlusRecordList *)
467 odr_malloc(odr, sizeof(Z_NamePlusRecordList));
468 rec->u.databaseOrSurDiagnostics->records = (Z_NamePlusRecord **)
469 odr_malloc(odr, sizeof(Z_NamePlusRecord *) * number);
471 for (i = 0; i < number; i++)
473 rec->u.databaseOrSurDiagnostics->records[i] = (Z_NamePlusRecord *)
474 odr_malloc(odr, sizeof(Z_NamePlusRecord));
475 Z_NamePlusRecord *npr = rec->u.databaseOrSurDiagnostics->records[i];
476 npr->databaseName = odr_strdup(odr, fset->db.c_str());
477 npr->which = Z_NamePlusRecord_databaseRecord;
480 if (!get_result(it->doc, 0, start - 1 + i, &ndoc))
486 xmlNode *ndoc_root = xmlDocGetRootElement(ndoc);
495 xmlNode *n = ndoc_root;
498 if (n->type == XML_ELEMENT_NODE)
500 if (!strcmp((const char *) n->name, "uri"))
502 uri = mp::xml::get_text(n->children);
512 rec->which = Z_Records_NSD;
513 rec->u.nonSurrogateDiagnostic =
514 zget_DefaultDiagFormat(
516 YAZ_BIB1_SYSTEM_ERROR_IN_PRESENTING_RECORDS, 0);
522 mp::wrbuf addinfo, query, w;
523 int error = yaz_sparql_from_uri_wrbuf(it->conf->s,
525 uri.c_str(), schema);
528 yaz_log(YLOG_LOG, "query=%s", query.c_str());
529 error = invoke_sparql(package, query.c_str(),
534 rec->which = Z_Records_NSD;
535 rec->u.nonSurrogateDiagnostic =
536 zget_DefaultDiagFormat(
539 addinfo.len() ? addinfo.c_str() : 0);
543 npr->u.databaseRecord =
544 z_ext_record_xml(odr, w.c_str(), w.len());
549 xmlBufferPtr buf = xmlBufferCreate();
550 xmlNodeDump(buf, ndoc, ndoc_root, 0, 0);
551 yaz_log(YLOG_LOG, "record %s %.*s", uri_lookup ? "uri" : "normal",
552 (int) buf->use, (const char *) buf->content);
553 npr->u.databaseRecord =
554 z_ext_record_xml(odr, (const char *) buf->content, buf->use);
559 rec->u.databaseOrSurDiagnostics->num_records = i;
560 *number_returned = i;
561 if (start + number > fset->hits)
564 *next_position = start + number;
568 int yf::SPARQL::Session::invoke_sparql(mp::Package &package,
569 const char *sparql_query,
573 Package http_package(package.session(), package.origin());
576 http_package.copy_filter(package);
577 Z_GDU *gdu = z_get_HTTP_Request_uri(odr, conf->uri.c_str(), 0, 1);
579 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
580 "Content-Type", "application/x-www-form-urlencoded");
581 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
582 "Accept", "application/sparql-results+xml,"
583 "application/rdf+xml");
584 const char *names[2];
587 const char *values[1];
588 values[0] = sparql_query;
590 yaz_array_to_uri(&path, odr, (char **) names, (char **) values);
592 gdu->u.HTTP_Request->content_buf = path;
593 gdu->u.HTTP_Request->content_len = strlen(path);
595 yaz_log(YLOG_LOG, "sparql: HTTP request\n%s", sparql_query);
597 http_package.request() = gdu;
600 Z_GDU *gdu_resp = http_package.response().get();
602 if (!gdu_resp || gdu_resp->which != Z_GDU_HTTP_Response)
604 wrbuf_puts(w, "no HTTP response from backend");
605 return YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
607 else if (gdu_resp->u.HTTP_Response->code != 200)
609 wrbuf_printf(w, "sparql: HTTP error %d from backend",
610 gdu_resp->u.HTTP_Response->code);
611 return YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
613 Z_HTTP_Response *resp = gdu_resp->u.HTTP_Response;
614 wrbuf_write(w, resp->content_buf, resp->content_len);
618 Z_APDU *yf::SPARQL::Session::search(mp::Package &package,
621 const char *sparql_query,
622 ConfPtr conf, FrontendSetPtr fset)
624 Z_SearchRequest *req = apdu_req->u.searchRequest;
625 Z_APDU *apdu_res = 0;
628 int error = invoke_sparql(package, sparql_query, conf, w);
631 apdu_res = odr.create_searchResponse(apdu_req, error,
637 xmlDocPtr doc = xmlParseMemory(w.c_str(), w.len());
640 apdu_res = odr.create_searchResponse(
642 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
643 "invalid XML from backendbackend");
648 Z_Records *records = 0;
649 int number_returned = 0;
650 int next_position = 0;
656 fset->results.push_back(result);
657 yaz_log(YLOG_LOG, "saving sparql result xmldoc=%p", doc);
659 get_result(result.doc, &fset->hits, -1, 0);
660 m_frontend_sets[req->resultSetName] = fset;
665 const char *element_set_name = 0;
666 mp::util::piggyback_sr(req, fset->hits, number, &element_set_name);
669 Z_ElementSetNames *esn;
671 if (number > *req->smallSetUpperBound)
672 esn = req->mediumSetElementSetNames;
674 esn = req->smallSetElementSetNames;
675 records = fetch(package, fset,
676 odr, req->preferredRecordSyntax, esn,
685 odr.create_searchResponse(
686 apdu_req, error_code, addinfo.c_str());
691 odr.create_searchResponse(apdu_req, 0, 0);
692 Z_SearchResponse *resp = apdu_res->u.searchResponse;
693 *resp->resultCount = fset->hits;
694 *resp->numberOfRecordsReturned = number_returned;
695 *resp->nextResultSetPosition = next_position;
696 resp->records = records;
703 void yf::SPARQL::Session::handle_z(mp::Package &package, Z_APDU *apdu_req)
706 Z_APDU *apdu_res = 0;
707 if (apdu_req->which == Z_APDU_initRequest)
709 apdu_res = odr.create_initResponse(apdu_req, 0, 0);
710 Z_InitRequest *req = apdu_req->u.initRequest;
711 Z_InitResponse *resp = apdu_res->u.initResponse;
713 resp->implementationName = odr_strdup(odr, "sparql");
714 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
715 m_support_named_result_sets = true;
717 static const int masks[] = {
718 Z_Options_search, Z_Options_present,
719 Z_Options_namedResultSets, -1
721 for (i = 0; masks[i] != -1; i++)
722 if (ODR_MASK_GET(req->options, masks[i]))
723 ODR_MASK_SET(resp->options, masks[i]);
724 static const int versions[] = {
730 for (i = 0; versions[i] != -1; i++)
731 if (ODR_MASK_GET(req->protocolVersion, versions[i]))
732 ODR_MASK_SET(resp->protocolVersion, versions[i]);
735 *resp->preferredMessageSize = *req->preferredMessageSize;
736 *resp->maximumRecordSize = *req->maximumRecordSize;
738 else if (apdu_req->which == Z_APDU_close)
740 apdu_res = odr.create_close(apdu_req,
741 Z_Close_finished, 0);
742 package.session().close();
744 else if (apdu_req->which == Z_APDU_searchRequest)
746 Z_SearchRequest *req = apdu_req->u.searchRequest;
748 FrontendSets::iterator fset_it =
749 m_frontend_sets.find(req->resultSetName);
750 if (fset_it != m_frontend_sets.end())
752 // result set already exist
753 // if replace indicator is off: we return diagnostic if
754 // result set already exist.
755 if (*req->replaceIndicator == 0)
758 odr.create_searchResponse(
760 YAZ_BIB1_RESULT_SET_EXISTS_AND_REPLACE_INDICATOR_OFF,
762 package.response() = apdu;
764 m_frontend_sets.erase(fset_it);
766 if (req->query->which != Z_Query_type_1)
768 apdu_res = odr.create_searchResponse(
769 apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
771 else if (req->num_databaseNames != 1)
773 apdu_res = odr.create_searchResponse(
775 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, 0);
779 std::string db = req->databaseNames[0];
780 std::list<ConfPtr>::const_iterator it;
781 FrontendSetPtr fset(new FrontendSet);
783 m_frontend_sets.erase(req->resultSetName);
785 it = m_sparql->db_conf.begin();
786 for (; it != m_sparql->db_conf.end(); it++)
787 if ((*it)->schema.length() > 0
788 && yaz_match_glob((*it)->db.c_str(), db.c_str()))
790 mp::wrbuf addinfo_wr;
793 yaz_sparql_from_rpn_wrbuf((*it)->s,
794 addinfo_wr, sparql_wr,
795 req->query->u.type_1);
798 apdu_res = odr.create_searchResponse(
800 addinfo_wr.len() ? addinfo_wr.c_str() : 0);
804 Z_APDU *apdu_1 = search(package, apdu_req, odr,
805 sparql_wr.c_str(), *it,
813 apdu_res = odr.create_searchResponse(
814 apdu_req, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db.c_str());
818 else if (apdu_req->which == Z_APDU_presentRequest)
820 Z_PresentRequest *req = apdu_req->u.presentRequest;
821 FrontendSets::iterator fset_it =
822 m_frontend_sets.find(req->resultSetId);
823 if (fset_it == m_frontend_sets.end())
826 odr.create_presentResponse(
827 apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
829 package.response() = apdu_res;
832 int number_returned = 0;
833 int next_position = 0;
836 Z_ElementSetNames *esn = 0;
837 if (req->recordComposition)
839 if (req->recordComposition->which == Z_RecordComp_simple)
840 esn = req->recordComposition->u.simple;
844 odr.create_presentResponse(
846 YAZ_BIB1_ONLY_A_SINGLE_ELEMENT_SET_NAME_SUPPORTED,
848 package.response() = apdu_res;
852 Z_Records *records = fetch(
855 odr, req->preferredRecordSyntax, esn,
856 *req->resultSetStartPoint, *req->numberOfRecordsRequested,
863 odr.create_presentResponse(apdu_req, error_code,
869 odr.create_presentResponse(apdu_req, 0, 0);
870 Z_PresentResponse *resp = apdu_res->u.presentResponse;
871 resp->records = records;
872 *resp->numberOfRecordsReturned = number_returned;
873 *resp->nextResultSetPosition = next_position;
878 apdu_res = odr.create_close(apdu_req,
879 Z_Close_protocolError,
880 "sparql: unhandled APDU");
881 package.session().close();
885 package.response() = apdu_res;
888 void yf::SPARQL::process(mp::Package &package) const
891 SessionPtr p = get_session(package, &apdu);
894 p->handle_z(package, apdu);
898 release_session(package);
901 static mp::filter::Base* filter_creator()
903 return new mp::filter::SPARQL;
907 struct metaproxy_1_filter_struct metaproxy_1_filter_sparql = {
918 * c-file-style: "Stroustrup"
919 * indent-tabs-mode: nil
921 * vim: shiftwidth=4 tabstop=8 expandtab