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 {
43 typedef boost::shared_ptr<Session> SessionPtr;
44 typedef boost::shared_ptr<Conf> ConfPtr;
46 typedef boost::shared_ptr<FrontendSet> FrontendSetPtr;
47 typedef std::map<std::string,FrontendSetPtr> FrontendSets;
51 void process(metaproxy_1::Package & package) const;
52 void configure(const xmlNode * ptr, bool test_only,
54 SessionPtr get_session(Package &package, Z_APDU **apdu) const;
55 void release_session(Package &package) const;
56 boost::scoped_ptr<Rep> m_p;
57 std::list<ConfPtr> db_conf;
69 boost::condition m_cond_session_ready;
71 std::map<mp::Session,SessionPtr> m_clients;
73 class SPARQL::FrontendSet {
84 class SPARQL::Session {
86 Session(const SPARQL *);
88 void handle_z(Package &package, Z_APDU *apdu);
89 Z_APDU *run_sparql(mp::Package &package,
92 const char *sparql_query,
96 ODR odr, Odr_oid *preferredRecordSyntax,
97 Z_ElementSetNames *esn,
98 int start, int number, int &error_code, std::string &addinfo,
99 int *number_returned, int *next_position);
102 bool m_support_named_result_sets;
103 FrontendSets m_frontend_sets;
104 const SPARQL *m_sparql;
109 yf::SPARQL::FrontendSet::~FrontendSet()
115 yf::SPARQL::FrontendSet::FrontendSet()
120 yf::SPARQL::SPARQL() : m_p(new Rep)
124 yf::SPARQL::~SPARQL()
128 void yf::SPARQL::configure(const xmlNode *xmlnode, bool test_only,
131 const xmlNode *ptr = xmlnode->children;
134 for (; ptr; ptr = ptr->next)
136 if (ptr->type != XML_ELEMENT_NODE)
138 if (!strcmp((const char *) ptr->name, "defaults"))
140 const struct _xmlAttr *attr;
141 for (attr = ptr->properties; attr; attr = attr->next)
143 if (!strcmp((const char *) attr->name, "uri"))
144 uri = mp::xml::get_text(attr->children);
146 throw mp::filter::FilterException(
147 "Bad attribute " + std::string((const char *)
151 else if (!strcmp((const char *) ptr->name, "db"))
153 yaz_sparql_t s = yaz_sparql_create();
154 ConfPtr conf(new Conf);
158 const struct _xmlAttr *attr;
159 for (attr = ptr->properties; attr; attr = attr->next)
161 if (!strcmp((const char *) attr->name, "path"))
162 conf->db = mp::xml::get_text(attr->children);
163 else if (!strcmp((const char *) attr->name, "uri"))
164 conf->uri = mp::xml::get_text(attr->children);
165 else if (!strcmp((const char *) attr->name, "schema"))
166 conf->schema = mp::xml::get_text(attr->children);
168 throw mp::filter::FilterException(
169 "Bad attribute " + std::string((const char *)
172 xmlNode *p = ptr->children;
173 for (; p; p = p->next)
175 if (p->type != XML_ELEMENT_NODE)
177 std::string name = (const char *) p->name;
178 const struct _xmlAttr *attr;
179 for (attr = p->properties; attr; attr = attr->next)
181 if (!strcmp((const char *) attr->name, "type"))
184 name.append(mp::xml::get_text(attr->children));
187 throw mp::filter::FilterException(
188 "Bad attribute " + std::string((const char *)
191 std::string value = mp::xml::get_text(p);
192 if (yaz_sparql_add_pattern(s, name.c_str(), value.c_str()))
194 throw mp::filter::FilterException(
195 "Bad SPARQL config " + name);
198 if (!conf->uri.length())
200 throw mp::filter::FilterException("Missing uri");
202 if (!conf->db.length())
204 throw mp::filter::FilterException("Missing path");
206 db_conf.push_back(conf);
210 throw mp::filter::FilterException
212 + std::string((const char *) ptr->name)
213 + " in sparql filter");
218 yf::SPARQL::Conf::~Conf()
220 yaz_sparql_destroy(s);
223 yf::SPARQL::Session::Session(const SPARQL *sparql) :
225 m_support_named_result_sets(false),
230 yf::SPARQL::Session::~Session()
234 yf::SPARQL::SessionPtr yf::SPARQL::get_session(Package & package,
239 Z_GDU *gdu = package.request().get();
241 boost::mutex::scoped_lock lock(m_p->m_mutex);
243 std::map<mp::Session,SPARQL::SessionPtr>::iterator it;
245 if (gdu && gdu->which == Z_GDU_Z3950)
246 *apdu = gdu->u.z3950;
252 it = m_p->m_clients.find(package.session());
253 if (it == m_p->m_clients.end())
255 if (!it->second->m_in_use)
257 it->second->m_in_use = true;
260 m_p->m_cond_session_ready.wait(lock);
265 // new Z39.50 session ..
266 SessionPtr p(new Session(this));
267 m_p->m_clients[package.session()] = p;
271 void yf::SPARQL::release_session(Package &package) const
273 boost::mutex::scoped_lock lock(m_p->m_mutex);
274 std::map<mp::Session,SessionPtr>::iterator it;
276 it = m_p->m_clients.find(package.session());
277 if (it != m_p->m_clients.end())
279 it->second->m_in_use = false;
281 if (package.session().is_closed())
282 m_p->m_clients.erase(it);
283 m_p->m_cond_session_ready.notify_all();
287 static bool get_result(xmlDoc *doc, Odr_int *sz, Odr_int pos,
290 xmlNode *ptr = xmlDocGetRootElement(doc);
295 *ndoc = xmlNewDoc(BAD_CAST "1.0");
297 if (ptr->type == XML_ELEMENT_NODE &&
298 !strcmp((const char *) ptr->name, "RDF"))
302 q0 = xmlCopyNode(ptr, 2);
303 xmlDocSetRootElement(*ndoc, q0);
307 while (ptr && ptr->type != XML_ELEMENT_NODE)
309 if (ptr && ptr->type == XML_ELEMENT_NODE &&
310 !strcmp((const char *) ptr->name, "Description"))
312 xmlNode *p = ptr->children;
314 while (p && p->type != XML_ELEMENT_NODE)
316 if (p && p->type == XML_ELEMENT_NODE &&
317 !strcmp((const char *) p->name, "type"))
318 { /* SELECT RESULT */
319 for (ptr = ptr->children; ptr; ptr = ptr->next)
320 if (ptr->type == XML_ELEMENT_NODE &&
321 !strcmp((const char *) ptr->name, "solution"))
327 xmlNode *q1 = xmlCopyNode(ptr, 1);
335 { /* CONSTRUCT result */
336 for (; ptr; ptr = ptr->next)
337 if (ptr->type == XML_ELEMENT_NODE &&
338 !strcmp((const char *) ptr->name, "Description"))
344 xmlNode *q1 = xmlCopyNode(ptr, 1);
355 for (; ptr; ptr = ptr->next)
356 if (ptr->type == XML_ELEMENT_NODE &&
357 !strcmp((const char *) ptr->name, "sparql"))
363 q0 = xmlCopyNode(ptr, 2);
364 xmlDocSetRootElement(*ndoc, q0);
366 for (ptr = ptr->children; ptr; ptr = ptr->next)
367 if (ptr->type == XML_ELEMENT_NODE &&
368 !strcmp((const char *) ptr->name, "results"))
376 q1 = xmlCopyNode(ptr, 0);
379 for (ptr = ptr->children; ptr; ptr = ptr->next)
380 if (ptr->type == XML_ELEMENT_NODE &&
381 !strcmp((const char *) ptr->name, "result"))
387 xmlNode *q2 = xmlCopyNode(ptr, 1);
400 Z_Records *yf::SPARQL::Session::fetch(
402 ODR odr, Odr_oid *preferredRecordSyntax,
403 Z_ElementSetNames *esn,
404 int start, int number, int &error_code, std::string &addinfo,
405 int *number_returned, int *next_position)
407 Z_Records *rec = (Z_Records *) odr_malloc(odr, sizeof(Z_Records));
408 if (esn && esn->which == Z_ElementSetNames_generic &&
409 fset->conf->schema.length())
411 if (strcmp(esn->u.generic, fset->conf->schema.c_str()))
413 rec->which = Z_Records_NSD;
414 rec->u.nonSurrogateDiagnostic =
415 zget_DefaultDiagFormat(
417 YAZ_BIB1_SPECIFIED_ELEMENT_SET_NAME_NOT_VALID_FOR_SPECIFIED_,
422 rec->which = Z_Records_DBOSD;
423 rec->u.databaseOrSurDiagnostics = (Z_NamePlusRecordList *)
424 odr_malloc(odr, sizeof(Z_NamePlusRecordList));
425 rec->u.databaseOrSurDiagnostics->records = (Z_NamePlusRecord **)
426 odr_malloc(odr, sizeof(Z_NamePlusRecord *) * number);
428 for (i = 0; i < number; i++)
430 rec->u.databaseOrSurDiagnostics->records[i] = (Z_NamePlusRecord *)
431 odr_malloc(odr, sizeof(Z_NamePlusRecord));
432 Z_NamePlusRecord *npr = rec->u.databaseOrSurDiagnostics->records[i];
433 npr->databaseName = odr_strdup(odr, fset->db.c_str());
434 npr->which = Z_NamePlusRecord_databaseRecord;
437 if (!get_result(fset->doc, 0, start - 1 + i, &ndoc))
443 xmlNode *ndoc_root = xmlDocGetRootElement(ndoc);
449 xmlBufferPtr buf = xmlBufferCreate();
450 xmlNodeDump(buf, ndoc, ndoc_root, 0, 0);
451 npr->u.databaseRecord =
452 z_ext_record_xml(odr, (const char *) buf->content, buf->use);
456 rec->u.databaseOrSurDiagnostics->num_records = i;
457 *number_returned = i;
458 if (start + number > fset->hits)
461 *next_position = start + number;
465 Z_APDU *yf::SPARQL::Session::run_sparql(mp::Package &package,
468 const char *sparql_query,
471 Z_SearchRequest *req = apdu_req->u.searchRequest;
472 Package http_package(package.session(), package.origin());
474 http_package.copy_filter(package);
475 Z_GDU *gdu = z_get_HTTP_Request_uri(odr, conf->uri.c_str(), 0, 1);
477 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
478 "Content-Type", "application/x-www-form-urlencoded");
479 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
480 "Accept", "application/sparql-results+xml,"
481 "application/rdf+xml");
482 const char *names[2];
485 const char *values[1];
486 values[0] = sparql_query;
488 yaz_array_to_uri(&path, odr, (char **) names, (char **) values);
490 gdu->u.HTTP_Request->content_buf = path;
491 gdu->u.HTTP_Request->content_len = strlen(path);
493 yaz_log(YLOG_LOG, "sparql: HTTP request\n%s", sparql_query);
495 http_package.request() = gdu;
498 Z_GDU *gdu_resp = http_package.response().get();
499 Z_APDU *apdu_res = 0;
500 if (!gdu_resp || gdu_resp->which != Z_GDU_HTTP_Response)
502 yaz_log(YLOG_LOG, "sparql: no HTTP response");
503 apdu_res = odr.create_searchResponse(apdu_req,
504 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
505 "no HTTP response from backend");
507 else if (gdu_resp->u.HTTP_Response->code != 200)
511 wrbuf_printf(w, "sparql: HTTP error %d from backend",
512 gdu_resp->u.HTTP_Response->code);
513 apdu_res = odr.create_searchResponse(apdu_req,
514 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
519 Z_HTTP_Response *resp = gdu_resp->u.HTTP_Response;
520 FrontendSetPtr fset(new FrontendSet);
522 fset->doc = xmlParseMemory(resp->content_buf, resp->content_len);
523 fset->db = req->databaseNames[0];
526 apdu_res = odr.create_searchResponse(apdu_req,
527 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
528 "invalid XML from backendbackend");
531 Z_Records *records = 0;
532 int number_returned = 0;
533 int next_position = 0;
537 get_result(fset->doc, &fset->hits, -1, 0);
538 m_frontend_sets[req->resultSetName] = fset;
541 const char *element_set_name = 0;
542 mp::util::piggyback_sr(req, fset->hits, number, &element_set_name);
545 Z_ElementSetNames *esn;
547 if (number > *req->smallSetUpperBound)
548 esn = req->mediumSetElementSetNames;
550 esn = req->smallSetElementSetNames;
551 records = fetch(fset,
552 odr, req->preferredRecordSyntax, esn,
561 odr.create_searchResponse(
562 apdu_req, error_code, addinfo.c_str());
567 odr.create_searchResponse(apdu_req, 0, 0);
568 Z_SearchResponse *resp = apdu_res->u.searchResponse;
569 *resp->resultCount = fset->hits;
570 *resp->numberOfRecordsReturned = number_returned;
571 *resp->nextResultSetPosition = next_position;
572 resp->records = records;
579 void yf::SPARQL::Session::handle_z(mp::Package &package, Z_APDU *apdu_req)
582 Z_APDU *apdu_res = 0;
583 if (apdu_req->which == Z_APDU_initRequest)
585 apdu_res = odr.create_initResponse(apdu_req, 0, 0);
586 Z_InitRequest *req = apdu_req->u.initRequest;
587 Z_InitResponse *resp = apdu_res->u.initResponse;
589 resp->implementationName = odr_strdup(odr, "sparql");
590 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
591 m_support_named_result_sets = true;
593 static const int masks[] = {
594 Z_Options_search, Z_Options_present,
595 Z_Options_namedResultSets, -1
597 for (i = 0; masks[i] != -1; i++)
598 if (ODR_MASK_GET(req->options, masks[i]))
599 ODR_MASK_SET(resp->options, masks[i]);
600 static const int versions[] = {
606 for (i = 0; versions[i] != -1; i++)
607 if (ODR_MASK_GET(req->protocolVersion, versions[i]))
608 ODR_MASK_SET(resp->protocolVersion, versions[i]);
611 *resp->preferredMessageSize = *req->preferredMessageSize;
612 *resp->maximumRecordSize = *req->maximumRecordSize;
614 else if (apdu_req->which == Z_APDU_close)
616 apdu_res = odr.create_close(apdu_req,
617 Z_Close_finished, 0);
618 package.session().close();
620 else if (apdu_req->which == Z_APDU_searchRequest)
622 Z_SearchRequest *req = apdu_req->u.searchRequest;
624 FrontendSets::iterator fset_it =
625 m_frontend_sets.find(req->resultSetName);
626 if (fset_it != m_frontend_sets.end())
628 // result set already exist
629 // if replace indicator is off: we return diagnostic if
630 // result set already exist.
631 if (*req->replaceIndicator == 0)
634 odr.create_searchResponse(
636 YAZ_BIB1_RESULT_SET_EXISTS_AND_REPLACE_INDICATOR_OFF,
638 package.response() = apdu_res;
640 m_frontend_sets.erase(fset_it);
642 if (req->query->which != Z_Query_type_1)
644 apdu_res = odr.create_searchResponse(
645 apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
647 else if (req->num_databaseNames != 1)
649 apdu_res = odr.create_searchResponse(
651 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, 0);
655 std::string db = req->databaseNames[0];
656 std::list<ConfPtr>::const_iterator it;
658 it = m_sparql->db_conf.begin();
659 for (; it != m_sparql->db_conf.end(); it++)
660 if (yaz_match_glob((*it)->db.c_str(), db.c_str()))
662 if (it == m_sparql->db_conf.end())
664 apdu_res = odr.create_searchResponse(
665 apdu_req, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db.c_str());
669 WRBUF addinfo_wr = wrbuf_alloc();
670 WRBUF sparql_wr = wrbuf_alloc();
672 yaz_sparql_from_rpn_wrbuf((*it)->s,
673 addinfo_wr, sparql_wr,
674 req->query->u.type_1);
677 apdu_res = odr.create_searchResponse(
679 wrbuf_len(addinfo_wr) ?
680 wrbuf_cstr(addinfo_wr) : 0);
684 apdu_res = run_sparql(package, apdu_req, odr,
685 wrbuf_cstr(sparql_wr), *it);
687 wrbuf_destroy(addinfo_wr);
688 wrbuf_destroy(sparql_wr);
692 else if (apdu_req->which == Z_APDU_presentRequest)
694 Z_PresentRequest *req = apdu_req->u.presentRequest;
695 FrontendSets::iterator fset_it =
696 m_frontend_sets.find(req->resultSetId);
697 if (fset_it == m_frontend_sets.end())
700 odr.create_presentResponse(
701 apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
703 package.response() = apdu_res;
706 int number_returned = 0;
707 int next_position = 0;
710 Z_ElementSetNames *esn = 0;
711 if (req->recordComposition)
713 if (req->recordComposition->which == Z_RecordComp_simple)
714 esn = req->recordComposition->u.simple;
718 odr.create_presentResponse(
720 YAZ_BIB1_ONLY_A_SINGLE_ELEMENT_SET_NAME_SUPPORTED,
722 package.response() = apdu_res;
726 Z_Records *records = fetch(
728 odr, req->preferredRecordSyntax, esn,
729 *req->resultSetStartPoint, *req->numberOfRecordsRequested,
736 odr.create_presentResponse(apdu_req, error_code,
742 odr.create_presentResponse(apdu_req, 0, 0);
743 Z_PresentResponse *resp = apdu_res->u.presentResponse;
744 resp->records = records;
745 *resp->numberOfRecordsReturned = number_returned;
746 *resp->nextResultSetPosition = next_position;
751 apdu_res = odr.create_close(apdu_req,
752 Z_Close_protocolError,
753 "sparql: unhandled APDU");
754 package.session().close();
758 package.response() = apdu_res;
761 void yf::SPARQL::process(mp::Package &package) const
764 SessionPtr p = get_session(package, &apdu);
767 p->handle_z(package, apdu);
771 release_session(package);
774 static mp::filter::Base* filter_creator()
776 return new mp::filter::SPARQL;
780 struct metaproxy_1_filter_struct metaproxy_1_filter_sparql = {
791 * c-file-style: "Stroustrup"
792 * indent-tabs-mode: nil
794 * vim: shiftwidth=4 tabstop=8 expandtab