Skip to content
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
66 changes: 66 additions & 0 deletions lib/CronInfo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\ServerInfo;

use OCP\IAppConfig;
use OCP\IConfig;

class CronInfo {
public function __construct(
private IConfig $config,
private IAppConfig $appConfig,
) {
}

/**
* @return array{
* mode: string,
* lastRun: int,
* secondsSince: int,
* status: string
* }
*/
public function getCronInfo(): array {
$mode = $this->config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
$lastRun = $this->appConfig->getValueInt('core', 'lastcron', 0);
$secondsSince = $lastRun > 0 ? max(0, time() - $lastRun) : -1;

return [
'mode' => $mode,
'lastRun' => $lastRun,
'secondsSince' => $secondsSince,
'status' => $this->statusFor($mode, $secondsSince),
];
}

private function statusFor(string $mode, int $secondsSince): string {
if ($secondsSince < 0) {
return 'critical';
}
// Cron job runs every 5 minutes; allow a generous grace period.
if ($mode === 'cron') {
if ($secondsSince > 3600) {
return 'critical';
}
if ($secondsSince > 900) {
return 'warning';
}
return 'ok';
}
// Webcron / ajax modes: looser thresholds.
if ($secondsSince > 7200) {
return 'critical';
}
if ($secondsSince > 3600) {
return 'warning';
}
return 'ok';
}
}
108 changes: 108 additions & 0 deletions lib/JobQueueInfo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\ServerInfo;

use OCP\IDBConnection;

class JobQueueInfo {
private const STUCK_THRESHOLD_SECONDS = 12 * 3600;

public function __construct(
private IDBConnection $db,
) {
}

/**
* @return array{
* total: int,
* reserved: int,
* stuck: int,
* oldestLastRun: int,
* topClasses: list<array{class: string, count: int}>
* }
*/
public function getJobQueueInfo(): array {
return [
'total' => $this->countTotal(),
'reserved' => $this->countReserved(),
'stuck' => $this->countStuck(),
'oldestLastRun' => $this->oldestLastRun(),
'topClasses' => $this->topClasses(5),
];
}

private function countTotal(): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('id'))
->from('jobs');
$result = $qb->executeQuery();
$count = (int)$result->fetchOne();
$result->closeCursor();
return $count;
}

private function countReserved(): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('id'))
->from('jobs')
->where($qb->expr()->gt('reserved_at', $qb->createNamedParameter(0)));
$result = $qb->executeQuery();
$count = (int)$result->fetchOne();
$result->closeCursor();
return $count;
}

private function countStuck(): int {
$threshold = time() - self::STUCK_THRESHOLD_SECONDS;
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('id'))
->from('jobs')
->where($qb->expr()->gt('reserved_at', $qb->createNamedParameter(0)))
->andWhere($qb->expr()->lt('reserved_at', $qb->createNamedParameter($threshold)));
$result = $qb->executeQuery();
$count = (int)$result->fetchOne();
$result->closeCursor();
return $count;
}

private function oldestLastRun(): int {
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->min('last_run'))
->from('jobs')
->where($qb->expr()->gt('last_run', $qb->createNamedParameter(0)));
$result = $qb->executeQuery();
$min = $result->fetchOne();
$result->closeCursor();
return $min === false || $min === null ? 0 : (int)$min;
}

/**
* @return list<array{class: string, count: int}>
*/
private function topClasses(int $limit): array {
$qb = $this->db->getQueryBuilder();
$qb->select('class')
->selectAlias($qb->func()->count('id'), 'count')
->from('jobs')
->groupBy('class')
->orderBy('count', 'DESC')
->setMaxResults($limit);
$result = $qb->executeQuery();
$out = [];
while (($row = $result->fetch()) !== false) {
$out[] = [
'class' => (string)($row['class'] ?? ''),
'count' => (int)($row['count'] ?? 0),
];
}
$result->closeCursor();
return $out;
}
}
9 changes: 9 additions & 0 deletions lib/Settings/AdminSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@

namespace OCA\ServerInfo\Settings;

use OCA\ServerInfo\CronInfo;
use OCA\ServerInfo\DatabaseStatistics;
use OCA\ServerInfo\FpmStatistics;
use OCA\ServerInfo\JobQueueInfo;
use OCA\ServerInfo\Os;
use OCA\ServerInfo\PhpStatistics;
use OCA\ServerInfo\SessionStatistics;
use OCA\ServerInfo\ShareStatistics;
use OCA\ServerInfo\SlowestJobs;
use OCA\ServerInfo\StorageStatistics;
use OCA\ServerInfo\SystemStatistics;
use OCP\AppFramework\Http\TemplateResponse;
Expand All @@ -36,6 +39,9 @@ public function __construct(
private ShareStatistics $shareStatistics,
private SessionStatistics $sessionStatistics,
private SystemStatistics $systemStatistics,
private CronInfo $cronInfo,
private JobQueueInfo $jobQueueInfo,
private SlowestJobs $slowestJobs,
private IConfig $config,
) {
}
Expand All @@ -60,6 +66,9 @@ public function getForm(): TemplateResponse {
'activeUsers' => $this->sessionStatistics->getSessionStatistics(),
'system' => $this->systemStatistics->getSystemStatistics(true, true),
'thermalzones' => $this->os->getThermalZones(),
'cron' => $this->cronInfo->getCronInfo(),
'jobQueue' => $this->jobQueueInfo->getJobQueueInfo(),
'slowestJobs' => $this->slowestJobs->getSlowestJobs(),
'phpinfo' => $this->config->getAppValue('serverinfo', 'phpinfo', 'no') === 'yes',
'phpinfoUrl' => $this->urlGenerator->linkToRoute('serverinfo.page.phpinfo')
];
Expand Down
58 changes: 58 additions & 0 deletions lib/SlowestJobs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\ServerInfo;

use OCP\IDBConnection;
use Psr\Log\LoggerInterface;

class SlowestJobs {
public function __construct(
private IDBConnection $db,
private LoggerInterface $logger,
) {
}

/**
* Returns the job classes with the highest average execution time
* (last_run - last_checked when reservations are released). Pulls
* the columns directly because there is no public API.
*
* @return list<array{class: string, count: int, avgSeconds: int, maxSeconds: int}>
*/
public function getSlowestJobs(int $limit = 5): array {
$qb = $this->db->getQueryBuilder();
$qb->select('class')
->selectAlias($qb->func()->count('id'), 'count')
->selectAlias($qb->createFunction('AVG(' . $qb->getColumnName('execution_duration') . ')'), 'avg_dur')
->selectAlias($qb->createFunction('MAX(' . $qb->getColumnName('execution_duration') . ')'), 'max_dur')
->from('jobs')
->where($qb->expr()->gt('execution_duration', $qb->createNamedParameter(0)))
->groupBy('class')
->orderBy('avg_dur', 'DESC')
->setMaxResults($limit);
try {
$result = $qb->executeQuery();
} catch (\Throwable $e) {
$this->logger->warning('Failed to query slowest jobs', ['exception' => $e]);
return [];
}
$out = [];
while (($row = $result->fetch()) !== false) {
$out[] = [
'class' => (string)($row['class'] ?? ''),
'count' => (int)($row['count'] ?? 0),
'avgSeconds' => (int)round((float)($row['avg_dur'] ?? 0)),
'maxSeconds' => (int)($row['max_dur'] ?? 0),
];
}
$result->closeCursor();
return $out;
}
}
96 changes: 96 additions & 0 deletions tests/lib/CronInfoTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\ServerInfo\Tests;

use OCA\ServerInfo\CronInfo;
use OCP\IAppConfig;
use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject;

class CronInfoTest extends \Test\TestCase {
private IConfig&MockObject $config;
private IAppConfig&MockObject $appConfig;
private CronInfo $instance;

protected function setUp(): void {
parent::setUp();

$this->config = $this->createMock(IConfig::class);
$this->appConfig = $this->createMock(IAppConfig::class);
$this->instance = new CronInfo($this->config, $this->appConfig);
}

public function testNeverRanIsCritical(): void {
$this->config->method('getAppValue')->willReturn('cron');
$this->appConfig->method('getValueInt')->willReturn(0);

$info = $this->instance->getCronInfo();

$this->assertSame('cron', $info['mode']);
$this->assertSame(0, $info['lastRun']);
$this->assertSame(-1, $info['secondsSince']);
$this->assertSame('critical', $info['status']);
}

public function testCronModeRecentRunIsOk(): void {
$this->config->method('getAppValue')->willReturn('cron');
$this->appConfig->method('getValueInt')->willReturn(time() - 60);

$info = $this->instance->getCronInfo();

$this->assertSame('ok', $info['status']);
}

public function testCronModeOver15MinIsWarning(): void {
$this->config->method('getAppValue')->willReturn('cron');
$this->appConfig->method('getValueInt')->willReturn(time() - 1000);

$info = $this->instance->getCronInfo();

$this->assertSame('warning', $info['status']);
}

public function testCronModeOver1HourIsCritical(): void {
$this->config->method('getAppValue')->willReturn('cron');
$this->appConfig->method('getValueInt')->willReturn(time() - 4000);

$info = $this->instance->getCronInfo();

$this->assertSame('critical', $info['status']);
}

public function testWebcronModeOver2HoursIsCritical(): void {
$this->config->method('getAppValue')->willReturn('webcron');
$this->appConfig->method('getValueInt')->willReturn(time() - 8000);

$info = $this->instance->getCronInfo();

$this->assertSame('webcron', $info['mode']);
$this->assertSame('critical', $info['status']);
}

public function testWebcronModeOver1HourIsWarning(): void {
$this->config->method('getAppValue')->willReturn('webcron');
$this->appConfig->method('getValueInt')->willReturn(time() - 5000);

$info = $this->instance->getCronInfo();

$this->assertSame('warning', $info['status']);
}

public function testWebcronModeRecentRunIsOk(): void {
$this->config->method('getAppValue')->willReturn('webcron');
$this->appConfig->method('getValueInt')->willReturn(time() - 60);

$info = $this->instance->getCronInfo();

$this->assertSame('ok', $info['status']);
}
}
Loading
Loading