-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolverManager.cpp
616 lines (495 loc) · 15.3 KB
/
SolverManager.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
/*
Copyright (c) Dan Liew 2012
This file is part of NSolv.
NSolv 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.
NSolv 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 NSolv. If not, see <http://www.gnu.org/licenses/>
*/
#include "global.h"
#include "SolverManager.h"
#include <iostream>
#include <cmath>
#include <signal.h>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <cstdio>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sstream>
using namespace std;
SolverManager::SolverManager(const std::string& _inputFile, double _timeout, bool _loggingMode ) :
solvers(), pidToSolverMap(), inputFile(_inputFile), empty(""), fdToSolverMap(), largestFileDescriptor(0),
loggingMode(_loggingMode)
{
//set timeout
double intPart;
modf(_timeout,&intPart);
originalTimeout.tv_sec = timeout.tv_sec = static_cast<time_t>(intPart);
originalTimeout.tv_nsec = timeout.tv_nsec = 0;
if(verbose && _timeout != 0)
cerr << "SolverManager: Using timeout of " << timeout.tv_sec << " second(s)." << endl;
if(loggingMode)
{
if(verbose) cerr << "SolverManager: Using logging mode. Log file is " << loggingPath << endl;
//Open the file for output and append to previous logging data
loggingFile.open(loggingPath.c_str(), ios_base::out | ios_base::app);
//set precision for use with times
loggingFile.setf(ios::fixed,ios::floatfield);
loggingFile.precision(9); //show nanosecond precision.
if(! loggingFile.is_open())
{
cerr << "Error : Could not open log file." << endl;
exit(1);
}
else
loggingFile << "#Start" << endl;
}
if(verbose && !loggingMode)
cerr << "SolverManager: Using performance mode" << endl;
//Setup up semaphore
solverSynchronisingSemaphore=NULL;
stringstream s;
s << "/nsolv-sem-" << time(NULL); //pick a unique name for the semaphore
solverSyncName=s.str();
solverSynchronisingSemaphore=sem_open(solverSyncName.c_str(),
O_CREAT | //Create a new semaphore if it doesn't already exist
O_EXCL | //Only allow exclusive access (i.e. with O_CREAT means that we can only create a new semaphore)
O_CLOEXEC, //Close semaphore on exec() call
S_IRWXU,
0U);
if(solverSynchronisingSemaphore==SEM_FAILED)
{
cerr << "SolverManager: Failed to create semaphore for synchronisation" << endl;
perror(NULL);
}
else
if(verbose) cerr << "SolverManger: Created named semaphore \"" << solverSyncName << "\"" << endl;
}
SolverManager::~SolverManager()
{
//clean up the semaphore
if(sem_close(solverSynchronisingSemaphore)!=0)
{
cerr << "SolverManager: Failed to close semaphore" << endl;
perror(NULL);
}
else
if(verbose) cerr << "SolverManger: Closing semaphore \"" << solverSyncName << "\"" << endl;
//We assume that we are the parent process and so only the parent performs the unlink
if(sem_unlink(solverSyncName.c_str())!=0)
{
cerr << "SolverManager: Failed to unlink semaphore" << endl;
perror(NULL);
}
else
if(verbose) cerr << "SolverManger: Unlinking semaphore \"" << solverSyncName << "\"" << endl;
string solverName("");
//Try to delete all the solvers
for(map<pid_t,Solver*>::iterator i = pidToSolverMap.begin(); i != pidToSolverMap.end(); ++i)
{
solverName=i->second->toString();
//Delete the solver. This should kill the solver even if it's still running for some reason
delete i->second;
i->second=NULL;
//Try to reap the child. We don't want any zombies lying around!!
if(i->first != 0)
{
if(verbose) cerr << "Reaping child PID:" << i->first << " (" << solverName << ")" << endl;
waitpid(i->first,NULL,0);
}
}
//close log
if(loggingMode) { loggingFile << endl; loggingFile.close();}
}
void SolverManager::addSolver(const std::string& name,
const std::string& cmdLineArgs, bool inputOnStdin)
{
Solver* s=NULL;
try
{
s=new Solver(name,cmdLineArgs,inputFile, inputOnStdin);
solvers.push_back(s);
if(! fdToSolverMap.insert( make_pair(s->getReadFileDescriptor(),s)).second)
cerr << "Warning: Failed to record file descriptor -> solver mapping" << endl;
if(verbose)
cerr << "SolverManager: Added solver \"" << name << "\"" << endl;
}
catch(exception& e)
{
cerr << "Failed to allocate memory for solver " << name << " : " << e.what() << endl;
exit(1);
}
}
void SolverManager::addSolver(const std::string& name, bool inputOnStdin)
{
addSolver(name,empty, inputOnStdin);
}
bool SolverManager::invokeSolvers()
{
if(getNumberOfSolvers() == 0)
{
cerr << "SolverManager::invokeSolvers : There are no solvers to invoke." << endl;
return false;
}
if(loggingMode) {listSolversToLog(); printSolverHeaderToLog();}
/* Loop over the solvers. For each solver fork the current process and
* execute the solver's code
*/
for(vector<Solver*>::iterator s = solvers.begin(); s!= solvers.end(); ++s)
{
fflush(stdout);
fflush(stderr);
pid_t pid = fork();
if(pid < 0)
{
cerr << "SolverManager::invokeSolvers() : Failed to fork!" << endl;
return false;
}
if(pid == 0)
{
//In child
if(verbose) cerr << "SolverManager: Solver \"" << (*s)->toString() << "\" blocking..." << endl;
/* We will now block (assuming our semaphores is initialised to zero)
* until the NSolv parent process lets us go.
*/
if(sem_wait(solverSynchronisingSemaphore) !=0)
{
perror("Waiting for semaphore failed:");
}
if(verbose) cerr << "SolverManager: Solver \"" << (*s)->toString() << "\" unblocked..." << endl;
//Child code
(*s)->exec();
}
else
{
//parent code
//Add the pid and solver to the map
if(! pidToSolverMap.insert(std::make_pair(pid,*s)).second )
{
cerr << "SolverManager::invokeSolvers() : Failed toSolverManager::invokeSolvers() associate solver " << (*s)->toString() <<
"with PID:" << pid << endl;
return false;
}
(*s)->setPID(pid);
}
}
/* (Parent). All the solvers have now been created. They should all be blocked on our semaphore.
* We'll now release the semaphores in the hope that all the solvers will get a fair (depends on
* your OS's scheduler) start.
*/
for(int numberOfSolvers=0; numberOfSolvers < solvers.size(); numberOfSolvers++)
sem_post(solverSynchronisingSemaphore);
//record the start time
if(clock_gettime(CLOCK_MONOTONIC,&startTime) == -1)
cerr << "WARNING: Failed to record start time!" << endl;
Solver* solverOfInterest=NULL;
int numberOfReadySolvers=0;
int numberOfUsableSolvers=solvers.size();
int status=0;
Solver* winningSolver=NULL;
Solver::Result solverResult=Solver::ERROR;
while(numberOfUsableSolvers!=0)
{
setupFileDescriptorSet();
//Now wait for a solver to return.
if(timeoutEnabled())
{
numberOfReadySolvers = pselect(largestFileDescriptor +1,&lookingToRead,NULL,NULL,&timeout,NULL);
}
else
{
numberOfReadySolvers = pselect(largestFileDescriptor +1,&lookingToRead,NULL,NULL,NULL,NULL);
}
if(numberOfReadySolvers==0)
{
//Timeout expired!
cerr << "Timeout expired!" << endl;
if(loggingMode) printUnfinishedSolversToLog();
return false;
}
if(numberOfReadySolvers == -1)
{
switch(errno)
{
case EBADF:
cerr << "Bad file descriptor in set given to pselect()" << endl;
return false;
case EINTR:
//Unexpected signal
cerr << "Received unexpected signal while waiting in pselect()" << endl;
return false;
case EINVAL:
//Invalid parameters
cerr << "Invalid parameters given to pselect()" << endl;
return false;
default:
cerr << "Something went wrong waiting for solver via pselect()" << endl;
return false;
}
}
solverOfInterest = getSolverFromFileDescriptorSet();
if(solverOfInterest==NULL)
{
cerr << "Error: Couldn't find solver from its file descriptor." << endl;
return false;
}
if(verbose) cerr << "Solver:" << solverOfInterest->toString() << " returned. Checking result..." << endl;
//remove that solver from the file descriptor map.
removeSolverFromFileDescriptorSet(solverOfInterest);
solverResult=solverOfInterest->getResult();
switch(solverResult)
{
case Solver::SAT:
if(verbose) cerr << "Result: sat" << endl;
if(winningSolver==NULL)
{
winningSolver=solverOfInterest;//Record the solver that won so we can print its output later.
if(loggingMode)
loggingFile << "#First solver to finish " << solverOfInterest->toString() << endl;
}
if(!loggingMode)
{
//We don't want to let any other solvers run
numberOfUsableSolvers=0;
continue;
}
else
{
//Log output
printSolverAnswerToLog(solverResult,solverOfInterest->toString());
//Try the other solvers.
adjustRemainingTime();
numberOfUsableSolvers--;
continue;
}
case Solver::UNSAT:
if(verbose) cerr << "Result: unsat" << endl;
if(winningSolver==NULL)
{
winningSolver=solverOfInterest;//Record the winning solver so we can output its output later.
if(loggingMode)
loggingFile << "#First solver to finish " << solverOfInterest->toString() << endl;
}
if(!loggingMode)
{
//We don't want to let any other solvers run
numberOfUsableSolvers=0;
continue;
}
else
{
//Log output
printSolverAnswerToLog(solverResult,solverOfInterest->toString());
//Try the other solvers.
adjustRemainingTime();
numberOfUsableSolvers--;
continue;
}
case Solver::UNKNOWN:
if(verbose) cerr << "Result: unknown" << endl << "Trying another solver..." << endl;
if(loggingMode) printSolverAnswerToLog(solverResult,solverOfInterest->toString());
//Try another solver
adjustRemainingTime();
numberOfUsableSolvers--;
continue;
case Solver::ERROR:
cerr << "Result: Solver (" << solverOfInterest->toString() <<
") failed." << endl << "Trying another solver..." << endl;
if(loggingMode) printSolverAnswerToLog(solverResult,solverOfInterest->toString());
//Try another solver
adjustRemainingTime();
numberOfUsableSolvers--;
continue;
default:
return false;
}
}
if(winningSolver==NULL)
{
cerr << "SolverManager::invokeSolvers() : Ran out of usable solvers!" << endl;
return false;
}
else
{
/* kill all other solvers if possible.
* For some reason if we don't do this calling dumpResult() on the winning solver
* blocks. I don't know why, it shouldn't happen because the file descriptor of each solver
* should be separate from each other.
*/
for(vector<Solver*>::iterator i=solvers.begin(); i!= solvers.end(); ++i)
{
if(*i != winningSolver)
(*i)->kill();
}
//print the output of the winning solver
winningSolver->dumpResult();
return true;
}
}
size_t SolverManager::getNumberOfSolvers()
{
return solvers.size();
}
bool SolverManager::timeoutEnabled() {
return (originalTimeout.tv_sec != 0);
}
void SolverManager::adjustRemainingTime()
{
timespec current;
if(clock_gettime(CLOCK_MONOTONIC,¤t) == -1)
{
cerr << "Failed to determine current time." << endl;
return;
}
//calculate elapsed time since start
timespec elapsedTime= subtract(current,startTime);
if(elapsedTime >= originalTimeout)
timeout.tv_sec= timeout.tv_nsec =0;
else
timeout= subtract(originalTimeout,elapsedTime);
if(verbose && timeoutEnabled()) cerr << "Remaining time:" << toDouble(timeout) << " second(s)." << endl;
}
void SolverManager::setupFileDescriptorSet()
{
//set no file descriptors
FD_ZERO(&lookingToRead);
largestFileDescriptor=0;
//Add the file descriptors currently in the map.
for(map<int,Solver*>::const_iterator i= fdToSolverMap.begin(); i!= fdToSolverMap.end(); ++i)
{
//Try to record the largest file descriptor
if(i->first > largestFileDescriptor) largestFileDescriptor=i->first;
FD_SET(i->first,&lookingToRead);
}
}
Solver* SolverManager::getSolverFromFileDescriptorSet()
{
//Loop through known solvers using the first found solver
for(vector<Solver*>::const_iterator i=solvers.begin(); i!= solvers.end(); ++i)
{
if(FD_ISSET((*i)->getReadFileDescriptor(),&lookingToRead))
return *i;
}
//We didn't find anything.
return NULL;
}
void SolverManager::removeSolverFromFileDescriptorSet(Solver* s)
{
for(map<int,Solver*>::iterator i= fdToSolverMap.begin(); i!= fdToSolverMap.end(); ++i)
{
if(i->second == s)
{
//remove this solver
fdToSolverMap.erase(i);
return;
}
}
}
void SolverManager::listSolversToLog()
{
if(!loggingFile.good())
return;
loggingFile << "# " << solvers.size() << " solvers: ";
for(vector<Solver*>::const_iterator i=solvers.begin(); i!= solvers.end(); ++i)
{
loggingFile << (*i)->toString() << "," ;
}
loggingFile << endl;
}
void SolverManager::printSolverHeaderToLog()
{
if(!loggingFile.good())
return;
loggingFile << "# [Solver name ] [ time (seconds)] [answer]" << endl;
}
void SolverManager::printSolverAnswerToLog(Solver::Result result,
const std::string& name)
{
if(!loggingFile.good())
return;
timespec current;
if(clock_gettime(CLOCK_MONOTONIC,¤t) == -1)
{
cerr << "Failed to determine current time." << endl;
return;
}
//calculate elapsed time since start
timespec elapsedTime = subtract(current,startTime);
loggingFile << name << " " << toDouble(elapsedTime) << " " << Solver::resultToString(result) << endl;
}
void SolverManager::printUnfinishedSolversToLog()
{
if(!loggingFile.good())
return;
timespec current;
if(clock_gettime(CLOCK_MONOTONIC,¤t) == -1)
{
cerr << "Failed to determine current time." << endl;
return;
}
//calculate elapsed time since start
timespec elapsedTime = subtract(current,startTime);
for(map<int,Solver*>::const_iterator i= fdToSolverMap.begin() ; i!= fdToSolverMap.end(); ++i)
{
loggingFile << i->second->toString() << " " << toDouble(elapsedTime) << " timeout" << endl;
}
}
struct timespec subtract(struct timespec a, struct timespec b)
{
/* Based on by Alex Measday's ts_util function from his General purpose library.
* http://www.geonius.com/software/libgpl/ts_util.html
*/
struct timespec result;
/* Handle the case where we would calculate a negative time.
* We just return 0.
*/
if( (a.tv_sec < b.tv_sec) ||
((a.tv_sec == b.tv_sec) && (a.tv_nsec < b.tv_nsec) )
)
{
result.tv_sec = result.tv_sec =0;
return result;
}
//the result will be positive.
result.tv_sec = a.tv_sec - b.tv_sec;
//check if we need to borrow from the seconds.
if( a.tv_nsec < b.tv_nsec)
{
result.tv_sec -=1; //borrow a second
result.tv_nsec = 1000000000L + a.tv_nsec - b.tv_nsec;
}
else
result.tv_nsec = a.tv_nsec - b.tv_nsec;
return result;
}
double toDouble(struct timespec t)
{
double value = t.tv_sec;
value += (static_cast<double>(t.tv_nsec))/1E9;
return value;
}
bool operator==(struct timespec a, struct timespec b)
{
if(a.tv_sec == b.tv_sec && a.tv_nsec == b.tv_nsec)
return true;
else
return false;
}
bool operator>(struct timespec a, struct timespec b)
{
if(a.tv_sec > b.tv_sec)
return true;
if( (a.tv_sec == b.tv_sec) && (a.tv_nsec > b.tv_nsec) )
return true;
return false;
}
bool operator>=(struct timespec a, struct timespec b) { return ( a==b || a>b);}