-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWSScheduler.cpp
1836 lines (1467 loc) · 78.2 KB
/
WSScheduler.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
/*
HydroGate is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Regarding this entire document or any portion of it , the author
makes no guarantees and is not responsible for any damage resulting
from its use.
Ahmet Artu Yildirim
Utah State University
*/
#include "WSScheduler.h"
#include "WSException.h"
#include "WSCrypt.h"
#include "WSHelper.h"
#include <uuid/uuid.h>
#include <curl/curl.h>
#include <cstdio>
struct RemoteFile {
string filename;
CURL *curl;
ssh_scp scp;
bool isinitialized;
WSSshSession* sshsession;
string exception;
};
struct RemoteFile2 {
ssh_scp scp;
WSSshSession* sshsession;
string exception;
};
WSScheduler* WSScheduler::instance_ = NULL;
int WSScheduler::thread_num_ = 0;
WSScheduler::WSScheduler() {
hpcsessionpool_ = new map<int, WSSshSessionPool*>();
workitempool_ = new list<WSScheduler::WSSchedulerWorkItem*>();
hpcworkqueue_ = new list<WSHPCWork*>();
pthread_mutex_init(&mutex_, NULL);
pthread_cond_init(&cond_, NULL);
pthread_mutex_init(&mutex_cpool_, NULL);
keydata_ = "";
initial_thread_count_ = 50;
max_connection_per_hpc_ = 10;
scp_bufsiz_ = 102400;
stdout_bufsiz_ = 512;
job_status_check_delay_in_seconds_ = 10;
isinputinlocalmode_ = true;
isoutputinlocalmode_ = true;
inputurl_ = "";
outputurl_ = "";
outputurlsrc_ = "";
}
WSScheduler::~WSScheduler() {
delete hpcsessionpool_;
delete workitempool_;
delete hpcworkqueue_;
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&cond_);
pthread_mutex_destroy(&mutex_cpool_);
}
WSScheduler* WSScheduler::instance() {
if (!instance_) {
instance_ = new WSScheduler();
}
return instance_;
}
void WSScheduler::initialize() {
pthread_attr_t bckattr;
pthread_attr_init(&bckattr);
pthread_attr_setdetachstate(&bckattr, PTHREAD_CREATE_JOINABLE);
int rc;
rc = pthread_create(&background_worker_thread_, &bckattr, WSScheduler::backgroundWorkerEntry, (void *) this);
if (rc) {
pthread_attr_destroy(&bckattr);
WSLogger::instance()->log("WSScheduler", "Failed to create background worker");
}
int i;
for (i = 0; i < initial_thread_count_; i++) {
WSScheduler::WSSchedulerWorkItem* witem = new WSScheduler::WSSchedulerWorkItem();
witem->scheduler = this;
witem->thread_num = WSScheduler::thread_num_++;
witem->state = WITEM_WAITING;
witem->cont = true;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc;
rc = pthread_create(&witem->job_submit_thread, &attr, WSScheduler::workerEntry, (void *) witem);
if (rc) {
WSLogger::instance()->log("WSScheduler", "Failed to create worker item");
pthread_attr_destroy(&attr);
delete witem;
continue;
}
workitempool_->push_back(witem);
}
}
string WSScheduler::getUniqueFileName(string prefix, string suffix) {
uuid_t package_uuid;
uuid_generate_time_safe(package_uuid);
char str_uuid[40];
uuid_unparse_lower(package_uuid, str_uuid);
uuid_clear(package_uuid);
return prefix + string(str_uuid) + suffix;
}
WSSshSessionPool* WSScheduler::getSSHConnectionPool(WSDHpcCenter& hpcrecord) {
std::map<int, WSSshSessionPool*>::iterator it = hpcsessionpool_->find(hpcrecord.hpc_id);
if (it == hpcsessionpool_->end()) {
string hpc_pass = WSCrypt::instance()->decrypt(hpcrecord.account_password, keydata_, hpcrecord.tsalt1, hpcrecord.tsalt2);
WSSshSessionPool* sessionpool = new WSSshSessionPool(hpcrecord.account_name, hpc_pass, hpcrecord.address, max_connection_per_hpc_);
hpcsessionpool_->insert(std::pair<int, WSSshSessionPool*>(hpcrecord.hpc_id, sessionpool));
return sessionpool;
}
return it->second;
}
void WSScheduler::addHPCWork(WSHPCWork* work) {
pthread_mutex_lock(&mutex_);
hpcworkqueue_->push_back(work);
pthread_cond_signal(&cond_);
pthread_mutex_unlock(&mutex_);
}
WSHPCWork* WSScheduler::removeHPCWork() {
pthread_mutex_lock(&mutex_);
while (hpcworkqueue_->size() == 0) {
pthread_cond_wait(&cond_, &mutex_);
}
WSHPCWork* workitem = hpcworkqueue_->front();
hpcworkqueue_->pop_front();
pthread_mutex_unlock(&mutex_);
return workitem;
}
void WSScheduler::runRemoteCommand(ssh_session session, string my_stdin, string* my_stdout) {
int rc;
ssh_channel channel;
channel = ssh_channel_new(session);
if (channel == NULL) {
string error = string("failed to create ssh channel") + string(ssh_get_error(session));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_channel_open_session(channel);
if (rc != SSH_OK) {
ssh_channel_free(channel);
string error = string("failed to open session") + string(ssh_get_error(session));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_channel_request_exec(channel, my_stdin.c_str());
if (rc != SSH_OK) {
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
string error = string("failed to run remote command. error: ") + string(ssh_get_error(session)) + string(" stdin: ") + my_stdin;
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
char* buffer = (char*) malloc(stdout_bufsiz_);
unsigned int nbytes;
nbytes = ssh_channel_read(channel, buffer, stdout_bufsiz_, 0);
char* stdout_str = (char*) malloc(nbytes);
int stdout_index = 0;
while (nbytes > 0) {
if (stdout_index > 0)
stdout_str = (char*) realloc(stdout_str, stdout_index + nbytes);
memcpy(stdout_str + stdout_index, buffer, nbytes);
stdout_index += nbytes;
nbytes = ssh_channel_read(channel, buffer, stdout_bufsiz_, 0);
}
*my_stdout = string(stdout_str);
free(buffer);
if (nbytes < 0) {
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
string error = string("execution is failed. error: ") + string(ssh_get_error(session)) + string(" stdin: ") + my_stdin;
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
int exit_status = ssh_channel_get_exit_status(channel);
if (exit_status != 0) {
ssh_channel_free(channel);
string error = string("execution is failed to get exit status code. error: ") + string(ssh_get_error(session)) + string(" stdin: ") + my_stdin;
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
ssh_channel_free(channel);
}
void WSScheduler::freeWorkflowArray(vector<WSWorkflowTask*>* workflowArray) {
for (vector<int>::size_type i = 0; i != workflowArray->size(); i++) {
WSWorkflowTask* workflowitem = workflowArray->at(i);
delete workflowitem;
}
delete workflowArray;
}
bool WSScheduler::readRemoteTextFile(ssh_session session, string path, string* textfile_content, string* error_desc) {
*textfile_content = "";
*error_desc = "";
ssh_scp scp;
int rc;
scp = ssh_scp_new
(session, SSH_SCP_READ, path.c_str());
if (scp == NULL) {
*error_desc = string("error allocating scp session: ") + string(ssh_get_error(session));
return false;
}
rc = ssh_scp_init(scp);
if (rc != SSH_OK) {
ssh_scp_free(scp);
*error_desc = string("error initializing scp session: ") + string(ssh_get_error(session));
return false;
}
rc = ssh_scp_pull_request(scp);
if (rc != SSH_SCP_REQUEST_NEWFILE) {
ssh_scp_free(scp);
*error_desc = string("error in receiving remote file: ") + string(ssh_get_error(session));
return false;
}
int size = ssh_scp_request_get_size(scp);
ssh_scp_accept_request(scp);
//TODO: add here maximum allowable buffer size
char *pChars = new char[size];
if (!pChars) {
ssh_scp_close(scp);
ssh_scp_free(scp);
*error_desc = string("failed to allocate memory for reading package data");
return false;
}
int nbytes = ssh_scp_read(scp, pChars, size);
*textfile_content += string(pChars);
if (nbytes == SSH_ERROR) {
free(pChars);
ssh_scp_close(scp);
ssh_scp_free(scp);
*error_desc = string("error in receiving remote file: ") + string(ssh_get_error(session));
return false;
}
free(pChars);
ssh_scp_close(scp);
ssh_scp_free(scp);
return true;
}
void WSScheduler::parseSQueueForRunningJobs(string& input, map<string, string>& joblist) {
std::istringstream in(input);
std::string s;
std::getline(in, s);
while (!in.eof()) {
string job_definition;
std::getline(in, s);
std::istringstream ss(s);
ss >> job_definition;
if (ss.eof())
break;
string job_status;
for (int i = 0; i < 4; i++)
ss >> job_status;
joblist.insert(make_pair(job_definition, job_status));
}
}
void WSScheduler::parseQStatForRunningJobs(string& input, map<string, string>& joblist) {
std::istringstream in(input);
std::string s;
while (1) {
string prefix = "---------";
std::getline(in, s);
if (in.eof()) {
return;
}
if (s.substr(0, prefix.size()) == prefix) {
break;
}
}
while (!in.eof()) {
string job_definition;
std::getline(in, s);
std::istringstream ss(s);
ss >> job_definition;
if (ss.eof())
break;
string job_status;
for (int i = 0; i < 9; i++)
ss >> job_status;
joblist.insert(make_pair(job_definition, job_status));
}
}
void* WSScheduler::runBackgroundWorker() {
list<WSDHpcCenter*>* hpclist = new list<WSDHpcCenter*>();
WSData::instance()->getAllHPCs(true, *hpclist);
CURL *curl = NULL;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
while (1) {
sleep(job_status_check_delay_in_seconds_);
for (std::list<WSDHpcCenter*>::const_iterator hpciterator = hpclist->begin(), hpciteratorend = hpclist->end(); hpciterator != hpciteratorend; ++hpciterator) {
WSSshSessionPool* sessionpool = NULL;
WSSshSession* sshsession = NULL;
list<WSDJobCompact*>* joblist = NULL;
map<string, string>* joblistonhpc = NULL;
try {
WSDHpcCenter* hpcdata = *hpciterator;
joblist = new list<WSDJobCompact*>();
WSData::instance()->getAllSubmittedAndRunningJobsByHPCID(true, hpcdata->hpc_id, *joblist);
if (joblist->size() == 0) {
delete joblist;
joblist = NULL;
continue;
}
if (hpcdata->qtype == 1) {
// get hpc job status here
sessionpool = getSSHConnectionPool(*hpcdata);
sshsession = sessionpool->getConnectionFromPool("localhost");
string my_stdin = string("qstat -u ") + hpcdata->account_name;
string my_stdout = "";
runRemoteCommand(sshsession->session_, my_stdin, &my_stdout);
joblistonhpc = new map<string, string>();
parseQStatForRunningJobs(my_stdout, *joblistonhpc);
} else if (hpcdata->qtype == 2) {
sessionpool = getSSHConnectionPool(*hpcdata);
sshsession = sessionpool->getConnectionFromPool("localhost");
string my_stdin = string("squeue -u ") + hpcdata->account_name;
string my_stdout = "";
runRemoteCommand(sshsession->session_, my_stdin, &my_stdout);
joblistonhpc = new map<string, string>();
parseSQueueForRunningJobs(my_stdout, *joblistonhpc);
} else {
continue;
}
for (std::list<WSDJobCompact*>::const_iterator jobiterator = joblist->begin(), jobiteratorend = joblist->end(); jobiterator != jobiteratorend; ++jobiterator) {
WSDJobCompact* jobdata = *jobiterator;
string callbackurl = jobdata->callbackurl;
if (callbackurl != "") {
char tempbuffer[15];
sprintf(tempbuffer, "%d", jobdata->job_id);
string str_id = string(tempbuffer);
WSHelper::instance()->replaceStringInPlace(callbackurl, "$id", str_id, true);
}
map<string, string>::iterator it = joblistonhpc->find(jobdata->hpc_job_desc);
if (it == joblistonhpc->end()) {
//bool isjobstatechanged;
//WSData::instance()->setJobState(true, jobdata->job_id, WSDJobOutputStateTransferInQueue, &isjobstatechanged);
// set completed if there exists log file
// otherwise set deleted that might be done by admin
// do not know whether it is deleted or completed within check delay
// let worker thread decide that!
/*
string jstatus = "";
try {
jstatus = WSData::instance()->getJobStatus(true, jobdata->job_id);
} catch (...) {
WSLogger::instance()->log("WSSchedulerBackgroundWorker", "Error in getting job status");
}
if (jstatus == "InHPCQueue") {
continue;
}*/
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateCompletedInHPC, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateCompletedInHPC, false);
WSHPCWork* workitem = new WSHPCWork();
workitem->jobtype = HPCJobCheckResult;
workitem->clientip = "localhost";
workitem->jobid = jobdata->job_id;
workitem->hpcid = jobdata->hpc_id;
workitem->packageid = jobdata->package_id;
workitem->optional = 1; // means do not know
workitem->callbackurl = callbackurl;
WSScheduler::instance()->addHPCWork(workitem);
} else {
if (hpcdata->qtype == 1) {
if (it->second == "R") {
// set running, if in queue
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateRunning, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateRunning, false);
} else if (it->second == "C") {
// set completed if running or in queue
// start job output file transfer
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateCompletedInHPC, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateCompletedInHPC, false);
WSHPCWork* workitem = new WSHPCWork();
workitem->jobtype = HPCJobCheckResult;
workitem->clientip = "localhost";
workitem->jobid = jobdata->job_id;
workitem->hpcid = jobdata->hpc_id;
workitem->packageid = jobdata->package_id;
workitem->optional = 2; // it is known as completed
workitem->callbackurl = callbackurl;
WSScheduler::instance()->addHPCWork(workitem);
} else if (it->second == "E") {
// exiting
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateExiting, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateExiting, false);
} else if (it->second == "H") {
// job is held
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateHeld, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateHeld, false);
} else if (it->second == "Q") {
// job is in queue on hpc
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateInHPCQueue, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateInHPCQueue, false);
} else if (it->second == "T") {
// job is moved
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateMoved, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateMoved, false);
} else if (it->second == "W") {
// job is waiting for its execution time
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateWaiting, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateWaiting, false);
} else if (it->second == "S") {
// job is suspended
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateSuspended, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateSuspended, false);
} else {
// parse error, do not change the state
WSLogger::instance()->log("WSSchedulerBackgroundWorker", "Error in parsing qstat, Err: " + it->second);
}
} else if (hpcdata->qtype == 2) {
if (it->second == "R") {
// set running, if in queue
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateRunning, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateRunning, false);
} else if (it->second == "S") {
// job is suspended
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateSuspended, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateSuspended, false);
} else if (it->second == "CD") {
// set completed if running or in queue
// start job output file transfer
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateCompletedInHPC, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateCompletedInHPC, false);
WSHPCWork* workitem = new WSHPCWork();
workitem->jobtype = HPCJobCheckResult;
workitem->clientip = "localhost";
workitem->jobid = jobdata->job_id;
workitem->hpcid = jobdata->hpc_id;
workitem->packageid = jobdata->package_id;
workitem->optional = 2; // it is known as completed
workitem->callbackurl = callbackurl;
WSScheduler::instance()->addHPCWork(workitem);
} else if (it->second == "CG") {
// exiting
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateExiting, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateExiting, false);
} else if (it->second == "PD") {
// job is waiting for its execution time
bool isjobstatechanged;
WSData::instance()->setJobState(true, jobdata->job_id, WSDJobStateWaiting, &isjobstatechanged);
if (isjobstatechanged)
doCallback(curl, callbackurl, WSDJobStateWaiting, false);
} else {
// parse error, do not change the state
WSLogger::instance()->log("WSSchedulerBackgroundWorker", "Error in parsing squeue, Err: " + it->second);
}
}
}
}
} catch (WSException& e) {
WSLogger::instance()->log("WSSchedulerBackgroundWorker", e);
} catch (const std::exception& e) {
WSLogger::instance()->log("WSSchedulerBackgroundWorker", string(e.what()));
} catch (...) {
WSLogger::instance()->log("WSSchedulerBackgroundWorker", "Unidentified exception");
}
if (joblistonhpc) {
delete joblistonhpc;
joblistonhpc = NULL;
}
if (joblist) {
for (std::list<WSDJobCompact*>::const_iterator jobiterator = joblist->begin(), jobiteratorend = joblist->end(); jobiterator != jobiteratorend; ++jobiterator) {
WSDJobCompact* jobdata = *jobiterator;
delete jobdata;
}
delete joblist;
joblist = NULL;
}
if (sessionpool && sshsession)
sessionpool->returnConnectionToPool(sshsession);
}
}
if (curl)
curl_easy_cleanup(curl);
}
static size_t null_function(void *buffer, size_t size, size_t nmemb, void *mydata) {
return size;
}
bool WSScheduler::doCallback(CURL *curl, string url, WSDHPCWorkState state, bool ispackage) {
if (!curl)
return false;
if (url == "")
return false;
CURLcode res;
string str_state = "unknown";
switch (state) {
case WSDJobStateError:
str_state = "JobError";
break;
case WSDPackageStateError:
str_state = "PackageError";
break;
case WSDHPCWorkUnknownError:
str_state = "UnknownError";
break;
case WSDPackageStateInQueue:
str_state = "PackageInServiceQueue";
break;
case WSDPackageStateRunning:
str_state = "PreparingPackage";
break;
case WSDPackageStateTransferring:
str_state = "TransferringPackage";
break;
case WSDPackageStateUnzipping:
str_state = "UnzippingPackage";
break;
case WSDPackageStateDone:
str_state = "PackageTransferDone";
break;
case WSDJobStateInServiceQueue:
str_state = "JobInServiceQueue";
break;
case WSDJobStateInHPCQueue:
str_state = "JobInHPCQueue";
break;
case WSDJobStateRunning:
str_state = "JobRunning";
break;
case WSDJobStateExiting:
str_state = "JobExiting";
break;
case WSDJobStateHeld:
str_state = "JobHeld";
break;
case WSDJobStateMoved:
str_state = "JobMoved";
break;
case WSDJobStateWaiting:
str_state = "JobWaiting";
break;
case WSDJobStateSuspended:
str_state = "JobSuspended";
break;
case WSDJobStateCompleted:
str_state = "JobCompleted";
break;
case WSDJobStateDeleted:
str_state = "JobDeleted";
break;
case WSDJobOutputStateTransferInQueue:
str_state = "JobOutputTransferInQueue";
break;
case WSDJobOutputStateTransferring:
str_state = "JobOutputTransferring";
break;
case WSDJobOutputStateTransferDone:
str_state = "JobOutputTransferDone";
break;
case WSDPackageDeleted:
str_state = "JobPackageDeleted";
break;
case WSDJobStateCompletedInHPC:
str_state = "JobCompletedInHPC";
break;
}
WSHelper::instance()->replaceStringInPlace(url, "$state", str_state, true);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, null_function);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
return false;
}
return true;
}
static size_t remoteToSCPWrite(void *buffer, size_t size, size_t nmemb, void *stream) {
struct RemoteFile *out = (struct RemoteFile *) stream;
int rc;
if (out && !out->isinitialized) {
out->isinitialized = true;
double filelength;
curl_easy_getinfo(out->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD,
&filelength);
string package_file_name = WSHelper::instance()->getSafeFileName(out->filename);
rc = ssh_scp_push_file
(out->scp, "package.zip", filelength, S_IRUSR | S_IWUSR);
if (rc != SSH_OK) {
string error = string("can't open remote file: ") + string(ssh_get_error(out->sshsession->session_));
out->exception = error;
return -1;
}
}
rc = ssh_scp_write(out->scp, buffer, nmemb * size);
if (rc != SSH_OK) {
string error = string("can't write to remote file: ") + string(ssh_get_error(out->sshsession->session_));
out->exception = error;
return -1;
}
return nmemb * size;
}
static size_t remoteToSCPRead(void *buffer, size_t size, size_t nmemb, void *stream) {
struct RemoteFile2 *out = (struct RemoteFile2 *) stream;
size_t nbytes = ssh_scp_read(out->scp, buffer, nmemb * size);
if (nbytes == SSH_ERROR) {
string error = string("can't read from remote file: ") + string(ssh_get_error(out->sshsession->session_));
out->exception = error;
return -1;
}
return nbytes;
}
void* WSScheduler::runWorkerItemEntry(WSScheduler::WSSchedulerWorkItem* witem) {
curl_global_init(CURL_GLOBAL_DEFAULT);
while (witem->cont) {
WSHPCWork* workitem = NULL;
WSSshSession* sshsession = NULL;
WSSshSessionPool* sessionpool = NULL;
string my_stdout = "";
string my_stderr = "";
string my_stdin = "";
int error_code = -1;
CURL *curl = NULL;
string callbackurl = "";
try {
workitem = witem->scheduler->removeHPCWork();
witem->state = WITEM_PROCESSING;
if (workitem->jobtype == HPCJobPackageUpload) {
char tempbuffer [15];
string callbackurl = workitem->callbackurl;
if (callbackurl != "") {
curl = curl_easy_init();
//bool jobcallbackhttps = false;
//int pos = callbackurl.find("https");
//if (pos == 0)
// jobcallbackhttps = true;
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
sprintf(tempbuffer, "%d", workitem->packageid);
string str_id = string(tempbuffer);
WSHelper::instance()->replaceStringInPlace(callbackurl, "$id", str_id, true);
}
WSData::instance()->updatePackageState(true, workitem->packageid, WSDPackageStateRunning);
doCallback(curl, callbackurl, WSDPackageStateRunning, true);
WSDHpcCenter hpc_center_rec;
WSData::instance()->getHpcCenterByID(true, workitem->hpcid, &hpc_center_rec);
sessionpool = witem->scheduler->getSSHConnectionPool(hpc_center_rec);
sshsession = sessionpool->getConnectionFromPool(workitem->clientip);
uuid_t package_uuid;
uuid_generate_time_safe(package_uuid);
char str_uuid[37];
uuid_unparse_lower(package_uuid, str_uuid);
uuid_clear(package_uuid);
string remote_dirname = string(str_uuid);
WSData::instance()->setPackageFolder(true, workitem->packageid, remote_dirname);
ssh_scp scp;
int rc;
scp = ssh_scp_new
(sshsession->session_, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
if (scp == NULL) {
string error = string("error allocating scp session: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_scp_init(scp);
if (rc != SSH_OK) {
ssh_scp_free(scp);
string error = string("error initializing scp session: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_scp_push_directory(scp, ".hydrogate", S_IRWXU);
if (rc != SSH_OK) {
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("can't create remote directory: .hydrogate error: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_scp_push_directory(scp, "data", S_IRWXU);
if (rc != SSH_OK) {
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("can't create remote directory: data error: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
rc = ssh_scp_push_directory(scp, remote_dirname.c_str(), S_IRWXU);
if (rc != SSH_OK) {
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("can't create remote directory: ") + remote_dirname + " error: " + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
if (isinputinlocalmode_) {
ifstream ifs(workitem->packagepath.c_str(), ios::binary | ios::ate);
if (!ifs.good()) {
ifs.close();
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("couldn't find the file: ") + workitem->packagepath;
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
ifstream::pos_type length = ifs.tellg();
ifs.seekg(0, ios::beg);
char *pChars = new char[scp_bufsiz_];
if (!pChars) {
ifs.close();
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("failed to allocate memory for reading package data");
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
try {
WSData::instance()->updatePackageState(true, workitem->packageid, WSDPackageStateTransferring);
} catch (WSException& e) {
ifs.close();
free(pChars);
ssh_scp_close(scp);
ssh_scp_free(scp);
throw;
}
doCallback(curl, callbackurl, WSDPackageStateTransferring, true);
rc = ssh_scp_push_file
(scp, "package.zip", length, S_IRUSR | S_IWUSR);
if (rc != SSH_OK) {
ifs.close();
free(pChars);
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("can't open remote file: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
int percentagedone = 0;
size_t uploadedsofar = 0;
while (true) {
ifs.read(pChars, scp_bufsiz_);
int numofreadbytes = ifs.gcount();
uploadedsofar += numofreadbytes;
percentagedone = (int) ((((double) uploadedsofar) / ((double) length)) * 100.0);
if (numofreadbytes <= 0)
break;
rc = ssh_scp_write(scp, pChars, numofreadbytes);
if (rc != SSH_OK) {
ifs.close();
free(pChars);
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("can't write to remote file: ") + string(ssh_get_error(sshsession->session_));
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}
}
ifs.close();
free(pChars);
} else {
try {
WSData::instance()->updatePackageState(true, workitem->packageid, WSDPackageStateTransferring);
} catch (WSException& e) {
ssh_scp_close(scp);
ssh_scp_free(scp);
throw;
}
doCallback(curl, callbackurl, WSDPackageStateTransferring, true);
bool isIrods = false;
if (workitem->packagepath[0] == '/') {
isIrods = true;
}
if (isIrods) {
string pathinlocal = getUniqueFileName(workitem->inputfolder, ".zip");
string command = "iget " + workitem->packagepath + " " + pathinlocal;
int ret = system(command.c_str());
if (ret != 0) {
string error = string("failed to iget the file ") + command;
throw WSException(WS_EXCEPTION_IRODS, error);
}
ifstream ifs(pathinlocal.c_str(), ios::binary | ios::ate);
if (!ifs.good()) {
ifs.close();
ssh_scp_close(scp);
ssh_scp_free(scp);
string error = string("couldn't find the file: ") + pathinlocal;
remove(pathinlocal.c_str());
throw WSException(WS_EXCEPTION_SSH_ERROR, error);
}