NCBI C++ ToolKit
grid_cgi_sample.cpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /* $Id: grid_cgi_sample.cpp 90001 2020-05-04 12:53:02Z ivanov $
2  * ===========================================================================
3  *
4  * PUBLIC DOMAIN NOTICE
5  * National Center for Biotechnology Information
6  *
7  * This software/database is a "United States Government Work" under the
8  * terms of the United States Copyright Act. It was written as part of
9  * the author's official duties as a United States Government employee and
10  * thus cannot be copyrighted. This software/database is freely available
11  * to the public for use. The National Library of Medicine and the U.S.
12  * Government have not placed any restriction on its use or reproduction.
13  *
14  * Although all reasonable efforts have been taken to ensure the accuracy
15  * and reliability of the software and data, the NLM and the U.S.
16  * Government do not and cannot warrant the performance or results that
17  * may be obtained by using this software or data. The NLM and the U.S.
18  * Government disclaim all warranties, express or implied, including
19  * warranties of performance, merchantability or fitness for any particular
20  * purpose.
21  *
22  * Please cite the author in any work or product based on this material.
23  *
24  * ===========================================================================
25  *
26  * Author: Maxim Didenko
27  *
28  * File Description:
29  *
30  */
31 
32 #include <ncbi_pch.hpp>
33 #include <corelib/ncbistr.hpp>
34 #include <cgi/cgiapp.hpp>
35 #include <cgi/cgictx.hpp>
37 #include <html/commentdiag.hpp>
38 #include <html/html.hpp>
39 #include <html/page.hpp>
40 
42 
43 #include <vector>
44 
46 
47 
48 /////////////////////////////////////////////////////////////////////////////
49 // CGridCgiSampleApplication::
50 //
51 
53 {
54 public:
55  virtual void Init(void);
56  virtual string GetProgramVersion(void) const
57  {
58  // Next formats are valid and supported:
59  // ProgramName 1.2.3
60  // ProgramName version 1.2.3
61  // ProgramName v. 1.2.3
62  // ProgramName ver. 1.2.3
63 
64  return "SampleNodeCgiClient version 1.0.1";
65  }
66 
67 protected:
68 
69  // Render the job input parameters HTML page
70  virtual void ShowParamsPage(CGridCgiContext& ctx) const;
71 
72  // Collect parameters from the HTML page.
73  virtual bool CollectParams(CGridCgiContext&);
74 
75  // Prepare the job's input data
76  virtual void PrepareJobData(CGridClient& grid_client);
77 
78  // Show an information page
79  virtual void OnJobSubmitted(CGridCgiContext& ctx);
80 
81  // Get the job's result.
82  virtual void OnJobDone(CGridClient& grid_client, CGridCgiContext& ctx);
83 
84  // Report the job's failure.
85  virtual void OnJobFailed(const string& msg, CGridCgiContext& ctx);
86 
87  // Report when the job is canceled
88  virtual void OnJobCanceled(CGridCgiContext& ctx);
89 
90  virtual void OnJobPending(CGridCgiContext& ctx);
91 
92  virtual void OnJobRunning(CGridCgiContext& ctx);
93 
94  // Return job cancellation status.
95  virtual bool JobStopRequested(void) const;
96 
98 
99  // Get the HTML page title.
100  virtual string GetPageTitle() const;
101 
102  // Get the HTML page template file.
103  virtual string GetPageTemplate() const;
104 
105 private:
106  // This function just demonstrate the use of cmd-line argument parsing
107  // mechanism in CGI application -- for the processing of both cmd-line
108  // arguments and HTTP entries
109  void x_SetupArgs(void);
110 
111  // Just a helper function
112  static string VectorToString( const vector<double>& vec);
113  vector<double> m_Doubles;
114 
115 };
116 
117 
118 /////////////////////////////////////////////////////////////////////////////
119 // CGridCgiSampleApplication::
120 //
121 
123 {
124  return "Grid Sample CGI";
125 }
126 
127 
129 {
130  return "grid_cgi_sample.html";
131 }
132 
133 
135 {
136  // Standard CGI framework initialization
138 
139  // Allows CGI client to put the diagnostics to:
140  // HTML body (as comments) -- using CGI arg "&diag-destination=comments"
141  RegisterDiagFactory("comments", new CCommentDiagFactory);
142  // E-mail -- using CGI arg "&diag-destination=email:user@host"
144 
145  // Describe possible cmd-line and HTTP entries
146  // (optional)
147  x_SetupArgs();
148 }
149 
150 
152 {
153  CHTMLText* inp_text = new CHTMLText(
154  "<p>Enter your Input doubles here: "
155  "<INPUT TYPE=\"text\" NAME=\"message\" VALUE=\"\"><p>"
156  "<INPUT TYPE=\"submit\" NAME=\"SUBMIT\" VALUE=\"Submit\">"
157  "<INPUT TYPE=\"reset\" VALUE=\"Reset\">" );
158  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
159 }
160 
161 
163 {
164  // You can catch CArgException& here to process argument errors,
165  // or you can handle it in OnException()
166  const CArgs& args = GetArgs();
167 
168  // "args" now contains both command line arguments and the arguments
169  // extracted from the HTTP request
170 
171  if ( args["message"] ) {
172  // get the first "message" argument only...
173  const string& m = args["message"].AsString();
174  vector<string> sdoubles;
175  NStr::Split(m, " ", sdoubles);
176  for (auto sd : sdoubles) {
177  try {
179  m_Doubles.push_back(d);
180  }
181  catch(...) {}
182  }
183  } else {
184  // no "message" argument is present
185  }
186  return m_Doubles.size() > 1;
187 }
188 
189 
191 {
192  CNcbiOstream& os = grid_client.GetOStream();
193  // Send jobs input data
194  os << "doubles "; // request output type just a list of doubles
195  os << m_Doubles.size() << ' ';
196  for (auto d : m_Doubles) {
197  os << d << ' ';
198  }
199 }
200 
201 
203 {
204  // Render a report page
205  CHTMLText* inp_text = new CHTMLText(
206  "<p/>Input Data : <@INPUT_DATA@><br/>"
207  "<INPUT TYPE=\"submit\" NAME=\"Check Status\" VALUE=\"Check Status\">");
208  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
210  ctx.GetHTMLPage().AddTagMap("INPUT_DATA", idoubles);
211 }
212 
213 
215 {
216  CNcbiIstream& is = grid_client.GetIStream();
217  int count;
218 
219  // Get the result
220  m_Doubles.clear();
221  is >> count;
222  for (int i = 0; i < count; ++i) {
223  if (!is.good()) {
224  ERR_POST( "Input stream error. Index : " << i );
225  break;
226  }
227  double d;
228  is >> d;
229  m_Doubles.push_back(d);
230  }
231 
232  // Render the result page
233  CHTMLText* inp_text = new CHTMLText(
234  "<p/>Job is done.<br/>"
235  "<p>Result received : <@OUTPUT_DATA@> <br/>"
236  "<INPUT TYPE=\"submit\" NAME=\"Submit new Data\" "
237  "VALUE=\"Submit new Data\">");
238  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
240  ctx.GetHTMLPage().AddTagMap("OUTPUT_DATA",idoubles);
241 }
242 
243 
245 {
246  // Render a error page
247  CHTMLText* inp_text = new CHTMLText(
248  "<p/>Job failed.<br/>"
249  "Error Message : <@MSG@><br/>"
250  "<INPUT TYPE=\"submit\" NAME=\"Submit new Data\" "
251  "VALUE=\"Submit new Data\">");
252  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
253  CHTMLPlainText* err = new CHTMLPlainText(msg);
254  ctx.GetHTMLPage().AddTagMap("MSG",err);
255 }
256 
257 
259 {
260  // Render a job cancellation page
261  CHTMLText* inp_text = new CHTMLText(
262  "<p/>Job is canceled.<br/>"
263  "<INPUT TYPE=\"submit\" NAME=\"Submit new Data\" "
264  "VALUE=\"Submit new Data\">");
265 
266  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
267 }
268 
269 
271 {
272  // Render a status report page
273  CHTMLText* inp_text = new CHTMLText(
274  "<p/>Job is still in a queue...<br/>"
275  "<INPUT TYPE=\"submit\" NAME=\"Check Status\" VALUE=\"Check\">"
276  "<INPUT TYPE=\"submit\" NAME=\"Cancel\" "
277  "VALUE=\"Cancel the job\">");
278  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
279 }
280 
281 
283 {
284  // Render a status report page
285  CHTMLText* inp_text = new CHTMLText(
286  "<p/>Job is still running.<br/>"
287  "Progress message: <@PROGRESS_MSG@><br/>"
288  "<INPUT TYPE=\"submit\" NAME=\"Check Status\" VALUE=\"Check\">"
289  "<INPUT TYPE=\"submit\" NAME=\"Cancel\" "
290  "VALUE=\"Cancel the job\">");
291  ctx.GetHTMLPage().AddTagMap("VIEW", inp_text);
292  CHTMLText* proress_text = new CHTMLText(ctx.GetJobProgressMessage());
293  ctx.GetHTMLPage().AddTagMap("PROGRESS_MSG", proress_text);
294 }
295 
296 
298 {
299  ctx.GetHTMLPage().AddTagMap("DATE",
300  new CHTMLText(GetFastLocalTime().AsString("M B Y, h:m")));
301 }
302 
303 
305 {
306  const CArgs& args = GetArgs();
307 
308  // Check if job cancellation has been requested.
309  if ( args["Cancel"] )
310  return true;
311  return false;
312 }
313 
314 
316 {
317  // Disregard the case of CGI arguments
319 
320  // Create CGI argument descriptions class
321  // (For CGI applications only keys can be used)
322  unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
323 
324  // Specify USAGE context
325  arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
326  "CGI sample application");
327 
328  // Describe possible cmd-line and HTTP entries
329  // (optional)
330  arg_desc->AddOptionalKey("message",
331  "message",
332  "Message passed to CGI application",
335 
336  arg_desc->AddOptionalKey("Cancel",
337  "Cancel",
338  "Cancel the job",
340 
341  // Setup arg.descriptions for this application
342  SetupArgDescriptions(arg_desc.release());
343 }
344 
345 
346 string CGridCgiSampleApplication::VectorToString( const vector<double>& vec)
347 {
348  string ret;
349  if (vec.size() > 0) {
350  for (size_t i = 0; i < vec.size(); ++i) {
351  if (i != 0)
352  ret += ", ";
353  ret += NStr::DoubleToString(vec[i],3);
354  }
355  }
356  else
357  ret = "<EMPTY>";
358 
359  return ret;
360 }
361 
362 
363 /////////////////////////////////////////////////////////////////////////////
364 // MAIN
365 //
366 int NcbiSys_main(int argc, ncbi::TXChar* argv[])
367 {
368  int result = CGridCgiSampleApplication().AppMain(argc, argv);
369  _TRACE("back to normal diagnostics");
370  return result;
371 }
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgs –.
Definition: ncbiargs.hpp:379
Grid Cgi Application.
Grid CGI Context Context in which a request is processed.
Definition: grid_cgiapp.hpp:68
static string VectorToString(const vector< double > &vec)
virtual void OnJobDone(CGridClient &grid_client, CGridCgiContext &ctx)
This method is call when a worker node finishes its job and result is ready to be retrieved.
virtual string GetPageTemplate() const
Return a name of a file this HTML page template.
virtual void OnJobRunning(CGridCgiContext &ctx)
This method is call when a job is taken by a worker node to be processed.
virtual bool JobStopRequested(void) const
When job is still running this method is called to check if cancel has been requested via the user in...
virtual string GetProgramVersion(void) const
Get program version (like: MyProgram v.
virtual string GetPageTitle() const
Return page name.
virtual void ShowParamsPage(CGridCgiContext &ctx) const
Show a page with input data.
virtual void Init(void)
This method is called on the CGI application initialization – before starting to process a HTTP reque...
virtual void OnJobFailed(const string &msg, CGridCgiContext &ctx)
This method is called when worker node reported a failure.
virtual void PrepareJobData(CGridClient &grid_client)
This method is called when a job is ready to be send to a the queue.
void OnEndProcessRequest(CGridCgiContext &ctx)
This method is call at the very end of the request processing.
virtual bool CollectParams(CGridCgiContext &)
Collect parameters from HTML form If this method returns false that means that input parameters were ...
virtual void OnJobPending(CGridCgiContext &ctx)
This method is call when a job is in NetSchedule queue and is waiting for a worker node.
virtual void OnJobCanceled(CGridCgiContext &ctx)
This method is called if job was canceled during its execution.
virtual void OnJobSubmitted(CGridCgiContext &ctx)
This method is called just after a job has been submitted.
Grid Client (the submitter).
Diagnostic handler for embedding diagnostics in comments.
The NCBI C++ standard methods for dealing with std::string.
CS_CONTEXT * ctx
Definition: t0006.c:12
int NcbiSys_main(int argc, ncbi::TXChar *argv[])
USING_NCBI_SCOPE
NetSchedule Framework specs.
int AppMain(int argc, const char *const *argv, const char *const *envp=0, EAppDiagStream diag=eDS_Default, const char *conf=NcbiEmptyCStr, const string &name=NcbiEmptyString)
Main function (entry point) for the NCBI application.
Definition: ncbiapp.cpp:799
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
@ fAllowMultiple
Repeated key arguments are legal (use with AddKey)
Definition: ncbiargs.hpp:635
@ eString
An arbitrary string.
Definition: ncbiargs.hpp:589
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: cgiapp.cpp:794
void SetRequestFlags(int flags)
Set cgi parsing flag.
Definition: cgiapp.hpp:130
void RegisterDiagFactory(const string &key, CDiagFactory *fact)
Definition: cgiapp.cpp:1209
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments extended with CGI parameters.
Definition: cgiapp.cpp:1065
@ fCaseInsensitiveArgs
use case insensitive CGI arguments
Definition: ncbicgi.hpp:714
#define _TRACE(message)
Definition: ncbidbg.hpp:122
#define ERR_POST(message)
Error posting with file, line number information but without error codes.
Definition: ncbidiag.hpp:186
virtual void Init(void)
This method is called on the CGI application initialization – before starting to process a HTTP reque...
CNcbiIstream & GetIStream()
Get a stream with a job's result.
CNcbiOstream & GetOStream()
Get a stream where a client can write an input data for the remote job.
Definition: grid_client.cpp:93
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
IO_PREFIX::istream CNcbiIstream
Portable alias for istream.
Definition: ncbistre.hpp:146
static string DoubleToString(double value, int precision=-1, TNumToStringFlags flags=0)
Convert double to string.
Definition: ncbistr.hpp:5186
static list< string > & Split(const CTempString str, const CTempString delim, list< string > &arr, TSplitFlags flags=0, vector< SIZE_TYPE > *token_pos=NULL)
Split a string using specified delimiters.
Definition: ncbistr.cpp:3457
char TXChar
Definition: ncbistr.hpp:172
static double StringToDouble(const CTempStringEx str, TStringToNumFlags flags=0)
Convert string to double.
Definition: ncbistr.cpp:1387
@ fAllowTrailingSymbols
Ignore trailing non-numerics characters.
Definition: ncbistr.hpp:298
CTime GetFastLocalTime(void)
Quick and dirty getter of local time.
Definition: ncbitime.cpp:4166
HTML classes.
int i
The HTML page.
else result
Definition: token2.c:20
Modified on Sat Dec 02 09:21:58 2023 by modify_doxy.py rev. 669887