-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandController.cpp
650 lines (533 loc) · 16.1 KB
/
CommandController.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
#include"RxCommand/CommandController.h"
namespace Reactor { namespace details
{
// ---------------------------------------------------------------
// CommandControllerState
// ---------------------------------------------------------------
CommandControllerState::CommandControllerState(RxThreadPool::Ptr threadPool)
: controllerPool_(threadPool)
, commandPool_(threadPool)
, triggered_(false)
{}
CommandControllerState::~CommandControllerState()
{
commands_.Clear();
}
const CommandsGroup &CommandControllerState::commands() const
{
return commands_;
}
CommandsGroup &CommandControllerState::commands()
{
return commands_;
}
const CommandsGroup &CommandControllerState::fallback() const
{
return fallback_;
}
CommandsGroup &CommandControllerState::fallback()
{
return fallback_;
}
bool CommandControllerState::SetCommands(const CommandsGroup &commands)
{
commands_ = commands;
return true;
}
bool CommandControllerState::SetFallback(const CommandsGroup &commands)
{
fallback_ = commands;
return true;
}
RxThreadPool::Ptr CommandControllerState::ControllerPool() const
{
return controllerPool_;
}
RxThreadPool::Ptr CommandControllerState::CommandPool() const
{
return commandPool_;
}
bool CommandControllerState::SetCommandPool(RxThreadPool::Ptr commandPool)
{
commandPool_ = commandPool;
return true;
}
const Templates::BooleanTrigger &CommandControllerState::Trigger() const
{
return triggered_;
}
Templates::BooleanTrigger &CommandControllerState::Trigger()
{
return triggered_;
}
// ---------------------------------------------------------------
// CommandController
// ---------------------------------------------------------------
CommandController::CommandController(CommandControllerPolicy policy, RxThreadPool::Ptr threadPool)
: Templates::ContextObjectShared<CommandControllerPolicy, CommandControllerState, Status::ExecutionStatus>(
new CommandControllerPolicy(policy),
new CommandControllerState(threadPool),
new Status::ExecutionStatus()
)
{ }
CommandController::~CommandController()
{ }
CommandController::Ptr CommandController::GetPtr()
{
return shared_from_this();
}
// -----------------------------------------------------------
// Interface Runnable
// -----------------------------------------------------------
/**
* Execute attached commands until they are done.
* A command is done when its Attempt policy is met.
*/
void CommandController::run()
{
try
{
if(this->data()->ControllerPool() == nullptr)
{
throw CriticalException("RxThreadPool is null for CommandController");
}
IList<CommandBase::Ptr> scheduledCommands = scheduleFromRun();
// TODO: event OnScheduled(scheduledCommands);
if(scheduledCommands.empty())
{
IWARNING() << "Scheduling nothing!";
}
}
catch(CriticalException exception)
{
Locker locker(this);
ICRITICAL() << "Error while scheduling commands in CommandController";
finishedWithFatalError(exception);
}
catch(GeneralException exception)
{
// TODO: There is a risk that an infinite loop occurs here ... implement a loop breaker. UPDATE: One loop breaker is the timeout policy.
// AlarmChecker.isInInfiniteLoop(state().getExecutionStatus(), state().getCommands());
ICRITICAL() << "Error while scheduling commands in CommandController";
this->data()->ControllerPool()->OnSchedule((Runnable*)this, computeMaxWaitTimeMs());
}
}
std::string CommandController::GetName() const
{
return std::string("CommandControllerInTest");
}
// ---------------------------------------------------------------
// Interface CommandControllerBase
// ---------------------------------------------------------------
/**
* Set thread pool for commands to avoid CommandController starvation, which
* occurs when commands use all threads in thread-pool.
*/
bool CommandController::SetCommandThreadPool(RxThreadPool::Ptr commandThreadPool)
{
Locker locker(this);
if(this->status()->IsExecuting()) return false;
return this->data()->SetCommandPool(commandThreadPool);
}
bool CommandController::SetCommands(const CommandsGroup &commands)
{
Locker locker(this);
if(this->status()->IsExecuting()) return false;
return this->data()->SetCommands(commands);
}
bool CommandController::SetFallback(const CommandsGroup &commands)
{
Locker locker(this);
if(this->status()->IsExecuting()) return false;
return this->data()->SetFallback(commands);
}
bool CommandController::AddCommand(CommandBase::Ptr command)
{
Locker locker(this);
if(this->status()->IsExecuting()) return false;
this->data()->commands().Add(command);
return true;
}
bool CommandController::AddFallback(CommandBase::Ptr command)
{
Locker locker(this);
if(this->status()->IsExecuting()) return false;
this->data()->fallback().Add(command);
return true;
}
CommandsGroup CommandController::GetCommands() const
{
Locker locker(this);
return this->data()->commands();
}
CommandsGroup CommandController::GetFallback() const
{
Locker locker(this);
return this->data()->fallback();
}
bool CommandController::Shutdown()
{
Locker locker(this);
return shutdown();
}
bool CommandController::Cancel()
{
Locker locker(this);
return shutdown();
}
void CommandController::Resume()
{
Locker locker(this);
this->status()->Resume();
}
void CommandController::Suspend()
{
Locker locker(this);
this->status()->Suspend();
}
bool CommandController::Interrupt()
{
//Locker locker(this);
//this->status()->Interrupt();
// TODO: How to interrupt? Interrupt scheduled future in progress on this->run
return false;
}
void CommandController::Trigger()
{
Locker locker(this);
if(this->status()->IsExecuting() || this->data()->Trigger().IsTriggered())
{
return;
}
this->data()->Trigger().UpdateTrigger(true);
this->data()->ControllerPool()->OnReady((Runnable*)this);
}
bool CommandController::Reset()
{
Locker locker(this);
if(this->status()->IsExecuting())
{
return false;
}
else
{
reset();
return true;
}
}
bool CommandController::IsSuccess() const
{
Locker locker(this);
return isSuccess();
}
bool CommandController::IsDone() const
{
Locker locker(this);
return isDoneForever();
}
bool CommandController::IsExecuting() const
{
return this->status()->IsExecuting();
}
bool CommandController::IsCancelled() const
{
return this->status()->IsCancelled();
}
bool CommandController::IsTimeout() const
{
return isTimeout();
}
bool CommandController::IsSuspended() const
{
return this->status()->IsSuspended();
}
bool CommandController::IsInterrupted() const
{
return this->status()->IsInterrupted();
}
bool CommandController::IsPolicyViolated() const
{
return BaseLib::Strategy::IsPolicyViolated::Perform(
this->status().delegate(),
this->config()->GetInterval(),
this->config()->Timeout(),
this->config()->GetAttempt());
}
bool CommandController::AreCommandsExecuting() const
{
return this->data()->commands().AreCommandsExecuting();
}
int CommandController::NumCommandsExecuting() const
{
return this->data()->commands().NumTasksExecuting();
}
Duration CommandController::TimeoutIn() const
{
return Strategy::ComputeTimeUntilTimeout::Perform(
status().delegate(),
config()->Timeout()
);
}
Status::ExecutionStatus &CommandController::Status()
{
Locker locker(this);
return this->status().operator *();
}
const Status::ExecutionStatus &CommandController::StatusConst() const
{
Locker locker(this);
return this->status().delegate();
}
IList<CommandBase::Ptr> CommandController::Schedule()
{
Locker locker(this);
return schedule();
}
// ---------------------------------------------------------------
// private functions
// ---------------------------------------------------------------
/**
* Tries to acquire a scheduling mutex, gives up within a give threshold.
*/
IList<CommandBase::Ptr> CommandController::scheduleFromRun()
{
ScopedTimer t(IINFO());
TryMutexTypeLocker<Mutex> lock(&(this->data()->schedulingMutex()), ACQUIRE_LOCK_TIMEOUT_IN_MS);
if(!lock.isLocked())
{
IWARNING() << "Could not acquire scheduling lock within " << ACQUIRE_LOCK_TIMEOUT_IN_MS << " ms";
return CollectionUtils::EmptyIList<CommandBase::Ptr>();
}
return schedule();
}
IList<CommandBase::Ptr> CommandController::schedule()
{
// TODO: Support fallback use
if(isDoneForever())
{
stopScheduling();
return CollectionUtils::EmptyIList<CommandBase::Ptr>();
}
else
{
if(isCommandGroupDone())
{
bool hasNext = nextGroupExecution();
if(!hasNext)
{
IWARNING() << "Ignoring prepare next execution!";
//ASSERT(hasNext);
}
return CollectionUtils::EmptyIList<CommandBase::Ptr>();
}
// else if(isFallback())
// {
// // set CommandsGroup fallback as the current execution group.
// }
else
{
IList<CommandBase::Ptr> scheduledCommands = scheduleReady();
// TODO: Move to run? Then Schedule can be called externally to mean "Schedule once"
scheduleController();
return scheduledCommands;
}
}
}
bool CommandController::nextGroupExecution()
{
// ------------------------------------------
// Update commands execution status
// ------------------------------------------
if(!this->data()->Trigger().IsTriggered())
{
if(this->data()->commands().IsSuccess())
{
this->data()->commands().status()->Success();
}
else
{
this->data()->commands().status()->Failure();
}
}
// ------------------------------------------
// Is there a next execution?
// ------------------------------------------
if(this->data()->Trigger().IsTriggered() || BaseLib::Strategy::IsInAttempt::Perform(this->data()->commands().status().delegate(), this->config()->GetAttempt()))
{
IINFO() << "Current is done, starting fresh execution. Max: " << this->config()->GetAttempt().MaxNumAttempts() << " done: " << this->status()->Count().NumSuccesses();
IINFO() << "Commands status " << this->data()->commands().status().delegate();
this->data()->commands().Reset();
this->data()->Trigger().UpdateTrigger(false);
this->data()->commands().status()->Start();
// ---------------------------------
// schedule next using controller interval policy -- Use commands status?
// ---------------------------------
Duration waitTimeMs = BaseLib::Strategy::ComputeTimeUntilNextExecution::Perform(this->status().delegate(), this->config()->GetInterval());
if(!waitTimeMs.IsInfinite())
{
IINFO() << "Time until next command group execution " << waitTimeMs;
this->data()->ControllerPool()->OnSchedule((Runnable*)this, waitTimeMs.InMillis());
}
else
{
IINFO() << "Ignoring scheduling time " << waitTimeMs;
}
return true;
}
else
{
ASSERT(!data()->Trigger().IsTriggered() && !Strategy::IsInAttempt::Perform(
this->data()->commands().status().delegate(),
this->config()->GetAttempt()
));
IWARNING() << "No more executions are possible";
return false;
}
}
/**
* Next schedule time. NB! waitTime == 0 should not be filtered out.
*/
void CommandController::scheduleController()
{
Duration waitTimeMs = computeMaxWaitTimeMs();
if(waitTimeMs < Duration::Infinite())
{
IINFO() << "Time until next command group execution " << waitTimeMs;
this->data()->ControllerPool()->OnSchedule((Runnable*)this, waitTimeMs);
}
else
{
IINFO() << "Ignoring scheduling time " << waitTimeMs;
}
}
void CommandController::stopScheduling()
{
if(status()->IsExecuting())
{
if(isSuccess())
{
finished();
}
else
{
if(isTimeout())
{
doTimeout();
}
finishedWithError(Exception("CommandController finished with error!"));
}
}
else
{
IWARNING() << "CommandController is already done";
}
}
// -----------------------------------------------------------
// Private implementation
// -----------------------------------------------------------
void CommandController::reset()
{
this->status().Set(new Status::ExecutionStatus());
this->data()->commands().Reset();
}
IList<CommandBase::Ptr> CommandController::scheduleReady()
{
// --------------------------------------
// Algorithm: command.doTimeout() leads to callback to this.processOnError(command, ..) which cancels command through its future.
// ---------------------------------------
this->data()->commands().StopTimeoutCommands();
int maxNumCommandsToExecute = std::max(0, this->config()->MaxConcurrentCommands().Limit() - this->data()->commands().NumTasksExecuting());
IList<CommandBase::Ptr> readyCommands = this->config()->findReadyCommands()->Perform(maxNumCommandsToExecute, this->data()->commands());
return executeCommands(readyCommands);
}
IList<CommandBase::Ptr> CommandController::executeCommands(const IList<CommandBase::Ptr> &commands)
{
IList<CommandBase::Ptr> scheduledCommands;
for(CommandBase::Ptr command : commands)
{
if(!command->IsExecuting() && command->IsReady())
{
bool isExecuted = executeCommand(command);
ASSERT(isExecuted);
scheduledCommands.push_back(command);
}
}
return scheduledCommands;
}
// ---------------------------------------------------------------
// private functions
// ---------------------------------------------------------------
Duration CommandController::computeMaxWaitTimeMs() const
{
return this->data()->commands().EarliestReadyIn();
}
bool CommandController::isTimeout() const
{
return BaseLib::Strategy::IsTimeout::Perform(
this->status().delegate(),
this->config()->Timeout()
);
}
// TODO: Rename to "is current command group execution done"
bool CommandController::isCommandGroupDone() const
{
if(this->status()->IsCancelled())
{
IINFO() << "CommandController is cancelled";
return true;
}
if(isTimeout())
{
IINFO() << "CommandController timed out";
return true;
}
IINFO() << "Command group status: " << this->data()->commands().status().delegate();
return this->data()->commands().IsDone();
}
bool CommandController::isDoneForever() const
{
if(this->data()->Trigger().IsTriggered())
{
IINFO() << "CommandController is triggered";
return false;
}
if(this->status()->IsCancelled())
{
IINFO() << "CommandController is cancelled";
return true;
}
if(isTimeout())
{
IINFO() << "CommandController timed out";
return true;
}
bool isDone = this->data()->commands().IsDone();
bool isInAttempt = Strategy::IsInAttempt::Perform(
this->data()->commands().status().delegate(),
this->config()->GetAttempt()
);
IINFO() << "Command group status: " << this->data()->commands().status().delegate();
if(isDone && !isInAttempt)
IINFO() << "Controller Done! inAttempt?" << isInAttempt << " done?" << isDone;
return isDone && !isInAttempt;
}
bool CommandController::isSuccess() const
{
return this->data()->commands().IsSuccess();
}
void CommandController::doTimeout()
{
IINFO() << "CommandController is being timed out";
this->data()->commands().Timeout();
this->status()->Cancel();
}
/**
* Cancel all attached commands and set execution state.
*/
bool CommandController::shutdown()
{
this->data()->commands().Shutdown();
this->status()->Cancel();
return true;
}
}}