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;
68 boost::condition m_cond_session_ready;
70 std::map<mp::Session,SessionPtr> m_clients;
72 class SPARQL::FrontendSet {
82 class SPARQL::Session {
84 Session(const SPARQL *);
86 void handle_z(Package &package, Z_APDU *apdu);
87 Z_APDU *run_sparql(mp::Package &package,
90 const char *sparql_query,
94 ODR odr, Odr_oid *preferredRecordSyntax,
95 Z_ElementSetNames *esn,
96 int start, int number, int &error_code, std::string &addinfo,
97 int *number_returned, int *next_position);
100 bool m_support_named_result_sets;
101 FrontendSets m_frontend_sets;
102 const SPARQL *m_sparql;
107 yf::SPARQL::FrontendSet::~FrontendSet()
113 yf::SPARQL::FrontendSet::FrontendSet()
118 yf::SPARQL::SPARQL() : m_p(new Rep)
122 yf::SPARQL::~SPARQL()
126 void yf::SPARQL::configure(const xmlNode *xmlnode, bool test_only,
129 const xmlNode *ptr = xmlnode->children;
131 for (; ptr; ptr = ptr->next)
133 if (ptr->type != XML_ELEMENT_NODE)
135 if (!strcmp((const char *) ptr->name, "db"))
137 yaz_sparql_t s = yaz_sparql_create();
138 ConfPtr conf(new Conf);
141 const struct _xmlAttr *attr;
142 for (attr = ptr->properties; attr; attr = attr->next)
144 if (!strcmp((const char *) attr->name, "path"))
145 conf->db = mp::xml::get_text(attr->children);
146 else if (!strcmp((const char *) attr->name, "uri"))
147 conf->uri = mp::xml::get_text(attr->children);
149 throw mp::filter::FilterException(
150 "Bad attribute " + std::string((const char *)
153 xmlNode *p = ptr->children;
154 for (; p; p = p->next)
156 if (p->type != XML_ELEMENT_NODE)
158 std::string name = (const char *) p->name;
159 const struct _xmlAttr *attr;
160 for (attr = p->properties; attr; attr = attr->next)
162 if (!strcmp((const char *) attr->name, "type"))
165 name.append(mp::xml::get_text(attr->children));
168 throw mp::filter::FilterException(
169 "Bad attribute " + std::string((const char *)
172 std::string value = mp::xml::get_text(p);
173 if (yaz_sparql_add_pattern(s, name.c_str(), value.c_str()))
175 throw mp::filter::FilterException(
176 "Bad SPARQL config " + name);
179 if (!conf->uri.length())
181 throw mp::filter::FilterException("Missing uri");
183 if (!conf->db.length())
185 throw mp::filter::FilterException("Missing path");
187 db_conf.push_back(conf);
191 throw mp::filter::FilterException
193 + std::string((const char *) ptr->name)
194 + " in sparql filter");
199 yf::SPARQL::Conf::~Conf()
201 yaz_sparql_destroy(s);
204 yf::SPARQL::Session::Session(const SPARQL *sparql) :
206 m_support_named_result_sets(false),
211 yf::SPARQL::Session::~Session()
215 yf::SPARQL::SessionPtr yf::SPARQL::get_session(Package & package,
220 Z_GDU *gdu = package.request().get();
222 boost::mutex::scoped_lock lock(m_p->m_mutex);
224 std::map<mp::Session,SPARQL::SessionPtr>::iterator it;
226 if (gdu && gdu->which == Z_GDU_Z3950)
227 *apdu = gdu->u.z3950;
233 it = m_p->m_clients.find(package.session());
234 if (it == m_p->m_clients.end())
236 if (!it->second->m_in_use)
238 it->second->m_in_use = true;
241 m_p->m_cond_session_ready.wait(lock);
246 // new Z39.50 session ..
247 SessionPtr p(new Session(this));
248 m_p->m_clients[package.session()] = p;
252 void yf::SPARQL::release_session(Package &package) const
254 boost::mutex::scoped_lock lock(m_p->m_mutex);
255 std::map<mp::Session,SessionPtr>::iterator it;
257 it = m_p->m_clients.find(package.session());
258 if (it != m_p->m_clients.end())
260 it->second->m_in_use = false;
262 if (package.session().is_closed())
263 m_p->m_clients.erase(it);
264 m_p->m_cond_session_ready.notify_all();
268 static xmlNode *get_result(xmlDoc *doc, Odr_int *sz, Odr_int pos)
270 xmlNode *ptr = xmlDocGetRootElement(doc);
273 if (ptr->type == XML_ELEMENT_NODE &&
274 !strcmp((const char *) ptr->name, "RDF"))
278 while (ptr && ptr->type != XML_ELEMENT_NODE)
280 if (ptr && ptr->type == XML_ELEMENT_NODE &&
281 !strcmp((const char *) ptr->name, "Description"))
283 xmlNode *p = ptr->children;
285 while (p && p->type != XML_ELEMENT_NODE)
287 if (p && p->type == XML_ELEMENT_NODE &&
288 !strcmp((const char *) p->name, "type"))
289 { /* SELECT RESULT */
290 for (ptr = ptr->children; ptr; ptr = ptr->next)
291 if (ptr->type == XML_ELEMENT_NODE &&
292 !strcmp((const char *) ptr->name, "solution"))
299 { /* CONSTRUCT result */
300 for (; ptr; ptr = ptr->next)
301 if (ptr->type == XML_ELEMENT_NODE &&
302 !strcmp((const char *) ptr->name, "Description"))
312 for (; ptr; ptr = ptr->next)
313 if (ptr->type == XML_ELEMENT_NODE &&
314 !strcmp((const char *) ptr->name, "sparql"))
318 for (ptr = ptr->children; ptr; ptr = ptr->next)
319 if (ptr->type == XML_ELEMENT_NODE &&
320 !strcmp((const char *) ptr->name, "results"))
325 for (ptr = ptr->children; ptr; ptr = ptr->next)
326 if (ptr->type == XML_ELEMENT_NODE &&
327 !strcmp((const char *) ptr->name, "result"))
339 Z_Records *yf::SPARQL::Session::fetch(
341 ODR odr, Odr_oid *preferredRecordSyntax,
342 Z_ElementSetNames *esn,
343 int start, int number, int &error_code, std::string &addinfo,
344 int *number_returned, int *next_position)
346 Z_Records *rec = (Z_Records *) odr_malloc(odr, sizeof(Z_Records));
347 rec->which = Z_Records_DBOSD;
348 rec->u.databaseOrSurDiagnostics = (Z_NamePlusRecordList *)
349 odr_malloc(odr, sizeof(Z_NamePlusRecordList));
350 rec->u.databaseOrSurDiagnostics->records = (Z_NamePlusRecord **)
351 odr_malloc(odr, sizeof(Z_NamePlusRecord *) * number);
353 for (i = 0; i < number; i++)
355 rec->u.databaseOrSurDiagnostics->records[i] = (Z_NamePlusRecord *)
356 odr_malloc(odr, sizeof(Z_NamePlusRecord));
357 Z_NamePlusRecord *npr = rec->u.databaseOrSurDiagnostics->records[i];
358 npr->databaseName = odr_strdup(odr, fset->db.c_str());
359 npr->which = Z_NamePlusRecord_databaseRecord;
361 xmlNode *node = get_result(fset->doc, 0, start - 1 + i);
364 assert(node->type == XML_ELEMENT_NODE);
365 xmlNode *tmp = xmlCopyNode(node, 1);
366 xmlBufferPtr buf = xmlBufferCreate();
367 xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
368 npr->u.databaseRecord =
369 z_ext_record_xml(odr, (const char *) buf->content, buf->use);
373 rec->u.databaseOrSurDiagnostics->num_records = i;
374 *number_returned = i;
375 if (start + number > fset->hits)
378 *next_position = start + number;
382 Z_APDU *yf::SPARQL::Session::run_sparql(mp::Package &package,
385 const char *sparql_query,
388 Z_SearchRequest *req = apdu_req->u.searchRequest;
389 Package http_package(package.session(), package.origin());
391 http_package.copy_filter(package);
392 Z_GDU *gdu = z_get_HTTP_Request_uri(odr, uri, 0, 1);
394 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
395 "Content-Type", "application/x-www-form-urlencoded");
396 z_HTTP_header_add(odr, &gdu->u.HTTP_Request->headers,
397 "Accept", "application/rdf+xml");
398 const char *names[2];
401 const char *values[1];
402 values[0] = sparql_query;
404 yaz_array_to_uri(&path, odr, (char **) names, (char **) values);
406 gdu->u.HTTP_Request->content_buf = path;
407 gdu->u.HTTP_Request->content_len = strlen(path);
409 yaz_log(YLOG_LOG, "sparql: HTTP request\n%s", sparql_query);
411 http_package.request() = gdu;
414 Z_GDU *gdu_resp = http_package.response().get();
415 Z_APDU *apdu_res = 0;
416 if (!gdu_resp || gdu_resp->which != Z_GDU_HTTP_Response)
418 yaz_log(YLOG_LOG, "sparql: no HTTP response");
419 apdu_res = odr.create_searchResponse(apdu_req,
420 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
421 "no HTTP response from backend");
423 else if (gdu_resp->u.HTTP_Response->code != 200)
427 wrbuf_printf(w, "sparql: HTTP error %d from backend",
428 gdu_resp->u.HTTP_Response->code);
429 apdu_res = odr.create_searchResponse(apdu_req,
430 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
435 Z_HTTP_Response *resp = gdu_resp->u.HTTP_Response;
436 FrontendSetPtr fset(new FrontendSet);
438 fset->doc = xmlParseMemory(resp->content_buf, resp->content_len);
439 fset->db = req->databaseNames[0];
441 apdu_res = odr.create_searchResponse(apdu_req,
442 YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
443 "invalid XML from backendbackend");
446 Z_Records *records = 0;
447 int number_returned = 0;
448 int next_position = 0;
452 get_result(fset->doc, &fset->hits, -1);
453 m_frontend_sets[req->resultSetName] = fset;
456 const char *element_set_name = 0;
457 mp::util::piggyback_sr(req, fset->hits, number, &element_set_name);
460 Z_ElementSetNames *esn;
462 if (number > *req->smallSetUpperBound)
463 esn = req->mediumSetElementSetNames;
465 esn = req->smallSetElementSetNames;
466 records = fetch(fset,
467 odr, req->preferredRecordSyntax, esn,
476 odr.create_searchResponse(
477 apdu_req, error_code, addinfo.c_str());
482 odr.create_searchResponse(apdu_req, 0, 0);
483 Z_SearchResponse *resp = apdu_res->u.searchResponse;
484 *resp->resultCount = fset->hits;
485 *resp->numberOfRecordsReturned = number_returned;
486 *resp->nextResultSetPosition = next_position;
487 resp->records = records;
494 void yf::SPARQL::Session::handle_z(mp::Package &package, Z_APDU *apdu_req)
497 Z_APDU *apdu_res = 0;
498 if (apdu_req->which == Z_APDU_initRequest)
500 apdu_res = odr.create_initResponse(apdu_req, 0, 0);
501 Z_InitRequest *req = apdu_req->u.initRequest;
502 Z_InitResponse *resp = apdu_res->u.initResponse;
504 resp->implementationName = odr_strdup(odr, "sparql");
505 if (ODR_MASK_GET(req->options, Z_Options_namedResultSets))
506 m_support_named_result_sets = true;
508 static const int masks[] = {
509 Z_Options_search, Z_Options_present,
510 Z_Options_namedResultSets, -1
512 for (i = 0; masks[i] != -1; i++)
513 if (ODR_MASK_GET(req->options, masks[i]))
514 ODR_MASK_SET(resp->options, masks[i]);
515 static const int versions[] = {
521 for (i = 0; versions[i] != -1; i++)
522 if (ODR_MASK_GET(req->protocolVersion, versions[i]))
523 ODR_MASK_SET(resp->protocolVersion, versions[i]);
526 *resp->preferredMessageSize = *req->preferredMessageSize;
527 *resp->maximumRecordSize = *req->maximumRecordSize;
529 else if (apdu_req->which == Z_APDU_close)
531 apdu_res = odr.create_close(apdu_req,
532 Z_Close_finished, 0);
533 package.session().close();
535 else if (apdu_req->which == Z_APDU_searchRequest)
537 Z_SearchRequest *req = apdu_req->u.searchRequest;
539 FrontendSets::iterator fset_it =
540 m_frontend_sets.find(req->resultSetName);
541 if (fset_it != m_frontend_sets.end())
543 // result set already exist
544 // if replace indicator is off: we return diagnostic if
545 // result set already exist.
546 if (*req->replaceIndicator == 0)
549 odr.create_searchResponse(
551 YAZ_BIB1_RESULT_SET_EXISTS_AND_REPLACE_INDICATOR_OFF,
553 package.response() = apdu_res;
555 m_frontend_sets.erase(fset_it);
557 if (req->query->which != Z_Query_type_1)
559 apdu_res = odr.create_searchResponse(
560 apdu_req, YAZ_BIB1_QUERY_TYPE_UNSUPP, 0);
562 else if (req->num_databaseNames != 1)
564 apdu_res = odr.create_searchResponse(
566 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED, 0);
570 std::string db = req->databaseNames[0];
571 std::list<ConfPtr>::const_iterator it;
573 it = m_sparql->db_conf.begin();
574 for (; it != m_sparql->db_conf.end(); it++)
575 if (yaz_match_glob((*it)->db.c_str(), db.c_str()))
577 if (it == m_sparql->db_conf.end())
579 apdu_res = odr.create_searchResponse(
580 apdu_req, YAZ_BIB1_DATABASE_DOES_NOT_EXIST, db.c_str());
584 WRBUF addinfo_wr = wrbuf_alloc();
585 WRBUF sparql_wr = wrbuf_alloc();
587 yaz_sparql_from_rpn_wrbuf((*it)->s,
588 addinfo_wr, sparql_wr,
589 req->query->u.type_1);
592 apdu_res = odr.create_searchResponse(
594 wrbuf_len(addinfo_wr) ?
595 wrbuf_cstr(addinfo_wr) : 0);
599 apdu_res = run_sparql(package, apdu_req, odr,
600 wrbuf_cstr(sparql_wr),
603 wrbuf_destroy(addinfo_wr);
604 wrbuf_destroy(sparql_wr);
608 else if (apdu_req->which == Z_APDU_presentRequest)
610 Z_PresentRequest *req = apdu_req->u.presentRequest;
611 FrontendSets::iterator fset_it =
612 m_frontend_sets.find(req->resultSetId);
613 if (fset_it == m_frontend_sets.end())
616 odr.create_presentResponse(
617 apdu_req, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
619 package.response() = apdu_res;
622 int number_returned = 0;
623 int next_position = 0;
626 Z_ElementSetNames *esn = 0;
627 if (req->recordComposition)
629 if (req->recordComposition->which == Z_RecordComp_simple)
630 esn = req->recordComposition->u.simple;
634 odr.create_presentResponse(
636 YAZ_BIB1_ONLY_A_SINGLE_ELEMENT_SET_NAME_SUPPORTED,
638 package.response() = apdu_res;
642 Z_Records *records = fetch(
644 odr, req->preferredRecordSyntax, esn,
645 *req->resultSetStartPoint, *req->numberOfRecordsRequested,
652 odr.create_presentResponse(apdu_req, error_code,
658 odr.create_presentResponse(apdu_req, 0, 0);
659 Z_PresentResponse *resp = apdu_res->u.presentResponse;
660 resp->records = records;
661 *resp->numberOfRecordsReturned = number_returned;
662 *resp->nextResultSetPosition = next_position;
667 apdu_res = odr.create_close(apdu_req,
668 Z_Close_protocolError,
669 "sparql: unhandled APDU");
670 package.session().close();
674 package.response() = apdu_res;
677 void yf::SPARQL::process(mp::Package &package) const
680 SessionPtr p = get_session(package, &apdu);
683 p->handle_z(package, apdu);
687 release_session(package);
690 static mp::filter::Base* filter_creator()
692 return new mp::filter::SPARQL;
696 struct metaproxy_1_filter_struct metaproxy_1_filter_sparql = {
707 * c-file-style: "Stroustrup"
708 * indent-tabs-mode: nil
710 * vim: shiftwidth=4 tabstop=8 expandtab