]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker/Cron.php
8e354344b87f8254a784982840dd9fd4843777ee
[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\GServer;
30 use Friendica\Model\Post;
31 use Friendica\Protocol\ActivityPub;
32 use Friendica\Protocol\Delivery;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Strings;
35
36 /**
37  * Contains the class for jobs that are executed in an interval
38  */
39 class Cron
40 {
41         /**
42          * Runs the cron processes
43          *
44          * @return void
45          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
46          */
47         public static function run()
48         {
49                 Logger::info('Add cron entries');
50
51                 // Check for spooled items
52                 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
53
54                 // Run the cron job that calls all other jobs
55                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
56
57                 // Cleaning dead processes
58                 self::killStaleWorkers();
59
60                 // Remove old entries from the workerqueue
61                 self::cleanWorkerQueue();
62
63                 // Directly deliver or requeue posts to ActivityPub systems
64                 self::deliverAPPosts();
65
66                 // Directly deliver or requeue posts to other systems
67                 self::deliverPosts();
68         }
69
70         /**
71          * fix the queue entry if the worker process died
72          *
73          * @return void
74          * @throws \Exception
75          */
76         public static function killStaleWorkers()
77         {
78                 $entries = DBA::select(
79                         'workerqueue',
80                         ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
81                         ['NOT `done` AND `pid` != 0'],
82                         ['order' => ['priority', 'retrial', 'created']]
83                 );
84
85                 $max_duration_defaults = DI::config()->get('system', 'worker_max_duration');
86
87                 while ($entry = DBA::fetch($entries)) {
88                         if (!posix_kill($entry["pid"], 0)) {
89                                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['id' => $entry["id"]]);
90                         } else {
91                                 // Kill long running processes
92
93                                 // Define the maximum durations
94                                 $max_duration = $max_duration_defaults[$entry['priority']] ?? 0;
95                                 if (empty($max_duration)) {
96                                         continue;
97                                 }
98
99                                 $argv = json_decode($entry['parameter'], true);
100                                 if (!empty($entry['command'])) {
101                                         $command = $entry['command'];
102                                 } elseif (!empty($argv)) {
103                                         $command = array_shift($argv);
104                                 } else {
105                                         return;
106                                 }
107
108                                 $command = basename($command);
109
110                                 // How long is the process already running?
111                                 $duration = (time() - strtotime($entry["executed"])) / 60;
112                                 if ($duration > $max_duration) {
113                                         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]);
114                                         posix_kill($entry["pid"], SIGTERM);
115
116                                         // We killed the stale process.
117                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
118                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
119                                         $new_priority = $entry['priority'];
120                                         if ($entry['priority'] == Worker::PRIORITY_HIGH) {
121                                                 $new_priority = Worker::PRIORITY_MEDIUM;
122                                         } elseif ($entry['priority'] == Worker::PRIORITY_MEDIUM) {
123                                                 $new_priority = Worker::PRIORITY_LOW;
124                                         } elseif ($entry['priority'] != Worker::PRIORITY_CRITICAL) {
125                                                 $new_priority = Worker::PRIORITY_NEGLIGIBLE;
126                                         }
127                                         DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]]
128                                         );
129                                 } else {
130                                         Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
131                                 }
132                         }
133                 }
134                 DBA::close($entries);
135         }
136
137         /**
138          * Remove old entries from the workerqueue
139          *
140          * @return void
141          */
142         private static function cleanWorkerQueue()
143         {
144                 DBA::delete('workerqueue', ["`done` AND `executed` < ?", DateTimeFormat::utc('now - 1 hour')]);
145
146                 // Optimizing this table only last seconds
147                 if (DI::config()->get('system', 'optimize_tables')) {
148                         // We are acquiring the two locks from the worker to avoid locking problems
149                         if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
150                                 if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
151                                         DBA::e("OPTIMIZE TABLE `workerqueue`");
152                                         DBA::e("OPTIMIZE TABLE `process`");
153                                         DI::lock()->release(Worker::LOCK_WORKER);
154                                 }
155                                 DI::lock()->release(Worker::LOCK_PROCESS);
156                         }
157                 }
158         }
159
160         /**
161          * Directly deliver AP messages or requeue them.
162          *
163          * This function is placed here as a safeguard. Even when the worker queue is completely blocked, messages will be delivered.
164          */
165         private static function deliverAPPosts()
166         {
167                 $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` ORDER BY RAND()");
168                 while ($delivery = DBA::fetch($deliveries)) {
169                         if ($delivery['failed'] > 0) {
170                                 Logger::info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]);
171                                 Post\Delivery::removeFailed($delivery['inbox']);
172                         }
173
174                         if ($delivery['failed'] == 0) {
175                                 $result = ActivityPub\Delivery::deliver($delivery['inbox']);
176                                 Logger::info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]);
177                                 continue;
178                         } elseif ($delivery['failed'] < 3) {
179                                 $priority = Worker::PRIORITY_HIGH;
180                         } elseif ($delivery['failed'] < 6) {
181                                 $priority = Worker::PRIORITY_MEDIUM;
182                         } elseif ($delivery['failed'] < 8) {
183                                 $priority = Worker::PRIORITY_LOW;
184                         } else {
185                                 $priority = Worker::PRIORITY_NEGLIGIBLE;
186                         }
187
188                         if (Worker::add(['priority' => $priority, 'force_priority' => true], 'APDelivery', '', 0, $delivery['inbox'], 0)) {
189                                 Logger::info('Priority for APDelivery worker adjusted', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]);
190                         }
191                 }
192
193                 // Optimizing this table only last seconds
194                 if (DI::config()->get('system', 'optimize_tables')) {
195                         Logger::info('Optimize start');
196                         DBA::e("OPTIMIZE TABLE `post-delivery`");
197                         Logger::info('Optimize end');
198                 }
199         }
200
201         /**
202          * Directly deliver messages or requeue them.
203          */
204         private static function deliverPosts()
205         {
206                 $deliveries = DBA::p("SELECT `gsid`, MAX(`failed`) AS `failed` FROM `delivery-queue` GROUP BY `gsid` ORDER BY RAND()");
207                 while ($delivery = DBA::fetch($deliveries)) {
208                         if ($delivery['failed'] > 0) {
209                                 Logger::info('Removing failed deliveries', ['gsid' => $delivery['gsid'], 'failed' => $delivery['failed']]);
210                                 Delivery::removeFailedQueue($delivery['gsid']);
211                         }
212
213                         if (($delivery['failed'] < 3) || GServer::isReachableById($delivery['gsid'])) {
214                                 $priority = Worker::PRIORITY_HIGH;
215                         } elseif ($delivery['failed'] < 6) {
216                                 $priority = Worker::PRIORITY_MEDIUM;
217                         } elseif ($delivery['failed'] < 8) {
218                                 $priority = Worker::PRIORITY_LOW;
219                         } else {
220                                 $priority = Worker::PRIORITY_NEGLIGIBLE;
221                         }
222
223                         if (Worker::add(['priority' => $priority, 'force_priority' => true], 'BulkDelivery', $delivery['gsid'])) {
224                                 Logger::info('Priority for BulkDelivery worker adjusted', ['gsid' => $delivery['gsid'], 'failed' => $delivery['failed'], 'priority' => $priority]);
225                         }
226                 }
227
228                 // Optimizing this table only last seconds
229                 if (DI::config()->get('system', 'optimize_tables')) {
230                         Logger::info('Optimize start');
231                         DBA::e("OPTIMIZE TABLE `delivery-queue`");
232                         Logger::info('Optimize end');
233                 }
234         }
235
236         /**
237          * Add missing "intro" records.
238          *
239          * @return void
240          */
241         private static function addIntros()
242         {
243                 $contacts = DBA::p("SELECT `uid`, `id`, `created` FROM `contact` WHERE `rel` = ? AND `pending` AND NOT `id` IN (SELECT `contact-id` FROM `intro`)", Contact::FOLLOWER);
244                 while ($contact = DBA::fetch($contacts)) {
245                         $fields = [
246                                 'uid'        => $contact['uid'],
247                                 'contact-id' => $contact['id'],
248                                 'datetime'   => $contact['created'],
249                                 'hash'       => Strings::getRandomHex()
250                         ];
251                         Logger::notice('Adding missing intro', ['fields' => $fields]);
252                         DBA::insert('intro', $fields);
253                 }
254         }
255 }