OpenSDN source code
task.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  */
4 
5 #ifndef ctrlplane_task_h
6 #define ctrlplane_task_h
7 
8 #include <boost/scoped_ptr.hpp>
9 #include <boost/intrusive/list.hpp>
10 #include <map>
11 #include <shared_mutex>
12 #include <vector>
13 #include <mutex>
14 #define TBB_SUPPRESS_DEPRECATED_MESSAGES 1
15 #include <oneapi/tbb/task.h>
16 #include <oneapi/tbb/task_arena.h>
17 #include <oneapi/tbb/task_group.h>
18 #include <oneapi/tbb/global_control.h>
19 
20 #include "base/util.h"
21 
22 class TaskGroup;
23 class TaskEntry;
24 class SandeshTaskScheduler;
25 class TaskTbbKeepAwake;
26 class EventManager;
27 class TaskMonitor;
28 class TaskScheduler;
29 
81 class Task {
82 public:
83 
85  enum State {
86 
89 
92 
94  RUN
95  };
96 
98  enum TbbState {
102  TBB_DONE
103  };
104 
106  const static int kTaskInstanceAny = -1;
107 
110  Task(int task_id, int task_data_id);
111 
112 
115  Task(int task_id);
116 
118  virtual ~Task() { };
119 
122  virtual bool Run() = 0;
123 
127  virtual void OnTaskCancel() { };
128 
129  // Accessor methods
130 
132  State state() const { return state_; };
133 
135  int task_code_id() const { return task_code_id_; };
136 
138  int task_data_id() const { return task_data_id_; };
139 
141  uint64_t seqno() const { return seqno_; };
142 
145  friend std::ostream& operator<<(std::ostream& out, const Task &task);
146 
149  static Task *Running();
150 
152  bool task_cancelled() const { return task_cancel_; };
153 
155  virtual std::string Description() const = 0;
156 
158  uint64_t enqueue_time() const { return enqueue_time_; }
159 
161  uint64_t schedule_time() const { return schedule_time_; }
162 
164  uint32_t execute_delay() const { return execute_delay_; }
165 
168  uint32_t schedule_delay() const { return schedule_delay_; }
169 
170 private:
171 
173  friend class TaskEntry;
174 
176  friend class TaskScheduler;
177 
179  friend class TaskFunctor;
180 
182  void seqno(uint64_t seqno) {seqno_ = seqno;};
183 
185  void tbb_state(TbbState s) { tbb_state_ = s; };
186 
188  void state(State s) { state_ = s; };
189 
191  void set_task_recycle() { task_recycle_ = true; };
192 
194  void set_task_complete() { task_recycle_ = false; };
195 
197  void StartTask(TaskScheduler *scheduler, TaskGroup *group);
198 
201 
204 
207  oneapi::tbb::task_handle task_impl_;
208 
211 
214 
216  uint64_t seqno_;
217 
221 
224 
227  uint64_t enqueue_time_;
228 
230  uint64_t schedule_time_;
231 
234  uint32_t execute_delay_;
235 
238  uint32_t schedule_delay_;
239 
240  // Hook in intrusive list for TaskEntry::waitq_
241  boost::intrusive::list_member_hook<> waitq_hook_;
242 
244 };
245 
249 
252  TaskExclusion(int task_code_id)
253  : match_code_id(task_code_id), match_data_id(-1) {}
254 
257  TaskExclusion(int task_code_id, int task_data_id)
258  : match_code_id(task_code_id), match_data_id(task_data_id) {
259  }
260 
264 
268 };
269 
272 typedef std::vector<TaskExclusion> TaskPolicy;
273 
276 struct TaskStats {
277 
280 
283 
286 
288  uint64_t enqueue_count_;
289 
292 
294  uint64_t last_exit_time_;
295 };
296 
307 public:
308  typedef boost::function<void(const char *file_name, uint32_t line_no,
309  const Task *task, const char *description,
310  uint64_t delay)> LogFn;
311 
316  TaskScheduler(int thread_count = 0);
317 
319  ~TaskScheduler();
320 
321  static void Initialize(uint32_t thread_count = 0, EventManager *evm = NULL);
322  static TaskScheduler *GetInstance();
323 
329  void Enqueue(Task *task);
330 
331  void EnqueueUnLocked(Task *task);
332 
337  };
338 
343 
353  void SetPolicy(int task_id, TaskPolicy &policy);
354 
355  bool GetRunStatus() { return running_; };
356  int GetTaskId(const std::string &name);
357  std::string GetTaskName(int task_id) const;
358 
359  TaskStats *GetTaskGroupStats(int task_id);
360  TaskStats *GetTaskStats(int task_id);
361  TaskStats *GetTaskStats(int task_id, int instance_id);
362  void ClearTaskGroupStats(int task_id);
363  void ClearTaskStats(int task_id);
364  void ClearTaskStats(int task_id, int instance_id);
365 
367  TaskGroup *GetTaskGroup(int task_id);
368 
371  TaskGroup *QueryTaskGroup(int task_id);
372 
375  bool IsTaskGroupEmpty(int task_id) const;
376 
378  TaskEntry *GetTaskEntry(int task_id, int instance_id);
379 
381  TaskEntry *QueryTaskEntry(int task_id, int instance_id);
382 
385  void OnTaskExit(Task *task);
386 
388  void Stop();
389 
391  void Start();
392 
394  void Print();
395 
400  bool IsEmpty(bool running_only = false);
401 
402  void Terminate();
403 
405 
408  static int GetThreadCount(int thread_count = 0);
409  static bool ShouldUseSpawn();
410 
411  static int GetDefaultThreadCount();
412 
413  uint64_t enqueue_count() const { return enqueue_count_; }
414  uint64_t done_count() const { return done_count_; }
415  uint64_t cancel_count() const { return cancel_count_; }
416 
418  void SetMaxThreadCount(int n);
419  void GetSandeshData(SandeshTaskScheduler *resp, bool summary);
420  void Log(const char *file_name, uint32_t line_no, const Task *task,
421  const char *description, uint64_t delay);
422  void RegisterLog(LogFn fn);
423 
424  void SetTrackRunTime(bool value) { track_run_time_ = value; }
425  bool track_run_time() const { return track_run_time_; }
426 
428  void EnableLatencyThresholds(uint32_t execute, uint32_t schedule);
429  uint32_t schedule_delay() const { return schedule_delay_; }
430  uint32_t execute_delay() const { return execute_delay_; }
431 
432  bool measure_delay() const { return measure_delay_; }
433  void SetLatencyThreshold(const std::string &name, uint32_t execute,
434  uint32_t schedule);
435  uint32_t schedule_delay(Task *task) const;
436  uint32_t execute_delay(Task *task) const;
438 
439  void DisableTaskGroup(int task_id);
440  void EnableTaskGroup(int task_id);
441  void DisableTaskEntry(int task_id, int instance_id);
442  void EnableTaskEntry(int task_id, int instance_id);
443 
444  void ModifyTbbKeepAwakeTimeout(uint32_t timeout);
445 
447  void EnableMonitor(EventManager *evm, uint64_t tbb_keepawake_time_msec,
448  uint64_t inactivity_time_msec,
449  uint64_t poll_interval_msec);
450  const TaskMonitor *task_monitor() const { return task_monitor_; }
452  bool use_spawn() const { return use_spawn_; }
453 
456  static void SetThreadAmpFactor(int n);
457 
459  oneapi::tbb::task_arena &tbb_arena() {
460  return task_scheduler_;
461  }
462 
463 private:
464  friend class ConcurrencyScope;
465  typedef std::vector<TaskGroup *> TaskGroupDb;
466  typedef std::map<std::string, int> TaskIdMap;
467 
468  static const int kVectorGrowSize = 16;
469  static boost::scoped_ptr<TaskScheduler> singleton_;
470 
471  // XXX
472  // Following two methods are only for Unit Testing to control
473  // current running task. Usage of this method would result in
474  // unexpected behavior.
475 
479  void SetRunningTask(Task *);
480  void ClearRunningTask();
481 
485 
486  oneapi::tbb::global_control tbb_global_control_;
487  oneapi::tbb::task_arena task_scheduler_;
488  mutable std::mutex mutex_;
489  bool running_;
490  uint64_t seqno_;
492 
493  std::shared_mutex id_map_mutex_;
495  int id_max_;
496 
499 
502 
504  uint32_t schedule_delay_;
505 
507  uint32_t execute_delay_;
508 
509  uint64_t enqueue_count_;
510  uint64_t done_count_;
511  uint64_t cancel_count_;
513 
516  static int ThreadAmpFactor_;
517 
521 };
522 
523 #endif
A class maintaning information for every <task, instance>
Definition: task.cc:106
A private class used to implement tbb::task An object is created when task is ready for execution and...
Definition: task.cc:46
TaskGroup maintains per <task-id> information including,.
Definition: task.cc:240
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:306
void EnqueueUnLocked(Task *task)
Definition: task.cc:666
uint64_t enqueue_count_
Definition: task.h:509
uint64_t done_count_
Definition: task.h:510
bool IsTaskGroupEmpty(int task_id) const
Check if there are any Tasks in the given TaskGroup. Assumes that all task ids are mutually exclusive...
Definition: task.cc:600
void Stop()
Stops scheduling of all tasks.
Definition: task.cc:819
bool measure_delay_
Definition: task.h:501
TaskTbbKeepAwake * tbb_awake_task_
Definition: task.h:518
TaskEntry * stop_entry_
Definition: task.h:484
oneapi::tbb::task_arena task_scheduler_
Definition: task.h:487
uint64_t cancel_count_
Definition: task.h:511
int hw_thread_count_
Definition: task.h:498
static boost::scoped_ptr< TaskScheduler > singleton_
Definition: task.h:469
TaskIdMap id_map_
Definition: task.h:494
void Terminate()
Definition: task.cc:950
void EnableTaskGroup(int task_id)
Definition: task.cc:999
int GetTaskId(const std::string &name)
Definition: task.cc:883
oneapi::tbb::global_control tbb_global_control_
Definition: task.h:486
static int GetThreadCount(int thread_count=0)
Get number of tbb worker threads. For testing purposes only. Limit the number of tbb worker threads.
Definition: task.cc:428
CancelReturnCode
Definition: task.h:333
@ CANCELLED
Definition: task.h:334
std::mutex mutex_
Definition: task.h:488
uint64_t enqueue_count() const
Definition: task.h:413
void SetMaxThreadCount(int n)
Force number of threads.
void Log(const char *file_name, uint32_t line_no, const Task *task, const char *description, uint64_t delay)
Definition: task.cc:549
TaskGroup * QueryTaskGroup(int task_id)
Query TaskGroup for a task_id.Assumes valid entry is present for task_id.
Definition: task.cc:596
LogFn log_fn_
Definition: task.h:497
static void SetThreadAmpFactor(int n)
following function allows one to increase max num of threads used by TBB
Definition: task.cc:985
bool measure_delay() const
Definition: task.h:432
boost::function< void(const char *file_name, uint32_t line_no, const Task *task, const char *description, uint64_t delay)> LogFn
Definition: task.h:310
uint64_t cancel_count() const
Definition: task.h:415
TaskMonitor * task_monitor_
Definition: task.h:519
oneapi::tbb::task_arena & tbb_arena()
returns current TBB arena.
Definition: task.h:459
void GetSandeshData(SandeshTaskScheduler *resp, bool summary)
Definition: task.cc:1592
TaskScheduler(int thread_count=0)
TaskScheduler constructor. TBB assumes it can use the "thread" invoking tbb::scheduler can be used fo...
Definition: task.cc:466
void DisableTaskEntry(int task_id, int instance_id)
Definition: task.cc:1006
void DisableTaskGroup(int task_id)
Definition: task.cc:989
uint32_t execute_delay_
Log if time taken to execute exceeds the delay.
Definition: task.h:507
void ModifyTbbKeepAwakeTimeout(uint32_t timeout)
Definition: task.cc:531
void Enqueue(Task *task)
Enqueues a task for running. Starts task if all policy rules are met else puts task in waitq....
Definition: task.cc:661
static int GetDefaultThreadCount()
Definition: task.cc:451
void SetTrackRunTime(bool value)
Definition: task.h:424
TaskStats * GetTaskGroupStats(int task_id)
Definition: task.cc:926
std::map< std::string, int > TaskIdMap
Definition: task.h:466
void EnableMonitor(EventManager *evm, uint64_t tbb_keepawake_time_msec, uint64_t inactivity_time_msec, uint64_t poll_interval_msec)
Enable Task monitoring.
Definition: task.cc:537
TaskGroupDb task_group_db_
Definition: task.h:491
EventManager * evm_
Definition: task.h:512
void ClearRunningTask()
Definition: task.cc:980
~TaskScheduler()
Frees up the task_entry_db_ allocated for scheduler.
Definition: task.cc:481
static void Initialize(uint32_t thread_count=0, EventManager *evm=NULL)
Definition: task.cc:504
void SetPolicy(int task_id, TaskPolicy &policy)
Sets the task exclusion policy. Adds policy entries for the task Examples:
Definition: task.cc:636
std::string GetTaskName(int task_id) const
Definition: task.cc:873
void EnableTaskEntry(int task_id, int instance_id)
Definition: task.cc:1011
uint64_t done_count() const
Definition: task.h:414
int id_max_
Definition: task.h:495
uint64_t seqno_
Definition: task.h:490
TaskEntry * GetTaskEntry(int task_id, int instance_id)
Get TaskGroup for a task_id. Grows task_entry_db_ if necessary.
Definition: task.cc:609
void SetLatencyThreshold(const std::string &name, uint32_t execute, uint32_t schedule)
Definition: task.cc:628
DISALLOW_COPY_AND_ASSIGN(TaskScheduler)
static TaskScheduler * GetInstance()
Definition: task.cc:573
static int ThreadAmpFactor_
following variable allows one to increase max num of threads used by TBB
Definition: task.h:516
void Start()
Starts scheduling of all tasks.
Definition: task.cc:825
TaskGroup * GetTaskGroup(int task_id)
Get TaskGroup for a task_id. Grows task_entry_db_ if necessary.
Definition: task.cc:580
std::vector< TaskGroup * > TaskGroupDb
Definition: task.h:465
TaskEntry * QueryTaskEntry(int task_id, int instance_id)
Query TaskEntry for a task-id and task-instance.
Definition: task.cc:614
bool GetRunStatus()
Definition: task.h:355
int HardwareThreadCount()
Definition: task.h:404
uint32_t schedule_delay_
Log if time between enqueue and task-execute exceeds the delay.
Definition: task.h:504
void ClearTaskStats(int task_id)
Definition: task.cc:910
TaskStats * GetTaskStats(int task_id)
Definition: task.cc:934
bool running_
Definition: task.h:489
void OnTaskExit(Task *task)
Method invoked on exit of a Task. Exit of a task can potentially start tasks in pendingq.
Definition: task.cc:789
bool track_run_time_
Definition: task.h:500
bool track_run_time() const
Definition: task.h:425
bool use_spawn_
Use spawn() to run a tbb::task instead of enqueue()
Definition: task.h:483
void RegisterLog(LogFn fn)
Definition: task.cc:557
static bool ShouldUseSpawn()
Definition: task.cc:455
void set_event_manager(EventManager *evm)
Definition: task.cc:519
uint32_t schedule_delay() const
Definition: task.h:429
void Print()
Debug print routine.
Definition: task.cc:835
uint32_t execute_delay() const
Definition: task.h:430
const TaskMonitor * task_monitor() const
Definition: task.h:450
const TaskTbbKeepAwake * tbb_awake_task() const
Definition: task.h:451
CancelReturnCode Cancel(Task *task)
Cancels a Task that can be in RUN/WAIT state. The caller needs to ensure that the task exists when Ca...
Definition: task.cc:726
static const int kVectorGrowSize
Definition: task.h:468
bool IsEmpty(bool running_only=false)
Returns true if there are no tasks running and/or enqueued If running_only is true,...
Definition: task.cc:850
std::shared_mutex id_map_mutex_
Definition: task.h:493
bool use_spawn() const
Definition: task.h:452
void ClearTaskGroupStats(int task_id)
Definition: task.cc:902
void EnableLatencyThresholds(uint32_t execute, uint32_t schedule)
Enable logging of tasks exceeding configured latency.
Definition: task.cc:621
void SetRunningTask(Task *)
This function should not be called in production code. It is only for unit testing to control current...
Definition: task.cc:975
Task is a class to describe a computational task within OpenSDN control plane applications....
Definition: task.h:81
static Task * Running()
Returns a pointer to the current task the code is executing under.
Definition: task.cc:1532
friend std::ostream & operator<<(std::ostream &out, const Task &task)
Provides access to private members of a task for the output stream redirection operator.
static const int kTaskInstanceAny
Specifies value for wildcard (any or *) task data ID.
Definition: task.h:106
uint64_t seqno() const
Returns the sequence number of this task.
Definition: task.h:141
bool task_recycle_
Determines if the task must be rescheduled (reused) after its completion.
Definition: task.h:220
void state(State s)
Sets a state for this task.
Definition: task.h:188
TbbState tbb_state_
Stores a state of the TBB object.
Definition: task.h:213
void tbb_state(TbbState s)
Sets a TBB state for the task.
Definition: task.h:185
uint64_t seqno_
Stores the sequence number.
Definition: task.h:216
bool task_cancelled() const
Returns true if the task has been canceled.
Definition: task.h:152
DISALLOW_COPY_AND_ASSIGN(Task)
uint64_t schedule_time() const
Returns the time when the task execution was started.
Definition: task.h:161
State state_
Stores a state of the task.
Definition: task.h:210
virtual ~Task()
Destroys a task.
Definition: task.h:118
void set_task_recycle()
Marks this task for recycle.
Definition: task.h:191
int task_data_id_
The dataset id within a code path.
Definition: task.h:203
oneapi::tbb::task_handle task_impl_
A handle to a oneTBB object storing low-level information about the managed task.
Definition: task.h:207
uint32_t schedule_delay() const
Returns the time threshold for time difference between moments when the task was started and when it ...
Definition: task.h:168
virtual void OnTaskCancel()
Called on task exit, if it is marked for cancellation. If the user wants to do any cleanup on task ca...
Definition: task.h:127
int task_code_id() const
Returns the code ID of this task.
Definition: task.h:135
int task_data_id() const
Returns the data ID of this task.
Definition: task.h:138
uint64_t enqueue_time() const
Returns the time when the task was enqueued for execution.
Definition: task.h:158
Task(int task_id, int task_data_id)
Creates a new task with the given values of task code ID and task data ID.
Definition: task.cc:1504
uint64_t schedule_time_
Contains the time when the task was started.
Definition: task.h:230
TbbState
Describes states of a task according to TBB library.
Definition: task.h:98
@ TBB_DONE
Definition: task.h:102
@ TBB_INIT
Definition: task.h:99
@ TBB_EXEC
Definition: task.h:101
@ TBB_ENQUEUED
Definition: task.h:100
void set_task_complete()
Marks this task as completed (forbids recycling)
Definition: task.h:194
void seqno(uint64_t seqno)
Sets sequence number of the task.
Definition: task.h:182
virtual bool Run()=0
Code to execute in a task. Returns true if task is completed. Return false to reschedule the task.
virtual std::string Description() const =0
Gives a description of the task.
bool task_cancel_
Determines if the task's execution was canceled.
Definition: task.h:223
uint32_t execute_delay_
Sets threshold for the task's execution time. If the threshold is exceeded, the event is logged.
Definition: task.h:234
State state() const
Returns a state value of a task.
Definition: task.h:132
uint32_t schedule_delay_
Sets threshold for delay between enqueueing and execution. If the threshold is exceeded,...
Definition: task.h:238
uint32_t execute_delay() const
Returns the threshold for the task execution duration.
Definition: task.h:164
void StartTask(TaskScheduler *scheduler, TaskGroup *group)
Starts execution of a task.
Definition: task.cc:1517
int task_code_id_
The code path executed by the task.
Definition: task.h:200
uint64_t enqueue_time_
Contains the time when the task was enqueued for execution.
Definition: task.h:227
State
Task states.
Definition: task.h:85
@ WAIT
A task is waiting in a queue.
Definition: task.h:91
@ RUN
A task is being run.
Definition: task.h:94
@ INIT
A task was initialized.
Definition: task.h:88
boost::intrusive::list_member_hook waitq_hook_
Definition: task.h:241
static EventManager evm
The class is used to specify a Task label for formulating a task exclusion list (an execution policy)...
Definition: task.h:248
int match_data_id
Specifies task data ID for a task execution policy. The value of -1 corresponds to wildcard (any).
Definition: task.h:267
TaskExclusion(int task_code_id)
Creates a new task exclusion from the given task code ID value and wildcard for task data ID.
Definition: task.h:252
TaskExclusion(int task_code_id, int task_data_id)
Creates a new task exclusion from the given task code ID and task data ID values.
Definition: task.h:257
int match_code_id
Specifies task code ID (must be a valid id >= 0) for a task execution policy.
Definition: task.h:263
uint64_t total_tasks_completed_
Number of total tasks ran.
Definition: task.h:291
uint64_t last_exit_time_
Number of time stamp of latest exist.
Definition: task.h:294
int run_count_
Number of entries currently running.
Definition: task.h:282
int defer_count_
Number of entries in deferq.
Definition: task.h:285
int wait_count_
Number of entries in waitq.
Definition: task.h:279
uint64_t enqueue_count_
Number of tasks enqueued.
Definition: task.h:288
Definition: task_int.h:10
std::vector< TaskExclusion > TaskPolicy
Defines a type to store an execution policy (a list of task exclusions).
Definition: task.h:272