OpenSDN source code
task.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #ifndef ctrlplane_task_h
7 #define ctrlplane_task_h
8 
9 #include <boost/scoped_ptr.hpp>
10 #include <boost/intrusive/list.hpp>
11 #include <map>
12 #include <shared_mutex>
13 #include <vector>
14 #include <mutex>
15 #define TBB_SUPPRESS_DEPRECATED_MESSAGES 1
16 #include <oneapi/tbb/task.h>
17 #include <oneapi/tbb/task_arena.h>
18 #include <oneapi/tbb/task_group.h>
19 #include <oneapi/tbb/global_control.h>
20 
21 #include "base/util.h"
22 
23 class TaskGroup;
24 class TaskEntry;
25 class SandeshTaskScheduler;
26 class TaskTbbKeepAwake;
27 class EventManager;
28 class TaskMonitor;
29 class TaskScheduler;
30 
82 class Task {
83 public:
84 
86  enum State {
87 
90 
93 
95  RUN
96  };
97 
99  enum TbbState {
103  TBB_DONE
104  };
105 
107  const static int kTaskInstanceAny = -1;
108 
111  Task(int task_id, int task_data_id);
112 
113 
116  Task(int task_id);
117 
119  virtual ~Task() { };
120 
123  virtual bool Run() = 0;
124 
128  virtual void OnTaskCancel() { };
129 
130  // Accessor methods
131 
133  State state() const { return state_; };
134 
136  int task_code_id() const { return task_code_id_; };
137 
139  int task_data_id() const { return task_data_id_; };
140 
142  uint64_t seqno() const { return seqno_; };
143 
146  friend std::ostream& operator<<(std::ostream& out, const Task &task);
147 
150  static Task *Running();
151 
153  bool task_cancelled() const { return task_cancel_; };
154 
156  virtual std::string Description() const = 0;
157 
159  uint64_t enqueue_time() const { return enqueue_time_; }
160 
162  uint64_t schedule_time() const { return schedule_time_; }
163 
165  uint32_t execute_delay() const { return execute_delay_; }
166 
169  uint32_t schedule_delay() const { return schedule_delay_; }
170 
171 private:
172 
174  friend class TaskEntry;
175 
177  friend class TaskScheduler;
178 
180  friend class TaskFunctor;
181 
183  void seqno(uint64_t seqno) {seqno_ = seqno;};
184 
186  void tbb_state(TbbState s) { tbb_state_ = s; };
187 
189  void state(State s) { state_ = s; };
190 
192  void set_task_recycle() { task_recycle_ = true; };
193 
195  void set_task_complete() { task_recycle_ = false; };
196 
198  void StartTask(TaskScheduler *scheduler, TaskGroup *group);
199 
202 
205 
208  oneapi::tbb::task_handle task_impl_;
209 
212 
215 
217  uint64_t seqno_;
218 
222 
225 
228  uint64_t enqueue_time_;
229 
231  uint64_t schedule_time_;
232 
235  uint32_t execute_delay_;
236 
239  uint32_t schedule_delay_;
240 
241  // Hook in intrusive list for TaskEntry::waitq_
242  boost::intrusive::list_member_hook<> waitq_hook_;
243 
245 };
246 
250 
253  TaskExclusion(int task_code_id)
254  : match_code_id(task_code_id), match_data_id(-1) {}
255 
258  TaskExclusion(int task_code_id, int task_data_id)
259  : match_code_id(task_code_id), match_data_id(task_data_id) {
260  }
261 
265 
269 };
270 
273 typedef std::vector<TaskExclusion> TaskPolicy;
274 
277 struct TaskStats {
278 
281 
284 
287 
289  uint64_t enqueue_count_;
290 
293 
295  uint64_t last_exit_time_;
296 };
297 
308 public:
309  typedef boost::function<void(const char *file_name, uint32_t line_no,
310  const Task *task, const char *description,
311  uint64_t delay)> LogFn;
312 
317  TaskScheduler(int thread_count = 0);
318 
320  ~TaskScheduler();
321 
322  static void Initialize(uint32_t thread_count = 0, EventManager *evm = NULL);
323  static TaskScheduler *GetInstance();
324 
330  void Enqueue(Task *task);
331 
332  void EnqueueUnLocked(Task *task);
333 
338  };
339 
344 
354  void SetPolicy(int task_id, TaskPolicy &policy);
355 
356  bool GetRunStatus() { return running_; };
357  int GetTaskId(const std::string &name);
358  std::string GetTaskName(int task_id) const;
359 
360  TaskStats *GetTaskGroupStats(int task_id);
361  TaskStats *GetTaskStats(int task_id);
362  TaskStats *GetTaskStats(int task_id, int instance_id);
363  void ClearTaskGroupStats(int task_id);
364  void ClearTaskStats(int task_id);
365  void ClearTaskStats(int task_id, int instance_id);
366 
368  TaskGroup *GetTaskGroup(int task_id);
369 
372  TaskGroup *QueryTaskGroup(int task_id);
373 
376  bool IsTaskGroupEmpty(int task_id) const;
377 
379  TaskEntry *GetTaskEntry(int task_id, int instance_id);
380 
382  TaskEntry *QueryTaskEntry(int task_id, int instance_id);
383 
386  void OnTaskExit(Task *task);
387 
389  void Stop();
390 
392  void Start();
393 
395  void Print();
396 
401  bool IsEmpty(bool running_only = false);
402 
403  void Terminate();
404 
406 
409  static int GetThreadCount(int thread_count = 0);
410  static bool ShouldUseSpawn();
411 
412  static int GetDefaultThreadCount();
413 
414  uint64_t enqueue_count() const { return enqueue_count_; }
415  uint64_t done_count() const { return done_count_; }
416  uint64_t cancel_count() const { return cancel_count_; }
417 
419  void SetMaxThreadCount(int n);
420  void GetSandeshData(SandeshTaskScheduler *resp, bool summary);
421  void Log(const char *file_name, uint32_t line_no, const Task *task,
422  const char *description, uint64_t delay);
423  void RegisterLog(LogFn fn);
424 
425  void SetTrackRunTime(bool value) { track_run_time_ = value; }
426  bool track_run_time() const { return track_run_time_; }
427 
429  void EnableLatencyThresholds(uint32_t execute, uint32_t schedule);
430  uint32_t schedule_delay() const { return schedule_delay_; }
431  uint32_t execute_delay() const { return execute_delay_; }
432 
433  bool measure_delay() const { return measure_delay_; }
434  void SetLatencyThreshold(const std::string &name, uint32_t execute,
435  uint32_t schedule);
436  uint32_t schedule_delay(Task *task) const;
437  uint32_t execute_delay(Task *task) const;
439 
440  void DisableTaskGroup(int task_id);
441  void EnableTaskGroup(int task_id);
442  void DisableTaskEntry(int task_id, int instance_id);
443  void EnableTaskEntry(int task_id, int instance_id);
444 
445  void ModifyTbbKeepAwakeTimeout(uint32_t timeout);
446 
448  void EnableMonitor(EventManager *evm, uint64_t tbb_keepawake_time_msec,
449  uint64_t inactivity_time_msec,
450  uint64_t poll_interval_msec);
451  const TaskMonitor *task_monitor() const { return task_monitor_; }
453  bool use_spawn() const { return use_spawn_; }
454 
457  static void SetThreadAmpFactor(int n);
458 
460  oneapi::tbb::task_arena &tbb_arena() {
461  return task_scheduler_;
462  }
463 
464 private:
465  friend class ConcurrencyScope;
466  typedef std::vector<TaskGroup *> TaskGroupDb;
467  typedef std::map<std::string, int> TaskIdMap;
468 
469  static const int kVectorGrowSize = 16;
470  static boost::scoped_ptr<TaskScheduler> singleton_;
471 
472  // XXX
473  // Following two methods are only for Unit Testing to control
474  // current running task. Usage of this method would result in
475  // unexpected behavior.
476 
480  void SetRunningTask(Task *);
481  void ClearRunningTask();
482 
486 
487  oneapi::tbb::global_control tbb_global_control_;
488  oneapi::tbb::task_arena task_scheduler_;
489  mutable std::mutex mutex_;
490  bool running_;
491  uint64_t seqno_;
493 
494  std::shared_mutex id_map_mutex_;
496  int id_max_;
497 
500 
503 
505  uint32_t schedule_delay_;
506 
508  uint32_t execute_delay_;
509 
510  uint64_t enqueue_count_;
511  uint64_t done_count_;
512  uint64_t cancel_count_;
514 
517  static int ThreadAmpFactor_;
518 
522 };
523 
524 #endif
A class maintaning information for every <task, instance>
Definition: task.cc:107
A private class used to implement tbb::task An object is created when task is ready for execution and...
Definition: task.cc:47
TaskGroup maintains per <task-id> information including,.
Definition: task.cc:241
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
void EnqueueUnLocked(Task *task)
Definition: task.cc:667
uint64_t enqueue_count_
Definition: task.h:510
uint64_t done_count_
Definition: task.h:511
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:601
void Stop()
Stops scheduling of all tasks.
Definition: task.cc:820
bool measure_delay_
Definition: task.h:502
TaskTbbKeepAwake * tbb_awake_task_
Definition: task.h:519
TaskEntry * stop_entry_
Definition: task.h:485
oneapi::tbb::task_arena task_scheduler_
Definition: task.h:488
uint64_t cancel_count_
Definition: task.h:512
int hw_thread_count_
Definition: task.h:499
static boost::scoped_ptr< TaskScheduler > singleton_
Definition: task.h:470
TaskIdMap id_map_
Definition: task.h:495
void Terminate()
Definition: task.cc:951
void EnableTaskGroup(int task_id)
Definition: task.cc:1000
int GetTaskId(const std::string &name)
Definition: task.cc:884
oneapi::tbb::global_control tbb_global_control_
Definition: task.h:487
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:429
CancelReturnCode
Definition: task.h:334
@ CANCELLED
Definition: task.h:335
std::mutex mutex_
Definition: task.h:489
uint64_t enqueue_count() const
Definition: task.h:414
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:550
TaskGroup * QueryTaskGroup(int task_id)
Query TaskGroup for a task_id.Assumes valid entry is present for task_id.
Definition: task.cc:597
LogFn log_fn_
Definition: task.h:498
static void SetThreadAmpFactor(int n)
following function allows one to increase max num of threads used by TBB
Definition: task.cc:986
bool measure_delay() const
Definition: task.h:433
boost::function< void(const char *file_name, uint32_t line_no, const Task *task, const char *description, uint64_t delay)> LogFn
Definition: task.h:311
uint64_t cancel_count() const
Definition: task.h:416
TaskMonitor * task_monitor_
Definition: task.h:520
oneapi::tbb::task_arena & tbb_arena()
returns current TBB arena.
Definition: task.h:460
void GetSandeshData(SandeshTaskScheduler *resp, bool summary)
Definition: task.cc:1593
TaskScheduler(int thread_count=0)
TaskScheduler constructor. TBB assumes it can use the "thread" invoking tbb::scheduler can be used fo...
Definition: task.cc:467
void DisableTaskEntry(int task_id, int instance_id)
Definition: task.cc:1007
void DisableTaskGroup(int task_id)
Definition: task.cc:990
uint32_t execute_delay_
Log if time taken to execute exceeds the delay.
Definition: task.h:508
void ModifyTbbKeepAwakeTimeout(uint32_t timeout)
Definition: task.cc:532
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:662
static int GetDefaultThreadCount()
Definition: task.cc:452
void SetTrackRunTime(bool value)
Definition: task.h:425
TaskStats * GetTaskGroupStats(int task_id)
Definition: task.cc:927
std::map< std::string, int > TaskIdMap
Definition: task.h:467
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:538
TaskGroupDb task_group_db_
Definition: task.h:492
EventManager * evm_
Definition: task.h:513
void ClearRunningTask()
Definition: task.cc:981
~TaskScheduler()
Frees up the task_entry_db_ allocated for scheduler.
Definition: task.cc:482
static void Initialize(uint32_t thread_count=0, EventManager *evm=NULL)
Definition: task.cc:505
void SetPolicy(int task_id, TaskPolicy &policy)
Sets the task exclusion policy. Adds policy entries for the task Examples:
Definition: task.cc:637
std::string GetTaskName(int task_id) const
Definition: task.cc:874
void EnableTaskEntry(int task_id, int instance_id)
Definition: task.cc:1012
uint64_t done_count() const
Definition: task.h:415
int id_max_
Definition: task.h:496
uint64_t seqno_
Definition: task.h:491
TaskEntry * GetTaskEntry(int task_id, int instance_id)
Get TaskGroup for a task_id. Grows task_entry_db_ if necessary.
Definition: task.cc:610
void SetLatencyThreshold(const std::string &name, uint32_t execute, uint32_t schedule)
Definition: task.cc:629
DISALLOW_COPY_AND_ASSIGN(TaskScheduler)
static TaskScheduler * GetInstance()
Definition: task.cc:574
static int ThreadAmpFactor_
following variable allows one to increase max num of threads used by TBB
Definition: task.h:517
void Start()
Starts scheduling of all tasks.
Definition: task.cc:826
TaskGroup * GetTaskGroup(int task_id)
Get TaskGroup for a task_id. Grows task_entry_db_ if necessary.
Definition: task.cc:581
std::vector< TaskGroup * > TaskGroupDb
Definition: task.h:466
TaskEntry * QueryTaskEntry(int task_id, int instance_id)
Query TaskEntry for a task-id and task-instance.
Definition: task.cc:615
bool GetRunStatus()
Definition: task.h:356
int HardwareThreadCount()
Definition: task.h:405
uint32_t schedule_delay_
Log if time between enqueue and task-execute exceeds the delay.
Definition: task.h:505
void ClearTaskStats(int task_id)
Definition: task.cc:911
TaskStats * GetTaskStats(int task_id)
Definition: task.cc:935
bool running_
Definition: task.h:490
void OnTaskExit(Task *task)
Method invoked on exit of a Task. Exit of a task can potentially start tasks in pendingq.
Definition: task.cc:790
bool track_run_time_
Definition: task.h:501
bool track_run_time() const
Definition: task.h:426
bool use_spawn_
Use spawn() to run a tbb::task instead of enqueue()
Definition: task.h:484
void RegisterLog(LogFn fn)
Definition: task.cc:558
static bool ShouldUseSpawn()
Definition: task.cc:456
void set_event_manager(EventManager *evm)
Definition: task.cc:520
uint32_t schedule_delay() const
Definition: task.h:430
void Print()
Debug print routine.
Definition: task.cc:836
uint32_t execute_delay() const
Definition: task.h:431
const TaskMonitor * task_monitor() const
Definition: task.h:451
const TaskTbbKeepAwake * tbb_awake_task() const
Definition: task.h:452
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:727
static const int kVectorGrowSize
Definition: task.h:469
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:851
std::shared_mutex id_map_mutex_
Definition: task.h:494
bool use_spawn() const
Definition: task.h:453
void ClearTaskGroupStats(int task_id)
Definition: task.cc:903
void EnableLatencyThresholds(uint32_t execute, uint32_t schedule)
Enable logging of tasks exceeding configured latency.
Definition: task.cc:622
void SetRunningTask(Task *)
This function should not be called in production code. It is only for unit testing to control current...
Definition: task.cc:976
Task is a class to describe a computational task within OpenSDN control plane applications....
Definition: task.h:82
static Task * Running()
Returns a pointer to the current task the code is executing under.
Definition: task.cc:1533
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:107
uint64_t seqno() const
Returns the sequence number of this task.
Definition: task.h:142
bool task_recycle_
Determines if the task must be rescheduled (reused) after its completion.
Definition: task.h:221
void state(State s)
Sets a state for this task.
Definition: task.h:189
TbbState tbb_state_
Stores a state of the TBB object.
Definition: task.h:214
void tbb_state(TbbState s)
Sets a TBB state for the task.
Definition: task.h:186
uint64_t seqno_
Stores the sequence number.
Definition: task.h:217
bool task_cancelled() const
Returns true if the task has been canceled.
Definition: task.h:153
DISALLOW_COPY_AND_ASSIGN(Task)
uint64_t schedule_time() const
Returns the time when the task execution was started.
Definition: task.h:162
State state_
Stores a state of the task.
Definition: task.h:211
virtual ~Task()
Destroys a task.
Definition: task.h:119
void set_task_recycle()
Marks this task for recycle.
Definition: task.h:192
int task_data_id_
The dataset id within a code path.
Definition: task.h:204
oneapi::tbb::task_handle task_impl_
A handle to a oneTBB object storing low-level information about the managed task.
Definition: task.h:208
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:169
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:128
int task_code_id() const
Returns the code ID of this task.
Definition: task.h:136
int task_data_id() const
Returns the data ID of this task.
Definition: task.h:139
uint64_t enqueue_time() const
Returns the time when the task was enqueued for execution.
Definition: task.h:159
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:1505
uint64_t schedule_time_
Contains the time when the task was started.
Definition: task.h:231
TbbState
Describes states of a task according to TBB library.
Definition: task.h:99
@ TBB_DONE
Definition: task.h:103
@ TBB_INIT
Definition: task.h:100
@ TBB_EXEC
Definition: task.h:102
@ TBB_ENQUEUED
Definition: task.h:101
void set_task_complete()
Marks this task as completed (forbids recycling)
Definition: task.h:195
void seqno(uint64_t seqno)
Sets sequence number of the task.
Definition: task.h:183
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:224
uint32_t execute_delay_
Sets threshold for the task's execution time. If the threshold is exceeded, the event is logged.
Definition: task.h:235
State state() const
Returns a state value of a task.
Definition: task.h:133
uint32_t schedule_delay_
Sets threshold for delay between enqueueing and execution. If the threshold is exceeded,...
Definition: task.h:239
uint32_t execute_delay() const
Returns the threshold for the task execution duration.
Definition: task.h:165
void StartTask(TaskScheduler *scheduler, TaskGroup *group)
Starts execution of a task.
Definition: task.cc:1518
int task_code_id_
The code path executed by the task.
Definition: task.h:201
uint64_t enqueue_time_
Contains the time when the task was enqueued for execution.
Definition: task.h:228
State
Task states.
Definition: task.h:86
@ WAIT
A task is waiting in a queue.
Definition: task.h:92
@ RUN
A task is being run.
Definition: task.h:95
@ INIT
A task was initialized.
Definition: task.h:89
boost::intrusive::list_member_hook waitq_hook_
Definition: task.h:242
static EventManager evm
The class is used to specify a Task label for formulating a task exclusion list (an execution policy)...
Definition: task.h:249
int match_data_id
Specifies task data ID for a task execution policy. The value of -1 corresponds to wildcard (any).
Definition: task.h:268
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:253
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:258
int match_code_id
Specifies task code ID (must be a valid id >= 0) for a task execution policy.
Definition: task.h:264
uint64_t total_tasks_completed_
Number of total tasks ran.
Definition: task.h:292
uint64_t last_exit_time_
Number of time stamp of latest exist.
Definition: task.h:295
int run_count_
Number of entries currently running.
Definition: task.h:283
int defer_count_
Number of entries in deferq.
Definition: task.h:286
int wait_count_
Number of entries in waitq.
Definition: task.h:280
uint64_t enqueue_count_
Number of tasks enqueued.
Definition: task.h:289
Definition: task_int.h:11
std::vector< TaskExclusion > TaskPolicy
Defines a type to store an execution policy (a list of task exclusions).
Definition: task.h:273