scheduling.php 19.9 KB
Newer Older
Prosper De Laure's avatar
Prosper De Laure committed
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
<?php

/*
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle batchProcessing.
 *
 * Bundle batchProcessing is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bundle batchProcessing is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with bundle batchProcessing.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace bundle\batchProcessing\Controller;

/**
 * Class scheduling
 *
 * @package batchProcessing
 * @author  Alexandre Morin <alexandre.morin@maarch.org>
 */
class scheduling
{
    /* Properties */

    public $sdoFactory;

Alexis Ragot's avatar
Alexis Ragot committed
36
37
    public $logSchedulingController;

Prosper De Laure's avatar
Prosper De Laure committed
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
    /**
     * Constructor of access control class
     * @param \dependency\sdo\Factory $sdoFactory The factory
     */
    public function __construct(\dependency\sdo\Factory $sdoFactory)
    {
        $this->sdoFactory = $sdoFactory;
        $this->logSchedulingController = \laabs::newController("batchProcessing/logScheduling");
    }

    /**
     * List the schedulings
     *
     * @return array Array of batchProcessing/scheduling object
     */
    public function index()
    {
        $schedulingList = $this->sdoFactory->find("batchProcessing/scheduling");

        return $schedulingList;
    }

    /**
     * List the tasks
     *
     * @return batchProcessing/task List task
     */
    public function readTaskList()
    {
67
68
69
70
71
72
73
74
75
        $tasks= \laabs::configuration('batchProcessing')['tasks'];

        $taskList = [];
        foreach ($tasks as $value) {
            $task = \laabs::newInstance('batchProcessing/task');
            $task->taskId = $value['taskId'];
            $task->route = $value['route'];
            $task->description = $value['description'];

76
            $taskList[$task->taskId] = $task;
77
        }
Prosper De Laure's avatar
Prosper De Laure committed
78
79
80
81

        return $taskList;
    }

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    /**
     * Get task by id
     *
     * @return batchProcessing/task task
     */
    public function readTask($taskId)
    {
        $tasks= \laabs::configuration('batchProcessing')['tasks'];

        foreach ($tasks as $value) {
            if ($taskId === $value['taskId']) {
                $task = \laabs::newInstance('batchProcessing/task');
                $task->taskId = $value['taskId'];
                $task->route = $value['route'];
                $task->description = $value['description'];

                return $task;
            }
        }
        return false;
    }

Prosper De Laure's avatar
Prosper De Laure committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    /**
     * Create the requested scheduling
     * @param batchProcessing/scheduling $scheduling
     *
     * @return boolean status of the query
     */
    public function create($scheduling)
    {

        $scheduling->schedulingId = \laabs::newId();
        $scheduling->status = 'scheduled';

        $this->sdoFactory->create($scheduling, "batchProcessing/scheduling");

        return $scheduling->schedulingId;
    }

    /**
     * Update a scheduling
     * @param batchProcessing/scheduling $scheduling
     *
125
     * @return bool True if the operation succeed
Prosper De Laure's avatar
Prosper De Laure committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
     */
    public function update($scheduling)
    {
        try {
            $this->sdoFactory->update($scheduling, "batchProcessing/scheduling");
        } catch (\Exception $e) {
            throw \laabs::newException("batchProcessing/schedulingException", "Scheduling not updated.");
        }

        return true;
    }

    /**
     * Delete a scheduling
     * @param id $schedulingId Scheduling identifier
     *
142
     * @return boolean True if the operation succeed
Prosper De Laure's avatar
Prosper De Laure committed
143
144
145
146
147
148
149
150
151
152
153
154
155
     */
    public function delete($schedulingId)
    {
        try {
            $this->sdoFactory->delete($schedulingId, "batchProcessing/scheduling");
        } catch (\Exception $e) {
            throw \laabs::newException("batchProcessing/schedulingException", "Scheduling not deleted.");
        }

        return true;
    }

    /**
156
     * Execute a scheduling task
Prosper De Laure's avatar
Prosper De Laure committed
157
     *
158
     * @param string $schedulingId The Scheduling identifier
Prosper De Laure's avatar
Prosper De Laure committed
159
     *
160
     * @return batchProcessing/scheduling The scheduling object
Prosper De Laure's avatar
Prosper De Laure committed
161
162
163
164
     */
    public function execute($schedulingId)
    {
        $status = true;
165
        $info = null;
Prosper De Laure's avatar
Prosper De Laure committed
166
167

        $scheduling = $this->sdoFactory->read("batchProcessing/scheduling", $schedulingId);
168
        $task = $this->readTask($scheduling->taskId);
Prosper De Laure's avatar
Prosper De Laure committed
169

170
        if (!$scheduling || !$task) {
171
            throw \laabs::newException("batchProcessing/schedulingException", "Invalid identifier.");
Prosper De Laure's avatar
Prosper De Laure committed
172
173
174
175
176
177
178
179
180
181
182
183
184
        }

        if ($accountToken = \laabs::getToken('AUTH')) {
            $launchedBy = $accountToken->accountId;
        } else {
            $launchedBy = "__system__";
        }

        $this->serviceToken($scheduling->executedBy);

        $this->changeStatus($schedulingId, "running");

        try {
Alexandre Morin's avatar
Alexandre Morin committed
185
186
            $pathRouter = new \core\Route\PathRouter($task->route);
            \core\Observer\Dispatcher::notify(LAABS_SERVICE_PATH,$pathRouter->path);
187
188
189
190
191
192
193
            if (!empty($scheduling->parameters)) {
                \laabs::callServiceArgs($task->route, (array) $scheduling->parameters);

            } else {
                \laabs::callService($task->route);
            }

194
        } catch (\Exception $info) {
Prosper De Laure's avatar
Prosper De Laure committed
195
196
            $this->changeStatus($schedulingId, "error");
            $status = false;
197
198
199
            
            \laabs::notify(LAABS_BUSINESS_EXCEPTION, $info);
        }       
Alexandre Morin's avatar
Alexandre Morin committed
200

201
        if ($status) {
202
203
            $scheduling->lastExecution = \laabs::newDateTime();
            $scheduling->lastExecution->setTimezone(new \DateTimeZone('UTC'));
204
205
206
207
208
209
210
            $scheduling->status = "scheduled";

            $frequency = explode(";", $scheduling->frequency);
            $scheduling->nextExecution = $this->nextExecution($frequency);
        } else {
            $scheduling->status = "error";
        }
Prosper De Laure's avatar
Prosper De Laure committed
211
212
213

        $this->update($scheduling);

214
        $observerPool = \core\Observer\Dispatcher::getPool(\bundle\audit\AUDIT_ENTRY_OUTPUT);
215
        foreach ($observerPool as $key => $value) {
216
217
218
219
220
221
            if ($value instanceof \bundle\audit\Observer\logger) {
                $info = $value->output;
                break;
            }
        }

Prosper De Laure's avatar
Prosper De Laure committed
222
223
224
225
226
227
228
229
        $this->logSchedulingController->add($schedulingId, $scheduling->executedBy, $launchedBy, $status, $info);

        return $scheduling;
    }

    /**
     * Process all scheduling
     *
230
     * @return array The list of executedTask status
Prosper De Laure's avatar
Prosper De Laure committed
231
232
233
234
     */
    public function process()
    {
        $schedulings = $this->sdoFactory->find("batchProcessing/scheduling");
235
236
        $currentDate = \laabs::newDateTime();
        $currentDate->setTimezone(new \DateTimeZone('UTC'));
Prosper De Laure's avatar
Prosper De Laure committed
237
238
239
240

        $res = [];

        foreach ($schedulings as $scheduling) {
241
242
243
244
245
246
            $executedTask = null;

            if ($scheduling->status != "scheduled") {
                continue;
            }

247
248
249
250
251
            // if (empty($scheduling->nextExecution)) {
            //     $frequency = explode(";", $scheduling->frequency);
            //     $scheduling->nextExecution = $this->nextExecution($frequency);
            //     $this->sdoFactory->update($scheduling,"batchProcessing/scheduling");
            // }
252
253
254
255
256
257
258
259
260

            $interval = $scheduling->nextExecution->getTimestamp() - $currentDate->getTimestamp();

            if ($interval <= 0) {
                $executedTask = $this->execute($scheduling->schedulingId);
            }

            if (!empty($executedTask)) {
                $res[$executedTask->schedulingId] = $executedTask->status;
Prosper De Laure's avatar
Prosper De Laure committed
261
262
            }
        }
263

Prosper De Laure's avatar
Prosper De Laure committed
264
265
266
267
268
269
270
271
272
        return $res; 
    }

    /**
     * Change status
     * 
     * @param type $schedulingId
     * @param type $status
     *
273
     * @return batchProcessing/scheduling The scheduling object
Prosper De Laure's avatar
Prosper De Laure committed
274
275
276
277
278
279
280
281
282
283
     */
    public function changeStatus($schedulingId, $status)
    {
        $scheduling = $this->sdoFactory->read("batchProcessing/scheduling", $schedulingId);

        if ($status == "paused") {
            $scheduling->nextExecution = null;
        }
        
        if (!$scheduling) {
284
            throw \laabs::newException("batchProcessing/schedulingException", "Invalid identifier.");
Prosper De Laure's avatar
Prosper De Laure committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        }

        $scheduling->status = $status;
        $this->update($scheduling);

        return $scheduling;
    }

    /**
     * Date of next execution
     *
     * @param array $frequency
     * @return DateTime
     */
    private function nextExecution($frequency)
    {
301
302
303
304
305
        $currentDate = \laabs::newDateTime();
        $endDate = \laabs::newDateTime();

        $currentDate->setTimezone(new \DateTimeZone('UTC'));
        $endDate->setTimezone(new \DateTimeZone('UTC'));
306
307
308
        $UTC_Offset = date('Z');

        $H_Offset = $UTC_Offset/3600;
Prosper De Laure's avatar
Prosper De Laure committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        /**
         * [0] start Minutes
         * [1] start Hours
         * [2] Day week ex : Fri
         * [3] Day month ex : 1,2,3
         * [4] month ex : apr, may, jun
         * [5] number of case 7
         * [6] Frequence unity minute (m) or hour (h)
         * [7] end Minutes
         * [8] end Hours
         * Exemple frequency = [0;18;"Thu";"";"";"5";"m";"0";"20"];
         * Thursday 18h -> 20h every 5 Minutes
         */

323
        if(!empty($frequency[1])) {
324
            $frequency[1] -= $H_Offset; 
325
        }
Alexandre Morin's avatar
Alexandre Morin committed
326
        if(!empty($frequency[8] && $frequency[8] != "00")) {
327
            $frequency[8] -= $H_Offset; 
328
        }
329
330
        if ($frequency[1] < 0) {
            $frequency[1] = 24 + $frequency[1];
331
332
        } elseif ($frequency[1] >= 24) {
            $frequency[1] = $frequency[1] - 24;
333
334
335
        }
        if ($frequency[8] < 0) {
            $frequency[8] = 24 + $frequency[8];
336
337
        } elseif ($frequency[8] >= 24) {
            $frequency[8] = $frequency[8] - 24;
338
        }
339
        
Prosper De Laure's avatar
Prosper De Laure committed
340
341
342
343
344
        if ($frequency[6] != "") {
            if ($frequency[2] == "" && $frequency[3] == "") {
                $timeAdd = strtoupper("PT".$frequency[5].$frequency[6]);
                $currentDate->add(new \DateInterval($timeAdd));

Alexandre Morin's avatar
Alexandre Morin committed
345
                if (($frequency[7] != "" && $frequency[8] != "") && ($frequency[7] != "00" && $frequency[8] != "00")) {
Prosper De Laure's avatar
Prosper De Laure committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
                    $endDate->setTime($frequency[8], $frequency[7], "0");
                } else {
                    $endDate->add(new \DateInterval("P1D"));
                    $endDate->setTime("0", "0", "0");
                }

                $interval = $currentDate->diff($endDate, false);

                if ($interval->invert == 0) {
                    return $currentDate;
                } else {
                    $endDate->add(new \DateInterval("P1D"));
                    $endDate->setTime($frequency[1], $frequency[0], "0");

                    return $endDate;
                }
            } else {
                if ($frequency[2] != "") {
                    $daysWeek = explode(",", $frequency[2]);
                    $timeAdd = strtoupper("PT".$frequency[5].$frequency[6]);
                    $currentDate->add(new \DateInterval($timeAdd));
Alexandre Morin's avatar
Alexandre Morin committed
367
                    if ($frequency[7] != "" && $frequency[8] != "" && ($frequency[7] != "00" && $frequency[8] != "00")) {
Prosper De Laure's avatar
Prosper De Laure committed
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
                        $endDate->setTime($frequency[8], $frequency[7], "0");
                    } else {
                        $endDate->add(new \DateInterval("P1D"));
                        $endDate->setTime("0", "0", "0");
                    }
                    $interval = $currentDate->diff($endDate, false);

                    if ($interval->invert == 0) {
                        return $currentDate;
                    } else {
                        if (sizeof($daysWeek) == 1) {
                            $endDate->add(new \DateInterval("P7D"));
                            $endDate->setTime($frequency[1], $frequency[0], "0");
                        } else {
                            $endDate = $this->nextDayOfWeek($daysWeek, $currentDate);
                            $endDate->setTime($frequency[1], $frequency[0], "0");
                        }

                        return $endDate;
                    }
                } else {
                    $dayMonths = explode(",", $frequency[3]);
                    $timeAdd = strtoupper("PT".$frequency[5].$frequency[6]);
                    $currentDate->add(new \DateInterval($timeAdd));

Alexandre Morin's avatar
Alexandre Morin committed
393
                    if ($frequency[7] != "" && $frequency[8] != "" && ($frequency[7] != "00" && $frequency[8] != "00")) {
Prosper De Laure's avatar
Prosper De Laure committed
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
                        $endDate->setTime($frequency[8], $frequency[7], "0");
                    } else {
                        $endDate->add(new \DateInterval("P1M"));
                        $endDate->setTime("0", "0", "0");
                    }
                    $interval = $currentDate->diff($endDate, false);

                    if ($interval->invert == 0) {
                        return $currentDate;
                    } else {
                        if (count($dayMonths) == 1) {
                            $endDate->add(new \DateInterval("P1M"));
                            $endDate->setTime($frequency[1], $frequency[0], "0");
                        } else {
                            $endDate = $this->nextDayOfMonth($dayMonths);
                            $endDate->setTime($frequency[1], $frequency[0], "0");
                        }

                        if ($frequency[4] != "") {
                            $currentMonth = $endDate->format("m");
                            $monthInterval = $this->getNextMonthInterval($currentMonth, $frequency[4]);
                            $endDate->add(new \DateInterval("P".$monthInterval."M"));
                        }

                        return $endDate;
                    }
                }
            }
        } else {
            if ($frequency[2] != "") {
                $daysWeek = explode(",", $frequency[2]);

                if (count($daysWeek) == 1) {
                    $endDate->add(new \DateInterval("P7D"));
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                } else {
                    $endDate = $this->nextDayOfWeek($daysWeek, $currentDate);
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                }
            } elseif ($frequency[3] != "" && $frequency[4] != "") {
                $dayMonths = explode(",", $frequency[3]);

                if (count($dayMonths) == 1) {
                    $endDate->add(new \DateInterval("P1M"));
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                } else {
                    $endDate = $this->nextDayOfMonth($dayMonths);
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                }

                $currentMonth = $endDate->format("m");
                $monthInterval = $this->getNextMonthInterval($currentMonth, $frequency[4]);
                $endDate->add(new \DateInterval("P".$monthInterval."M"));
            } elseif ($frequency[3] != "") {
                $dayMonths = explode(",", $frequency[3]);

                if (count($dayMonths) == 1) {
                    $endDate->add(new \DateInterval("P1M"));
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                } else {
                    $endDate = $this->nextDayOfMonth($dayMonths);
                    $endDate->setTime($frequency[1], $frequency[0], "0");
                }
            } else {
                $endDate->add(new \DateInterval("P1D"));
                $endDate->setTime($frequency[1], $frequency[0], "0");
            }

            return $endDate;
        }
    }

    /**
     * Next day of execution (Week)
     *
     * @param array    $daysWeek
     * @param Datetime $currentDate
     * @return DateTime
     */
    private function nextDayOfWeek($daysWeek, $currentDate)
    {
        $currentTime = strtotime($currentDate->format("Y-m-d\TH:i:s"));
        $nextDayTime = 0;

        foreach ($daysWeek as $day) {
            $dayTime = strtotime($day.",".$currentDate->format("Y-m-d\TH:i:s"));
            if ($dayTime != $currentTime) {
                if (!$nextDayTime || $dayTime < $nextDayTime) {
                    $nextDayTime = $dayTime;
                }
            }
        }
486
        $nextDate = \laabs::newDateTime('UTC');
Prosper De Laure's avatar
Prosper De Laure committed
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        $nextDate->setTimestamp($nextDayTime);

        return $nextDate;
    }

    /**
     * Next day of execution (Month)
     *
     * @param array $dayMonths
     * @return DateTime
     */
    private function nextDayOfMonth($dayMonths)
    {
        $lastDayOfMonth = date('t', strtotime('today'));
        $currentDayNum = strtoupper(date("d"));
502
        $endDate = \laabs::newDateTime('UTC');
Prosper De Laure's avatar
Prosper De Laure committed
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
        $totalMore = 0;
        $totalLess = 0;

        foreach ($dayMonths as $dayMonth) {
            if ($dayMonth > $lastDayOfMonth) {
                $dayMonth = $lastDayOfMonth;
            }
            $dayDiff = $dayMonth - $currentDayNum;

            if ($dayDiff > 0) {
                if ($totalMore == 0 || $totalMore > $dayDiff) {
                    $totalMore = $dayDiff;
                }
            } else {
                if ($totalLess > $dayDiff) {
                    $totalLess = $dayDiff;
                }
            }
        }

        if ($totalMore != 0) {
            $endDate->add(new \DateInterval("P".$totalMore."D"));

            return $endDate;
        } else {
            $totalLess = $totalLess * -1;
            $endDate->add(new \DateInterval("P1M"));
            $endDate->sub(new \DateInterval("P".$totalLess."D"));

            return $endDate;
        }
    }

    /**
     * Get positive interval of next month in frequency
     *
     * @param int    $currentMonth The numerical current month
     * @param string $frequency    Months in string with comma separator
     *
     * @return int The interval between the current month and the next month in frequency
     */
    private function getNextMonthInterval($currentMonth, $frequency)
    {
        $months = \laabs\explode(',', $frequency);
        $numericMonths = [];

        foreach ($months as $month) {
            $numericMonths[] = (int) date('m', strtotime($month))-1;
        }

        sort($numericMonths);

        for ($i = 0; !in_array(($currentMonth -1 + $i) % 12, $numericMonths); $i++);

        return $i;
    }
    
560
    private function serviceToken($serviceAccountId)
Prosper De Laure's avatar
Prosper De Laure committed
561
562
563
    {
        $account = $this->sdoFactory->read("auth/account", $serviceAccountId);

564
        if(!$account->enabled) {
Shiva SIVANESARAJAH's avatar
Shiva SIVANESARAJAH committed
565
            throw \laabs::newException("auth/authenticationException", "Service account disabled");
566
567
        }

Prosper De Laure's avatar
Prosper De Laure committed
568
569
570
        $data = new \StdClass();
        $data->accountId = $serviceAccountId;

571
572
573
        $cryptedToken = base64_decode($account->password);
        $jsonToken = \laabs::decrypt($cryptedToken, \laabs::getCryptKey());
        $authToken= \json_decode($jsonToken);
Prosper De Laure's avatar
Prosper De Laure committed
574
575
576
        $GLOBALS["TOKEN"]['AUTH'] = $authToken;

        if ($account->accountType == "service") {
577
578
            $servicePositionController = \laabs::newController("organization/servicePosition");
            $servicePosition = $servicePositionController->getPosition($serviceAccountId);
Prosper De Laure's avatar
Prosper De Laure committed
579
580
581
582
583
584
585

            if ($servicePosition != null) {
                $orgToken = new \core\token($servicePosition->organization, 0);
                $GLOBALS["TOKEN"]["ORGANIZATION"] = $orgToken;
            }
        }
    }
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

    /**
     * List service accounts available for a scheduling
     *
     * @param  string $schedulingId scheduling Identifier
     *
     * @return array $serviceAccounts List of service accounts
     */
    public function getServiceAccountsByScheduling($schedulingId)
    {
        $scheduling = $this->sdoFactory->read("batchProcessing/scheduling", $schedulingId);

        if (is_null($scheduling)) {
            throw \laabs::newException("batchProcessing/schedulingException", "Scheduling unknown");
        }

        $task = $this->readTask($scheduling->taskId);

        $serviceAccountController = \laabs::newController("auth/serviceAccount");
        $serviceAccounts = $serviceAccountController->getAccountsByPrivilege($task->route);

        return $serviceAccounts;
    }
Prosper De Laure's avatar
Prosper De Laure committed
609
}