3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Core\Worker;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBA;
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;
35 * Contains the class for jobs that are executed in an interval
40 * Runs the cron processes
43 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
45 public static function run()
47 Logger::info('Add cron entries');
49 // Check for spooled items
50 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
52 // Run the cron job that calls all other jobs
53 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
55 // Cleaning dead processes
56 self::killStaleWorkers();
58 // Remove old entries from the workerqueue
59 self::cleanWorkerQueue();
61 // Directly deliver or requeue posts
66 * fix the queue entry if the worker process died
71 public static function killStaleWorkers()
73 $entries = DBA::select(
75 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
76 ['NOT `done` AND `pid` != 0'],
77 ['order' => ['priority', 'retrial', 'created']]
80 $max_duration_defaults = DI::config()->get('system', 'worker_max_duration');
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"]]);
86 // Kill long running processes
88 // Define the maximum durations
89 $max_duration = $max_duration_defaults[$entry['priority']] ?? 0;
90 if (empty($max_duration)) {
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);
103 $command = basename($command);
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);
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'] == Worker::PRIORITY_HIGH) {
116 $new_priority = Worker::PRIORITY_MEDIUM;
117 } elseif ($entry['priority'] == Worker::PRIORITY_MEDIUM) {
118 $new_priority = Worker::PRIORITY_LOW;
119 } elseif ($entry['priority'] != Worker::PRIORITY_CRITICAL) {
120 $new_priority = Worker::PRIORITY_NEGLIGIBLE;
122 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]]
125 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
129 DBA::close($entries);
133 * Remove old entries from the workerqueue
137 private static function cleanWorkerQueue()
139 DBA::delete('workerqueue', ["`done` AND `executed` < ?", DateTimeFormat::utc('now - 1 hour')]);
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);
150 DI::lock()->release(Worker::LOCK_PROCESS);
156 * Directly deliver AP messages or requeue them.
158 * This function is placed here as a safeguard. Even when the worker queue is completely blocked, messages will be delivered.
160 private static function deliverPosts()
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` ORDER BY RAND()");
163 while ($delivery = DBA::fetch($deliveries)) {
164 if ($delivery['failed'] > 0) {
165 Logger::info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]);
166 Post\Delivery::removeFailed($delivery['inbox']);
169 if ($delivery['failed'] == 0) {
170 $result = ActivityPub\Delivery::deliver($delivery['inbox']);
171 Logger::info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]);
173 } elseif ($delivery['failed'] < 3) {
174 $priority = Worker::PRIORITY_HIGH;
175 } elseif ($delivery['failed'] < 6) {
176 $priority = Worker::PRIORITY_MEDIUM;
177 } elseif ($delivery['failed'] < 8) {
178 $priority = Worker::PRIORITY_LOW;
180 $priority = Worker::PRIORITY_NEGLIGIBLE;
183 if (Worker::add(['priority' => $priority, 'force_priority' => true], 'APDelivery', '', 0, $delivery['inbox'], 0)) {
184 Logger::info('Missing APDelivery worker added for inbox', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]);
188 // Optimizing this table only last seconds
189 if (DI::config()->get('system', 'optimize_tables')) {
190 Logger::info('Optimize start');
191 DBA::e("OPTIMIZE TABLE `post-delivery`");
192 Logger::info('Optimize end');
197 * Add missing "intro" records.
201 private static function addIntros()
203 $contacts = DBA::p("SELECT `uid`, `id`, `created` FROM `contact` WHERE `rel` = ? AND `pending` AND NOT `id` IN (SELECT `contact-id` FROM `intro`)", Contact::FOLLOWER);
204 while ($contact = DBA::fetch($contacts)) {
206 'uid' => $contact['uid'],
207 'contact-id' => $contact['id'],
208 'datetime' => $contact['created'],
209 'hash' => Strings::getRandomHex()
211 Logger::notice('Adding missing intro', ['fields' => $fields]);
212 DBA::insert('intro', $fields);