Skip to content

Commit

Permalink
feat(taskprocessing): add occ commands to list tasks and compute stats
Browse files Browse the repository at this point in the history
Signed-off-by: Julien Veyssier <julien-nc@posteo.net>
  • Loading branch information
julien-nc committed Jul 15, 2024
1 parent 1aa989b commit f69cf17
Show file tree
Hide file tree
Showing 8 changed files with 296 additions and 6 deletions.
84 changes: 84 additions & 0 deletions core/Command/TaskProcessing/ListCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php
/**
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\Core\Command\TaskProcessing;

use OC\Core\Command\Base;
use OCP\TaskProcessing\IManager;
use OCP\TaskProcessing\Task;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ListCommand extends Base {
public function __construct(
protected IManager $taskProcessingManager,
) {
parent::__construct();
}

protected function configure() {

Check notice

Code scanning / Psalm

MissingReturnType Note

Method OC\Core\Command\TaskProcessing\ListCommand::configure does not have a return type, expecting void
$this
->setName('taskprocessing:task:list')
->setDescription('list tasks')
->addOption(
'userIdFilter',
'u',
InputOption::VALUE_OPTIONAL,
'only get the tasks for one user ID'
)
->addOption(
'type',
't',
InputOption::VALUE_OPTIONAL,
'only get the tasks for one task type'
)
->addOption(
'customId',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks for one custom ID'
)
->addOption(
'status',
's',
InputOption::VALUE_OPTIONAL,
'only get the tasks that have a specific status (STATUS_UNKNOWN=0, STATUS_SCHEDULED=1, STATUS_RUNNING=2, STATUS_SUCCESSFUL=3, STATUS_FAILED=4, STATUS_CANCELLED=5)'
)
->addOption(
'scheduledAfter',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks that were scheduled after a specific date (Unix timestamp)'
)
->addOption(
'endedBefore',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks that ended before a specific date (Unix timestamp)'
);
parent::configure();
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$userIdFilter = $input->getOption('userIdFilter');
if ($userIdFilter === null) {
$userIdFilter = '';
} elseif ($userIdFilter === '') {
$userIdFilter = null;
}
$type = $input->getOption('type');
$customId = $input->getOption('customId');
$status = $input->getOption('status');
$scheduledAfter = $input->getOption('scheduledAfter');
$endedBefore = $input->getOption('endedBefore');

$tasks = $this->taskProcessingManager->getTasks($userIdFilter, $type, $customId, $status, $scheduledAfter, $endedBefore);
$arrayTasks = array_map(fn (Task $task): array => $task->jsonSerialize(), $tasks);

$this->writeArrayInOutputFormat($input, $output, $arrayTasks);
return 0;
}
}
145 changes: 145 additions & 0 deletions core/Command/TaskProcessing/Statistics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php
/**
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\Core\Command\TaskProcessing;

use OC\Core\Command\Base;
use OCP\TaskProcessing\IManager;
use OCP\TaskProcessing\Task;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class Statistics extends Base {
public function __construct(
protected IManager $taskProcessingManager,
) {
parent::__construct();
}

protected function configure() {

Check notice

Code scanning / Psalm

MissingReturnType Note

Method OC\Core\Command\TaskProcessing\Statistics::configure does not have a return type, expecting void
$this
->setName('taskprocessing:task:stats')
->setDescription('get statistics for tasks')
->addOption(
'userIdFilter',
'u',
InputOption::VALUE_OPTIONAL,
'only get the tasks for one user ID'
)
->addOption(
'type',
't',
InputOption::VALUE_OPTIONAL,
'only get the tasks for one task type'
)
->addOption(
'customId',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks for one custom ID'
)
->addOption(
'status',
's',
InputOption::VALUE_OPTIONAL,
'only get the tasks that have a specific status (STATUS_UNKNOWN=0, STATUS_SCHEDULED=1, STATUS_RUNNING=2, STATUS_SUCCESSFUL=3, STATUS_FAILED=4, STATUS_CANCELLED=5)'
)
->addOption(
'scheduledAfter',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks that were scheduled after a specific date (Unix timestamp)'
)
->addOption(
'endedBefore',
null,
InputOption::VALUE_OPTIONAL,
'only get the tasks that ended before a specific date (Unix timestamp)'
);
parent::configure();
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$userIdFilter = $input->getOption('userIdFilter');
if ($userIdFilter === null) {
$userIdFilter = '';
} elseif ($userIdFilter === '') {
$userIdFilter = null;
}
$type = $input->getOption('type');
$customId = $input->getOption('customId');
$status = $input->getOption('status');
$scheduledAfter = $input->getOption('scheduledAfter');
$endedBefore = $input->getOption('endedBefore');

$tasks = $this->taskProcessingManager->getTasks($userIdFilter, $type, $customId, $status, $scheduledAfter, $endedBefore);

$stats = ['Number of tasks' => count($tasks)];

$maxRunningTime = 0;
$totalRunningTime = 0;
$runningTimeCount = 0;

$maxQueuingTime = 0;
$totalQueuingTime = 0;
$queuingTimeCount = 0;

$maxUserWaitingTime = 0;
$totalUserWaitingTime = 0;
$userWaitingTimeCount = 0;
foreach ($tasks as $task) {
// running time
if ($task->getStartedAt() !== null && $task->getEndedAt() !== null) {
$taskRunningTime = $task->getEndedAt() - $task->getStartedAt();
$totalRunningTime += $taskRunningTime;
$runningTimeCount++;
if ($taskRunningTime >= $maxRunningTime) {
$maxRunningTime = $taskRunningTime;
}
}
// queuing time
if ($task->getScheduledAt() !== null && $task->getStartedAt() !== null) {
$taskQueuingTime = $task->getStartedAt() - $task->getScheduledAt();
$totalQueuingTime += $taskQueuingTime;
$queuingTimeCount++;
if ($taskQueuingTime >= $maxQueuingTime) {
$maxQueuingTime = $taskQueuingTime;
}
}
// user waiting time
if ($task->getScheduledAt() !== null && $task->getEndedAt() !== null) {
$taskUserWaitingTime = $task->getEndedAt() - $task->getScheduledAt();
$totalUserWaitingTime += $taskUserWaitingTime;
$userWaitingTimeCount++;
if ($taskUserWaitingTime >= $maxUserWaitingTime) {
$maxUserWaitingTime = $taskUserWaitingTime;
}
}
}

if ($runningTimeCount > 0) {
$stats['Max running time'] = $maxRunningTime;
$averageRunningTime = (int)($totalRunningTime / $runningTimeCount);
$stats['Average running time'] = $averageRunningTime;
$stats['Running time count'] = $runningTimeCount;
}
if ($queuingTimeCount > 0) {
$stats['Max queuing time'] = $maxQueuingTime;
$averageQueuingTime = (int)($totalQueuingTime / $queuingTimeCount);
$stats['Average queuing time'] = $averageQueuingTime;
$stats['Queuing time count'] = $queuingTimeCount;
}
if ($userWaitingTimeCount > 0) {
$stats['Max user waiting time'] = $maxUserWaitingTime;
$averageUserWaitingTime = (int)($totalUserWaitingTime / $userWaitingTimeCount);
$stats['Average user waiting time'] = $averageUserWaitingTime;
$stats['User waiting time count'] = $userWaitingTimeCount;
}

$this->writeArrayInOutputFormat($input, $output, $stats);
return 0;
}
}
6 changes: 3 additions & 3 deletions core/Migrations/Version30000Date20240708160048.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ public function changeSchema(IOutput $output, Closure $schemaClosure, array $opt

$table->addColumn('scheduled_at', Types::INTEGER, [
'notnull' => false,
'default' => 0,
'default' => null,
'unsigned' => true,
]);
$table->addColumn('started_at', Types::INTEGER, [
'notnull' => false,
'default' => 0,
'default' => null,
'unsigned' => true,
]);
$table->addColumn('ended_at', Types::INTEGER, [
'notnull' => false,
'default' => 0,
'default' => null,
'unsigned' => true,
]);

Expand Down
3 changes: 3 additions & 0 deletions core/register_command.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@
$application->add(Server::get(Command\Security\BruteforceResetAttempts::class));
$application->add(Server::get(Command\SetupChecks::class));
$application->add(Server::get(Command\FilesMetadata\Get::class));

$application->add(Server::get(Command\TaskProcessing\ListCommand::class));
$application->add(Server::get(Command\TaskProcessing\Statistics::class));
} else {
$application->add(Server::get(Command\Maintenance\Install::class));
}
6 changes: 3 additions & 3 deletions lib/private/TaskProcessing/Db/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ class Task extends Entity {
/**
* @var string[]
*/
public static array $columns = ['id', 'last_updated', 'type', 'input', 'output', 'status', 'user_id', 'app_id', 'custom_id', 'completion_expected_at', 'error_message', 'progress'];
public static array $columns = ['id', 'last_updated', 'type', 'input', 'output', 'status', 'user_id', 'app_id', 'custom_id', 'completion_expected_at', 'error_message', 'progress', 'scheduled_at', 'started_at', 'ended_at'];

/**
* @var string[]
*/
public static array $fields = ['id', 'lastUpdated', 'type', 'input', 'output', 'status', 'userId', 'appId', 'customId', 'completionExpectedAt', 'errorMessage', 'progress'];
public static array $fields = ['id', 'lastUpdated', 'type', 'input', 'output', 'status', 'userId', 'appId', 'customId', 'completionExpectedAt', 'errorMessage', 'progress', 'scheduledAt', 'startedAt', 'endedAt'];


public function __construct() {
Expand All @@ -83,7 +83,7 @@ public function __construct() {
$this->addType('completionExpectedAt', 'datetime');
$this->addType('errorMessage', 'string');
$this->addType('progress', 'float');
$this->addType('scheduleAt', 'integer');
$this->addType('scheduledAt', 'integer');
$this->addType('startedAt', 'integer');
$this->addType('endedAt', 'integer');
}
Expand Down
29 changes: 29 additions & 0 deletions lib/private/TaskProcessing/Db/TaskMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,35 @@ public function findUserTasksByApp(?string $userId, string $appId, ?string $cust
return array_values($this->findEntities($qb));
}

public function findTasks(?string $userId, ?string $taskType = null, ?string $customId = null, ?int $status = null, ?int $scheduleAfter = null, ?int $endedBefore = null): array {
$qb = $this->db->getQueryBuilder();
$qb->select(Task::$columns)
->from($this->tableName);

// empty string: no userId filter
if ($userId !== '') {
$qb->where($qb->expr()->eq('user_id', $qb->createPositionalParameter($userId)));
}
if ($taskType !== null) {
$qb->andWhere($qb->expr()->eq('type', $qb->createPositionalParameter($taskType)));
}
if ($customId !== null) {
$qb->andWhere($qb->expr()->eq('custom_id', $qb->createPositionalParameter($customId)));
}
if ($status !== null) {
$qb->andWhere($qb->expr()->eq('status', $qb->createPositionalParameter($status, IQueryBuilder::PARAM_INT)));
}
if ($scheduleAfter !== null) {
$qb->andWhere($qb->expr()->isNotNull('scheduled_at'));
$qb->andWhere($qb->expr()->gt('scheduled_at', $qb->createPositionalParameter($scheduleAfter, IQueryBuilder::PARAM_INT)));
}
if ($endedBefore !== null) {
$qb->andWhere($qb->expr()->isNotNull('ended_at'));
$qb->andWhere($qb->expr()->lt('ended_at', $qb->createPositionalParameter($endedBefore, IQueryBuilder::PARAM_INT)));
}
return array_values($this->findEntities($qb));
}

/**
* @param int $timeout
* @return int the number of deleted tasks
Expand Down
13 changes: 13 additions & 0 deletions lib/private/TaskProcessing/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,19 @@ public function getUserTasks(?string $userId, ?string $taskTypeId = null, ?strin
}
}

public function getTasks(
?string $userId, ?string $taskTypeId = null, ?string $customId = null, ?int $status = null, ?int $scheduleAfter = null, ?int $endedBefore = null
): array {

Check failure on line 807 in lib/private/TaskProcessing/Manager.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

MoreSpecificReturnType

lib/private/TaskProcessing/Manager.php:807:5: MoreSpecificReturnType: The declared return type 'list<OCP\TaskProcessing\Task>' for OC\TaskProcessing\Manager::getTasks is more specific than the inferred return type 'array<array-key, OCP\TaskProcessing\Task>' (see https://psalm.dev/070)

Check failure

Code scanning / Psalm

MoreSpecificReturnType Error

The declared return type 'list<OCP\TaskProcessing\Task>' for OC\TaskProcessing\Manager::getTasks is more specific than the inferred return type 'array<array-key, OCP\TaskProcessing\Task>'
try {
$taskEntities = $this->taskMapper->findTasks($userId, $taskTypeId, $customId, $status, $scheduleAfter, $endedBefore);
return array_map(fn ($taskEntity): Task => $taskEntity->toPublicTask(), $taskEntities);

Check failure on line 810 in lib/private/TaskProcessing/Manager.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

LessSpecificReturnStatement

lib/private/TaskProcessing/Manager.php:810:11: LessSpecificReturnStatement: The type 'array<array-key, OCP\TaskProcessing\Task>' is more general than the declared return type 'list<OCP\TaskProcessing\Task>' for OC\TaskProcessing\Manager::getTasks (see https://psalm.dev/129)

Check failure

Code scanning / Psalm

LessSpecificReturnStatement Error

The type 'array<array-key, OCP\TaskProcessing\Task>' is more general than the declared return type 'list<OCP\TaskProcessing\Task>' for OC\TaskProcessing\Manager::getTasks
} catch (\OCP\DB\Exception $e) {
throw new \OCP\TaskProcessing\Exception\Exception('There was a problem finding the tasks', 0, $e);
} catch (\JsonException $e) {
throw new \OCP\TaskProcessing\Exception\Exception('There was a problem parsing JSON after finding the tasks', 0, $e);
}
}

public function getUserTasksByApp(?string $userId, string $appId, ?string $customId = null): array {
try {
$taskEntities = $this->taskMapper->findUserTasksByApp($userId, $appId, $customId);
Expand Down
16 changes: 16 additions & 0 deletions lib/public/TaskProcessing/IManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,22 @@ public function getUserTask(int $id, ?string $userId): Task;
*/
public function getUserTasks(?string $userId, ?string $taskTypeId = null, ?string $customId = null): array;

/**
* @param string|null $userId The user id that scheduled the task
* @param string|null $taskTypeId The task type id to filter by
* @param string|null $customId
* @param int|null $status The task status
* @param int|null $scheduleAfter Minimum schedule time filter
* @param int|null $endedBefore Maximum ending time filter
* @return list<Task>
* @throws Exception If the query failed
* @throws NotFoundException If the task could not be found
* @since 30.0.0
*/
public function getTasks(
?string $userId, ?string $taskTypeId = null, ?string $customId = null, ?int $status = null, ?int $scheduleAfter = null, ?int $endedBefore = null
): array;

/**
* @param string|null $userId
* @param string $appId
Expand Down

0 comments on commit f69cf17

Please sign in to comment.