b87a8f60cdd4615db85a0bad0aa18990a21387d1
[core.git] / inc / main / classes / handler / tasks / class_TaskHandler.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Handler\Task;
4
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Registry\Registerable;
8
9 /**
10  * A Task handler
11  *
12  * @author              Roland Haeder <webmaster@shipsimu.org>
13  * @version             0.0.0
14  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15  * @license             GNU GPL 3.0 or any newer version
16  * @link                http://www.shipsimu.org
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
30  */
31 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
32         // Exception constants
33         const EXCEPTION_TASK_IS_INVALID = 0xb00;
34
35         /**
36          * Protected constructor
37          *
38          * @return      void
39          */
40         protected function __construct () {
41                 // Call parent constructor
42                 parent::__construct(__CLASS__);
43
44                 // Set handler name
45                 $this->setHandlerName('task');
46         }
47
48         /**
49          * Creates an instance of this class
50          *
51          * @return      $handlerInstance        An instance of a HandleableTask class
52          */
53         public static final function createTaskHandler () {
54                 // Get new instance
55                 $handlerInstance = new TaskHandler();
56
57                 // Output debug message
58                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
59
60                 // Init the task list
61                 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
62
63                 // Get default instance
64                 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
65
66                 // Init visitor instance for faster loop
67                 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
68
69                 // Register the first (and generic) idle-loop task
70                 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
71                 $handlerInstance->registerTask('idle_loop', $taskInstance);
72
73                 // Output debug message
74                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
75
76                 // Return the prepared instance
77                 return $handlerInstance;
78         }
79
80         /**
81          * Tries to execute the given task. If as task should not be started (yet)
82          * or the interval time (see task_interval_delay) is not yet reached the
83          * task is quietly skipped.
84          *
85          * @return      void
86          * @throws      InvalidTaskException    If the current task is invalid
87          */
88         private function executeCurrentTask () {
89                 // Update no task by default
90                 $updateTask = FALSE;
91
92                 // Is the current task valid?
93                 if (!$this->getListInstance()->getIterator()->valid()) {
94                         // Not valid!
95                         throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
96                 } // END - if
97
98                 // Get current task
99                 $currentTask = $this->getListInstance()->getIterator()->current();
100
101                 // Is the task not yet started?
102                 if ($currentTask['task_started'] === FALSE) {
103                         // Determine difference between current time and registration
104                         $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
105
106                         // Should we start now?
107                         if ($diff < $currentTask['task_startup_delay']) {
108                                 // Skip this silently
109                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
110                                 return;
111                         } // END - if
112
113                         // Launch the task and mark it as updated
114                         $currentTask['task_started'] = TRUE;
115                         $updateTask = TRUE;
116
117                         // Debug message
118                         self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
119                 } // END - if
120
121                 // Get time difference from interval delay
122                 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
123
124                 // Debug message
125                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
126
127                 // Is the interval delay reached?
128                 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
129                         // Should we update the task from startup?
130                         if ($updateTask === TRUE) {
131                                 // Update the task before leaving
132                                 $this->updateTask($currentTask);
133                         } // END - if
134
135                         // Skip this silently
136                         return;
137                 } // END - if
138
139                 // Set last activity
140                 $currentTask['task_last_activity'] = $this->getMilliTime();
141
142                 // Count this run
143                 $currentTask['task_total_runs']++;
144
145                 // Update the task
146                 $this->updateTask($currentTask);
147
148                 // And visit/run it
149                 // @TODO Messurement can be added around this call
150                 $currentTask['task_instance']->accept($this->getVisitorInstance());
151         }
152
153         /**
154          * Updates given task by updating the underlaying list
155          *
156          * @param       $taskEntry      An array with a task
157          * @return      void
158          */
159         private function updateTask (array $taskEntry) {
160                 // Get the key from current iteration
161                 $key = $this->getListInstance()->getIterator()->key();
162
163                 // Get the hash from key
164                 $hash = $this->getListInstance()->getHash($key);
165
166                 // Update the entry
167                 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
168         }
169
170         /**
171          * Unregisters the given task
172          *
173          * @param       $taskData       Data of the task
174          * @return      void
175          */
176         private function unregisterTask (array $taskData) {
177                 // Debug output
178                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
179
180                 // Remove the entry
181                 $this->getListInstance()->removeEntry('tasks', $taskData);
182
183                 // Debug output
184                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
185          }
186
187         /**
188          * Searches a task by given instance
189          *
190          * @param       $taskInstanc    An instanceof a Taskable class
191          * @return      $taskName               Name of the task as used while registration
192          */
193         public function searchTask (Taskable $taskInstance) {
194                 // Default is an empty (not found) task name
195                 $taskName = '';
196
197                 // Get whole list
198                 $taskList = $this->getListInstance()->getArrayFromList('tasks');
199
200                 // Search all instances
201                 foreach ($taskList as $currentTask) {
202                         // Does it match given task instance?
203                         if ($currentTask['task_instance']->equals($taskInstance)) {
204                                 // Found it
205                                 $taskName = $currentTask['id'];
206
207                                 // Abort here
208                                 break;
209                         } // END - if
210                 } // END - foreach
211
212                 // Return found name
213                 return $taskName;
214         }
215
216         /**
217          * Registers a task with a task handler.
218          *
219          * @param       $taskName               A task name to register the task on
220          * @param       $taskInstance   The instance we should register as a task
221          * @return      void
222          */
223         public function registerTask ($taskName, Visitable $taskInstance) {
224                 // Get interval delay
225                 $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
226                 $startupDelay  = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
227
228                 // If the task is 'idle_loop', a deplay of zero seconds is fine
229                 assert($intervalDelay >= 0);
230                 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
231                 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
232
233                 // Create the entry
234                 $taskEntry = array(
235                         // Identifier for the generateHash() method
236                         'id'                  => $taskName,
237                         // Whether the task is started
238                         'task_started'        => FALSE,
239                         // Whether the task is paused (not yet implemented)
240                         'task_paused'         => FALSE,
241                         // Whether the task can be paused (not yet implemented)
242                         'task_pauseable'      => TRUE,
243                         // Timestamp of registration
244                         'task_registered'     => $this->getMilliTime(),
245                         // Last activity timestamp
246                         'task_last_activity'  => 0,
247                         // Total runs of this task
248                         'task_total_runs'     => 0,
249                         // Task instance itself
250                         'task_instance'       => $taskInstance,
251                         // Startup delay in milliseconds
252                         'task_startup_delay'  => $startupDelay,
253                         // Interval time (delay) in milliseconds before this task is executed again
254                         'task_interval_delay' => $intervalDelay,
255                         // How often should this task run?
256                         'task_max_runs'       => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
257                 );
258
259                 // Add the entry
260                 $this->getListInstance()->addEntry('tasks', $taskEntry);
261
262                 // Debug message
263                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
264                         ' (taskInstance=' . $taskInstance->__toString() . ')' .
265                         ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
266                         ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
267                         ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
268                 );
269         }
270
271         /**
272          * Checks whether tasks are left including idle task
273          *
274          * @return      $tasksLeft      Whether there are tasks left to handle
275          */
276         public function hasTasksLeft () {
277                 // Do we have tasks there?
278                 $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
279
280                 // Return result
281                 return $tasksLeft;
282         }
283
284         /**
285          * Handles all tasks by checking if they should startup or if it is their
286          * turn to run. You should use this method in a while() loop in conjuntion
287          * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
288          * which will attempt to remove all tasks from the task handler.
289          *
290          * @return      void
291          */
292         public function handleTasks () {
293                 // Should we rewind?
294                 if (!$this->getListInstance()->getIterator()->valid()) {
295                         // Rewind to the beginning for next loop
296                         $this->getListInstance()->getIterator()->rewind();
297                 } // END - if
298
299                 // Try to execute the task
300                 $this->executeCurrentTask();
301
302                 // Go to next entry
303                 $this->getListInstance()->getIterator()->next();
304         }
305
306         /**
307          * Shuts down all tasks and the task handler itself. This method should be
308          * called from a corresponding filter class.
309          * 
310          * @return      void
311          */
312         public function doShutdown () {
313                 // Always rewind to the beginning for next loop
314                 $this->getListInstance()->getIterator()->rewind();
315
316                 // Debug message
317                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
318
319                 // Remember all tasks that has been shutdown for removal
320                 $tasks = array();
321
322                 // Instance a visitor
323                 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
324
325                 // Shutdown all tasks in once go
326                 while ($this->getListInstance()->getIterator()->valid()) {
327                         // Get current entry
328                         $currentTask = $this->getListInstance()->getIterator()->current();
329
330                         // Output debug message
331                         self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
332
333                         // Shutdown the task
334                         $currentTask['task_instance']->accept($this->getVisitorInstance());
335
336                         // Remember this task
337                         array_push($tasks, $currentTask);
338
339                         // Advance to next one
340                         $this->getListInstance()->getIterator()->next();
341                 } // END - while
342
343                 // Debug message
344                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
345
346                 // Remove all tasks
347                 foreach ($tasks as $entry) {
348                         $this->unregisterTask($entry);
349                 } // END - foreach
350         }
351
352 }