Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background job time windows #30945

Merged
merged 3 commits into from
Feb 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/contactsinteraction/lib/BackgroundJob/CleanupJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

use OCA\ContactsInteraction\Db\RecentContactMapper;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;

class CleanupJob extends TimedJob {
Expand All @@ -38,7 +39,8 @@ public function __construct(ITimeFactory $time,
RecentContactMapper $mapper) {
parent::__construct($time);

$this->setInterval(12 * 60 * 60);
$this->setInterval(24 * 60 * 60);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);

$this->mapper = $mapper;
}
Expand Down
2 changes: 2 additions & 0 deletions apps/dav/lib/BackgroundJob/UploadCleanup.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

use OC\User\NoUserException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\TimedJob;
use OCP\Files\File;
Expand All @@ -51,6 +52,7 @@ public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobLis

// Run once a day
$this->setInterval(60 * 60 * 24);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}

protected function run($argument) {
Expand Down
2 changes: 2 additions & 0 deletions apps/files_external/lib/BackgroundJob/CredentialsCleanup.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use OCA\Files_External\Lib\StorageConfig;
use OCA\Files_External\Service\UserGlobalStoragesService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;
use OCP\Security\ICredentialsManager;
use OCP\IUser;
Expand All @@ -53,6 +54,7 @@ public function __construct(

// run every day
$this->setInterval(24 * 60 * 60);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}

protected function run($argument) {
Expand Down
2 changes: 2 additions & 0 deletions apps/files_sharing/lib/ExpireSharesJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
namespace OCA\Files_Sharing;

use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;
use OCP\IDBConnection;
use OCP\Share\Exceptions\ShareNotFound;
Expand All @@ -50,6 +51,7 @@ public function __construct(ITimeFactory $time, IManager $shareManager, IDBConne

// Run once a day
$this->setInterval(24 * 60 * 60);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\TimedJob;
use OCP\IUserManager;
Expand Down Expand Up @@ -60,6 +61,7 @@ public function __construct(IRegistry $registry,
$this->jobList = $jobList;

$this->setInterval(60 * 60 * 24 * 14);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}

protected function run($argument) {
Expand Down
14 changes: 14 additions & 0 deletions config/config.sample.php
Original file line number Diff line number Diff line change
Expand Up @@ -1214,6 +1214,20 @@
*/
'maintenance' => false,

/**
* UTC Hour for maintenance windows
*
* Some background jobs only run once a day. When an hour is defined for this config,
* the background jobs which advertise themselves as not time sensitive will be
* delayed during the "working" hours and only run in the 4 hours after the given time.
* This is e.g. used for activity expiration, suspicious login training and update checks.
*
* A value of 1 e.g. will only run these background jobs between 01:00am UTC and 05:00am UTC.
*
* Defaults to ``100`` which disables the feature
*/
'maintenance_window_start' => 1,


/**
* SSL
Expand Down
55 changes: 55 additions & 0 deletions core/Migrations/Version24000Date20220131153041.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Joas Schilling <coding@nextcloud.com>
*
* @author Joas Schilling <coding@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version24000Date20220131153041 extends SimpleMigrationStep {
/**
* @param IOutput $output
* @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

$table = $schema->getTable('jobs');
if (!$table->hasColumn('time_sensitive')) {
$table->addColumn('time_sensitive', Types::SMALLINT, [
'default' => 1,
]);
$table->addIndex(['time_sensitive'], 'jobs_time_sensitive');
return $schema;
}
return null;
}
}
24 changes: 23 additions & 1 deletion cron.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,28 @@
$config->setAppValue('core', 'backgroundjobs_mode', 'cron');
}

// Low-load hours
$onlyTimeSensitive = false;
$startHour = $config->getSystemValueInt('maintenance_window_start', 100);
if ($startHour <= 23) {
$date = new \DateTime('now', new \DateTimeZone('UTC'));
$currentHour = (int) $date->format('G');
$endHour = $startHour + 4;

if ($startHour <= 20) {
// Start time: 01:00
// End time: 05:00
// Only run sensitive tasks when it's before the start or after the end
$onlyTimeSensitive = $currentHour < $startHour || $currentHour > $endHour;
} else {
// Start time: 23:00
// End time: 03:00
$endHour -= 24; // Correct the end time from 27:00 to 03:00
// Only run sensitive tasks when it's after the end and before the start
$onlyTimeSensitive = $currentHour > $endHour && $currentHour < $startHour;
}
}

// Work
$jobList = \OC::$server->getJobList();

Expand All @@ -119,7 +141,7 @@
$endTime = time() + 14 * 60;

$executedJobs = [];
while ($job = $jobList->getNext()) {
while ($job = $jobList->getNext($onlyTimeSensitive)) {
if (isset($executedJobs[$job->getId()])) {
$jobList->unlockJob($job);
break;
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,7 @@
'OC\\Core\\Migrations\\Version24000Date20211213081604' => $baseDir . '/core/Migrations/Version24000Date20211213081604.php',
'OC\\Core\\Migrations\\Version24000Date20211222112246' => $baseDir . '/core/Migrations/Version24000Date20211222112246.php',
'OC\\Core\\Migrations\\Version24000Date20211230140012' => $baseDir . '/core/Migrations/Version24000Date20211230140012.php',
'OC\\Core\\Migrations\\Version24000Date20220131153041' => $baseDir . '/core/Migrations/Version24000Date20220131153041.php',
'OC\\Core\\Notification\\CoreNotifier' => $baseDir . '/core/Notification/CoreNotifier.php',
'OC\\Core\\Service\\LoginFlowV2Service' => $baseDir . '/core/Service/LoginFlowV2Service.php',
'OC\\DB\\Adapter' => $baseDir . '/lib/private/DB/Adapter.php',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c
'OC\\Core\\Migrations\\Version24000Date20211213081604' => __DIR__ . '/../../..' . '/core/Migrations/Version24000Date20211213081604.php',
'OC\\Core\\Migrations\\Version24000Date20211222112246' => __DIR__ . '/../../..' . '/core/Migrations/Version24000Date20211222112246.php',
'OC\\Core\\Migrations\\Version24000Date20211230140012' => __DIR__ . '/../../..' . '/core/Migrations/Version24000Date20211230140012.php',
'OC\\Core\\Migrations\\Version24000Date20220131153041' => __DIR__ . '/../../..' . '/core/Migrations/Version24000Date20220131153041.php',
'OC\\Core\\Notification\\CoreNotifier' => __DIR__ . '/../../..' . '/core/Notification/CoreNotifier.php',
'OC\\Core\\Service\\LoginFlowV2Service' => __DIR__ . '/../../..' . '/core/Service/LoginFlowV2Service.php',
'OC\\DB\\Adapter' => __DIR__ . '/../../..' . '/lib/private/DB/Adapter.php',
Expand Down
17 changes: 14 additions & 3 deletions lib/private/BackgroundJob/JobList.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,10 @@ public function getAll() {
/**
* get the next job in the list
*
* @param bool $onlyTimeSensitive
* @return IJob|null
*/
public function getNext() {
public function getNext(bool $onlyTimeSensitive = true): ?IJob {
$query = $this->connection->getQueryBuilder();
$query->select('*')
->from('jobs')
Expand All @@ -195,6 +196,10 @@ public function getNext() {
->orderBy('last_checked', 'ASC')
->setMaxResults(1);

if ($onlyTimeSensitive) {
$query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
}

$update = $this->connection->getQueryBuilder();
$update->update('jobs')
->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
Expand All @@ -215,7 +220,7 @@ public function getNext() {

if ($count === 0) {
// Background job already executed elsewhere, try again.
return $this->getNext();
return $this->getNext($onlyTimeSensitive);
}
$job = $this->buildJob($row);

Expand All @@ -229,7 +234,7 @@ public function getNext() {
$reset->execute();

// Background job from disabled app, try again.
return $this->getNext();
return $this->getNext($onlyTimeSensitive);
}

return $job;
Expand Down Expand Up @@ -333,6 +338,12 @@ public function setLastRun(IJob $job) {
$query->update('jobs')
->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));

if ($job instanceof \OCP\BackgroundJob\TimedJob
&& !$job->isTimeSensitive()) {
$query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
}

$query->execute();
}

Expand Down
2 changes: 2 additions & 0 deletions lib/private/Security/Bruteforce/CleanupJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
namespace OC\Security\Bruteforce;

use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
Expand All @@ -41,6 +42,7 @@ public function __construct(ITimeFactory $time, IDBConnection $connection) {

// Run once a day
$this->setInterval(3600 * 24);
$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
}

protected function run($argument) {
Expand Down
9 changes: 9 additions & 0 deletions lib/public/BackgroundJob/IJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@
* @since 7.0.0
*/
interface IJob {
/**
* @since 24.0.0
*/
public const TIME_INSENSITIVE = 0;
/**
* @since 24.0.0
*/
public const TIME_SENSITIVE = 1;

/**
* Run the background job with the registered argument
*
Expand Down
5 changes: 3 additions & 2 deletions lib/public/BackgroundJob/IJobList.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,11 @@ public function getAll();
/**
* get the next job in the list
*
* @param bool $onlyTimeSensitive
* @return \OCP\BackgroundJob\IJob|null
* @since 7.0.0
* @since 7.0.0 - In 24.0.0 parameter $onlyTimeSensitive got added
*/
public function getNext();
public function getNext(bool $onlyTimeSensitive = false): ?IJob;

/**
* @param int $id
Expand Down
32 changes: 32 additions & 0 deletions lib/public/BackgroundJob/TimedJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
abstract class TimedJob extends Job {
/** @var int */
protected $interval = 0;
/** @var int */
protected $timeSensitivity = IJob::TIME_SENSITIVE;

/**
* set the interval for the job
Expand All @@ -50,6 +52,36 @@ public function setInterval(int $seconds) {
$this->interval = $seconds;
}

/**
* Whether the background job is time sensitive and needs to run soon after
* the scheduled interval, of if it is okay to be delayed until a later time.
*
* @return bool
* @since 24.0.0
*/
public function isTimeSensitive(): bool {
return $this->timeSensitivity === IJob::TIME_SENSITIVE;
}

/**
* If your background job is not time sensitive (sending instant email
* notifications, etc.) it would be nice to set it to IJob::TIME_INSENSITIVE
* This way the execution can be delayed during high usage times.
*
* @param int $sensitivity
* @psalm-param IJob::TIME_* $sensitivity
* @return void
* @since 24.0.0
*/
public function setTimeSensitivity(int $sensitivity): void {
if ($sensitivity !== IJob::TIME_SENSITIVE &&
$sensitivity !== IJob::TIME_INSENSITIVE) {
throw new \InvalidArgumentException('Invalid sensitivity');
}

$this->timeSensitivity = $sensitivity;
}

/**
* run the job if the last run is is more than the interval ago
*
Expand Down
3 changes: 2 additions & 1 deletion tests/lib/BackgroundJob/DummyJobList.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ public function getAll() {
/**
* get the next job in the list
*
* @param bool $onlyTimeSensitive
* @return IJob|null
*/
public function getNext() {
public function getNext(bool $onlyTimeSensitive = true): ?IJob {
if (count($this->jobs) > 0) {
if ($this->last < (count($this->jobs) - 1)) {
$i = $this->last + 1;
Expand Down