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 *run_sparql(mp::Package &package,
99 const char *sparql_query,
100 ConfPtr conf, FrontendSetPtr fset);
103 ODR odr, Odr_oid *preferredRecordSyntax,
104 Z_ElementSetNames *esn,
105 int start, int number, int &error_code, std::string &addinfo,
106 int *number_returned, int *next_position);
109 bool m_support_named_result_sets;
110 FrontendSets m_frontend_sets;
111 const SPARQL *m_sparql;
116 yf::SPARQL::Result::~Result()
122 yf::SPARQL::Result::Result()
127 yf::SPARQL::SPARQL() : m_p(new Rep)
131 yf::SPARQL::~SPARQL()
135 void yf::SPARQL::configure(const xmlNode *xmlnode, bool test_only,
138 const xmlNode *ptr = xmlnode->children;
141 for (; ptr; ptr = ptr->next)
143 if (ptr->type != XML_ELEMENT_NODE)
145 if (!strcmp((const char *) ptr->name, "defaults"))
147 const struct _xmlAttr *attr;
148 for (attr = ptr->properties; attr; attr = attr->next)
150 if (!strcmp((const char *) attr->name, "uri"))
151 uri = mp::xml::get_text(attr->children);
153 throw mp::filter::FilterException(
154 "Bad attribute " + std::string((const char *)
158 else if (!strcmp((const char *) ptr->name, "db"))
160 yaz_sparql_t s = yaz_sparql_create();
161 ConfPtr conf(new Conf);
165 const struct _xmlAttr *attr;
166 for (attr = ptr->properties; attr; attr = attr->next)
168 if (!strcmp((const char *) attr->name, "path"))
169 conf->db = mp::xml::get_text(attr->children);
170 else if (!strcmp((const char *) attr->name, "uri"))
171 conf->uri = mp::xml::get_text(attr->children);
172 else if (!strcmp((const char *) attr->name, "schema"))
173 conf->schema = mp::xml::get_text(attr->children);
175 throw mp::filter::FilterException(
176 "Bad attribute " + std::string((const char *)
179 xmlNode *p = ptr->children;
180 for (; p; p = p->next)
182 if (p->type != XML_ELEMENT_NODE)
184 std::string name = (const char *) p->name;
185 const struct _xmlAttr *attr;
186 for (attr = p->properties; attr; attr = attr->next)
188 if (!strcmp((const char *) attr->name, "type"))
191 name.append(mp::xml::get_text(attr->children));
194 throw mp::filter::FilterException(
195 "Bad attribute " + std::string((const char *)
198 std::string value = mp::xml::get_text(p);
199 if (yaz_sparql_add_pattern(s, name.c_str(), value.c_str()))
201 throw mp::filter::FilterException(
202 "Bad SPARQL config " + name);
205 if (!conf->uri.length())
207 throw mp::filter::FilterException("Missing uri");
209 if (!conf->db.length())
211 throw mp::filter::FilterException("Missing path");
213 db_conf.push_back(conf);
217 throw mp::filter::FilterException
219 + std::string((const char *) ptr->name)
220 + " in sparql filter");
225 yf::SPARQL::Conf::~Conf()
227 yaz_sparql_destroy(s);
230 yf::SPARQL::Session::Session(const SPARQL *sparql) :
232 m_support_named_result_sets(false),
237 yf::SPARQL::Session::~Session()
241 yf::SPARQL::SessionPtr yf::SPARQL::get_session(Package & package,
246 Z_GDU *gdu = package.request().get();
248 boost::mutex::scoped_lock lock(m_p->m_mutex);
250 std::map<mp::Session,SPARQL::SessionPtr>::iterator it;
252 if (gdu && gdu->which == Z_GDU_Z3950)
253 *apdu = gdu->u.z3950;
259 it = m_p->m_clients.find(package.session());
260 if (it == m_p->m_clients.end())
262 if (!it->second->m_in_use)
264 it->second->m_in_use = true;
267 m_p->m_cond_session_ready.wait(lock);
272 // new Z39.50 session ..
273 SessionPtr p(new Session(this));
274 m_p->m_clients[package.session()] = p;
278 void yf::SPARQL::release_session(Package &package) const
280 boost::mutex::scoped_lock lock(m_p->m_mutex);
281 std::map<mp::Session,SessionPtr>::iterator it;
283 it = m_p->m_clients.find(package.session());
284 if (it != m_p->m_clients.end())
286 it->second->m_in_use = false;
288 if (package.session().is_closed())
289 m_p->m_clients.erase(it);
290 m_p->m_cond_session_ready.notify_all();
294 static bool get_result(xmlDoc *doc, Odr_int *sz, Odr_int pos,
297 xmlNode *ptr = xmlDocGetRootElement(doc);
302 *ndoc = xmlNewDoc(BAD_CAST "1.0");
304 if (ptr->type == XML_ELEMENT_NODE &&
305 !strcmp((const char *) ptr->name, "RDF"))
309 q0 = xmlCopyNode(ptr, 2);
310 xmlDocSetRootElement(*ndoc, q0);
314 while (ptr && ptr->type != XML_ELEMENT_NODE)
316 if (ptr && ptr->type == XML_ELEMENT_NODE &&
317 !strcmp((const char *) ptr->name, "Description"))
319 xmlNode *p = ptr->children;
321 while (p && p->type != XML_ELEMENT_NODE)
323 if (p && p->type == XML_ELEMENT_NODE &&
324 !strcmp((const char *) p->name, "type"))
325 { /* SELECT RESULT */
326 for (ptr = ptr->children; ptr; ptr = ptr->next)
327 if (ptr->type == XML_ELEMENT_NODE &&
328 !strcmp((const char *) ptr->name, "solution"))
334 xmlNode *q1 = xmlCopyNode(ptr, 1);
342 { /* CONSTRUCT result */
343 for (; ptr; ptr = ptr->next)
344 if (ptr->type == XML_ELEMENT_NODE &&
345 !strcmp((const char *) ptr->name, "Description"))
351 xmlNode *q1 = xmlCopyNode(ptr, 1);
362 for (; ptr; ptr = ptr->next)
363 if (ptr->type == XML_ELEMENT_NODE &&
364 !strcmp((const char *) ptr->name, "sparql"))
370 q0 = xmlCopyNode(ptr, 2);
371 xmlDocSetRootElement(*ndoc, q0);
373 for (ptr = ptr->children; ptr; ptr = ptr->next)
374 if (ptr->type == XML_ELEMENT_NODE &&
375 !strcmp((const char *) ptr->name, "results"))
383 q1 = xmlCopyNode(ptr, 0);
386 for (ptr = ptr->children; ptr; ptr = ptr->next)
387 if (ptr->type == XML_ELEMENT_NODE &&
388 !strcmp((const char *) ptr->name, "result"))
394 xmlNode *q2 = xmlCopyNode(ptr, 1);
407 Z_Records *yf::SPARQL::Session::fetch(
409 ODR odr, Odr_oid *preferredRecordSyntax,
410 Z_ElementSetNames *esn,
411 int start, int number, int &error_code, std::string &addinfo,
412 int *number_returned, int *next_position)
414 Z_Records *rec = (Z_Records *) odr_malloc(odr, sizeof(Z_Records));
415 std::list<Result>::iterator it = fset->results.begin();
416 if (esn && esn->which == Z_ElementSetNames_generic && esn->u.generic)
418 for (; it != fset->results.end(); it++)
420 yaz_log(YLOG_LOG, "checking xmldoc=%p schema=%s user-schema=%s",
421 it->doc, it->conf->schema.c_str(), esn->u.generic);
422 if (!strcmp(esn->u.generic, it->conf->schema.c_str()))
425 if (it == fset->results.end())
427 rec->which = Z_Records_NSD;
428 rec->u.nonSurrogateDiagnostic =
429 zget_DefaultDiagFormat(
431 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
436 rec->which = Z_Records_DBOSD;
437 rec->u.databaseOrSurDiagnostics = (Z_NamePlusRecordList *)
438 odr_malloc(odr, sizeof(Z_NamePlusRecordList));
439 rec->u.databaseOrSurDiagnostics->records = (Z_NamePlusRecord **)
440 odr_malloc(odr, sizeof(Z_NamePlusRecord *) * number);
442 for (i = 0; i < number; i++)
444 rec->u.databaseOrSurDiagnostics->records[i] = (Z_NamePlusRecord *)
445 odr_malloc(odr, sizeof(Z_NamePlusRecord));
446 Z_NamePlusRecord *npr = rec->u.databaseOrSurDiagnostics->records[i];
447 npr->databaseName = odr_strdup(odr, fset->db.c_str());
448 npr->which = Z_NamePlusRecord_databaseRecord;
451 if (!get_result(it->doc, 0, start - 1 + i, &ndoc))
457 xmlNode *ndoc_root = xmlDocGetRootElement(ndoc);
463 xmlBufferPtr buf = xmlBufferCreate();
464 xmlNodeDump(buf, ndoc, ndoc_root, 0, 0);
465 npr->u.databaseRecord =
466 z_ext_record_xml(odr, (const char *) buf->content, buf->use);
470 rec->u.databaseOrSurDiagnostics->num_records = i;
471 *number_returned = i;
472 if (start + number > fset->hits)
475 *next_position = start + number;
479 Z_APDU *yf::SPARQL::Session::run_sparql(mp::Package &package,
482 const char *sparql_query,
483 ConfPtr conf, FrontendSetPtr fset)
485 Z_SearchRequest *req = apdu_req->u.searchRequest;
486 Package http_package(package.session(), package.origin());
488 http_package.copy_filter(package);
489 Z_GDU *gdu = z_get_HTTP_Request_uri(odr, conf->uri.c_str(), 0, 1);
491 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
492 "Content-Type", "application/x-www-form-urlencoded");
493 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
494 "Accept", "application/sparql-results+xml,"
495 "application/rdf+xml");
496 const char *names[2];
499 const char *values[1];
500 values[0] = sparql_query;
502 yaz_array_to_uri(&path, odr, (char **) names, (char **) values);
504 gdu->u.HTTP_Request->content_buf = path;
505 gdu->u.HTTP_Request->content_len = strlen(path);
507 yaz_log(YLOG_LOG, "sparql: HTTP request\n%s", sparql_query);
509 http_package.request() = gdu;
512 Z_GDU *gdu_resp = http_package.response().get();
513 Z_APDU *apdu_res = 0;
514 if (!gdu_resp || gdu_resp->which != Z_GDU_HTTP_Response)
516 yaz_log(YLOG_LOG, "sparql: no HTTP response");
517 apdu_res = odr.create_searchResponse(apdu_req,
518 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
519 "no HTTP response from backend");
521 else if (gdu_resp->u.HTTP_Response->code != 200)
525 wrbuf_printf(w, "sparql: HTTP error %d from backend",
526 gdu_resp->u.HTTP_Response->code);
527 apdu_res = odr.create_searchResponse(apdu_req,
528 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
533 Z_HTTP_Response *resp = gdu_resp->u.HTTP_Response;
534 xmlDocPtr doc = xmlParseMemory(resp->content_buf, resp->content_len);
536 apdu_res = odr.create_searchResponse(apdu_req,
537 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
538 "invalid XML from backendbackend");
542 Z_Records *records = 0;
543 int number_returned = 0;
544 int next_position = 0;
550 fset->results.push_back(result);
551 yaz_log(YLOG_LOG, "saving sparql result xmldoc=%p", doc);
553 get_result(result.doc, &fset->hits, -1, 0);
554 m_frontend_sets[req->resultSetName] = fset;
559 const char *element_set_name = 0;
560 mp::util::piggyback_sr(req, fset->hits, number, &element_set_name);
563 Z_ElementSetNames *esn;
565 if (number > *req->smallSetUpperBound)
566 esn = req->mediumSetElementSetNames;
568 esn = req->smallSetElementSetNames;
569 records = fetch(fset,
570 odr, req->preferredRecordSyntax, esn,
579 odr.create_searchResponse(
580 apdu_req, error_code, addinfo.c_str());
585 odr.create_searchResponse(apdu_req, 0, 0);
586 Z_SearchResponse *resp = apdu_res->u.searchResponse;
587 *resp->resultCount = fset->hits;
588 *resp->numberOfRecordsReturned = number_returned;
589 *resp->nextResultSetPosition = next_position;
590 resp->records = records;
597 void yf::SPARQL::Session::handle_z(mp::Package &package, Z_APDU *apdu_req)
600 Z_APDU *apdu_res = 0;
601 if (apdu_req->which == Z_APDU_initRequest)
603 apdu_res = odr.create_initResponse(apdu_req, 0, 0);
604 Z_InitRequest *req = apdu_req->u.initRequest;
605 Z_InitResponse *resp = apdu_res->u.initResponse;
607 resp->implementationName = odr_strdup(odr, "sparql");
608 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
609 m_support_named_result_sets = true;
611 static const int masks[] = {
612 Z_Options_search, Z_Options_present,
613 Z_Options_namedResultSets, -1
615 for (i = 0; masks[i] != -1; i++)
616 if (ODR_MASK_GET(req->options, masks[i]))
617 ODR_MASK_SET(resp->options, masks[i]);
618 static const int versions[] = {
624 for (i = 0; versions[i] != -1; i++)
625 if (ODR_MASK_GET(req->protocolVersion, versions[i]))
626 ODR_MASK_SET(resp->protocolVersion, versions[i]);
629 *resp->preferredMessageSize = *req->preferredMessageSize;
630 *resp->maximumRecordSize = *req->maximumRecordSize;
632 else if (apdu_req->which == Z_APDU_close)
634 apdu_res = odr.create_close(apdu_req,
635 Z_Close_finished, 0);
636 package.session().close();
638 else if (apdu_req->which == Z_APDU_searchRequest)
640 Z_SearchRequest *req = apdu_req->u.searchRequest;
642 FrontendSets::iterator fset_it =
643 m_frontend_sets.find(req->resultSetName);
644 if (fset_it != m_frontend_sets.end())
646 // result set already exist
647 // if replace indicator is off: we return diagnostic if
648 // result set already exist.
649 if (*req->replaceIndicator == 0)
652 odr.create_searchResponse(
654 YAZ_BIB1_RESULT_SET_EXISTS_AND_REPLACE_INDICATOR_OFF,
656 package.response() = apdu;
658 m_frontend_sets.erase(fset_it);
660 if (req->query->which != Z_Query_type_1)
662 apdu_res = odr.create_searchResponse(
663 apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
665 else if (req->num_databaseNames != 1)
667 apdu_res = odr.create_searchResponse(
669 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, 0);
673 std::string db = req->databaseNames[0];
674 std::list<ConfPtr>::const_iterator it;
675 FrontendSetPtr fset(new FrontendSet);
677 m_frontend_sets.erase(req->resultSetName);
679 it = m_sparql->db_conf.begin();
680 for (; it != m_sparql->db_conf.end(); it++)
681 if (yaz_match_glob((*it)->db.c_str(), db.c_str()))
683 WRBUF addinfo_wr = wrbuf_alloc();
684 WRBUF sparql_wr = wrbuf_alloc();
686 yaz_sparql_from_rpn_wrbuf((*it)->s,
687 addinfo_wr, sparql_wr,
688 req->query->u.type_1);
691 apdu_res = odr.create_searchResponse(
693 wrbuf_len(addinfo_wr) ?
694 wrbuf_cstr(addinfo_wr) : 0);
698 Z_APDU *apdu_1 = run_sparql(package, apdu_req, odr,
699 wrbuf_cstr(sparql_wr), *it,
704 wrbuf_destroy(addinfo_wr);
705 wrbuf_destroy(sparql_wr);
709 apdu_res = odr.create_searchResponse(
710 apdu_req, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db.c_str());
714 else if (apdu_req->which == Z_APDU_presentRequest)
716 Z_PresentRequest *req = apdu_req->u.presentRequest;
717 FrontendSets::iterator fset_it =
718 m_frontend_sets.find(req->resultSetId);
719 if (fset_it == m_frontend_sets.end())
722 odr.create_presentResponse(
723 apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
725 package.response() = apdu_res;
728 int number_returned = 0;
729 int next_position = 0;
732 Z_ElementSetNames *esn = 0;
733 if (req->recordComposition)
735 if (req->recordComposition->which == Z_RecordComp_simple)
736 esn = req->recordComposition->u.simple;
740 odr.create_presentResponse(
742 YAZ_BIB1_ONLY_A_SINGLE_ELEMENT_SET_NAME_SUPPORTED,
744 package.response() = apdu_res;
748 Z_Records *records = fetch(
750 odr, req->preferredRecordSyntax, esn,
751 *req->resultSetStartPoint, *req->numberOfRecordsRequested,
758 odr.create_presentResponse(apdu_req, error_code,
764 odr.create_presentResponse(apdu_req, 0, 0);
765 Z_PresentResponse *resp = apdu_res->u.presentResponse;
766 resp->records = records;
767 *resp->numberOfRecordsReturned = number_returned;
768 *resp->nextResultSetPosition = next_position;
773 apdu_res = odr.create_close(apdu_req,
774 Z_Close_protocolError,
775 "sparql: unhandled APDU");
776 package.session().close();
780 package.response() = apdu_res;
783 void yf::SPARQL::process(mp::Package &package) const
786 SessionPtr p = get_session(package, &apdu);
789 p->handle_z(package, apdu);
793 release_session(package);
796 static mp::filter::Base* filter_creator()
798 return new mp::filter::SPARQL;
802 struct metaproxy_1_filter_struct metaproxy_1_filter_sparql = {
813 * c-file-style: "Stroustrup"
814 * indent-tabs-mode: nil
816 * vim: shiftwidth=4 tabstop=8 expandtab