bes  Updated for version 3.20.5
BESDapResponseBuilder.cc
1 // -*- mode: c++; c-basic-offset:4 -*-
2 
3 // This file is part of libdap, A C++ implementation of the OPeNDAP Data
4 // Access Protocol.
5 
6 // Copyright (c) 2011 OPeNDAP, Inc.
7 // Author: James Gallagher <jgallagher@opendap.org>
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 //
23 // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
24 
25 #include "config.h"
26 
27 #include <signal.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 
31 #ifdef HAVE_UUID_UUID_H
32 #include <uuid/uuid.h> // used to build CID header value for data ddx
33 #elif defined(HAVE_UUID_H)
34 #include <uuid.h>
35 #else
36 #error "Could not find UUID library header"
37 #endif
38 
39 
40 #ifndef WIN32
41 #include <sys/wait.h>
42 #else
43 #include <io.h>
44 #include <fcntl.h>
45 #include <process.h>
46 #endif
47 
48 #include <iostream>
49 #include <string>
50 #include <sstream>
51 #include <fstream>
52 
53 #include <cstring>
54 #include <ctime>
55 
56 //#define DODS_DEBUG
57 #define CLEAR_LOCAL_DATA
58 #undef USE_LOCAL_TIMEOUT_SCHEME
59 
60 #include <DAS.h>
61 #include <DDS.h>
62 #include <Structure.h>
63 #include <ConstraintEvaluator.h>
64 #include <DDXParserSAX2.h>
65 #include <Ancillary.h>
66 #include <XDRStreamMarshaller.h>
67 #include <XDRFileUnMarshaller.h>
68 
69 #include <DMR.h>
70 #include <D4Group.h>
71 #include <XMLWriter.h>
72 #include <D4AsyncUtil.h>
73 #include <D4StreamMarshaller.h>
74 #include <chunked_ostream.h>
75 #include <chunked_istream.h>
76 #include <D4ConstraintEvaluator.h>
77 #include <D4FunctionEvaluator.h>
78 #include <D4BaseTypeFactory.h>
79 
80 #include <ServerFunctionsList.h>
81 
82 #include <mime_util.h> // for last_modified_time() and rfc_822_date()
83 #include <escaping.h>
84 #include <util.h>
85 #if USE_LOCAL_TIMEOUT_SCHEME
86 #ifndef WIN32
87 #include <SignalHandler.h>
88 #include <EventHandler.h>
89 #include <AlarmHandler.h>
90 #endif
91 #endif
92 
93 #include "TheBESKeys.h"
94 #include "BESDapResponseBuilder.h"
95 #include "BESContextManager.h"
96 #include "BESDapFunctionResponseCache.h"
97 #include "BESStoredDapResultCache.h"
98 
99 #include "BESResponseObject.h"
100 #include "BESDDSResponse.h"
101 #include "BESDataDDSResponse.h"
102 #include "BESDataHandlerInterface.h"
103 #include "BESInternalFatalError.h"
104 #include "BESDataNames.h"
105 
106 #include "BESUtil.h"
107 #include "BESDebug.h"
108 #include "BESStopWatch.h"
109 #include "DapFunctionUtils.h"
110 
111 using namespace std;
112 using namespace libdap;
113 
114 const string CRLF = "\r\n"; // Change here, expr-test.cc
115 const string BES_KEY_TIMEOUT_CANCEL = "BES.CancelTimeoutOnSend";
116 
122 {
123  bool found = false;
124  string cancel_timeout_on_send = "";
125  TheBESKeys::TheKeys()->get_value(BES_KEY_TIMEOUT_CANCEL, cancel_timeout_on_send, found);
126  if (found && !cancel_timeout_on_send.empty()) {
127  // The default value is false.
128  downcase(cancel_timeout_on_send);
129  if (cancel_timeout_on_send == "yes" || cancel_timeout_on_send == "true")
130  d_cancel_timeout_on_send = true;
131  }
132 }
133 
134 BESDapResponseBuilder::~BESDapResponseBuilder()
135 {
136 #if USE_LOCAL_TIMEOUT_SCHEME
137  // If an alarm was registered, delete it. The register code in SignalHandler
138  // always deletes the old alarm handler object, so only the one returned by
139  // remove_handler needs to be deleted at this point.
140  delete dynamic_cast<AlarmHandler*>(SignalHandler::instance()->remove_handler(SIGALRM));
141 #endif
142 }
143 
151 {
152  return d_dap2ce;
153 }
154 
166 {
167  d_dap2ce = www2id(_ce, "%", "%20");
168 }
169 
174 {
175  return d_dap4ce;
176 }
177 
189 {
190  d_dap4ce = www2id(_ce, "%", "%20");
191 }
192 
197 {
198  return d_dap4function;
199 }
200 
213 {
214  d_dap4function = www2id(_func, "%", "%20");
215 }
216 
217 std::string BESDapResponseBuilder::get_store_result() const
218 {
219  return d_store_result;
220 }
221 
222 void BESDapResponseBuilder::set_store_result(std::string _sr)
223 {
224  d_store_result = _sr;
225  BESDEBUG("dap", "BESDapResponseBuilder::set_store_result() - store_result: " << _sr << endl);
226 }
227 
228 std::string BESDapResponseBuilder::get_async_accepted() const
229 {
230  return d_async_accepted;
231 }
232 
233 void BESDapResponseBuilder::set_async_accepted(std::string _aa)
234 {
235  d_async_accepted = _aa;
236  BESDEBUG("dap", "BESDapResponseBuilder::set_async_accepted() - async_accepted: " << _aa << endl);
237 }
238 
248 {
249  return d_dataset;
250 }
251 
263 {
264  d_dataset = www2id(ds, "%", "%20");
265 }
266 
273 {
274  d_timeout = t;
275 }
276 
279 {
280  return d_timeout;
281 }
282 
289 void
291 {
292 #if USE_LOCAL_TIMEOUT_SCHEME
293 #ifndef WIN32
294  alarm(d_timeout);
295 #endif
296 #endif
297 }
298 
304 void
306 {
307 #if USE_LOCAL_TIMEOUT_SCHEME
308 #ifndef WIN32
309  alarm(0);
310 #endif
311 #endif
312 }
313 
329 {
330  if (d_cancel_timeout_on_send)
331  alarm(0);
332 }
333 
343 {
344 #if USE_LOCAL_TIMEOUT_SCHEME
345 #ifndef WIN32
346  SignalHandler *sh = SignalHandler::instance();
347  EventHandler *old_eh = sh->register_handler(SIGALRM, new AlarmHandler());
348  delete old_eh;
349 #endif
350 #endif
351 }
352 
353 
360 {
361 #if USE_LOCAL_TIMEOUT_SCHEME
362 #ifndef WIN32
363  if (d_timeout > 0) {
364  SignalHandler *sh = SignalHandler::instance();
365  EventHandler *old_eh = sh->register_handler(SIGALRM, new AlarmHandler());
366  delete old_eh;
367  alarm(d_timeout);
368  }
369 #endif
370 #endif
371 }
372 
387 static string::size_type find_closing_paren(const string &ce, string::size_type pos)
388 {
389  // Iterate over the string finding all ( or ) characters until the matching ) is found.
390  // For each ( found, increment count. When a ) is found and count is zero, it is the
391  // matching closing paren, otherwise, decrement count and keep looking.
392  int count = 1;
393  do {
394  pos = ce.find_first_of("()", pos + 1);
395  if (pos == string::npos)
396  throw Error(malformed_expr, "Expected to find a matching closing parenthesis in " + ce);
397 
398  if (ce[pos] == '(')
399  ++count;
400  else
401  --count; // must be ')'
402 
403  } while (count > 0);
404 
405  return pos;
406 }
407 
414 void BESDapResponseBuilder::split_ce(ConstraintEvaluator &eval, const string &expr)
415 {
416  BESDEBUG("dap", "BESDapResponseBuilder::split_ce() - source expression: " << expr << endl);
417 
418  string ce;
419  if (!expr.empty())
420  ce = expr;
421  else
422  ce = d_dap2ce;
423 
424  string btp_function_ce = "";
425  string::size_type pos = 0;
426 
427  // This hack assumes that the functions are listed first. Look for the first
428  // open paren and the last closing paren to accommodate nested function calls
429  string::size_type first_paren = ce.find("(", pos);
430  string::size_type closing_paren = string::npos;
431  if (first_paren != string::npos) closing_paren = find_closing_paren(ce, first_paren); //ce.find(")", pos);
432 
433  while (first_paren != string::npos && closing_paren != string::npos) {
434  // Maybe a BTP function; get the name of the potential function
435  string name = ce.substr(pos, first_paren - pos);
436 
437  // is this a BTP function
438  btp_func f;
439  if (eval.find_function(name, &f)) {
440  // Found a BTP function
441  if (!btp_function_ce.empty()) btp_function_ce += ",";
442  btp_function_ce += ce.substr(pos, closing_paren + 1 - pos);
443  ce.erase(pos, closing_paren + 1 - pos);
444  if (ce[pos] == ',') ce.erase(pos, 1);
445  }
446  else {
447  pos = closing_paren + 1;
448  // exception?
449  if (pos < ce.length() && ce.at(pos) == ',') ++pos;
450  }
451 
452  first_paren = ce.find("(", pos);
453  closing_paren = ce.find(")", pos);
454  }
455 
456  d_dap2ce = ce;
457  d_btp_func_ce = btp_function_ce;
458 
459  BESDEBUG("dap", "BESDapResponseBuilder::split_ce() - Modified constraint: " << d_dap2ce << endl);
460  BESDEBUG("dap", "BESDapResponseBuilder::split_ce() - BTP Function part: " << btp_function_ce << endl);
461  BESDEBUG("dap", "BESDapResponseBuilder::split_ce() - END" << endl);
462 }
463 
470 static void
471 throw_if_dap2_response_too_big(DDS *dds)
472 {
473  if (dds->get_response_limit() != 0 && ((dds->get_request_size(true)) > dds->get_response_limit())) {
474  string msg = "The Request for " + long_to_string(dds->get_request_size(true) / 1024)
475  + "KB is too large; requests on this server are limited to "
476  + long_to_string(dds->get_response_limit() /1024) + "KB.";
477  throw Error(msg);
478  }
479 }
480 
495 void BESDapResponseBuilder::send_das(ostream &out, DAS &das, bool with_mime_headers) const
496 {
497  if (with_mime_headers) set_mime_text(out, dods_das, x_plain, last_modified_time(d_dataset), "2.0");
498 
499  das.print(out);
500 
501  out << flush;
502 }
503 
521 void BESDapResponseBuilder::send_das(ostream &out, DDS **dds, ConstraintEvaluator &eval, bool constrained,
522  bool with_mime_headers)
523 {
524 #if USE_LOCAL_TIMEOUT_SCHEME
525  // Set up the alarm.
526  establish_timeout(out);
527  dds.set_timeout(d_timeout);
528 #endif
529  if (!constrained) {
530  if (with_mime_headers) set_mime_text(out, dods_das, x_plain, last_modified_time(d_dataset), "2.0");
531 
532  conditional_timeout_cancel();
533 
534  (*dds)->print_das(out);
535  out << flush;
536 
537  return;
538  }
539 
540  split_ce(eval);
541 
542  // If there are functions, parse them and eval.
543  // Use that DDS and parse the non-function ce
544  // Serialize using the second ce and the second dds
545  if (!d_btp_func_ce.empty()) {
546  ConstraintEvaluator func_eval;
547  BESDapFunctionResponseCache *responseCache = BESDapFunctionResponseCache::get_instance();
548 
549  DDS *fdds = 0; // nulll_ptr
550  if (responseCache && responseCache->can_be_cached(*dds, get_btp_func_ce())) {
551  fdds = responseCache->get_or_cache_dataset(*dds, get_btp_func_ce());
552  }
553  else {
554  func_eval.parse_constraint(get_btp_func_ce(), **dds);
555  fdds = func_eval.eval_function_clauses(**dds);
556  }
557 
558  delete *dds; *dds = 0;
559  *dds = fdds;
560 
561  if (with_mime_headers)
562  set_mime_text(out, dods_das, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
563 
564  conditional_timeout_cancel();
565 
566  (*dds)->print_das(out);
567  }
568  else {
569  eval.parse_constraint(d_dap2ce, **dds); // Throws Error if the ce doesn't parse.
570 
571  if (with_mime_headers)
572  set_mime_text(out, dods_das, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
573 
574  conditional_timeout_cancel();
575 
576  (*dds)->print_das(out);
577  }
578 
579  out << flush;
580 }
581 
582 
601 void BESDapResponseBuilder::send_dds(ostream &out, DDS **dds, ConstraintEvaluator &eval, bool constrained,
602  bool with_mime_headers)
603 {
604  if (!constrained) {
605  if (with_mime_headers)
606  set_mime_text(out, dods_dds, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
607 
608  conditional_timeout_cancel();
609 
610  (*dds)->print(out);
611  out << flush;
612  return;
613  }
614 
615 #if USE_LOCAL_TIMEOUT_SCHEME
616  // Set up the alarm.
617  establish_timeout(out);
618  dds.set_timeout(d_timeout);
619 #endif
620 
621  // Split constraint into two halves
622  split_ce(eval);
623 
624  // If there are functions, parse them and eval.
625  // Use that DDS and parse the non-function ce
626  // Serialize using the second ce and the second dds
627  if (!d_btp_func_ce.empty()) {
628  ConstraintEvaluator func_eval;
629 
630  BESDapFunctionResponseCache *responseCache = BESDapFunctionResponseCache::get_instance();
631 
632  DDS *fdds = 0; // nulll_ptr
633  if (responseCache && responseCache->can_be_cached(*dds, get_btp_func_ce())) {
634  fdds = responseCache->get_or_cache_dataset(*dds, get_btp_func_ce());
635  }
636  else {
637  func_eval.parse_constraint(get_btp_func_ce(), **dds);
638  fdds = func_eval.eval_function_clauses(**dds);
639  }
640 
641  delete *dds; *dds = 0;
642  *dds = fdds;
643 
644  // Server functions might mark variables to use their read()
645  // methods. Clear that so the CE in d_dap2ce will control what is
646  // sent. If that is empty (there was only a function call) all
647  // of the variables in the intermediate DDS (i.e., the function
648  // result) will be sent.
649  (*dds)->mark_all(false);
650 
651  // This next step utilizes a well known static method (so really it's a function;),
652  // promote_function_output_structures() to look for
653  // one or more top level Structures whose name indicates (by way of ending with
654  // "_uwrap") that their contents should be promoted (aka moved) to the top level.
655  // This is in support of a hack around the current API where server side functions
656  // may only return a single DAP object and not a collection of objects. The name suffix
657  // "_unwrap" is used as a signal from the function to the the various response
658  // builders and transmitters that the representation needs to be altered before
659  // transmission, and that in fact is what happens in our friend
660  // promote_function_output_structures()
661  promote_function_output_structures(*dds);
662 
663  eval.parse_constraint(d_dap2ce, **dds);
664 
665  if (with_mime_headers)
666  set_mime_text(out, dods_dds, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
667 
668 
669  conditional_timeout_cancel();
670 
671  (*dds)->print_constrained(out);
672  }
673  else {
674  eval.parse_constraint(d_dap2ce, **dds); // Throws Error if the ce doesn't parse.
675 
676  if (with_mime_headers)
677  set_mime_text(out, dods_dds, x_plain, last_modified_time(d_dataset),(*dds)->get_dap_version());
678 
679  conditional_timeout_cancel();
680 
681  (*dds)->print_constrained(out);
682  }
683 
684  out << flush;
685 }
686 
687 #ifdef DAP2_STORED_RESULTS
688 
702 bool BESDapResponseBuilder::store_dap2_result(ostream &out, DDS &dds, ConstraintEvaluator &eval)
703 {
704  if (get_store_result().empty()) return false;
705 
706  string serviceUrl = get_store_result();
707 
708  XMLWriter xmlWrtr;
709  D4AsyncUtil d4au;
710 
711  // FIXME Keys should be read in initialize(). Also, I think the D4AsyncUtil should
712  // be removed from libdap - it is much more about how the BES processes these kinds
713  // of operations. Change this when working on the response caching for ODSIP. But...
714  // do we really need to put the style sheet in the bes.conf file? Should it be baked
715  // into the code (because we don't want people to change it)?
716  bool found;
717  string *stylesheet_ref = 0, ss_ref_value;
718  TheBESKeys::TheKeys()->get_value(D4AsyncUtil::STYLESHEET_REFERENCE_KEY, ss_ref_value, found);
719  if (found && ss_ref_value.length() > 0) {
720  stylesheet_ref = &ss_ref_value;
721  }
722 
724  if (resultCache == NULL) {
725 
731  string msg = "The Stored Result request cannot be serviced. ";
732  msg += "Unable to acquire StoredResultCache instance. ";
733  msg += "This is most likely because the StoredResultCache is not (correctly) configured.";
734 
735  BESDEBUG("dap", "[WARNING] " << msg << endl);
736 
737  d4au.writeD4AsyncResponseRejected(xmlWrtr, UNAVAILABLE, msg, stylesheet_ref);
738  out << xmlWrtr.get_doc();
739  out << flush;
740 
741  BESDEBUG("dap", "BESDapResponseBuilder::store_dap2_result() - Sent AsyncRequestRejected" << endl);
742  }
743  else if (get_async_accepted().length() != 0) {
744 
748  BESDEBUG("dap", "BESDapResponseBuilder::store_dap2_result() - serviceUrl="<< serviceUrl << endl);
749 
751  string storedResultId = "";
752  storedResultId = resultCache->store_dap2_result(dds, get_ce(), this, &eval);
753 
754  BESDEBUG("dap",
755  "BESDapResponseBuilder::store_dap2_result() - storedResultId='"<< storedResultId << "'" << endl);
756 
757  string targetURL = BESUtil::assemblePath(serviceUrl, storedResultId);
758  BESDEBUG("dap", "BESDapResponseBuilder::store_dap2_result() - targetURL='"<< targetURL << "'" << endl);
759 
760  XMLWriter xmlWrtr;
761  d4au.writeD4AsyncAccepted(xmlWrtr, 0, 0, targetURL, stylesheet_ref);
762  out << xmlWrtr.get_doc();
763  out << flush;
764 
765  BESDEBUG("dap", "BESDapResponseBuilder::store_dap2_result() - sent DAP4 AsyncAccepted response" << endl);
766  }
767  else {
772  d4au.writeD4AsyncRequired(xmlWrtr, 0, 0, stylesheet_ref);
773  out << xmlWrtr.get_doc();
774  out << flush;
775 
776  BESDEBUG("dap", "BESDapResponseBuilder::store_dap2_result() - sent DAP4 AsyncRequired response" << endl);
777  }
778 
779  return true;
780 
781 }
782 #endif
783 
787 void BESDapResponseBuilder::serialize_dap2_data_dds(ostream &out, DDS **dds, ConstraintEvaluator &eval, bool ce_eval)
788 {
789  BESStopWatch sw;
790  if (BESISDEBUG(TIMING_LOG)) sw.start("BESDapResponseBuilder::serialize_dap2_data_dds", "");
791 
792  BESDEBUG("dap", "BESDapResponseBuilder::serialize_dap2_data_dds() - BEGIN" << endl);
793 
794  (*dds)->print_constrained(out);
795  out << "Data:\n";
796  out << flush;
797 
798  XDRStreamMarshaller m(out);
799 
800  // This only has an effect when the timeout in BESInterface::execute_request()
801  // is set. Otherwise it does nothing.
802  conditional_timeout_cancel();
803 
804  // Send all variables in the current projection (send_p())
805  for (DDS::Vars_iter i = (*dds)->var_begin(); i != (*dds)->var_end(); i++) {
806  if ((*i)->send_p()) {
807  (*i)->serialize(eval, **dds, m, ce_eval);
808 #ifdef CLEAR_LOCAL_DATA
809  (*i)->clear_local_data();
810 #endif
811  }
812  }
813 
814  BESDEBUG("dap", "BESDapResponseBuilder::serialize_dap2_data_dds() - END" << endl);
815 }
816 
817 #ifdef DAP2_STORED_RESULTS
818 
826 void BESDapResponseBuilder::serialize_dap2_data_ddx(ostream &out, DDS **dds, ConstraintEvaluator &eval,
827  const string &boundary, const string &start, bool ce_eval)
828 {
829  BESDEBUG("dap", __PRETTY_FUNCTION__ << " BEGIN" << endl);
830 
831  // Write the MPM headers for the DDX (text/xml) part of the response
832  libdap::set_mime_ddx_boundary(out, boundary, start, dods_ddx, x_plain);
833 
834  // Make cid
835  uuid_t uu;
836  uuid_generate(uu);
837  char uuid[37];
838  uuid_unparse(uu, &uuid[0]);
839  char domain[256];
840  if (getdomainname(domain, 255) != 0 || strlen(domain) == 0) strncpy(domain, "opendap.org", 255);
841 
842  string cid = string(&uuid[0]) + "@" + string(&domain[0]);
843 
844  // Send constrained DDX with a data blob reference.
845  // Note: CID passed but ignored jhrg 10/20/15
846  (*dds)->print_xml_writer(out, true, cid);
847 
848  // write the data part mime headers here
849  set_mime_data_boundary(out, boundary, cid, dods_data_ddx /* old value dap4_data*/, x_plain);
850 
851  XDRStreamMarshaller m(out);
852 
853  conditional_timeout_cancel();
854 
855 
856  // Send all variables in the current projection (send_p()).
857  for (DDS::Vars_iter i = (*dds)->var_begin(); i != (*dds)->var_end(); i++) {
858  if ((*i)->send_p()) {
859  (*i)->serialize(eval, **dds, m, ce_eval);
860 #ifdef CLEAR_LOCAL_DATA
861  (*i)->clear_local_data();
862 #endif
863  }
864  }
865 
866  BESDEBUG("dap", __PRETTY_FUNCTION__ << " END" << endl);
867 }
868 #endif
869 
887 {
888 #if USE_LOCAL_TIMEOUT_SCHEME
889  alarm(0);
890 #endif
891 }
892 
906 libdap::DDS *
908 {
909  BESDEBUG("dap", "BESDapResponseBuilder::process_dap2_dds() - BEGIN"<< endl);
910 
911  dhi.first_container();
912 
913  BESDDSResponse *bdds = dynamic_cast<BESDDSResponse *>(obj);
914  if (!bdds) throw BESInternalFatalError("Expected a BESDDSResponse instance", __FILE__, __LINE__);
915 
916  DDS *dds = bdds->get_dds();
917 
918  set_dataset_name(dds->filename());
919  set_ce(dhi.data[POST_CONSTRAINT]);
920  set_async_accepted(dhi.data[ASYNC]);
921  set_store_result(dhi.data[STORE_RESULT]);
922 
923  ConstraintEvaluator &eval = bdds->get_ce();
924 
925  // Split constraint into two halves
926  split_ce(eval);
927 
928  // If there are functions, parse them and eval.
929  // Use that DDS and parse the non-function ce
930  // Serialize using the second ce and the second dds
931  if (!d_btp_func_ce.empty()) {
932  BESDapFunctionResponseCache *responseCache = BESDapFunctionResponseCache::get_instance();
933 
934  ConstraintEvaluator func_eval;
935  DDS *fdds = 0; // nulll_ptr
936  if (responseCache && responseCache->can_be_cached(dds, get_btp_func_ce())) {
937  fdds = responseCache->get_or_cache_dataset(dds, get_btp_func_ce());
938  }
939  else {
940  func_eval.parse_constraint(get_btp_func_ce(), *dds);
941  fdds = func_eval.eval_function_clauses(*dds);
942  }
943 
944  delete dds; // Delete so that we can ...
945  bdds->set_dds(fdds); // Transfer management responsibility
946  dds = fdds;
947 
948  dds->mark_all(false);
949 
950  promote_function_output_structures(dds);
951  }
952 
953  eval.parse_constraint(d_dap2ce, *dds); // Throws Error if the ce doesn't parse.
954 
955  return dds;
956 }
957 
975 libdap::DDS *
977 {
978  BESDEBUG("dap", "BESDapResponseBuilder::intern_dap2_data() - BEGIN"<< endl);
979 
980  dhi.first_container();
981 
982  BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj);
983  if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance", __FILE__, __LINE__);
984 
985  DDS *dds = bdds->get_dds();
986 
987  set_dataset_name(dds->filename());
988  set_ce(dhi.data[POST_CONSTRAINT]);
989  set_async_accepted(dhi.data[ASYNC]);
990  set_store_result(dhi.data[STORE_RESULT]);
991 
992  ConstraintEvaluator &eval = bdds->get_ce();
993 
994  // Split constraint into two halves; stores the function and non-function parts in this instance.
995  split_ce(eval);
996 
997  // If there are functions, parse them and eval.
998  // Use that DDS and parse the non-function ce
999  // Serialize using the second ce and the second dds
1000  if (!get_btp_func_ce().empty()) {
1001  BESDEBUG("dap",
1002  "BESDapResponseBuilder::intern_dap2_data() - Found function(s) in CE: " << get_btp_func_ce() << endl);
1003 
1004  BESDapFunctionResponseCache *responseCache = BESDapFunctionResponseCache::get_instance();
1005 
1006  ConstraintEvaluator func_eval;
1007  DDS *fdds = 0; // nulll_ptr
1008  if (responseCache && responseCache->can_be_cached(dds, get_btp_func_ce())) {
1009  fdds = responseCache->get_or_cache_dataset(dds, get_btp_func_ce());
1010  }
1011  else {
1012  func_eval.parse_constraint(get_btp_func_ce(), *dds);
1013  fdds = func_eval.eval_function_clauses(*dds);
1014  }
1015 
1016  delete dds; // Delete so that we can ...
1017  bdds->set_dds(fdds); // Transfer management responsibility
1018  dds = fdds;
1019 
1020  // Server functions might mark (i.e. setting send_p) so variables will use their read()
1021  // methods. Clear that so the CE in d_dap2ce will control what is
1022  // sent. If that is empty (there was only a function call) all
1023  // of the variables in the intermediate DDS (i.e., the function
1024  // result) will be sent.
1025  dds->mark_all(false);
1026 
1027  // Look for one or more top level Structures whose name indicates (by way of ending with
1028  // "_uwrap") that their contents should be moved to the top level.
1029  //
1030  // This is in support of a hack around the current API where server side functions
1031  // may only return a single DAP object and not a collection of objects. The name suffix
1032  // "_unwrap" is used as a signal from the function to the the various response
1033  // builders and transmitters that the representation needs to be altered before
1034  // transmission, and that in fact is what happens in our friend
1035  // promote_function_output_structures()
1036  promote_function_output_structures(dds);
1037  }
1038 
1039  // evaluate the rest of the CE - the part that follows the function calls.
1040  eval.parse_constraint(get_ce(), *dds);
1041 
1042  dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
1043 
1044  throw_if_dap2_response_too_big(dds);
1045 
1046  // Iterate through the variables in the DataDDS and read
1047  // in the data if the variable has the send flag set.
1048  for (DDS::Vars_iter i = dds->var_begin(), e = dds->var_end(); i != e; ++i) {
1049  if ((*i)->send_p()) {
1050  (*i)->intern_data(eval, *dds);
1051  }
1052  }
1053 
1054  BESDEBUG("dap", "BESDapResponseBuilder::intern_dap2_data() - END"<< endl);
1055 
1056  return dds;
1057 }
1058 
1059 
1072 void BESDapResponseBuilder::send_dap2_data(ostream &data_stream, DDS **dds, ConstraintEvaluator &eval,
1073  bool with_mime_headers)
1074 {
1075  BESDEBUG("dap", "BESDapResponseBuilder::send_dap2_data() - BEGIN"<< endl);
1076 
1077 #if USE_LOCAL_TIMEOUT_SCHEME
1078  // Set up the alarm.
1079  establish_timeout(data_stream);
1080  dds.set_timeout(d_timeout);
1081 #endif
1082 
1083  // Split constraint into two halves
1084  split_ce(eval);
1085 
1086  // If there are functions, parse them and eval.
1087  // Use that DDS and parse the non-function ce
1088  // Serialize using the second ce and the second dds
1089  if (!get_btp_func_ce().empty()) {
1090  BESDEBUG("dap",
1091  "BESDapResponseBuilder::send_dap2_data() - Found function(s) in CE: " << get_btp_func_ce() << endl);
1092 
1093  BESDapFunctionResponseCache *response_cache = BESDapFunctionResponseCache::get_instance();
1094 
1095  ConstraintEvaluator func_eval;
1096  DDS *fdds = 0; // nulll_ptr
1097  if (response_cache && response_cache->can_be_cached(*dds, get_btp_func_ce())) {
1098  fdds = response_cache->get_or_cache_dataset(*dds, get_btp_func_ce());
1099  }
1100  else {
1101  func_eval.parse_constraint(get_btp_func_ce(), **dds);
1102  fdds = func_eval.eval_function_clauses(**dds);
1103  }
1104 
1105  delete *dds; *dds = 0;
1106  *dds = fdds;
1107 
1108  (*dds)->mark_all(false);
1109 
1110  promote_function_output_structures(*dds);
1111 
1112  // evaluate the rest of the CE - the part that follows the function calls.
1113  eval.parse_constraint(get_ce(), **dds);
1114 
1115  (*dds)->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
1116 
1117  throw_if_dap2_response_too_big(*dds);
1118 
1119  if (with_mime_headers)
1120  set_mime_binary(data_stream, dods_data, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
1121 
1122 #if STORE_DAP2_RESULT_FEATURE
1123  // This means: if we are not supposed to store the result, then serialize it.
1124  if (!store_dap2_result(data_stream, **dds, eval)) {
1125  serialize_dap2_data_dds(data_stream, dds, eval, true /* was 'false'. jhrg 3/10/15 */);
1126  }
1127 #else
1128  serialize_dap2_data_dds(data_stream, dds, eval, true /* was 'false'. jhrg 3/10/15 */);
1129 #endif
1130 
1131  }
1132  else {
1133  BESDEBUG("dap", "BESDapResponseBuilder::send_dap2_data() - Simple constraint" << endl);
1134 
1135  eval.parse_constraint(get_ce(), **dds); // Throws Error if the ce doesn't parse.
1136 
1137  (*dds)->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node.
1138 
1139  throw_if_dap2_response_too_big(*dds);
1140 
1141  if (with_mime_headers)
1142  set_mime_binary(data_stream, dods_data, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
1143 
1144 #if STORE_DAP2_RESULT_FEATURE
1145  // This means: if we are not supposed to store the result, then serialize it.
1146  if (!store_dap2_result(data_stream, **dds, eval)) {
1147  serialize_dap2_data_dds(data_stream, dds, eval);
1148  }
1149 #else
1150  serialize_dap2_data_dds(data_stream, dds, eval);
1151 #endif
1152  }
1153 
1154  data_stream << flush;
1155 
1156  BESDEBUG("dap", "BESDapResponseBuilder::send_dap2_data() - END"<< endl);
1157 
1158 }
1159 
1160 
1174 void BESDapResponseBuilder::send_ddx(ostream &out, DDS **dds, ConstraintEvaluator &eval, bool with_mime_headers)
1175 {
1176  if (d_dap2ce.empty()) {
1177  if (with_mime_headers)
1178  set_mime_text(out, dods_ddx, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
1179 
1180  (*dds)->print_xml_writer(out, false /*constrained */, "");
1181  //dds.print(out);
1182  out << flush;
1183  return;
1184  }
1185 
1186 #if USE_LOCAL_TIMEOUT_SCHEME
1187  // Set up the alarm.
1188  establish_timeout(out);
1189  dds.set_timeout(d_timeout);
1190 #endif
1191 
1192  // Split constraint into two halves
1193  split_ce(eval);
1194 
1195  // If there are functions, parse them and eval.
1196  // Use that DDS and parse the non-function ce
1197  // Serialize using the second ce and the second dds
1198  if (!d_btp_func_ce.empty()) {
1199  BESDapFunctionResponseCache *response_cache = BESDapFunctionResponseCache::get_instance();
1200 
1201  ConstraintEvaluator func_eval;
1202  DDS *fdds = 0; // nulll_ptr
1203  if (response_cache && response_cache->can_be_cached(*dds, get_btp_func_ce())) {
1204  fdds = response_cache->get_or_cache_dataset(*dds, get_btp_func_ce());
1205  }
1206  else {
1207  func_eval.parse_constraint(get_btp_func_ce(), **dds);
1208  fdds = func_eval.eval_function_clauses(**dds);
1209  }
1210 
1211  delete *dds; *dds = 0;
1212  *dds = fdds;
1213 
1214  (*dds)->mark_all(false);
1215 
1216  promote_function_output_structures(*dds);
1217 
1218  eval.parse_constraint(d_dap2ce, **dds);
1219 
1220  if (with_mime_headers)
1221  set_mime_text(out, dods_ddx, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
1222 
1223  conditional_timeout_cancel();
1224 
1225  (*dds)->print_xml_writer(out, true, "");
1226  }
1227  else {
1228  eval.parse_constraint(d_dap2ce, **dds); // Throws Error if the ce doesn't parse.
1229 
1230  if (with_mime_headers)
1231  set_mime_text(out, dods_ddx, x_plain, last_modified_time(d_dataset), (*dds)->get_dap_version());
1232 
1233  conditional_timeout_cancel();
1234 
1235 
1236  // dds.print_constrained(out);
1237  (*dds)->print_xml_writer(out, true, "");
1238  }
1239 
1240  out << flush;
1241 }
1242 
1243 void BESDapResponseBuilder::send_dmr(ostream &out, DMR &dmr, bool with_mime_headers)
1244 {
1245  // If the CE is not empty, parse it. The projections, etc., are set as a side effect.
1246  // If the parser returns false, the expression did not parse. The parser may also
1247  // throw Error
1248  if (!d_dap4ce.empty()) {
1249 
1250  BESDEBUG("dap", "BESDapResponseBuilder::send_dmr() - Parsing DAP4 constraint: '"<< d_dap4ce << "'"<< endl);
1251 
1252  D4ConstraintEvaluator parser(&dmr);
1253  bool parse_ok = parser.parse(d_dap4ce);
1254  if (!parse_ok) throw Error(malformed_expr, "Constraint Expression (" + d_dap4ce + ") failed to parse.");
1255  }
1256  // with an empty CE, send everything. Even though print_dap4() and serialize()
1257  // don't need this, other code may depend on send_p being set. This may change
1258  // if DAP4 has a separate function evaluation phase. jhrg 11/25/13
1259  else {
1260  dmr.root()->set_send_p(true);
1261  }
1262 
1263  if (with_mime_headers) set_mime_text(out, dap4_dmr, x_plain, last_modified_time(d_dataset), dmr.dap_version());
1264 
1265  conditional_timeout_cancel();
1266 
1267 
1268  XMLWriter xml;
1269  dmr.print_dap4(xml, /*constrained &&*/!d_dap4ce.empty() /* true == constrained */);
1270  out << xml.get_doc() << flush;
1271 }
1272 
1273 void BESDapResponseBuilder::send_dap4_data_using_ce(ostream &out, DMR &dmr, bool with_mime_headers)
1274 {
1275  if (!d_dap4ce.empty()) {
1276  D4ConstraintEvaluator parser(&dmr);
1277  bool parse_ok = parser.parse(d_dap4ce);
1278  if (!parse_ok) throw Error(malformed_expr, "Constraint Expression (" + d_dap4ce + ") failed to parse.");
1279  }
1280  // with an empty CE, send everything. Even though print_dap4() and serialize()
1281  // don't need this, other code may depend on send_p being set. This may change
1282  // if DAP4 has a separate function evaluation phase. jhrg 11/25/13
1283  else {
1284  dmr.root()->set_send_p(true);
1285  }
1286 
1287  if (dmr.response_limit() != 0 && (dmr.request_size(true) > dmr.response_limit())) {
1288  string msg = "The Request for " + long_to_string(dmr.request_size(true))
1289  + "KB is too large; requests for this server are limited to " + long_to_string(dmr.response_limit())
1290  + "KB.";
1291  throw Error(msg);
1292  }
1293 
1294  if (!store_dap4_result(out, dmr)) {
1295  serialize_dap4_data(out, dmr, with_mime_headers);
1296  }
1297 }
1298 
1299 void BESDapResponseBuilder::send_dap4_data(ostream &out, DMR &dmr, bool with_mime_headers)
1300 {
1301  // If a function was passed in with this request, evaluate it and use that DMR
1302  // for the remainder of this request.
1303  // TODO Add caching for these function invocations
1304  if (!d_dap4function.empty()) {
1305  D4BaseTypeFactory d4_factory;
1306  DMR function_result(&d4_factory, "function_results");
1307 
1308  // Function modules load their functions onto this list. The list is
1309  // part of libdap, not the BES.
1310  if (!ServerFunctionsList::TheList())
1311  throw Error(
1312  "The function expression could not be evaluated because there are no server functions defined on this server");
1313 
1314  D4FunctionEvaluator parser(&dmr, ServerFunctionsList::TheList());
1315  bool parse_ok = parser.parse(d_dap4function);
1316  if (!parse_ok) throw Error("Function Expression (" + d_dap4function + ") failed to parse.");
1317 
1318  parser.eval(&function_result);
1319 
1320  // Now use the results of running the functions for the remainder of the
1321  // send_data operation.
1322  send_dap4_data_using_ce(out, function_result, with_mime_headers);
1323  }
1324  else {
1325  send_dap4_data_using_ce(out, dmr, with_mime_headers);
1326  }
1327 }
1328 
1332 void BESDapResponseBuilder::serialize_dap4_data(std::ostream &out, libdap::DMR &dmr, bool with_mime_headers)
1333 {
1334  BESDEBUG("dap", "BESDapResponseBuilder::serialize_dap4_data() - BEGIN" << endl);
1335 
1336  if (with_mime_headers) set_mime_binary(out, dap4_data, x_plain, last_modified_time(d_dataset), dmr.dap_version());
1337 
1338  // Write the DMR
1339  XMLWriter xml;
1340  dmr.print_dap4(xml, !d_dap4ce.empty());
1341 
1342  // now make the chunked output stream; set the size to be at least chunk_size
1343  // but make sure that the whole of the xml plus the CRLF can fit in the first
1344  // chunk. (+2 for the CRLF bytes).
1345  chunked_ostream cos(out, max((unsigned int) CHUNK_SIZE, xml.get_doc_size() + 2));
1346 
1347  conditional_timeout_cancel();
1348 
1349  // using flush means that the DMR and CRLF are in the first chunk.
1350  cos << xml.get_doc() << CRLF << flush;
1351 
1352  // Write the data, chunked with checksums
1353  D4StreamMarshaller m(cos);
1354  dmr.root()->serialize(m, dmr, !d_dap4ce.empty());
1355 #ifdef CLEAR_LOCAL_DATA
1356  dmr.root()->clear_local_data();
1357 #endif
1358  cos << flush;
1359 
1360  BESDEBUG("dap", "BESDapResponseBuilder::serialize_dap4_data() - END" << endl);
1361 }
1362 
1377 bool BESDapResponseBuilder::store_dap4_result(ostream &out, libdap::DMR &dmr)
1378 {
1379  if (get_store_result().length() != 0) {
1380  string serviceUrl = get_store_result();
1381 
1382  D4AsyncUtil d4au;
1383  XMLWriter xmlWrtr;
1384 
1385  // FIXME See above comment for store dap2 result
1386  bool found;
1387  string *stylesheet_ref = 0, ss_ref_value;
1388  TheBESKeys::TheKeys()->get_value(D4AsyncUtil::STYLESHEET_REFERENCE_KEY, ss_ref_value, found);
1389  if (found && ss_ref_value.length() > 0) {
1390  stylesheet_ref = &ss_ref_value;
1391  }
1392 
1394  if (resultCache == NULL) {
1395 
1401  string msg = "The Stored Result request cannot be serviced. ";
1402  msg += "Unable to acquire StoredResultCache instance. ";
1403  msg += "This is most likely because the StoredResultCache is not (correctly) configured.";
1404 
1405  BESDEBUG("dap", "[WARNING] " << msg << endl);
1406  d4au.writeD4AsyncResponseRejected(xmlWrtr, UNAVAILABLE, msg, stylesheet_ref);
1407  out << xmlWrtr.get_doc();
1408  out << flush;
1409  BESDEBUG("dap", "BESDapResponseBuilder::store_dap4_result() - Sent AsyncRequestRejected" << endl);
1410 
1411  return true;
1412  }
1413 
1414  if (get_async_accepted().length() != 0) {
1415 
1419  BESDEBUG("dap", "BESDapResponseBuilder::store_dap4_result() - serviceUrl="<< serviceUrl << endl);
1420 
1421  string storedResultId = "";
1422  storedResultId = resultCache->store_dap4_result(dmr, get_ce(), this);
1423 
1424  BESDEBUG("dap",
1425  "BESDapResponseBuilder::store_dap4_result() - storedResultId='"<< storedResultId << "'" << endl);
1426 
1427  string targetURL = BESUtil::assemblePath(serviceUrl, storedResultId);
1428  BESDEBUG("dap", "BESDapResponseBuilder::store_dap4_result() - targetURL='"<< targetURL << "'" << endl);
1429 
1430  d4au.writeD4AsyncAccepted(xmlWrtr, 0, 0, targetURL, stylesheet_ref);
1431  out << xmlWrtr.get_doc();
1432  out << flush;
1433  BESDEBUG("dap", "BESDapResponseBuilder::store_dap4_result() - sent AsyncAccepted" << endl);
1434 
1435  }
1436  else {
1441  d4au.writeD4AsyncRequired(xmlWrtr, 0, 0, stylesheet_ref);
1442  out << xmlWrtr.get_doc();
1443  out << flush;
1444  BESDEBUG("dap", "BESDapResponseBuilder::store_dap4_result() - sent AsyncAccepted" << endl);
1445  }
1446 
1447  return true;
1448  }
1449 
1450  return false;
1451 }
void set_dds(libdap::DDS *ddsIn)
virtual libdap::DDS * intern_dap2_data(BESResponseObject *obj, BESDataHandlerInterface &dhi)
exception thrown if an internal error is found and is fatal to the BES
Holds a DDS object within the BES.
void set_dds(libdap::DDS *ddsIn)
libdap::DDS * get_dds()
virtual void send_dds(std::ostream &out, libdap::DDS **dds, libdap::ConstraintEvaluator &eval, bool constrained=false, bool with_mime_headers=true)
Transmit a DDS.
virtual string store_dap4_result(libdap::DMR &dmr, const string &constraint, BESDapResponseBuilder *rb)
void get_value(const std::string &s, std::string &val, bool &found)
Retrieve the value of a given key, if set.
Definition: TheBESKeys.cc:420
virtual bool start(string name)
Definition: BESStopWatch.cc:57
virtual void serialize_dap2_data_dds(std::ostream &out, libdap::DDS **dds, libdap::ConstraintEvaluator &eval, bool ce_eval=true)
virtual std::string get_dataset_name() const
Get the dataset name.
static TheBESKeys * TheKeys()
Definition: TheBESKeys.cc:61
virtual void remove_timeout() const
Transmit data.
static BESStoredDapResultCache * get_instance()
virtual libdap::DDS * get_or_cache_dataset(libdap::DDS *dds, const std::string &constraint)
Return a DDS loaded with data that can be serialized back to a client.
libdap::ConstraintEvaluator & get_ce()
virtual void split_ce(libdap::ConstraintEvaluator &eval, const std::string &expr="")
virtual void establish_timeout(std::ostream &stream) const
Represents an OPeNDAP DataDDS DAP2 data object within the BES.
void set_timeout(int timeout=0)
virtual void set_dataset_name(const std::string _dataset)
Set the dataset pathname.
virtual void set_dap4function(std::string _func)
Structure storing information used by the BES to handle the request.
map< string, string > data
the map of string data that will be required for the current request.
virtual std::string get_ce() const
Get the constraint expression.
virtual void send_dap2_data(std::ostream &data_stream, libdap::DDS **dds, libdap::ConstraintEvaluator &eval, bool with_mime_headers=true)
virtual std::string get_dap4function() const
Get the DAP4 server side function expression.
void first_container()
set the container pointer to the first container in the containers list
virtual void set_ce(std::string _ce)
Cache the results from server functions.
Abstract base class representing a specific set of information in response to a request to the BES.
virtual void send_ddx(std::ostream &out, libdap::DDS **dds, libdap::ConstraintEvaluator &eval, bool with_mime_headers=true)
virtual bool store_dap4_result(ostream &out, libdap::DMR &dmr)
virtual std::string get_dap4ce() const
Get the DAP4 constraint expression.
virtual void set_dap4ce(std::string _ce)
static string assemblePath(const string &firstPart, const string &secondPart, bool leadingSlash=false, bool trailingSlash=false)
Assemble path fragments making sure that they are separated by a single '/' character.
Definition: BESUtil.cc:818
virtual void serialize_dap4_data(std::ostream &out, libdap::DMR &dmr, bool with_mime_headers=true)
virtual libdap::DDS * process_dap2_dds(BESResponseObject *obj, BESDataHandlerInterface &dhi)
Process a DDS (i.e., apply a constraint) for a non-DAP transmitter.