-
Notifications
You must be signed in to change notification settings - Fork 122
/
SCARFTomoReconstruction.cpp
1498 lines (1377 loc) · 57.1 KB
/
SCARFTomoReconstruction.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <fstream>
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/InternetHelper.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/MandatoryValidator.h"
#include "MantidKernel/MaskedProperty.h"
#include "MantidKernel/NullValidator.h"
#include "MantidKernel/RemoteJobManager.h"
#include "MantidKernel/VisibleWhenProperty.h"
#include "MantidRemoteAlgorithms/SCARFTomoReconstruction.h"
#include <Poco/File.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/StreamCopier.h>
#include <boost/algorithm/string/replace.hpp>
namespace Mantid {
namespace RemoteAlgorithms {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(SCARFTomoReconstruction)
using namespace Mantid::Kernel;
std::map<std::string, SCARFTomoReconstruction::Token>
SCARFTomoReconstruction::m_tokenStash;
std::string SCARFTomoReconstruction::m_acceptType =
"text/plain,application/xml,text/xml";
const std::string SCARFTomoReconstruction::m_SCARFComputeResource =
"SCARF@STFC";
int SCARFTomoReconstruction::m_jobSeq = 1;
SCARFTomoReconstruction::SCARFTomoReconstruction()
: Mantid::API::Algorithm(), m_action() {}
void SCARFTomoReconstruction::init() {
// list of all actions
std::vector<std::string> actions{"LogIn", "LogOut", "Ping",
"Upload", "SubmitJob", "JobStatus",
"JobStatusByID", "Download", "CancelJob"};
auto listValue = boost::make_shared<StringListValidator>(actions);
auto nullV = boost::make_shared<Kernel::NullValidator>();
// Username always visible, it doesn't hurt and it is required to know the
// web service base URL for most LSF commands
auto requireStrValue = boost::make_shared<MandatoryValidator<std::string>>();
declareProperty("UserName", "", requireStrValue,
"Name of the user to authenticate as", Direction::Input);
// Action to perform
declareProperty("Action", "LogIn", listValue,
"Choose the operation to perform "
"on the compute resource " +
m_SCARFComputeResource,
Direction::Input);
// - Action: login
declareProperty(make_unique<MaskedProperty<std::string>>("Password", "",
Direction::Input),
"The password for the user");
setPropertySettings("Password", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "LogIn"));
// - Action: submit
declareProperty(make_unique<PropertyWithValue<std::string>>(
"RunnablePath",
"/work/imat/webservice_test/tomopy/imat_recon_FBP.py",
Direction::Input),
"The path (on the remote compute resource) of a file to run "
"(example: shell or python script)");
setPropertySettings("RunnablePath", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "SubmitJob"));
declareProperty(
make_unique<PropertyWithValue<std::string>>(
"JobOptions", "/work/imat/webservice_test/remote_output/test_",
Direction::Input),
"Options for the job command line, application dependent. It "
"can include for example the NXTomo input file when using savu "
"for tomographic reconstruction.");
setPropertySettings("JobOptions", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "SubmitJob"));
declareProperty(
"JobName", "", nullV,
"Optional name for the job, if not given then a "
"name will be generated internally or at the compute resource",
Direction::Input);
setPropertySettings("JobName", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "SubmitJob"));
// - Action: upload file
declareProperty(
make_unique<API::FileProperty>("FileToUpload", "",
API::FileProperty::OptionalLoad, "",
Direction::Input),
"Name of the file (local, full path) to upload to the compute "
"resource/server ");
setPropertySettings("FileToUpload", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "Upload"));
declareProperty(
make_unique<PropertyWithValue<std::string>>(
"DestinationDirectory", "/work/imat", Direction::Input),
"Path where to upload the file on the compute resource/server");
setPropertySettings(
"DestinationDirectory",
make_unique<VisibleWhenProperty>("Action", IS_EQUAL_TO, "Upload"));
// - Action: query status and info (of implicitly all jobs)
declareProperty(make_unique<ArrayProperty<std::string>>("RemoteJobsID",
Direction::Output),
"ID strings for the jobs");
declareProperty(make_unique<ArrayProperty<std::string>>("RemoteJobsNames",
Direction::Output),
"Names of the jobs");
declareProperty(make_unique<ArrayProperty<std::string>>("RemoteJobsStatus",
Direction::Output),
"Strings describing the current status of the jobs");
declareProperty(make_unique<ArrayProperty<std::string>>("RemoteJobsCommands",
Direction::Output),
"Strings with the command line run for the jobs");
// - Action: query status and info by ID
declareProperty(
make_unique<PropertyWithValue<int>>("JobID", 0, Direction::Input),
"The ID of a job currently running or recently run on the "
"compute resource");
setPropertySettings("JobID", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "JobStatusByID"));
declareProperty("RemoteJobName", "", nullV, "Name of the remote job",
Direction::Output);
declareProperty("RemoteJobStatus", "", nullV, "Current status of the job "
"(running, exited, etc.)",
Direction::Output);
declareProperty("RemoteJobCommand", "", nullV, "Command line run remotely "
"for this job ",
Direction::Output);
// - Action: download file
declareProperty(
make_unique<PropertyWithValue<std::string>>("RemoteJobFilename", "",
Direction::Input),
"Name of the job file to download - you can give an empty name "
"to download all the files of this job.");
setPropertySettings(
"RemoteJobFilename",
make_unique<VisibleWhenProperty>("Action", IS_EQUAL_TO, "Download"));
declareProperty(
make_unique<API::FileProperty>("LocalDirectory", "",
API::FileProperty::OptionalDirectory, "",
Direction::Input),
"Path to a local directory/folder where to download files from "
"the compute resource/server");
setPropertySettings("LocalDirectory", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "Download"));
declareProperty(
make_unique<PropertyWithValue<int>>("DownloadJobID", 0, Direction::Input),
"ID of the job for which to download files. A job with this ID "
"must be running or have been run on the compute resource.");
setPropertySettings("DownloadJobID", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "Download"));
// - Action: cancel job by ID
declareProperty(
make_unique<PropertyWithValue<int>>("CancelJobID", 0, Direction::Input),
"The ID for a currently running job on " + m_SCARFComputeResource);
setPropertySettings("CancelJobID", make_unique<VisibleWhenProperty>(
"Action", IS_EQUAL_TO, "CancelJob"));
}
/**
* Execute algorithm: check what action/command has to be run and call
* specific methods.
*
* The implementation of the more specific methods is based on:
* Mantid::Kernel::InternetHelper.
*/
void SCARFTomoReconstruction::exec() {
m_action = getAction();
g_log.information("Running SCARFTomoReconstruction");
// only action that doesn't require any credentials
if (Action::PING == m_action) {
doPing();
return;
}
// otherwise, check first username and then action-specific parameters
std::string username;
try {
username = getPropertyValue("UserName");
} catch (std::runtime_error & /*e*/) {
g_log.error()
<< "To use this algorithm to perform the requested action "
"you need to give a valid username on the compute resource" +
m_SCARFComputeResource << '\n';
throw;
}
// all actions that require at least a username
if (Action::LOGIN == m_action) {
std::string password;
try {
password = getPropertyValue("Password");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To log in using this algorithm you need to give a "
"valid username and password on the compute resource "
<< m_SCARFComputeResource << ".\n";
throw;
}
if (password.empty()) {
throw std::runtime_error("You have given an empty password but the "
"current login mechanism on " +
m_SCARFComputeResource +
" does not support "
"this. This may change in the future. For the "
"time being you need to provide a password.");
}
doLogin(username, password);
} else if (Action::LOGOUT == m_action) {
doLogout(username);
} else if (Action::SUBMIT == m_action) {
doSubmit(username);
} else if (Action::QUERYSTATUS == m_action) {
doQueryStatus(username);
} else if (Action::QUERYSTATUSBYID == m_action) {
std::string jobId;
try {
jobId = getPropertyValue("JobID");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To query the detailed status of a job by its ID you "
"need to give the ID of a job running on "
<< m_SCARFComputeResource << ".\n";
throw;
}
doQueryStatusById(username, jobId);
} else if (Action::CANCEL == m_action) {
std::string jobId;
try {
jobId = getPropertyValue("CancelJobID");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To cancel a job you need to give the ID of a job "
"running on " << m_SCARFComputeResource << ".\n";
throw;
}
doCancel(username, jobId);
} else if (Action::UPLOAD == m_action) {
std::string filename, destDir;
try {
filename = getPropertyValue("FileToUpload");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To upload a file you need to provide an existing "
"local file.\n";
throw;
}
try {
destDir = getPropertyValue("DestinationDirectory");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To upload a file you need to provide a destination "
"directory on " << m_SCARFComputeResource << ".\n";
throw;
}
doUploadFile(username, destDir, filename);
} else if (Action::DOWNLOAD == m_action) {
std::string jobId, fname, localDir;
try {
jobId = getPropertyValue("DownloadJobID");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To download a file you need to give the ID of a job "
"running on " << m_SCARFComputeResource << ".\n";
throw;
}
try {
fname = getPropertyValue("RemoteJobFilename");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To download a file you need to provide the name of a "
"file from the remote job.\n";
throw;
}
try {
localDir = getPropertyValue("LocalDirectory");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "To download a file you need to provide a destination "
"(local) directory.\n";
throw;
}
doDownload(username, jobId, fname, localDir);
}
}
/**
* Log into SCARF. If it goes well, it will produce a token that can
* be reused for a while in subsequent queries. Internally it relies
* on the InternetHelper to send an HTTP request and obtain the
* response.
*
* @param username normally an STFC federal ID
* @param password user password
*/
void SCARFTomoReconstruction::doLogin(const std::string &username,
const std::string &password) {
// log into "https://portal.scarf.rl.ac.uk/cgi-bin/token.py";
// this should go away and obtained from 'computeResourceInfo' (like
// a very simple InstrumentInfo) or similar. What we need here is
// computeResourceInfo::baseURL()
const std::string SCARFLoginBaseURL = "https://portal.scarf.rl.ac.uk/";
const std::string SCARFLoginPath = "/cgi-bin/token.py";
std::vector<std::string> res =
ConfigService::Instance().getFacility().computeResources();
auto it = std::find(res.begin(), res.end(), m_SCARFComputeResource);
if (res.end() == it)
throw std::runtime_error(
std::string("Failed to find a compute resource "
"for " +
m_SCARFComputeResource + " (facility: " +
ConfigService::Instance().getFacility().name() + ")."));
std::string httpsURL = SCARFLoginBaseURL + SCARFLoginPath + "?username=" +
username + "&password=" + password;
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error("Error while sending HTTP request to authenticate "
"(log in): " +
std::string(ie.what()));
}
// We would check (Poco::Net::HTTPResponse::HTTP_OK == code) but the SCARF
// login script (token.py) seems to return 200 whatever happens, as far as the
// request is well formed. So this is how to know if authentication succeeded:
const std::string expectedSubstr = "https://portal.scarf.rl.ac.uk";
std::string resp = ss.str();
if (InternetHelper::HTTP_OK == code &&
resp.find(expectedSubstr) != std::string::npos) {
// it went fine, stash cookie/token which looks like this (2 lines):
// https://portal.scarf.rl.ac.uk:8443/platform/
// scarf362"2015-02-10T18:50:00Z"Mv2ncX8Z0TpH0lZHxMyXNVCb7ucT6jHNOx...
std::string url, token_str;
std::getline(ss, url);
std::getline(ss, token_str);
// note that the token needs a substring replace and a prefix, like this:
boost::replace_all(token_str, "\"", "#quote#");
token_str = "platform_token=" + token_str;
// insert in the token stash
UsernameToken tok(username, Token(url, token_str));
m_tokenStash.insert(tok); // the password is never stored
g_log.notice() << "Got authentication token. You are now logged into "
<< m_SCARFComputeResource << '\n';
} else {
throw std::runtime_error("Login failed. Please check your username and "
"password. Got this response: " +
resp);
}
}
/**
* Log out from SCARF. In practice, it trashes the cookie (if we were
* successfully logged in).
*
* @param username Username to use (should have authenticated before)
*/
void SCARFTomoReconstruction::doLogout(const std::string &username) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"Logout failed. You do not seem to be logged in. "
"I do not remember this username. Please check your "
"username.");
}
// logout query, needs headers = {'Content-Type': 'text/plain', 'Cookie':
// token,
// 'Accept': 'text/plain,application/xml,text/xml'}
const std::string logoutPath = "webservice/pacclient/logout/";
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
std::string httpsURL = baseURL + logoutPath;
std::map<std::string, std::string> headers{{"Content-Type", "text/plain"},
{"Cookie", token},
{"Accept", m_acceptType}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error("Error while sending HTTP request to log out: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
g_log.notice() << "Logged out.\n";
g_log.debug() << "Response from server: " << ss.str() << '\n';
} else {
throw std::runtime_error("Failed to logout from the web service at: " +
httpsURL + ". Please check your username.");
}
// successfully logged out, forget the token
m_tokenStash.erase(it);
}
/**
* Submits a job to SCARF. The different ways jobs could be submitted
* (supported toolkits, LSF PAC submission forms, launcher scripts,
* supported options, etc.) are not well defined at the moment.
*
* @param username Username to use (should have authenticated before)
*/
void SCARFTomoReconstruction::doSubmit(const std::string &username) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"Job submission failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
// Not sure at this point if there could be commands without options
// For the time being it's possible.
std::string jobOptions;
try {
jobOptions = getPropertyValue("JobOptions");
} catch (std::runtime_error & /*e*/) {
g_log.warning() << "You did not specify any options for the job. Maybe you "
"forgot to pass the options?\n";
m_jobOptions = "";
}
std::string runnablePath;
try {
runnablePath = getPropertyValue("RunnablePath");
} catch (std::runtime_error & /*e*/) {
g_log.error() << "You did not specify a the path to the parameter file "
"which is required to create a new reconstruction job. "
"Please provide "
"a valid tomography reconstruction parameter file\n";
throw;
}
std::string jobName;
try {
jobName = getPropertyValue("JobName");
} catch (std::runtime_error & /*e*/) {
jobName = "";
}
progress(0, "Starting job...");
// Job submit query, requires specific parameters for LSF submit
// Example params passed to python submit utility:
// $ pacclient.py submit --app TOMOPY_0_0_3 --param "INPUT_FILE=
// /work/imat/webservice_test/tomopy/imat_recon_FBP.py;INPUT_ARGS=
// /work/imat/scripts/test_;JOB_NAME=01_test_job;OUTPUT_FILE=%J.output;ERROR_FILE=
// %J.error"
// Two applications are for now registered on SCARF:
// TOMOPY_0_0_3, PYASTRATOOLBOX_1_1 - old versions
// TOMOPY_0_1_9, PYASTRATOOLBOX_1_6 - newer versions (Dec 2015)
std::string appName = "TOMOPY_0_1_9";
// Basic attempt at guessing the app that we might really need. This
// is not fixed/unstable at the moment
if (runnablePath.find("--tool astra") != std::string::npos ||
runnablePath.find("--tool=astra") != std::string::npos) {
appName = "PYASTRATOOLBOX_1_6";
}
// this gets executed (for example via 'exec' or 'python', depending on the
// appName
const std::string boundary = "bqJky99mlBWa-ZuqjC53mG6EzbmlxB";
const std::string &body =
buildSubmitBody(appName, boundary, runnablePath, jobOptions, jobName);
// Job submit, needs these headers:
// headers = {'Content-Type': 'multipart/mixed; boundary='+boundary,
// 'Accept': 'text/xml,application/xml;', 'Cookie': token,
// 'Content-Length': str(len(body))}
// Content-Length is added by InternetHelper/Poco HTTP request
const std::string submitPath = "webservice/pacclient/submitapp";
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
std::string httpsURL = baseURL + submitPath;
std::map<std::string, std::string> headers{
{"Content-Type", "multipart/mixed; boundary=" + boundary},
{"Accept", m_acceptType},
{"Cookie", token}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers,
Poco::Net::HTTPRequest::HTTP_POST, body);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error(
"Error while sending HTTP request to submit a job: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
if (std::string::npos != resp.find("<errMsg>")) {
g_log.warning()
<< "Submitted job but got a a response that seems to contain "
"an error message from " << m_SCARFComputeResource << ": "
<< extractPACErrMsg(ss.str()) << '\n';
} else {
g_log.notice() << "Submitted job successfully.\n";
g_log.debug() << "Response from server: " << resp << '\n';
}
} else {
throw std::runtime_error(
"Failed to submit a job through the web service at:" + httpsURL +
". Please check your username, credentials, "
"and parameters.");
}
progress(1.0, "Job started on " + m_SCARFComputeResource);
}
/**
* Query the status of jobs running (if successful will return info on
* jobs running for our user)
*
* @param username Username to use (should have authenticated before)
*/
void SCARFTomoReconstruction::doQueryStatus(const std::string &username) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"Job status query failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
progress(0, "Checking the status of jobs...");
// Job query status, needs these headers:
// headers = {'Content-Type': 'application/xml', 'Cookie': token,
// 'Accept': ACCEPT_TYPE}
const std::string jobStatusPath = "webservice/pacclient/jobs?";
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
std::string httpsURL = baseURL + jobStatusPath;
std::map<std::string, std::string> headers{
{"Content-Type", "application/xml"},
{"Accept", m_acceptType},
{"Cookie", token}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error(
"Error while sending HTTP request to query the status "
"of jobs: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
if (std::string::npos != resp.find("<Jobs>") &&
std::string::npos != resp.find("<extStatus>")) {
genOutputStatusInfo(resp);
g_log.notice() << "Queried the status of jobs and stored the "
"information in output properties.\n";
} else {
g_log.warning() << "Queried the status of jobs but got what looks "
"like an error message as response: " << resp << '\n';
}
g_log.notice() << "Queried job status successfully.\n";
g_log.debug() << "Response from server: " << resp << '\n';
} else {
throw std::runtime_error(
"Failed to obtain job status information through the "
"web service at:" +
httpsURL + ". Please check your "
"username, credentials, and parameters.");
}
progress(1.0, "Status of jobs retrived.");
}
/**
* Query the status of jobs running (if successful will return info on
* jobs running for our user)
*
* @param username Username to use (should have authenticated before)
* @param jobId Identifier of a job as used by the job scheduler (integer
*number)
*/
void SCARFTomoReconstruction::doQueryStatusById(const std::string &username,
const std::string &jobId) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"Job status query failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
progress(0, "Checking the status of job with Id " + jobId);
// Job query status, needs these headers:
// headers = {'Content-Type': 'application/xml', 'Cookie': token,
// 'Accept': ACCEPT_TYPE}
const std::string jobIdStatusPath = "webservice/pacclient/jobs/";
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
std::string httpsURL = baseURL + jobIdStatusPath;
std::map<std::string, std::string> headers{
{"Content-Type", "application/xml"},
{"Accept", m_acceptType},
{"Cookie", token}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error(
"Error while sending HTTP request to query the status "
"of a job: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
if (std::string::npos != resp.find("<Jobs>") &&
std::string::npos != resp.find("<extStatus>")) {
genOutputStatusInfo(resp, jobId);
g_log.notice() << "Queried job status (Id " << jobId
<< ") and stored "
"information into output properties.\n";
g_log.debug() << "Response from server: " << resp << '\n';
} else {
g_log.warning() << "Queried job status (Id " << jobId
<< " ) but got what "
"looks like an error message as response: " << resp
<< '\n';
}
} else {
throw std::runtime_error("Failed to obtain job (Id:" + jobId +
" ) status "
"information through the web service at:" +
httpsURL +
". Please check your username, credentials, and "
"parameters.");
}
progress(1.0, "Status of job " + jobId + "retrived.");
}
/**
* Ping the server to see if the web service is active/available.
*
* @return true if the web service responds.
*/
bool SCARFTomoReconstruction::doPing() {
progress(0, "Pinging compute resource " + m_SCARFComputeResource);
// Job ping, needs these headers:
// headers = {'Content-Type': 'application/xml', 'Accept': ACCEPT_TYPE}
const std::string pingPath = "platform/webservice/pacclient/ping/";
// This could be retrieved from facilities or similar
// (like SCARFLoginBaseURL above) - TODO: clarify that in Facilities.xml
// the port number is known only after logging in
const std::string baseURL = "https://portal.scarf.rl.ac.uk:8443/";
std::string httpsURL = baseURL + pingPath;
std::map<std::string, std::string> headers{
{"Content-Type", "application/xml"}, {"Accept", m_acceptType}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error("Error while sending HTTP request to ping the "
"server " +
std::string(ie.what()));
}
bool ok = false;
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
if (std::string::npos != resp.find("Web Services are ready")) {
g_log.notice()
<< "Pinged compute resource with apparently good response: " << resp
<< '\n';
ok = true;
} else {
g_log.warning() << "Pinged compute resource but got what looks like an "
"error message: " << resp << '\n';
}
} else {
throw std::runtime_error(
"Failed to ping the web service at: " + httpsURL +
". Please check your parameters, software version, "
"etc.");
}
progress(1.0, "Ping compute resource " + m_SCARFComputeResource + " done.");
return ok;
}
/**
* Cancel a submitted job, identified by its ID in the job queue.
*
* @param username Username to use (should have authenticated before)
* @param jobId Identifier of a job as used by the job scheduler (integer
*number)
*/
void SCARFTomoReconstruction::doCancel(const std::string &username,
const std::string &jobId) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"Job status query failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
progress(0, "Cancelling/killing job " + jobId);
// Job kill, needs these headers:
// headers = {'Content-Type': 'text/plain', 'Cookie': token, 'Accept':
// ACCEPT_TYPE}
const std::string killPath =
"webservice/pacclient/jobOperation/kill/" + jobId;
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
std::string httpsURL = baseURL + killPath;
std::map<std::string, std::string> headers{
{"Content-Type", "application/xml"},
{"Cookie", token},
{"Accept", m_acceptType}};
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error(
"Error while sending HTTP request to cancel a job: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
if (std::string::npos != resp.find("<errMsg>")) {
g_log.warning() << "Killed job with Id" << jobId
<< " but got what looks like an "
"error message as response: " << extractPACErrMsg(resp)
<< '\n';
} else if (std::string::npos != resp.find("<actionMsg>")) {
g_log.notice() << "Killed job with Id" << jobId << ".\n";
g_log.debug() << "Response from server: " << resp << '\n';
} else {
g_log.warning() << "Killed job with Id" << jobId
<< " but got what a response "
"that I do not recognize: " << resp << '\n';
}
} else {
throw std::runtime_error(
"Failed to kill job (Id: " + jobId + " ) through the web "
"service at:" +
httpsURL + ". Please check your "
"existing jobs, username, and parameters.");
}
progress(1.0, "Killed job with Id " + jobId + ".");
}
/**
* Upload a file to a directory on the server.
*
* @param username Username to use (should have authenticated before)
* @param destDir Destination directory on the server
* @param filename File name of the local file to upload
*/
void SCARFTomoReconstruction::doUploadFile(const std::string &username,
const std::string &destDir,
const std::string &filename) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"File upload failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
progress(0, "Uploading file: " + filename);
// File upload, needs these headers:
// headers = {'Content-Type': 'multipart/mixed; boundary='+boundary,
// 'Accept': 'text/plain;', 'Cookie': token,
// 'Content-Length': str(len(body))}
// Content-Length is added by InternetHelper/Poco HTTP request
// The 0 at the end of the upload path is 'jobId' 0, if a jobId is given the
// upload goes to a path relative to the job path.
const std::string uploadPath = "webservice/pacclient/upfile/0";
const std::string boundary = "4k89ogja023oh1-gkdfk903jf9wngmujfs95m";
const std::string baseURL = it->second.m_url;
const std::string token = it->second.m_token_str;
InternetHelper session;
std::string httpsURL = baseURL + uploadPath;
std::map<std::string, std::string> headers{
{"Content-Type", "multipart/mixed; boundary=" + boundary},
{"Accept", m_acceptType},
{"Cookie", token}};
const std::string &body = buildUploadBody(boundary, destDir, filename);
int code;
std::stringstream ss;
try {
code = doSendRequestGetResponse(httpsURL, ss, headers,
Poco::Net::HTTPRequest::HTTP_POST, body);
} catch (Kernel::Exception::InternetError &ie) {
throw std::runtime_error(
"Error while sending HTTP request to upload a file: " +
std::string(ie.what()));
}
if (Poco::Net::HTTPResponse::HTTP_OK == code) {
std::string resp = ss.str();
g_log.notice() << "Uploaded file, response from server: " << resp << '\n';
} else {
throw std::runtime_error(
"Failed to upload file through the web service at:" + httpsURL +
". Please check your username, credentials, "
"and parameters.");
}
progress(1.0, "File uploaded to " + m_SCARFComputeResource);
}
/**
* Download a file or a set of files from a remote job into a local
* directory. Note that this download as supported by LSF at SCARF is
* job-specific: you download a file from a job and not a file in the
* file system in general. When downloading multiple files this action
* requires two steps: one first HTTP request to get the remote
* path(s) for all the job file(s), and a second request or series of
* requests to actually download the file(s).
*
* @param username Username to use (should have authenticated before)
* @param jobId Identifier of a job as used by the job scheduler (integer
*number)
* @param fname File name (of a job file on the compute resource). If no name is
* given then all the job files are downloaded into localDir
* @param localDir Local directory where to download the file(s)
*/
void SCARFTomoReconstruction::doDownload(const std::string &username,
const std::string &jobId,
const std::string &fname,
const std::string &localDir) {
auto it = m_tokenStash.find(username);
if (m_tokenStash.end() == it) {
throw std::runtime_error(
"File upload failed. You do not seem to be logged "
"in. I do not remember this username. Please check "
"your username.");
}
progress(0, "Downloading file: " + fname + " in " + localDir);
if (fname.empty()) {
// no/empty name implies we want all the files of a remote job
getAllJobFiles(jobId, localDir, it->second);
} else {
// name given, so we directly download this single file
getOneJobFile(jobId, fname, localDir, it->second);
}
}
/**
* Send the HHTP(S) request required to perform one of the actions.
*
* @param url Full URL, including request string
* @param rss Response body stream
* @param headers HTTP headers given as key-value pairs
* @param method By default GET (Poco::Net::HTTPRequest::HTTP_POST), also
*accepts
* POST (Poco::Net::HTTPRequest::HTTP_POST)
* @param body HTTP message body
*
* @return HTTP(S) response code
*/
int SCARFTomoReconstruction::doSendRequestGetResponse(
const std::string &url, std::ostream &rss, const StringToStringMap &headers,
const std::string &method, const std::string &body) {
InternetHelper session;
std::string ContTypeName = "Content-Type";
auto it = headers.find(ContTypeName);
if (headers.end() != it) {
session.setContentType(it->second);
}
session.headers() = headers;
if (!method.empty())
session.setMethod(method);
if (!body.empty()) {
session.setBody(body);
// beware, the inet helper will set method=POST if body not empty!
// But here, for example to download, we need a GET with non-empty body
if (Poco::Net::HTTPRequest::HTTP_GET == method) {
session.setMethod(method);
}
}
return session.sendRequest(url, rss);
}
/**
* Adds one param to a submit request body (first argument). This is
* part of a multipart body content.
*
* @param body Body string being built for an HTTP request
* @param boundary Boundary string between parameters, for request encoding
* @param paramName Name of a parameter, for example INPUT_FILE
* @param paramVal Value of the parameter
*/
void SCARFTomoReconstruction::encodeParam(std::string &body,
const std::string &boundary,
const std::string ¶mName,
const std::string ¶mVal) {
body += "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"" + paramName + "\"\r\n";
body += "Content-Type: application/xml; charset=US-ASCII\r\n";
body += "Content-Transfer-Encoding: 8bit\r\n";
body += "\r\n";
body += "<AppParam><id>" + paramName + "</id><value>" + paramVal +
"</value><type></type></AppParam>\r\n";
}
/**
* Tiny helper to generate an integer sequence number for the job
* names.
*/
int SCARFTomoReconstruction::jobSeqNo() { return m_jobSeq++; }
/**
* Helper method to do the somewhat ugly encoding of parameters for
* submit requests.
*
* @param appName A registered app name/form form SCARF, example: TOMOPY_0_0_3
* @param boundary Boundary string between parts of the multi-part body
* @param inputFile Input file parameter, this file will be run
* @param inputArgs Arguments to the command (application specific)
* @param jobName Name passed by the user (can be empty == no preference)
*
* @return A string ready to be used as body of a 'job submit' HTTP request
*/
std::string SCARFTomoReconstruction::buildSubmitBody(
const std::string &appName, const std::string &boundary,
const std::string &inputFile, const std::string &inputArgs,
const std::string &jobName) {
// BLOCK: start and encode app name like this:
// --bqJky99mlBWa-ZuqjC53mG6EzbmlxB
// Content-Disposition: form-data; name="AppName"
// Content-ID: <AppName>
//
// TOMOPY_0_0_3
std::string body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name=\"AppName\"\r\n"
"Content-ID: <AppName>\r\n"
"\r\n" +
appName + "\r\n";
// BLOCK: encode params head like this:
// --bqJky99mlBWa-ZuqjC53mG6EzbmlxB
// Content-Disposition: form-data; name="data"
// Content-Type: multipart/mixed; boundary=_Part_1_701508.1145579811786
// Content-ID: <data>
//
body += "--" + boundary + "\r\n";
const std::string boundaryInner = "_Part_1_701508.1145579811786";
body += "Content-Disposition: form-data; name=\"data\"\r\n";
body += "Content-Type: multipart/mixed; boundary=" + boundaryInner + "\r\n";
body += "Content-ID: <data>\r\n";
body += "\r\n";
// BLOCKS: encode params like this: