forked from ibethune/llr_wrapper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrapper.C
1086 lines (943 loc) · 30.2 KB
/
wrapper.C
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
// BOINC wrapper for running the LLR application
// Based on an old version of the wrapper developed
// by Andrew J. Younge and provided by BOINC
// See http://boinc.berkeley.edu/trac/wiki/WrapperApp for details
// Copyright (C) 2005 University of California
// Licensed under the GNU Lesser General Public License
// http://www.gnu.org/copyleft/lesser.html
// wrapper.C
// Current version modified by Iain Bethune
// Previous contributions by Mike Goetz, Rytis Slatkevicius, and others...
// System headers needed in all cases
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
#ifdef _WIN32
// Windows-only headers
#include "boinc_win.h"
#include "win_util.h" // for suspend_resume()
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
#else
// Linux/Mac headers
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <fstream>
#include <sys/resource.h>
#include <sys/times.h>
#endif
// BOINC includes
#include "boinc_api.h"
#include "diagnostics.h"
#include "filesys.h"
#include "util.h"
#include "error_numbers.h"
#include "version.h"
#define API_VERSION (BOINC_MAJOR_VERSION * 10000 + BOINC_MINOR_VERSION * 100 + BOINC_RELEASE)
#if API_VERSION >= 61302
#include "proc_control.h"
#endif
#ifndef BITNESS
#error "BITNESS must be defined e.g. 64 or 32"
#endif
#ifndef WRAPPER_VERSION
#error "WRAPPER_VERSION must be defined e.g. 7.00"
#endif
#define STR(X) STR2(X)
#define STR2(X) #X
#define POLL_PERIOD 1.0
#define TRICKLE_PERIOD 86400.0 // 24 hours
#define TRICKLE_FILE "trickle.dat"
#define TEST_TYPE_MAX_LENGTH 9
#define TEST_TYPE_PRP "PRP"
#define TEST_TYPE_PRIMALITY "Primality"
#define ERR_VERSION_CHECK -99
#define ERR_INVALID_ARGS -100
#define LINE_LENGTH 80
// The name of the executable that does the actual work:
#ifdef _WIN32
const std::string llr_app_name = "primegrid_cllr.exe";
#else
const std::string llr_app_name = "primegrid_llr";
#endif
// File names and arguments
const std::string llr_ini_file_name = "llr.ini";
const std::string llr_in_file_name = "llr.in";
const std::string wrapper_in_file_name = "wrapper.in";
const std::string out_file_name = "llr.out";
const std::string llr_verbose = "-d";
const std::string llr_print_version = "-v";
const std::string llr_doOnlyPRP = "-oForcePRP=1";
const std::string llr_doFermatPRP = "-oFermatPRPtest=1";
const std::string llr_multiThread = "-oThreadsPerTest=";
const std::string llr_checkpointPeriod = "-oDiskWriteTime=";
const std::string llr_results = "lresults.txt";
const std::string llr_results_parsed = "lresults_parsed.txt";
#ifndef _WIN32
const std::string llr_results_parsed_dos = "lresults_parsed.txt.dos";
#endif
struct TASK
{
int nthreads;
int checkpoint_period;
double progress;
double old_progress;
double old_time;
double old_checkpoint_time;
time_t last_trickle;
bool bGotFFT;
bool app_suspended;
#ifdef _WIN32
HANDLE pid_handle;
DWORD pid;
HANDLE hOutputReadTmp, hOutputRead, hOutputWrite;
#else
int pid;
int fdOutputRead;
#endif
TASK() : nthreads(0), checkpoint_period(10), progress(0.0),
old_progress(0.0), old_time(0.0), old_checkpoint_time(0.0),
last_trickle(time(NULL)),
#ifdef _WIN32
pid_handle(0),
#endif
pid(0), bGotFFT(false), app_suspended (false) {}
bool poll(int& status);
int run();
void terminate();
void kill();
void suspend();
void resume();
double cpu_time();
double read_status();
void poll_boinc_messages();
void send_status_message(double checkpoint_period);
void trickle_up_progress();
};
int TASK::run()
{
int retval;
bool forcePRP = false;
// First we check for a wrapper input file
std::string wrapper_in_file;
boinc_resolve_filename_s(wrapper_in_file_name.c_str(), wrapper_in_file);
int llr_version_req = 0, llr_major_req = 0, llr_minor_req = 0;
FILE *w_in = boinc_fopen(wrapper_in_file.c_str(), "r");
if (w_in)
{
char line[LINE_LENGTH], test_type[TEST_TYPE_MAX_LENGTH+1];
int wrapper_major_req, wrapper_minor_req;
// Read the control line from the wrapper input
if (fgets(line, LINE_LENGTH, w_in) != NULL &&
sscanf(line,"%d.%d %d.%d.%d %s", &wrapper_major_req, &wrapper_minor_req, &llr_version_req, &llr_major_req, &llr_minor_req, test_type) == 6)
{
int wrapper_major, wrapper_minor;
if (sscanf(STR(WRAPPER_VERSION),"%d.%d", &wrapper_major, &wrapper_minor) == 2)
{
if (wrapper_major_req > wrapper_major || (wrapper_major_req == wrapper_major && wrapper_minor_req > wrapper_minor))
{
std::cerr << "Req wrapper version: " << wrapper_major_req << "." << wrapper_minor_req << std::endl;
std::cerr << "Found wrapper version: " << wrapper_major << "." << wrapper_minor << std::endl;
std::cerr << "A newer version of the LLR wrapper is required!" << std::endl;
fclose(w_in);
return ERR_VERSION_CHECK;
}
}
else
{
std::cerr << "Failed to determine the wrapper version" << std::endl;
fclose(w_in);
return ERR_VERSION_CHECK;
}
if (strncmp(test_type, TEST_TYPE_PRP, TEST_TYPE_MAX_LENGTH) == 0)
{
std::cerr << "PRP test requested" << std::endl;
forcePRP = true;
}
else if (strncmp(test_type, TEST_TYPE_PRIMALITY, TEST_TYPE_MAX_LENGTH) == 0)
{
std::cerr << "Primality test requested" << std::endl;
}
else
{
std::cerr << "Could not parse test type, proceeding with a primality test..." << std::endl;
}
}
else
{
std::cerr << "Error reading from " << wrapper_in_file_name << std::endl;
fclose(w_in);
return ERR_READ;
}
// Copy the following two lines to the LLR input file
FILE *l_in = boinc_fopen(llr_in_file_name.c_str(), "w");
fgets(line, sizeof(line),w_in);
fputs(line, l_in);
fgets(line, sizeof(line),w_in);
fputs(line, l_in);
fclose(l_in);
fclose(w_in);
}
// Run LLR to get the version number
char buf[256];
#ifdef _WIN32
DWORD len;
// llr.ini MUST be writeable, so explicitly remove the read-only bit
// a read-only llr.ini might be the cause of the "3 second error"
if (SetFileAttributes(llr_ini_file_name.c_str(), FILE_ATTRIBUTE_NORMAL) == 0)
std::cerr << "Removing Read-Only from " << llr_ini_file_name << " FAILED!" << std::endl;
std::string command_line = llr_app_name + " " + llr_print_version;
std::replace(command_line.begin(), command_line.end(), '/', '\\');
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
SECURITY_ATTRIBUTES sa;
sa.nLength= sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
// Create a pipe to read from the child process
if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0))
{
std::cerr << "Failed to create pipe" << std::endl;
return 250; // 250: Failed to create pipe
}
if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp,
GetCurrentProcess(),
&hOutputRead, // Address of new handle.
0,FALSE, // Make it uninheritable.
DUPLICATE_SAME_ACCESS))
{
std::cerr << "Failed to DuplicateHandle()" << std::endl;
return 251;
}
memset(&process_info, 0, sizeof(process_info));
memset(&startup_info, 0, sizeof(startup_info));
// pass handles to app
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdError = hOutputWrite;
startup_info.hStdOutput = hOutputWrite;
if (!CreateProcess(llr_app_name.c_str(),
(LPSTR)command_line.c_str(),
NULL,
NULL,
true, // inherit handles
CREATE_NO_WINDOW|IDLE_PRIORITY_CLASS,
NULL,
NULL,
&startup_info,
&process_info
))
{
std::cerr << "Invocation of CreateProcess( " << llr_app_name << " ) FAILED!" << std::endl;
return ERR_EXEC;
}
// Wait for LLR to exit
WaitForSingleObject( process_info.hProcess, INFINITE );
CloseHandle( process_info.hProcess );
CloseHandle( process_info.hThread );
if(ReadFile(hOutputRead, buf, sizeof(buf)-1, &len, NULL))
{
buf[len] = '\0';
std::cerr << buf << std::endl;
}
else
{
std::cerr << "Error reading the LLR version number, continuing..." << std::endl;
}
#else
int len, fd_out[2];
if (pipe(fd_out) < 0)
{
std::cerr << "Failed to create pipe" << std::endl;
return 250; // 250: Failed to create pipe
}
pid = fork();
if (pid == -1)
{
boinc_finish(ERR_FORK);
}
if (pid == 0)
{
// we're in the child process here
close(fd_out[0]);
dup2(fd_out[1],STDOUT_FILENO);
retval = execl(llr_app_name.c_str(), llr_app_name.c_str(), llr_print_version.c_str(), NULL);
// If execl failed for some reason
// wait 5 seconds then try again,
// A second failure is fatal
std::cerr << "execl failed once: " << strerror(errno) << std::endl;
boinc_sleep(5.0);
retval = execl(llr_app_name.c_str(), llr_app_name.c_str(), llr_print_version.c_str(), NULL);
std::cerr << "execl failed twice: " << strerror(errno) << std::endl;
exit(ERR_EXEC);
}
else
{
// In the parent process
int status;
// Wait for LLR to exit
waitpid(pid, &status, WUNTRACED);
close(fd_out[1]);
/* Prevent parent read() blocking on child output pipe. */
fcntl(fd_out[0],F_SETFL,fcntl(fd_out[0],F_GETFL)|O_NONBLOCK);
if ((len = read(fd_out[0],buf,sizeof(buf)-1)) > 0)
{
buf[len] = '\0';
std::cerr << buf << std::endl;
}
else
{
std::cerr << "Error reading the LLR version number, continuing..." << std::endl;
}
}
#endif
if (llr_version_req != 0 || llr_major_req !=0 || llr_minor_req != 0)
{
int llr_version, llr_major, llr_minor;
// buf contains a null-terminated LLR version string (assumed to always be in this format)
if (sscanf(buf,"LLR Program - Version %d.%d.%d", &llr_version, &llr_major, &llr_minor) != 3)
{
std::cerr << "Error parsing the LLR version string!" << std::endl;
return ERR_VERSION_CHECK;
}
// A version number was specified in the wrapper.in, so check it
if (llr_version_req > llr_version ||
(llr_version_req == llr_version && llr_major_req > llr_major ) ||
(llr_version_req == llr_version && llr_major_req == llr_major && llr_minor_req > llr_minor))
{
std::cerr << "A newer version of LLR is required!" << std::endl;
return ERR_VERSION_CHECK;
}
}
// Now run LLR again to perform the test
std::string llr_in_file;
boinc_resolve_filename_s(llr_in_file_name.c_str(), llr_in_file);
std::ostringstream s;
s << checkpoint_period;
std::string checkpoint_str = llr_checkpointPeriod + s.str();
s.str("");
s << nthreads;
std::string multiThread_str = llr_multiThread + s.str();
#ifdef __WIN32
// Arguments that are always present
command_line = llr_app_name + " " + llr_verbose + " " + checkpoint_str;
// Optional arguments
if (nthreads != 0) // nthreads == 0 means the user didn't specify the number of threads
{
command_line = command_line + " " + multiThread_str;
}
if (forcePRP)
{
command_line = command_line + " " + llr_doOnlyPRP + " " + llr_doFermatPRP;
}
// Last, the input file
command_line = command_line + " " + llr_in_file;
std::replace(command_line.begin(), command_line.end(), '/', '\\');
std::cerr << "LLR command line: " << command_line << std::endl;
memset(&process_info, 0, sizeof(process_info));
memset(&startup_info, 0, sizeof(startup_info));
// pass handles to app
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdError = hOutputWrite;
startup_info.hStdOutput = hOutputWrite;
if (!CreateProcess(llr_app_name.c_str(),
(LPSTR)command_line.c_str(),
NULL,
NULL,
true, // inherit handles
CREATE_NO_WINDOW|IDLE_PRIORITY_CLASS,
NULL,
NULL,
&startup_info,
&process_info
))
{
std::cerr << "Invocation of CreateProcess( " << llr_app_name << " ) FAILED!" << std::endl;
return ERR_EXEC;
}
pid_handle = process_info.hProcess;
pid = process_info.dwProcessId;
HANDLE thread_handle = process_info.hThread;
SetThreadPriority(thread_handle, THREAD_PRIORITY_IDLE);
#else
if (pipe(fd_out) < 0)
{
std::cerr << "Failed to create pipe" << std::endl;
return 250; // 250: Failed to create pipe
}
// Build the argument list (max 9 args, including NULL terminator)
const char *argList[9];
int i = 0;
// Arguments that are always present
argList[i] = llr_app_name.c_str(); i++;
argList[i] = llr_verbose.c_str(); i++;
argList[i] = checkpoint_str.c_str(); i++;
// Optional arguments
if (nthreads != 0) // nthreads == 0 means the user didn't specify the number of threads
{
argList[i] = multiThread_str.c_str(); i++;
}
if (forcePRP)
{
argList[i] = llr_doOnlyPRP.c_str(); i++;
argList[i] = llr_doFermatPRP.c_str(); i++;
}
// Last, the input file
argList[i] = llr_in_file.c_str(); i++;
argList[i] = NULL;
std::cerr << "LLR command line: ";
for (int arg = 0; arg < i; arg++)
{
std::cerr << " " << argList[arg];
}
std::cerr << std::endl;
pid = fork();
if (pid == -1)
{
boinc_finish(ERR_FORK);
}
if (pid == 0)
{
// we're in the child process here
close(fd_out[0]);
dup2(fd_out[1],STDOUT_FILENO);
setpriority(PRIO_PROCESS, 0, PROCESS_IDLE_PRIORITY);
retval = execv(argList[0], (char **)argList);
// If execl failed for some reason
// wait 5 seconds then try again,
// A second failure is fatal
std::cerr << "execv failed once: " << strerror(errno) << std::endl;
boinc_sleep(5.0);
retval = execv(argList[0], (char **)argList);
std::cerr << "execv failed twice: " << strerror(errno) << std::endl;
exit(ERR_EXEC);
}
else
{
// In the parent process
close(fd_out[1]);
/* Prevent parent read() blocking on child output pipe. */
fcntl(fd_out[0],F_SETFL,fcntl(fd_out[0],F_GETFL)|O_NONBLOCK);
fdOutputRead = fd_out[0];
}
#endif
app_suspended = false;
return 0;
}
bool TASK::poll(int& status)
{
#ifdef _WIN32
unsigned long exit_code;
if (GetExitCodeProcess(pid_handle, &exit_code)) {
if (exit_code != STILL_ACTIVE) {
status = exit_code;
return true;
}
}
#else
int wpid;
struct rusage ru;
wpid = wait4(pid, &status, WNOHANG, &ru);
if (wpid) return true;
#endif
return false;
}
void TASK::kill()
{
#ifdef _WIN32
TerminateProcess(pid_handle, -1);
#else
// Send a KILL, LLR terminates ASAP
::kill(pid, SIGKILL);
#endif
}
void TASK::terminate()
{
#ifdef _WIN32
TerminateProcess(pid_handle, -1);
#else
// Send a TERM, then wait until LLR checkpoints and terminates
::kill(pid, SIGTERM);
int status;
waitpid(pid, &status, WUNTRACED);
#endif
}
void TASK::suspend()
{
#if API_VERSION >= 61302
suspend_or_resume_process(pid, false);
#else
#ifdef _WIN32
suspend_or_resume_threads(pid, 0, false);
#else
::kill(pid, SIGSTOP);
#endif
#endif
}
void TASK::resume()
{
#if API_VERSION >= 61302
suspend_or_resume_process(pid, true);
#else
#ifdef _WIN32
suspend_or_resume_threads(pid, 0, true);
#else
::kill(pid, SIGCONT);
#endif
#endif
}
void TASK::poll_boinc_messages()
{
BOINC_STATUS status;
boinc_get_status(&status);
if (status.no_heartbeat)
{
terminate();
exit(0);
}
if (status.quit_request)
{
terminate();
exit(0);
}
if (status.abort_request)
{
kill();
exit(0);
}
if (status.suspended)
{
if (!app_suspended)
{
suspend();
app_suspended = true;
}
}
else
{
if (app_suspended)
{
resume();
app_suspended = false;
}
}
}
double TASK::cpu_time()
{
#ifdef _WIN32
double cpu;
OSVERSIONINFOEX osvi;
SYSTEM_INFO si;
PGNSI pGNSI;
BOOL bOsVersionInfoEx;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
// Try calling GetVersionEx using the OSVERSIONINFOEX structure.
// If that fails, try using the OSVERSIONINFO structure.
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) {
osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
return FALSE;
}
// Call GetNativeSystemInfo if supported or GetSystemInfo otherwise.
pGNSI = (PGNSI) GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")),
"GetNativeSystemInfo");
if (NULL != pGNSI) {
pGNSI(&si);
} else {
GetSystemInfo(&si);
}
switch (osvi.dwPlatformId) {
case VER_PLATFORM_WIN32_NT:
FILETIME creation_time, exit_time, kernel_time, user_time;
ULARGE_INTEGER tKernel, tUser;
LONGLONG totTime;
GetProcessTimes(
pid_handle, &creation_time, &exit_time, &kernel_time, &user_time
);
tKernel.LowPart = kernel_time.dwLowDateTime;
tKernel.HighPart = kernel_time.dwHighDateTime;
tUser.LowPart = user_time.dwLowDateTime;
tUser.HighPart = user_time.dwHighDateTime;
totTime = tKernel.QuadPart + tUser.QuadPart;
cpu = totTime / 1.e7;
return cpu;
break;
case VER_PLATFORM_WIN32_WINDOWS:
cpu = 3600; // Better than nothing...
return cpu;
break;
}
return 0;
#elif defined(__linux__)
struct tms t;
FILE *f;
char fn[32];
unsigned long ut, st;
clock_t ticks = 0;
/* Add CPU times used by parent and completed children */
if (times(&t) != (clock_t)-1)
ticks += (t.tms_utime + t.tms_stime + t.tms_cutime + t.tms_cstime);
/* Add CPU times used by incomplete children */
sprintf(fn,"/proc/%d/stat",pid);
if ((f = fopen(fn,"r")) != NULL)
{
if (fscanf(f,"%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%lu%lu",&ut,&st)==2)
ticks += (ut + st);
fclose(f);
}
/* CLK_TCK should be defined in <sys/times.h>, but it goes missing when
compiling C++. */
#ifndef CLK_TCK
# define CLK_TCK ((clock_t)sysconf(_SC_CLK_TCK))
#endif
return (double)ticks/CLK_TCK;
#else
static double t=0, cpu;
if (t) {
double now = dtime();
cpu += now-t;
t = now;
} else {
t = dtime();
}
return cpu;
#endif
}
double TASK::read_status()
{
char buf[256];
for (;;)
{
#ifdef _WIN32
DWORD child_stdout = 0;
if (!::PeekNamedPipe(hOutputRead, NULL, 0, NULL,&child_stdout, NULL))
// break loop, child process terminated
break;
if (!child_stdout)
// no data available from child, return old_progress(?)...
return old_progress;
DWORD len;
if (ReadFile(hOutputRead, buf, sizeof(buf)-1, &len, NULL))
#else
ssize_t len;
if ((len = read(fdOutputRead,buf,sizeof(buf)-1)) > 0)
#endif
{
const char *fft_key[] = {"Using"};
const char *iter_key[] = {"iteration :", "bit:", "Iter:", "Bit:"};
char *str,*end;
size_t i;
char ch;
int x, y;
buf[len] = '\0';
if (bGotFFT == false)
{
for (i = 0; i < sizeof(fft_key)/sizeof(fft_key[0]); i++)
{
if ((str = strstr(buf,fft_key[i])) != NULL)
{
end = str;
// Find the next new line or carriage return
while (*end != '\0' && *end != '\r' && *end != '\n') end++;
*end = '\0';
std::cerr << str << std::endl;
bGotFFT = true;
break;
}
}
}
for (i = 0; i < sizeof(iter_key)/sizeof(iter_key[0]); i++)
{
if (((str = strstr(buf,iter_key[i])) != NULL) &&
(sscanf(str+strlen(iter_key[i])," %d / %d%c",&x,&y,&ch) == 3) &&
(y > 0))
{
return (double)x/y;
}
}
}
#ifndef _WIN32
// Mac and Linux don't loop back
break;
#endif
}
return -1.0;
}
void TASK::send_status_message(double checkpoint_period)
{
double new_checkpoint_time = old_checkpoint_time;
double cputime = cpu_time();
old_progress = progress;
progress = read_status();
new_checkpoint_time = cputime + old_time;
if (progress > old_progress)
old_checkpoint_time = new_checkpoint_time;
if (progress < 0)
progress = old_progress;
boinc_report_app_status(
cputime + old_time,
old_checkpoint_time,
progress
);
boinc_fraction_done(progress);
}
void TASK::trickle_up_progress()
{
time_t now = time(NULL);
// If the time since the last trickle is long enough, and we have valid progress to report
if (difftime(now, last_trickle) > TRICKLE_PERIOD && progress != 0.0)
{
// Send progress via a trickle-up message
last_trickle = now;
double progress = boinc_get_fraction_done();
double cpu;
boinc_wu_cpu_time(cpu); // Only from previous runs, since we don't checkpoint
cpu += cpu_time();
APP_INIT_DATA init_data;
boinc_get_init_data(init_data);
double run = boinc_elapsed_time() + init_data.starting_elapsed_time;
char msg[512];
sprintf(msg, "<trickle_up>\n"
" <progress>%f</progress>\n"
" <cputime>%f</cputime>\n"
" <runtime>%f</runtime>\n"
"</trickle_up>\n",
progress, cpu, run );
char variety[64];
sprintf(variety, "llr_progress");
int ret = boinc_send_trickle_up(variety, msg);
// Store the last_trickle timestamp to a file, so we can recover it when we restart.
FILE *f = boinc_fopen(TRICKLE_FILE, "wb"); // overwrite
if (f)
{
fwrite(&last_trickle, sizeof(time_t), 1, f);
fclose(f);
}
}
}
#ifndef _WIN32
bool unix2dos(const std::string& in, const std::string& out)
{
std::ifstream in_file(in.c_str());
std::ofstream out_file(out.c_str());
if ((!in_file) || (!out_file))
return false;
std::string buffer;
while (std::getline(in_file, buffer))
out_file << buffer << "\r\n";
out_file << std::flush;
out_file.close();
return true;
}
#endif
int main(int argc, char** argv)
{
BOINC_OPTIONS options;
TASK t;
int retval;
#ifndef _WIN32
// Close good amount of possibly opened (inherited) handles except standard 0-2
// (stdin, stdout, stderr) to avoid handle-inheritance-on-exec bug in older Boinc clients
// https://github.com/BOINC/boinc/issues/1388
for (int i = 3; i < 100; i++)
{
close(i);
}
#endif
boinc_init_diagnostics(
BOINC_DIAG_DUMPCALLSTACKENABLED |
BOINC_DIAG_HEAPCHECKENABLED |
BOINC_DIAG_TRACETOSTDERR |
BOINC_DIAG_REDIRECTSTDERR
);
memset(&options, 0, sizeof(options));
options.main_program = true;
options.check_heartbeat = true;
options.handle_process_control = true;
#if API_VERSION < 70500
options.handle_trickle_ups = true;
#endif
std::cerr << "BOINC llr wrapper (version " << STR(WRAPPER_VERSION) << ")" << std::endl;
std::cerr << "Using Jean Penne's llr (" << BITNESS << " bit)" << std::endl;
boinc_init_options (&options);
bool args_ok = false;
// First up, check command line args
// Only supported usage is ./llr_wrapper [-t N] | [--nthreads N] (multithreading)
if (argc == 1)
{
args_ok = true;
}
else if (argc == 3)
{
if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--nthreads") == 0)
{
char str1[132], end[10];
sprintf(str1, "%send", argv[2]);
if (sscanf(str1, "%d%s", &(t.nthreads), (char*)&end) != 2)
{
std::cerr << argv[1] << " requires a number" << std::endl;
}
else
{
if (t.nthreads < 1)
{
std::cerr << "Number of threads (" << argv[1] << ") must be >= 1" << std::endl;
}
else
{
args_ok = true;
}
}
}
else
{
std::cerr << "Unrecognised argument: " << argv[1] << std::endl;
}
}
if (!args_ok)
{
std::cerr << "Usage: " << argv[0] << " [-t N] | [--nthreads N]" << std::endl;
boinc_finish(ERR_INVALID_ARGS);
}
// Read the user's checkpoint frequency from BOINC
APP_INIT_DATA uc_aid;
boinc_get_init_data(uc_aid);
t.checkpoint_period = (int)ceilf(uc_aid.checkpoint_period / 60.0);
if (t.checkpoint_period < 1) t.checkpoint_period = 1;
// Start application
boinc_wu_cpu_time(t.old_time);
t.old_checkpoint_time = t.old_time;
retval = t.run();
if (retval)
{
std::cerr << "Can't run app: " << llr_app_name << " (Error code: " << retval << ")" << std::endl;
boinc_finish(retval);
}
// Attempt to read the last trickle timestamp from file
bool got_trickle = false;
FILE *f = boinc_fopen(TRICKLE_FILE, "rb");
if (f)
{
time_t last_trickle_read;
if (fread(&last_trickle_read, sizeof(time_t), 1, f) == 1)
{
t.last_trickle = last_trickle_read;
got_trickle = true;
}
fclose(f);
}
// If we couldn't read a trickle timestamp, try to create a new one
if (!got_trickle)
{
f = boinc_fopen(TRICKLE_FILE, "wb"); // overwrite
if (f)
{
fwrite(&(t.last_trickle), sizeof(time_t), 1, f);
fclose(f);
}
}
// Poll for application status
int status;
for(;;)
{
if (t.poll(status))
{
#ifndef _WIN32
if (WIFEXITED(status))
{
// process exited by calling exit() or returning from main
int child_ret_val = WEXITSTATUS(status);
std::cerr << "LLR exited with code: "
<< child_ret_val << std::endl;
if (child_ret_val != 0) {
// LLR exited with a non-zero exit status
boinc_finish(child_ret_val);
}
}
else if (WIFSIGNALED(status))
{