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