/
task.cc
1413 lines (1195 loc) · 42.9 KB
/
task.cc
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
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <assert.h>
#include <fstream>
#include <map>
#include <iostream>
#include <boost/intrusive/set.hpp>
#include "tbb/task.h"
#include "tbb/enumerable_thread_specific.h"
#include "base/logging.h"
#include "base/task.h"
#include "base/task_annotations.h"
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include <base/sandesh/task_types.h>
#if defined(__FreeBSD__)
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/user.h>
#include <libprocstat.h>
#endif
using namespace std;
using tbb::task;
int TaskScheduler::ThreadAmpFactor_ = 1;
class TaskEntry;
struct TaskDeferEntryCmp;
typedef tbb::enumerable_thread_specific<Task *> TaskInfo;
static TaskInfo task_running;
// Vector of Task entries
typedef std::vector<TaskEntry *> TaskEntryList;
boost::scoped_ptr<TaskScheduler> TaskScheduler::singleton_;
#define TASK_TRACE(scheduler, task, msg, delay)\
do {\
scheduler->Log(__FILE__, __LINE__, task, msg, delay);\
} while(false);\
// Private class used to implement tbb::task
// An object is created when task is ready for execution and
// registered with tbb::task
class TaskImpl : public tbb::task {
public:
TaskImpl(Task *t) : parent_(t) {};
virtual ~TaskImpl();
private:
tbb::task *execute();
Task *parent_;
DISALLOW_COPY_AND_ASSIGN(TaskImpl);
};
// Information maintained for every <task, instance>
// policyq_ : contains,
// - Policies configured for a task
// - Complementary policies for a task.
// Example, if a policy is of form <tid0> => <tid1, inst1> <tid2, -1>
// <tid1, inst1> cannot run if <tid0, inst1> is running
// <tid2, *> cannot run when <tid0, *> are running. These become
// complementary rule
// waitq_ : Tasks of this instance created and waiting to be executed. Tasks
// are stored and executed in order of their creation
// Task can be added here on Enqueue if policy conditions are not
// met. Its taken out from waitq_ only when its about to Run
// deferq_ : Tree of TaskEntry waiting on this task instance. The TaskEntry.
// This tree is populated if all conditions are met
// - This TaskEntry has tasks created
// - The TaskEntry in deferq_ has tasks created
// - The Tree is sorted on task seqno_
// run_task_ : Task running in context of this TaskEntry. Only entries in
// task_entry_db_ have this set. Entries in task_db_ will always
// have this as NULL
// Running task is not in waitq_ or deferq_
// run_count_: Number of running tasks for this TaskEntry
class TaskEntry {
public:
TaskEntry(int task_id);
TaskEntry(int task_id, int task_instance);
~TaskEntry();
void AddPolicy(TaskEntry *entry);
int WaitQSize() const {return waitq_.size();};
void AddToWaitQ(Task *t);
bool DeleteFromWaitQ(Task *t);
void AddToDeferQ(TaskEntry *entry);
void DeleteFromDeferQ(TaskEntry &entry);
TaskEntry *ActiveEntryInPolicy();
bool DeferOnPolicyFail(Task *t);
void RunTask(Task *t);
void RunDeferQ();
void RunCombinedDeferQ();
void RunWaitQ();
void RunDeferEntry();
void TaskExited(Task *t, TaskGroup *group);
TaskStats *GetTaskStats();
void ClearTaskStats();
void ClearQueues();
int GetTaskDeferEntrySeqno() const;
int GetTaskId() const { return task_id_; }
int GetTaskInstance() const { return task_instance_; }
int GetRunCount() const { return run_count_; }
void GetSandeshData(SandeshTaskEntry *resp) const;
private:
friend class TaskGroup;
friend class TaskScheduler;
// List of Task's in waitq_
typedef boost::intrusive::member_hook<Task,
boost::intrusive::list_member_hook<>, &Task::waitq_hook_> WaitQHook;
typedef boost::intrusive::list<Task, WaitQHook> TaskWaitQ;
boost::intrusive::set_member_hook<> task_defer_node;
typedef boost::intrusive::member_hook<TaskEntry,
boost::intrusive::set_member_hook<>,
&TaskEntry::task_defer_node> TaskDeferListOption;
// It is a tree of TaskEntries deferred and waiting on the containing task
// to exit. The tree is sorted by seqno_ of first task in the TaskEntry
typedef boost::intrusive::set<TaskEntry, TaskDeferListOption,
boost::intrusive::compare<TaskDeferEntryCmp> > TaskDeferList;
int task_id_;
int task_instance_;
int run_count_; // # of tasks running
Task *run_task_; // Task currently running
TaskWaitQ waitq_; // Tasks waiting to run on some condition
TaskEntryList policyq_; // Policy rules for a task
TaskDeferList *deferq_; // Tasks deferred for this to exit
TaskEntry *deferq_task_entry_;
TaskGroup *deferq_task_group_;
// Cummulative Maintenance stats
TaskStats stats_;
DISALLOW_COPY_AND_ASSIGN(TaskEntry);
};
// Comparison routine for the TaskDeferList
struct TaskDeferEntryCmp {
bool operator() (const TaskEntry &lhs, const TaskEntry &rhs) const {
return (lhs.GetTaskDeferEntrySeqno() <
rhs.GetTaskDeferEntrySeqno());
}
};
// TaskGroup maintains per <task-id> information including,
// polic_set_ : Boolean used to ensure policy is set only once per task
// Task policy change is not yet supported
// policy_ : List of policy rules for the task
// run_count_ : Number of tasks running in context of this task-group
// deferq_ : Tasks deferred till run_count_ on this task becomes 0
// task_entry_ : Default TaskEntry used for task without an instance
class TaskGroup {
public:
TaskGroup(int task_id);
~TaskGroup();
TaskEntry *QueryTaskEntry(int task_instance) const;
TaskEntry *GetTaskEntry(int task_instance);
void AddPolicy(TaskGroup *group);
void AddToDeferQ(TaskEntry *entry);
void DeleteFromDeferQ(TaskEntry &entry);
TaskGroup *ActiveGroupInPolicy();
bool DeferOnPolicyFail(TaskEntry *entry, Task *t);
bool IsWaitQEmpty();
int TaskRunCount() const {return run_count_;};
void RunDeferQ();
void TaskExited(Task *t);
void PolicySet();
void TaskStarted() {run_count_++;};
TaskStats *GetTaskGroupStats();
TaskStats *GetTaskStats();
TaskStats *GetTaskStats(int task_instance);
void ClearTaskGroupStats();
void ClearTaskStats();
void ClearTaskStats(int instance_id);
void GetSandeshData(SandeshTaskGroup *resp) const;
int task_id() const { return task_id_; }
int deferq_size() const { return deferq_.size(); }
size_t num_tasks() const {
size_t count = 0;
for (TaskEntryList::const_iterator it = task_entry_db_.begin();
it != task_entry_db_.end(); ++it) {
if (*it != NULL) {
count++;
}
}
return count;
}
private:
friend class TaskEntry;
friend class TaskScheduler;
// Vector of Task Group policies
typedef std::vector<TaskGroup *> TaskGroupPolicyList;
typedef boost::intrusive::member_hook<TaskEntry,
boost::intrusive::set_member_hook<>,
&TaskEntry::task_defer_node> TaskDeferListOption;
// It is a tree of TaskEntries deferred and waiting on the containing task
// to exit. The tree is sorted by seqno_ of first task in the TaskEntry
typedef boost::intrusive::set<TaskEntry, TaskDeferListOption,
boost::intrusive::compare<TaskDeferEntryCmp> > TaskDeferList;
static const int kVectorGrowSize = 16;
int task_id_;
bool policy_set_;// policy already set?
int run_count_; // # of tasks running in the group
TaskGroupPolicyList policy_; // Policy rules for the group
TaskDeferList deferq_; // Tasks deferred till run_count_ is 0
TaskEntry *task_entry_;// Task entry for instance(-1)
TaskEntryList task_entry_db_; // task-entries in this group
TaskStats stats_;
DISALLOW_COPY_AND_ASSIGN(TaskGroup);
};
////////////////////////////////////////////////////////////////////////////
// Implementation for class TaskImpl
////////////////////////////////////////////////////////////////////////////
// Method called from tbb::task to execute.
// Invoke Run() method of client.
// Supports task continuation when Run() returns false
tbb::task *TaskImpl::execute() {
TaskInfo::reference running = task_running.local();
running = parent_;
try {
uint64_t t = 0;
if (parent_->enqueue_time() != 0) {
t = ClockMonotonicUsec();
TaskScheduler *scheduler = TaskScheduler::GetInstance();
if ((t - parent_->enqueue_time()) > scheduler->schedule_delay()) {
TASK_TRACE(scheduler, parent_, "TBB schedule time(in usec) ",
(t - parent_->enqueue_time()));
}
}
bool is_complete = parent_->Run();
if (t != 0) {
int64_t delay = ClockMonotonicUsec() - t;
TaskScheduler *scheduler = TaskScheduler::GetInstance();
if (delay > scheduler->execute_delay()) {
TASK_TRACE(scheduler, parent_, "Run time(in usec) ", delay);
}
}
running = NULL;
if (is_complete == true) {
parent_->SetTaskComplete();
} else {
parent_->SetTaskRecycle();
}
} catch (std::exception &e) {
// Store exception information statically, to easily read exception
// information from the core.
static std::string what = e.what();
LOG(DEBUG, "!!!! ERROR !!!! Task caught fatal exception: " << what
<< " TaskImpl: " << this);
assert(0);
} catch (...) {
LOG(DEBUG, "!!!! ERROR !!!! Task caught fatal unknown exception"
<< " TaskImpl: " << this);
assert(0);
}
return NULL;
}
// Destructor called when a task execution is compeleted. Invoked
// implicitly by tbb::task.
// Invokes OnTaskExit to schedule tasks pending tasks
TaskImpl::~TaskImpl() {
assert(parent_ != NULL);
TaskScheduler *sched = TaskScheduler::GetInstance();
sched->OnTaskExit(parent_);
}
// XXX For testing purposes only. Limit the number of tbb worker threads.
int TaskScheduler::GetThreadCount(int thread_count) {
static bool init_;
static int num_cores_;
if (init_) {
return num_cores_ * ThreadAmpFactor_;
}
char *num_cores_str = getenv("TBB_THREAD_COUNT");
if (!num_cores_str) {
if (thread_count == 0)
num_cores_ = tbb::task_scheduler_init::default_num_threads();
else
num_cores_ = thread_count;
} else {
num_cores_ = strtol(num_cores_str, NULL, 0);
}
init_ = true;
return num_cores_ * ThreadAmpFactor_;
}
////////////////////////////////////////////////////////////////////////////
// Implementation for class TaskScheduler
////////////////////////////////////////////////////////////////////////////
// TaskScheduler constructor.
// TBB assumes it can use the "thread" invoking tbb::scheduler can be used
// for task scheduling. But, in our case we dont want "main" thread to be
// part of tbb. So, initialize TBB with one thread more than its default
TaskScheduler::TaskScheduler(int task_count) :
task_scheduler_(GetThreadCount(task_count) + 1),
running_(true), seqno_(0), id_max_(0), log_fn_(), measure_delay_(false),
schedule_delay_(0), execute_delay_(0), enqueue_count_(0), done_count_(0),
cancel_count_(0) {
hw_thread_count_ = GetThreadCount(task_count);
task_group_db_.resize(TaskScheduler::kVectorGrowSize);
stop_entry_ = new TaskEntry(-1);
}
// Free up the task_entry_db_ allocated for scheduler
TaskScheduler::~TaskScheduler() {
TaskGroup *group;
for (TaskGroupDb::iterator iter = task_group_db_.begin();
iter != task_group_db_.end(); ++iter) {
if ((group = *iter) == NULL) {
continue;
}
*iter = NULL;
delete group;
}
for (TaskIdMap::iterator loc = id_map_.begin(); loc != id_map_.end();
id_map_.erase(loc++)) {
}
delete stop_entry_;
stop_entry_ = NULL;
task_group_db_.clear();
return;
}
void TaskScheduler::Initialize(uint32_t thread_count) {
assert(singleton_.get() == NULL);
singleton_.reset(new TaskScheduler((int)thread_count));
}
void TaskScheduler::Log(const char *file_name, uint32_t line_no,
const Task *task, const char *description,
uint32_t delay) {
if (log_fn_.empty() == false) {
log_fn_(file_name, line_no, task, description, delay);
}
}
void TaskScheduler::RegisterLog(LogFn fn) {
log_fn_ = fn;
}
TaskScheduler *TaskScheduler::GetInstance() {
if (singleton_.get() == NULL) {
singleton_.reset(new TaskScheduler());
}
return singleton_.get();
}
// Get TaskGroup for a task_id. Grows task_entry_db_ if necessary
TaskGroup *TaskScheduler::GetTaskGroup(int task_id) {
assert(task_id >= 0);
int size = task_group_db_.size();
if (size <= task_id) {
task_group_db_.resize(task_id + TaskScheduler::kVectorGrowSize);
}
TaskGroup *group = task_group_db_[task_id];
if (group == NULL) {
group = new TaskGroup(task_id);
task_group_db_[task_id] = group;
}
return group;
}
// Query TaskGroup for a task_id.Assumes valid entry is present for task_id
TaskGroup *TaskScheduler::QueryTaskGroup(int task_id) {
return task_group_db_[task_id];
}
//
// Check if there are any Tasks in the given TaskGroup.
// Assumes that all task ids are mutually exclusive with bgp::Config.
//
bool TaskScheduler::IsTaskGroupEmpty(int task_id) const {
CHECK_CONCURRENCY("bgp::Config");
tbb::mutex::scoped_lock lock(mutex_);
TaskGroup *group = task_group_db_[task_id];
assert(group);
assert(group->TaskRunCount() == 0);
return group->IsWaitQEmpty();
}
// Get TaskGroup for a task_id. Grows task_entry_db_ if necessary
TaskEntry *TaskScheduler::GetTaskEntry(int task_id, int task_instance) {
TaskGroup *group = GetTaskGroup(task_id);
return group->GetTaskEntry(task_instance);
}
// Query TaskEntry for a task-id and task-instance
TaskEntry *TaskScheduler::QueryTaskEntry(int task_id, int task_instance) {
TaskGroup *group = QueryTaskGroup(task_id);
if (group == NULL)
return NULL;
return group->QueryTaskEntry(task_instance);
}
void TaskScheduler::EnableLatencyThresholds(uint32_t execute,
uint32_t schedule) {
execute_delay_ = execute;
schedule_delay_ = schedule;
measure_delay_ = (execute_delay_ != 0 || schedule_delay_ != 0);
}
// Sets Policy for a task.
// Adds policy entries for the task
// Example: Policy <tid0> => <tid1, -1> <tid2, inst2> will result in following,
// task_db_[tid0] : Rule <tid1, -1> is added to policyq
// task_group_db_[tid0, inst2] : Rule <tid2, inst2> is added to policyq
//
// The symmetry of policy will result in following additional rules,
// task_db_[tid1] : Rule <tid0, -1> is added to policyq
// task_group_db_[tid2, inst2] : Rule <tid0, inst2> is added to policyq
void TaskScheduler::SetPolicy(int task_id, TaskPolicy &policy) {
tbb::mutex::scoped_lock lock(mutex_);
TaskGroup *group = GetTaskGroup(task_id);
TaskEntry *group_entry = group->GetTaskEntry(-1);
group->PolicySet();
for (TaskPolicy::iterator it = policy.begin(); it != policy.end(); ++it) {
if (it->match_instance == -1) {
TaskGroup *policy_group = GetTaskGroup(it->match_id);
group->AddPolicy(policy_group);
policy_group->AddPolicy(group);
} else {
TaskEntry *entry = GetTaskEntry(task_id, it->match_instance);
TaskEntry *policy_entry = GetTaskEntry(it->match_id,
it->match_instance);
entry->AddPolicy(policy_entry);
policy_entry->AddPolicy(entry);
group_entry->AddPolicy(policy_entry);
policy_entry->AddPolicy(group_entry);
}
}
}
// Enqueue a Task for running. Starts task if all policy rules are met else
// puts task in waitq
void TaskScheduler::Enqueue(Task *t) {
tbb::mutex::scoped_lock lock(mutex_);
EnqueueUnLocked(t);
}
void TaskScheduler::EnqueueUnLocked(Task *t) {
if (measure_delay_) {
t->enqueue_time_ = ClockMonotonicUsec();
}
// Ensure that task is enqueued only once.
assert(t->GetSeqno() == 0);
enqueue_count_++;
t->SetSeqNo(++seqno_);
TaskGroup *group = GetTaskGroup(t->GetTaskId());
group->stats_.enqueue_count_++;
TaskEntry *entry = GetTaskEntry(t->GetTaskId(), t->GetTaskInstance());
entry->stats_.enqueue_count_++;
// Add task to waitq_ if its already populated
if (entry->WaitQSize() != 0) {
entry->AddToWaitQ(t);
return;
}
// Is scheduler stopped? Dont add task to deferq_ if scheduler is stopped.
// TaskScheduler::Start() will run tasks from waitq_
if (running_ == false) {
entry->AddToWaitQ(t);
stop_entry_->AddToDeferQ(entry);
return;
}
// Check Task Group policy. On policy violation, DeferOnPolicyFail()
// adds the Task to the TaskEntry's waitq_ and the TaskEntry will be
// added to deferq_ of the matching TaskGroup.
if (group->DeferOnPolicyFail(entry, t)) {
return;
}
// Check Task Entry policy. On policy violation, DeferOnPolicyFail()
// adds the Task to the TaskEntry's waitq_ and the TaskEntry will be
// added to deferq_ of the matching TaskEntry.
if (entry->DeferOnPolicyFail(t)) {
return;
}
entry->RunTask(t);
return;
}
// Cancel a Task that can be in RUN/WAIT state.
// [Note]: The caller needs to ensure that the task exists when Cancel() is invoked.
TaskScheduler::CancelReturnCode TaskScheduler::Cancel(Task *t) {
tbb::mutex::scoped_lock lock(mutex_);
// If the task is in RUN state, mark the task for cancellation and return.
if (t->state_ == Task::RUN) {
t->task_cancel_ = true;
} else if (t->state_ == Task::WAIT) {
TaskEntry *entry = QueryTaskEntry(t->GetTaskId(), t->GetTaskInstance());
assert(entry->WaitQSize());
// Get the first entry in the waitq_
Task *first_wait_task = &(*entry->waitq_.begin());
assert(entry->DeleteFromWaitQ(t) == true);
// If the waitq_ is empty, then remove the TaskEntry from the deferq.
if (!entry->WaitQSize()) {
if (entry->deferq_task_group_) {
assert(entry->deferq_task_entry_ == NULL);
entry->deferq_task_group_->DeleteFromDeferQ(*entry);
} else if (entry->deferq_task_entry_) {
entry->deferq_task_entry_->DeleteFromDeferQ(*entry);
} else {
assert(0);
}
} else if (t == first_wait_task) {
// TaskEntry is inserted in the deferq_ based on the Task seqno.
// deferq_ comparison function uses the seqno of the first entry in
// the waitq_. Therefore, if the task to be cancelled is the first
// entry in the waitq_, then delete the entry from the deferq_ and
// add it again.
TaskGroup *deferq_tgroup = entry->deferq_task_group_;
TaskEntry *deferq_tentry = entry->deferq_task_entry_;
if (deferq_tgroup) {
assert(deferq_tentry == NULL);
deferq_tgroup->DeleteFromDeferQ(*entry);
deferq_tgroup->AddToDeferQ(entry);
} else if (deferq_tentry) {
deferq_tentry->DeleteFromDeferQ(*entry);
deferq_tentry->AddToDeferQ(entry);
} else {
assert(0);
}
}
delete t;
cancel_count_++;
return CANCELLED;
} else {
return FAILED;
}
return QUEUED;
}
// Method invoked on exit of a Task.
// Exit of a task can potentially start tasks in pendingq.
void TaskScheduler::OnTaskExit(Task *t) {
tbb::mutex::scoped_lock lock(mutex_);
done_count_++;
TaskEntry *entry = QueryTaskEntry(t->GetTaskId(), t->GetTaskInstance());
entry->TaskExited(t, GetTaskGroup(t->GetTaskId()));
//
// Delete the task it is not marked for recycling or already cancelled.
//
if ((t->task_recycle_ == false) || (t->task_cancel_ == true)) {
// Delete the container Task object, if the
// task is not marked to be recycled (or)
// if the task is marked for cancellation
if (t->task_cancel_ == true) {
t->OnTaskCancel();
}
delete t;
return;
}
// Task is being recycled, reset the state, seq_no and TBB task handle
t->task_impl_ = NULL;
t->SetSeqNo(0);
t->state_ = Task::INIT;
EnqueueUnLocked(t);
}
void TaskScheduler::Stop() {
tbb::mutex::scoped_lock lock(mutex_);
running_ = false;
}
void TaskScheduler::Start() {
tbb::mutex::scoped_lock lock(mutex_);
running_ = true;
// Run all tasks that may be suspended
stop_entry_->RunDeferQ();
return;
}
void TaskScheduler::Print() {
for (TaskGroupDb::iterator iter = task_group_db_.begin();
iter != task_group_db_.end(); ++iter) {
TaskGroup *group = *iter;
if (group == NULL) {
continue;
}
cout << "id: " << group->task_id()
<< " run: " << group->TaskRunCount() << endl;
cout << "deferq: " << group->deferq_size()
<< " task count: " << group->num_tasks() << endl;
}
}
// Returns true if there are no tasks enqueued and/or running.
// If running_only is true, enqueued tasks are ignored i.e. return true if
// there are no running tasks.
bool TaskScheduler::IsEmpty(bool running_only) {
TaskGroup *group;
tbb::mutex::scoped_lock lock(mutex_);
for (TaskGroupDb::iterator it = task_group_db_.begin();
it != task_group_db_.end(); ++it) {
if ((group = *it) == NULL) {
continue;
}
if (group->TaskRunCount()) {
return false;
}
if ((false == running_only) && (false == group->IsWaitQEmpty())) {
return false;
}
}
return true;
}
std::string TaskScheduler::GetTaskName(int task_id) const {
for (TaskIdMap::const_iterator it = id_map_.begin(); it != id_map_.end();
it++) {
if (task_id == it->second)
return it->first;
}
return "ERROR";
}
int TaskScheduler::GetTaskId(const string &name) {
{
// Grab read-only lock first. Most of the time, task-id already exists
// in the id_map_. Hence there should not be any contention for lock
// aquisition.
tbb::reader_writer_lock::scoped_lock_read lock(id_map_mutex_);
TaskIdMap::iterator loc = id_map_.find(name);
if (loc != id_map_.end()) {
return loc->second;
}
}
// Grab read-write lock to allocate a new task id and insert into the map.
tbb::reader_writer_lock::scoped_lock lock(id_map_mutex_);
int tid = ++id_max_;
id_map_.insert(make_pair(name, tid));
return tid;
}
void TaskScheduler::ClearTaskGroupStats(int task_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return;
group->ClearTaskGroupStats();
}
void TaskScheduler::ClearTaskStats(int task_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return;
group->ClearTaskStats();
}
void TaskScheduler::ClearTaskStats(int task_id, int instance_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return;
group->ClearTaskStats(instance_id);
}
TaskStats *TaskScheduler::GetTaskGroupStats(int task_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return NULL;
return group->GetTaskGroupStats();
}
TaskStats *TaskScheduler::GetTaskStats(int task_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return NULL;
return group->GetTaskStats();
}
TaskStats *TaskScheduler::GetTaskStats(int task_id, int instance_id) {
TaskGroup *group = GetTaskGroup(task_id);
if (group == NULL)
return NULL;
return group->GetTaskStats(instance_id);
}
//
// Platfrom-dependent subroutine in Linux and FreeBSD implementations,
// used only in TaskScheduler::WaitForTerminateCompletion()
//
// In Linux, make sure that all the [tbb] threads launched have completely
// exited. We do so by looking for the Threads count of this process in
// /proc/<pid>/status
//
// In FreeBSD use libprocstat to check how many threads is running
// in specific process.
//
int TaskScheduler::CountThreadsPerPid(pid_t pid) {
int threads;
threads = 0;
#if defined(__FreeBSD__)
struct kinfo_proc *ki_proc;
struct procstat *pstat;
unsigned int count_procs;
count_procs = 0;
pstat = procstat_open_sysctl();
if(pstat == NULL) {
LOG(ERROR, "procstat_open_sysctl() failed");
return -1;
}
ki_proc = procstat_getprocs(pstat, KERN_PROC_PID, pid, &count_procs);
if (ki_proc == NULL) {
LOG(ERROR, "procstat_open_sysctl() failed");
return -1;
}
if (count_procs != 0)
procstat_getprocs(pstat, KERN_PROC_PID | KERN_PROC_INC_THREAD,
ki_proc->ki_pid, &threads);
procstat_freeprocs(pstat, ki_proc);
procstat_close(pstat);
#elif defined(__linux__)
std::ostringstream file_name;
std::string line;
file_name << "/proc/" << pid << "/status";
std::ifstream file(file_name.str().c_str());
if(!file) {
LOG(ERROR, "opening /proc failed");
return -1;
}
while (threads == 0 && file.good()) {
getline(file, line);
if (line == "Threads:\t1") threads = 1;
}
file.close();
#else
#error "TaskScheduler::CountThreadsPerPid() - unsupported platform."
#endif
return threads;
}
void TaskScheduler::WaitForTerminateCompletion() {
//
// Wait for a bit to give a chance for all the threads to exit
//
usleep(1000);
int count = 0;
int threadsRunning;
pid_t pid = getpid();
while (count++ < 12000) {
threadsRunning = CountThreadsPerPid(pid);
if (threadsRunning == 1)
break;
if (threadsRunning == -1) {
LOG(ERROR, "could not check if any thread is running");
usleep(10000);
break;
}
usleep(10000);
}
}
void TaskScheduler::Terminate() {
for (int i = 0; i < 10000; i++) {
if (IsEmpty()) break;
usleep(1000);
}
assert(IsEmpty());
singleton_->task_scheduler_.terminate();
WaitForTerminateCompletion();
singleton_.reset(NULL);
}
// XXX This function should not be called in production code.
// It is only for unit testing to control current running task
// This function modifies the running task as specified by the input
void TaskScheduler::SetRunningTask(Task *unit_test) {
TaskInfo::reference running = task_running.local();
running = unit_test;
}
void TaskScheduler::ClearRunningTask() {
TaskInfo::reference running = task_running.local();
running = NULL;
}
// following function allows one to increase max num of threads used by
// TBB
void TaskScheduler::SetThreadAmpFactor(int n) {
ThreadAmpFactor_ = n;
}
////////////////////////////////////////////////////////////////////////////
// Implementation for class TaskGroup
////////////////////////////////////////////////////////////////////////////
TaskGroup::TaskGroup(int task_id) : task_id_(task_id), policy_set_(false),
run_count_(0) {
task_entry_db_.resize(TaskGroup::kVectorGrowSize);
task_entry_ = new TaskEntry(task_id);
memset(&stats_, 0, sizeof(stats_));
}
TaskGroup::~TaskGroup() {
policy_.clear();
deferq_.clear();
delete task_entry_;
task_entry_ = NULL;
for (size_t i = 0; i < task_entry_db_.size(); i++) {
if (task_entry_db_[i] != NULL) {
delete task_entry_db_[i];
task_entry_db_[i] = NULL;
}
}
task_entry_db_.clear();
}
TaskEntry *TaskGroup::GetTaskEntry(int task_instance) {
if (task_instance == -1)
return task_entry_;
int size = task_entry_db_.size();
if (size <= task_instance) {
task_entry_db_.resize(task_instance + TaskGroup::kVectorGrowSize);
}
TaskEntry *entry = task_entry_db_.at(task_instance);
if (entry == NULL) {
entry = new TaskEntry(task_id_, task_instance);
task_entry_db_[task_instance] = entry;
}
return entry;
}
TaskEntry *TaskGroup::QueryTaskEntry(int task_instance) const {
if (task_instance == -1) {
return task_entry_;
}
if (task_instance >= (int)task_entry_db_.size())
return NULL;
return task_entry_db_[task_instance];
}
void TaskGroup::AddPolicy(TaskGroup *group) {
policy_.push_back(group);
}
TaskGroup *TaskGroup::ActiveGroupInPolicy() {
for (TaskGroupPolicyList::iterator it = policy_.begin();
it != policy_.end(); ++it) {
if ((*it)->run_count_ != 0) {
return (*it);
}
}
return NULL;
}
bool TaskGroup::DeferOnPolicyFail(TaskEntry *entry, Task *task) {
TaskGroup *group;
if ((group = ActiveGroupInPolicy()) != NULL) {
// TaskEntry is inserted in the deferq_ based on the Task seqno.
// deferq_ comparison function uses the seqno of the first Task queued
// in the waitq_. Therefore, add the Task to waitq_ before adding
// TaskEntry in the deferq_.
if (0 == entry->WaitQSize()) {
entry->AddToWaitQ(task);
}
group->AddToDeferQ(entry);
return true;
}
return false;
}
// Add task to deferq_
// Only one task of a given instance goes into deferq_ for its policies.
void TaskGroup::AddToDeferQ(TaskEntry *entry) {
stats_.defer_count_++;
deferq_.insert(*entry);
assert(entry->deferq_task_group_ == NULL);
entry->deferq_task_group_ = this;
}
// Delete task from deferq_
void TaskGroup::DeleteFromDeferQ(TaskEntry &entry) {
assert(this == entry.deferq_task_group_);
deferq_.erase(deferq_.iterator_to(entry));
entry.deferq_task_group_ = NULL;
}
void TaskGroup::PolicySet() {
assert(policy_set_ == false);
policy_set_ = true;
}
// Start executing tasks from deferq_ of a TaskGroup
void TaskGroup::RunDeferQ() {
TaskDeferList::iterator it;
it = deferq_.begin();
while (it != deferq_.end()) {
TaskEntry &entry = *it;
TaskDeferList::iterator it_work = it++;
DeleteFromDeferQ(*it_work);
entry.RunDeferEntry();
}
return;
}
inline void TaskGroup::TaskExited(Task *t) {
run_count_--;
stats_.total_tasks_completed_++;
}
// Returns true, if the waiq_ of all the tasks in the group are empty.
//
// Note: This function is invoked from TaskScheduler::IsEmpty() for each
// task group and is intended to be invoked only in the test code. If this
// function needs to be used outside test code, then we may want to consider
// storing the waitq_ count for performance reason.
bool TaskGroup::IsWaitQEmpty() {
TaskEntry *entry;