]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker/Cron.php
Refactor files related to the Compose page and frio theme settings
[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                 $max_duration_defaults = DI::config()->get('system', 'worker_max_duration');
81
82                 while ($entry = DBA::fetch($entries)) {
83                         if (!posix_kill($entry["pid"], 0)) {
84                                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['id' => $entry["id"]]);
85                         } else {
86                                 // Kill long running processes
87
88                                 // Define the maximum durations
89                                 $max_duration = $max_duration_defaults[$entry['priority']] ?? 0;
90                                 if (empty($max_duration)) {
91                                         continue;
92                                 }
93
94                                 $argv = json_decode($entry['parameter'], true);
95                                 if (!empty($entry['command'])) {
96                                         $command = $entry['command'];
97                                 } elseif (!empty($argv)) {
98                                         $command = array_shift($argv);
99                                 } else {
100                                         return;
101                                 }
102
103                                 $command = basename($command);
104
105                                 // How long is the process already running?
106                                 $duration = (time() - strtotime($entry["executed"])) / 60;
107                                 if ($duration > $max_duration) {
108                                         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]);
109                                         posix_kill($entry["pid"], SIGTERM);
110
111                                         // We killed the stale process.
112                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
113                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
114                                         $new_priority = $entry['priority'];
115                                         if ($entry['priority'] == PRIORITY_HIGH) {
116                                                 $new_priority = PRIORITY_MEDIUM;
117                                         } elseif ($entry['priority'] == PRIORITY_MEDIUM) {
118                                                 $new_priority = PRIORITY_LOW;
119                                         } elseif ($entry['priority'] != PRIORITY_CRITICAL) {
120                                                 $new_priority = PRIORITY_NEGLIGIBLE;
121                                         }
122                                         DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]]
123                                         );
124                                 } else {
125                                         Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
126                                 }
127                         }
128                 }
129                 DBA::close($entries);
130         }
131
132         /**
133          * Remove old entries from the workerqueue
134          *
135          * @return void
136          */
137         private static function cleanWorkerQueue()
138         {
139                 DBA::delete('workerqueue', ["`done` AND `executed` < ?", DateTimeFormat::utc('now - 1 hour')]);
140
141                 // Optimizing this table only last seconds
142                 if (DI::config()->get('system', 'optimize_tables')) {
143                         // We are acquiring the two locks from the worker to avoid locking problems
144                         if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
145                                 if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
146                                         DBA::e("OPTIMIZE TABLE `workerqueue`");
147                                         DBA::e("OPTIMIZE TABLE `process`");
148                                         DI::lock()->release(Worker::LOCK_WORKER);
149                                 }
150                                 DI::lock()->release(Worker::LOCK_PROCESS);
151                         }
152                 }
153         }
154
155         /**
156          * Directly deliver AP messages or requeue them.
157          *
158          * This function is placed here as a safeguard. Even when the worker queue is completely blocked, messages will be delivered.
159          */
160         private static function deliverPosts()
161         {
162                 $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`");
163                 while ($delivery = DBA::fetch($deliveries)) {
164                         if ($delivery['failed'] == 0) {
165                                 $result = ActivityPub\Delivery::deliver($delivery['inbox']);
166                                 Logger::info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]);
167                                 continue;
168                         } elseif ($delivery['failed'] < 3) {
169                                 $priority = PRIORITY_HIGH;
170                         } elseif ($delivery['failed'] < 6) {
171                                 $priority = PRIORITY_MEDIUM;
172                         } elseif ($delivery['failed'] < 8) {
173                                 $priority = PRIORITY_LOW;
174                         } else {
175                                 $priority = PRIORITY_NEGLIGIBLE;
176                         }
177
178                         if ($delivery['failed'] >= DI::config()->get('system', 'worker_defer_limit')) {
179                                 Logger::info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]);
180                                 Post\Delivery::removeFailed($delivery['inbox']);
181                         }
182
183                         if (Worker::add($priority, 'APDelivery', '', 0, $delivery['inbox'], 0)) {
184                                 Logger::info('Missing APDelivery worker added for inbox', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]);
185                         }
186                 }
187         }
188
189         /**
190          * Add missing "intro" records.
191          *
192          * @return void
193          */
194         private static function addIntros()
195         {
196                 $contacts = DBA::p("SELECT `uid`, `id`, `created` FROM `contact` WHERE `rel` = ? AND `pending` AND NOT `id` IN (SELECT `contact-id` FROM `intro`)", Contact::FOLLOWER);
197                 while ($contact = DBA::fetch($contacts)) {
198                         $fields = [
199                                 'uid'        => $contact['uid'],
200                                 'contact-id' => $contact['id'],
201                                 'datetime'   => $contact['created'],
202                                 'hash'       => Strings::getRandomHex()
203                         ];
204                         Logger::notice('Adding missing intro', ['fields' => $fields]);
205                         DBA::insert('intro', $fields);
206                 }
207         }
208 }