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

Go to the SVN repository for this file.

1 /* $Id: remote_app_client_sample.cpp 90014 2020-05-04 17:30:22Z 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  * Authors: Maxim Didenko
27  *
28  * File Description:
29  *
30  */
31 
32 #include <ncbi_pch.hpp>
33 #include <corelib/ncbiapp.hpp>
34 #include <corelib/ncbimisc.hpp>
35 #include <corelib/ncbi_system.hpp>
36 
40 
42 
43 
44 /////////////////////////////////////////////////////////////////////////////
45 // CRemoteAppClientSampleApp::
46 //
47 
49 {
50 public:
51  virtual void Init(void);
52  virtual int Run(void);
53  virtual string GetProgramVersion(void) const
54  {
55  // Next formats are valid and supported:
56  // ProgramName 1.2.3
57  // ProgramName version 1.2.3
58  // ProgramName v. 1.2.3
59  // ProgramName ver. 1.2.3
60 
61  return "SampleNodeClient version 1.0.1";
62  }
63 
64 protected:
65  void PrintJobInfo(const string& job_key, CNetCacheAPI::TInstance netcache_api);
66  void ShowBlob(const string& blob_key);
67 
68  virtual bool UseProgressMessage() const { return false; }
69  virtual bool UseAutomaticCleanup() const { return false; }
70 };
71 
72 
74 {
75  // Don't forget to call it
77 
78  // Create command-line argument descriptions class
79  unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
80 
81  // Specify USAGE context
82  arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
83  "Remote app client sample");
84 
85  arg_desc->AddOptionalKey("jobs",
86  "jobs",
87  "Number of jobs to submit",
89 
90  arg_desc->AddOptionalKey("jobinfo",
91  "job",
92  "Get job's info",
94 
95  arg_desc->AddOptionalKey("showblob",
96  "blob",
97  "Show blob content",
99 
100  // Setup arg.descriptions for this application
101  SetupArgDescriptions(arg_desc.release());
102 }
103 
104 
106 {
107  const char* kData =
108  "!====================================================================================================!";
109  const size_t kDataSize = strlen(kData);
110 
111  const CArgs& args = GetArgs();
112 
113  if (args["showblob"]) {
114  ShowBlob(args["showblob"].AsString());
115  return 0;
116  }
117 
118  CNetCacheAPI netcache_api(GetGridClient().GetNetCacheAPI());
119 
120  if (args["jobinfo"]) {
121  PrintJobInfo(args["jobinfo"].AsString(), netcache_api);
122  return 0;
123  }
124 
125  int jobs_number = 10;
126  if (args["jobs"]) {
127  jobs_number = args["jobs"].AsInteger();
128  }
129 
130  cout << "Submitting jobs..." << jobs_number << endl;
131 
132  typedef list<string> TJobKeys;
133  TJobKeys job_keys;
134 
135  CRemoteAppRequest request(netcache_api);
136  for (int i = 0; i < jobs_number; ++i) {
137  CNcbiOstream& os = request.GetStdIn();
138 
139  if (i % 5 == 0) {
140  os.write(kData, kDataSize);
141  os << endl << i << endl;
142  os.write(kData, kDataSize);
143  os.write(kData, kDataSize);
144  os.write(kData, kDataSize);
145  os.write(kData, kDataSize);
146  } else
147  os << "Request data";
148 
149  request.SetCmdLine("-a sss -f=/tmp/dddd.f1");
150  request.AddFileForTransfer("/tmp/dddd.f1");
151 
152  // Get a job submitter
153  CGridClient& grid_client = GetGridClient();
154 
155  // Serialize the request;
156  request.Send(grid_client.GetOStream());
157 
158  // Submit a job
159  job_keys.push_back(grid_client.Submit());
160  }
161  cout << endl << "Done." << endl;
162 
163  cout << "Waiting for jobs..." << endl;
164 
165  CRemoteAppResult result(netcache_api);
166  TJobKeys failed_jobs;
167 
168  unsigned int cnt = 0;
169  while (1) {
170  SleepMilliSec(100);
171 
172  typedef list<TJobKeys::iterator> TDoneJobs;
173  TDoneJobs done_jobs;
174 
175  for(auto it = job_keys.begin(); it != job_keys.end(); ++it) {
176  // Get a job status
177  CGridClient& grid_client(GetGridClient());
178  grid_client.SetJobKey(*it);
180  status = grid_client.GetStatus();
181 
182  // A job is done here
183  if (status == CNetScheduleAPI::eDone) {
184 
185  result.Receive(grid_client.GetIStream());
186 
187  cout << "Job : " << *it << endl;
188  cout << "Return code: " << result.GetRetCode() << endl;
189  if (result.GetRetCode()==-1)
190  failed_jobs.push_back(*it);
191  cout << "StdOut : " << endl;
192  cout << result.GetStdOut().rdbuf();
193  cout.clear();
194  cout << endl << "StdErr : " << endl;
195  cout << result.GetStdErr().rdbuf();
196  cout.clear();
197  cout << endl << "----------------------" << endl;
198  done_jobs.push_back(it);
199  }
200 
201  // A job has failed
202  if (status == CNetScheduleAPI::eFailed) {
203  ERR_POST( "Job " << *it << " failed : "
204  << grid_client.GetErrorMessage() );
205  failed_jobs.push_back(*it);
206  done_jobs.push_back(it);
207  }
208 
209  // A job has been canceled
210  if (status == CNetScheduleAPI::eCanceled) {
211  ERR_POST( Warning << Note << "Job " << *it << " is canceled.");
212  done_jobs.push_back(it);
213  }
214  }
215  for (const auto& job : done_jobs) {
216  job_keys.erase(job);
217  }
218  if (job_keys.empty())
219  break;
220 
221  // A job is still running
222  if (++cnt % 1000 == 0) {
223  cout << "Still waiting..." << endl;
224  }
225  }
226 
227  ERR_POST(Info << Note
228  << "==================== All finished ==================");
229  for (const auto& job : job_keys) {
230  PrintJobInfo(job, netcache_api);
231  }
232  return 0;
233 }
234 
235 
236 void CRemoteAppClientSampleApp::ShowBlob(const string& blob_key)
237 {
238  CNetCacheAPI nc_api(GetGridClient().GetNetCacheAPI());
239  unique_ptr<CNcbiIstream> is(nc_api.GetIStream(blob_key));
240  NcbiStreamCopy(cout, *is);
241  cout << endl;
242 }
243 
244 
245 void CRemoteAppClientSampleApp::PrintJobInfo(const string& job_key,
246  CNetCacheAPI::TInstance netcache_api)
247 {
248  CGridClient& grid_client(GetGridClient());
249  grid_client.SetJobKey(job_key);
251  status = grid_client.GetStatus();
252 
253  // A job is done here
254  if (status == CNetScheduleAPI::eDone) {
255  cout << "Job : " << job_key << endl;
256  cout << "Input : " << grid_client.GetJobInput() << endl;
257  cout << "Output : " << grid_client.GetJobOutput() << endl;
258  cout << "======================================" << endl;
259  CRemoteAppResult result(netcache_api);
260  result.Receive(grid_client.GetIStream());
261  cout << "Return code: " << result.GetRetCode() << endl;
262  cout << "StdOut : " << endl;
263  cout << result.GetStdOut().rdbuf();
264  cout.clear();
265  cout << endl << "StdErr : " << endl;
266  cout << result.GetStdErr().rdbuf();
267  cout.clear();
268  }
269 
270  // A job has failed
271  if (status == CNetScheduleAPI::eFailed) {
272  ERR_POST( "Job " << job_key << " failed : "
273  << grid_client.GetErrorMessage() );
274  }
275  // A job has been canceled
276  if (status == CNetScheduleAPI::eCanceled) {
277  ERR_POST( Warning << Note << "Job " << job_key << " is canceled.");
278  }
279 }
280 
281 
282 int NcbiSys_main(int argc, ncbi::TXChar* argv[])
283 {
284  return CRemoteAppClientSampleApp().AppMain(argc, argv);
285 }
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgs –.
Definition: ncbiargs.hpp:379
Grid Client Application.
Grid Client (the submitter).
Client API for NetCache server.
virtual int Run(void)
Run the application.
virtual string GetProgramVersion(void) const
Get program version (like: MyProgram v.
virtual bool UseAutomaticCleanup() const
virtual bool UseProgressMessage() const
virtual void Init(void)
If you override this method, do call CGridClientApp::Init() from inside your overriding method.
void ShowBlob(const string &blob_key)
void PrintJobInfo(const string &job_key, CNetCacheAPI::TInstance netcache_api)
Remote Application Request (both client side and application executor side)
Definition: remote_app.hpp:96
void Send(CNcbiOstream &os)
Serialize a request to a given stream.
Definition: remote_app.cpp:164
void AddFileForTransfer(const string &fname, EStdOutErrStorageType tt=eBlobStorage)
Transfer a file to an application executor side.
Definition: remote_app.hpp:118
CNcbiOstream & GetStdIn()
Get an output stream to write data to a remote application stdin.
Definition: remote_app.hpp:126
void SetCmdLine(const string &cmdline)
Set the command line for the remote application.
Definition: remote_app.hpp:106
Remote Application Result (both client side and application executor side)
Definition: remote_app.hpp:209
NetSchedule Framework specs.
NetSchedule Framework specs.
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments.
Definition: ncbiapp.cpp:305
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:832
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: ncbiapp.cpp:1208
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
@ eString
An arbitrary string.
Definition: ncbiargs.hpp:589
@ eInteger
Convertible into an integer number (int or Int8)
Definition: ncbiargs.hpp:592
#define ERR_POST(message)
Error posting with file, line number information but without error codes.
Definition: ncbidiag.hpp:186
void Warning(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1191
void Info(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1185
CNcbiIstream * GetIStream(const string &key, size_t *blob_size=NULL, const CNamedParameterList *optional=NULL)
Create an istream object for reading blob data.
EJobStatus
Job status codes.
const string & GetJobInput()
Get a job's input sting.
void SetJobKey(const string &job_key)
const string & GetErrorMessage()
If something bad has happened this method will return an explanation.
virtual void Init(void)
If you override this method, do call CGridClientApp::Init() from inside your overriding method.
CNetScheduleAPI::EJobStatus GetStatus()
Get a job status.
CNcbiIstream & GetIStream()
Get a stream with a job's result.
string Submit(const string &affinity=kEmptyStr)
Submit a job to the queue.
CNcbiOstream & GetOStream()
Get a stream where a client can write an input data for the remote job.
Definition: grid_client.cpp:93
const string & GetJobOutput()
Get a job's output string.
CGridClient & GetGridClient()
Get a grid client.
@ eDone
Job is ready (computed successfully)
@ eCanceled
Explicitly canceled.
@ eFailed
Failed to run (execution timeout)
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
bool NcbiStreamCopy(CNcbiOstream &os, CNcbiIstream &is)
Copy the entire contents of stream "is" to stream "os".
Definition: ncbistre.cpp:211
char TXChar
Definition: ncbistr.hpp:172
where both of them are integers Note
int i
void SleepMilliSec(unsigned long ml_sec, EInterruptOnSignal onsignal=eRestartOnSignal)
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Miscellaneous common-use basic types and functionality.
static unsigned cnt[256]
int NcbiSys_main(int argc, ncbi::TXChar *argv[])
else result
Definition: token2.c:20
Modified on Fri Sep 20 14:57:26 2024 by modify_doxy.py rev. 669887