]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker/Cron.php
Merge pull request #11925 from mexon/mat/dont-remove-slash
[friendica.git] / src / Core / Worker / Cron.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core\Worker;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Post;
30 use Friendica\Protocol\ActivityPub;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
33
34 /**
35  * Contains the class for jobs that are executed in an interval
36  */
37 class Cron
38 {
39         /**
40          * Runs the cron processes
41          *
42          * @return void
43          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
44          */
45         public static function run()
46         {
47                 Logger::info('Add cron entries');
48
49                 // Check for spooled items
50                 Worker::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
51
52                 // Run the cron job that calls all other jobs
53                 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
54
55                 // Cleaning dead processes
56                 self::killStaleWorkers();
57
58                 // Remove old entries from the workerqueue
59                 self::cleanWorkerQueue();
60
61                 // Directly deliver or requeue posts
62                 self::deliverPosts();
63         }
64
65         /**
66          * fix the queue entry if the worker process died
67          *
68          * @return void
69          * @throws \Exception
70          */
71         public static function killStaleWorkers()
72         {
73                 $entries = DBA::select(
74                         'workerqueue',
75                         ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
76                         ['NOT `done` AND `pid` != 0'],
77                         ['order' => ['priority', 'retrial', 'created']]
78                 );
79
80                 while ($entry = DBA::fetch($entries)) {
81                         if (!posix_kill($entry["pid"], 0)) {
82                                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['id' => $entry["id"]]);
83                         } else {
84                                 // Kill long running processes
85
86                                 // Define the maximum durations
87                                 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
88                                 $max_duration          = $max_duration_defaults[$entry['priority']];
89
90                                 $argv = json_decode($entry['parameter'], true);
91                                 if (!empty($entry['command'])) {
92                                         $command = $entry['command'];
93                                 } elseif (!empty($argv)) {
94                                         $command = array_shift($argv);
95                                 } else {
96                                         return;
97                                 }
98
99                                 $command = basename($command);
100
101                                 // How long is the process already running?
102                                 $duration = (time() - strtotime($entry["executed"])) / 60;
103                                 if ($duration > $max_duration) {
104                                         Logger::warning('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
105                                         posix_kill($entry["pid"], SIGTERM);
106
107                                         // We killed the stale process.
108                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
109                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
110                                         $new_priority = $entry['priority'];
111                                         if ($entry['priority'] == PRIORITY_HIGH) {
112                                                 $new_priority = PRIORITY_MEDIUM;
113                                         } elseif ($entry['priority'] == PRIORITY_MEDIUM) {
114                                                 $new_priority = PRIORITY_LOW;
115                                         } elseif ($entry['priority'] != PRIORITY_CRITICAL) {
116                                                 $new_priority = PRIORITY_NEGLIGIBLE;
117                                         }
118                                         DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]]
119                                         );
120                                 } else {
121                                         Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
122                                 }
123                         }
124                 }
125                 DBA::close($entries);
126         }
127
128         /**
129          * Remove old entries from the workerqueue
130          *
131          * @return void
132          */
133         private static function cleanWorkerQueue()
134         {
135                 DBA::delete('workerqueue', ["`done` AND `executed` < ?", DateTimeFormat::utc('now - 1 hour')]);
136
137                 // Optimizing this table only last seconds
138                 if (DI::config()->get('system', 'optimize_tables')) {
139                         // We are acquiring the two locks from the worker to avoid locking problems
140                         if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
141                                 if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
142                                         DBA::e("OPTIMIZE TABLE `workerqueue`");
143                                         DBA::e("OPTIMIZE TABLE `process`");
144                                         DI::lock()->release(Worker::LOCK_WORKER);
145                                 }
146                                 DI::lock()->release(Worker::LOCK_PROCESS);
147                         }
148                 }
149         }
150
151         /**
152          * Directly deliver AP messages or requeue them.
153          *
154          * This function is placed here as a safeguard. Even when the worker queue is completely blocked, messages will be delivered.
155          */
156         private static function deliverPosts()
157         {
158                 $deliveries = DBA::p("SELECT `item-uri`.`uri` AS `inbox`, MAX(`failed`) AS `failed` FROM `post-delivery` INNER JOIN `item-uri` ON `item-uri`.`id` = `post-delivery`.`inbox-id` GROUP BY `inbox`");
159                 while ($delivery = DBA::fetch($deliveries)) {
160                         if ($delivery['failed'] == 0) {
161                                 $result = ActivityPub\Delivery::deliver($delivery['inbox']);
162                                 Logger::info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]);
163                                 continue;
164                         } elseif ($delivery['failed'] < 3) {
165                                 $priority = PRIORITY_HIGH;
166                         } elseif ($delivery['failed'] < 6) {
167                                 $priority = PRIORITY_MEDIUM;
168                         } elseif ($delivery['failed'] < 8) {
169                                 $priority = PRIORITY_LOW;
170                         } else {
171                                 $priority = PRIORITY_NEGLIGIBLE;
172                         }
173
174                         if ($delivery['failed'] >= DI::config()->get('system', 'worker_defer_limit')) {
175                                 Logger::info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]);
176                                 Post\Delivery::removeFailed($delivery['inbox']);
177                         }
178
179                         if (Worker::add($priority, 'APDelivery', '', 0, $delivery['inbox'], 0)) {
180                                 Logger::info('Missing APDelivery worker added for inbox', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]);
181                         }
182                 }
183         }
184
185         /**
186          * Add missing "intro" records.
187          *
188          * @return void
189          */
190         private static function addIntros()
191         {
192                 $contacts = DBA::p("SELECT `uid`, `id`, `created` FROM `contact` WHERE `rel` = ? AND `pending` AND NOT `id` IN (SELECT `contact-id` FROM `intro`)", Contact::FOLLOWER);
193                 while ($contact = DBA::fetch($contacts)) {
194                         $fields = [
195                                 'uid'        => $contact['uid'],
196                                 'contact-id' => $contact['id'],
197                                 'datetime'   => $contact['created'],
198                                 'hash'       => Strings::getRandomHex()
199                         ];
200                         Logger::notice('Adding missing intro', ['fields' => $fields]);
201                         DBA::insert('intro', $fields);
202                 }
203         }
204 }