14 namespace Fossology\UI\Api\Controllers;
29 use Psr\Http\Message\ServerRequestInterface;
30 use Slim\Psr7\Request;
73 $queryParams = $request->getQueryParams();
74 $query = $apiVersion == ApiVersion::V2 ? $queryParams : array_map(
function($header) {
75 return implode(
",", $header);
76 }, $request->getHeaders());
78 $limit = isset($query[
'limit']) ? intval($query[
'limit']) : 0;
79 $page = isset($query[
'page']) ? intval($query[
'page']) : 1;
80 $sort = $queryParams[
'sort'] ??
"ASC";
81 $status = $queryParams[
'status'] ??
null;
83 if ($limit < 0 || $page < 1) {
87 return $this->
getAllResults(
null, $status, $request, $response, $sort, $limit, $page, $apiVersion);
99 public function getJobs($request, $response, $args)
102 $userId = $this->restHelper->getUserId();
104 $queryParams = $request->getQueryParams();
105 $query = $apiVersion == ApiVersion::V2 ? $queryParams : array_map(
function($header) {
106 return implode(
",", $header);
107 }, $request->getHeaders());
109 $limit = isset($query[
'limit']) ? intval($query[
'limit']) : 0;
110 $page = isset($query[
'page']) ? intval($query[
'page']) : 1;
111 $sort = $queryParams[
'sort'] ??
"ASC";
112 $status = $queryParams[
'status'] ??
null;
114 if ($limit < 0 || $page < 1) {
118 $id = isset($args[
'id']) ? intval($args[
'id']) :
null;
119 if ($id !==
null && !$this->dbHelper->doesIdExist(
"job",
"job_pk", $id)) {
126 return $this->
getAllResults($id, $status, $request, $response, $sort, $limit, $page, $apiVersion);
129 if (array_key_exists(self::UPLOAD_PARAM, $queryParams)) {
132 $status, $request, $response, $sort, $limit, $page, $apiVersion);
136 return $this->
getAllUserResults($userId, $status, $request, $response, $sort, $limit, $page, $apiVersion);
153 if ($apiVersion == ApiVersion::V2) {
154 $query = $request->getQueryParams();
155 $folder = $query[
"folderId"] ??
null;
156 $upload = $query[
"uploadId"] ??
null;
158 $folder = $request->hasHeader(
'folderId') ? $request->getHeaderLine(
'folderId') :
null;
159 $upload = $request->hasHeader(
'uploadId') ? $request->getHeaderLine(
'uploadId') :
null;
161 if (is_numeric($folder) && is_numeric($upload) && $folder > 0 && $upload > 0) {
163 if (empty($scanOptionsJSON)) {
167 $info = $uploadHelper->handleScheduleAnalysis($upload, $folder,
168 $scanOptionsJSON,
false, $apiVersion);
169 return $response->withJson($info->getArray(), $info->getCode());
172 "Folder id and upload id should be integers!");
187 $userId = $this->restHelper->getUserId();
188 $userName = $this->restHelper->getUserDao()->getUserName($userId);
191 $jobId = intval($args[
'id']);
192 if (! $this->dbHelper->doesIdExist(
"job",
"job_pk", $jobId)) {
197 $canDeleteJob = $this->restHelper->getJobDao()->hasActionPermissionsOnJob($jobId, $userId, $this->restHelper->getGroupId());
198 if (! $canDeleteJob) {
200 "You don't have permission to delete this job.");
203 $queueId = $args[
'queue'];
206 $JobQueue = $this->restHelper->getShowJobDao()->getJobInfo([$jobId])[$jobId][
"jobqueue"];
208 if (!array_key_exists($queueId, $JobQueue)) {
210 "Job queue " . $queueId .
" doesn't exist in Job " . $jobId);
214 $dependentJobs[] = $queueId;
216 foreach ($JobQueue as $job) {
217 if (in_array($queueId, $job[
"depends"])) {
218 $dependentJobs[] = $job[
"jq_pk"];
223 foreach ($dependentJobs as $job) {
224 $Msg =
"\"" . _(
"Killed by") .
" " . $userName .
"\"";
225 $command =
"kill $job $Msg";
229 "Failed to kill job $jobId");
232 $returnVal =
new Info(200,
"Job deleted successfully", InfoType::INFO);
233 return $response->withJson($returnVal->getArray(), $returnVal->getCode());
249 private function getAllUserResults($userId, $status, $request, $response, $sort, $limit, $page, $apiVersion)
251 list($jobs, $count) = $this->dbHelper->getUserJobs($userId, $status, $sort, $limit, $page);
253 foreach ($jobs as $job) {
255 if ($apiVersion == ApiVersion::V2) {
258 $finalJobs[] = $job->getArray($apiVersion);
260 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
278 private function getAllResults($id, $status, $request, $response, $sort, $limit, $page, $apiVersion)
280 list($jobs, $count) = $this->dbHelper->getJobs($id, $status, $sort, $limit, $page,
null);
281 if ($id !==
null && !empty($jobs)) {
287 foreach ($jobs as $job) {
289 if ($apiVersion == ApiVersion::V2) {
292 $finalJobs[] = $job->getArray($apiVersion);
295 $finalJobs = $finalJobs[0];
297 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
315 private function getFilteredResults($uploadId, $status, $request, $response, $sort, $limit, $page, $apiVersion)
318 list($jobs, $count) = $this->dbHelper->getJobs(
null, $status, $sort, $limit, $page, $uploadId);
320 foreach ($jobs as $job) {
322 if ($apiVersion == ApiVersion::V2) {
325 $finalJobs[] = $job->getArray($apiVersion);
327 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
338 $job->getUploadId()));
350 $showJobDao = $this->restHelper->getShowJobDao();
351 $eta = $showJobDao->getEstimatedTime($jobId,
'', 0, $uploadId);
352 $eta = explode(
":", $eta);
353 if (count($eta) > 1) {
354 $eta = (intval($eta[0]) * 3600) + (intval($eta[1]) * 60) + intval($eta[2]);
370 public function getJobsHistory($request, $response, $args)
372 $query = $request->getQueryParams();
373 if (!array_key_exists(self::UPLOAD_PARAM, $query)) {
376 $upload_fk = intval($query[self::UPLOAD_PARAM]);
384 $dbManager = $this->dbHelper->getDbManager();
387 $query =
"SELECT job_pk FROM job WHERE job_upload_fk=$1;";
388 $statement = __METHOD__.
".getJobs";
389 $result = $dbManager->getRows($query, [$upload_fk], $statement);
392 $allJobPks = array_column($result,
'job_pk');
395 $showJobData = $this->getJobQueue($allJobPks);
398 $allJobsHistory = array();
399 foreach ($showJobData as $jobValObj) {
400 $finalJobqueue = array();
401 foreach ($jobValObj[
'job'][
'jobQueue'] as $jqVal) {
403 if ($jqVal[
'depends'][0] !=
null) {
404 $depends = $jqVal[
'depends'];
407 if (!empty($jqVal[
'download'])) {
409 "text" => $jqVal[
"download"],
414 $jobQueue =
new JobQueue($jqVal[
'jq_pk'], $jqVal[
'jq_type'],
415 $jqVal[
'jq_starttime'], $jqVal[
'jq_endtime'], $jqVal[
'jq_endtext'],
416 $jqVal[
'jq_itemsprocessed'], $jqVal[
'jq_log'], $depends,
417 $jqVal[
'itemsPerSec'], $jqVal[
'canDoActions'], $jqVal[
'isInProgress'],
418 $jqVal[
'isReady'], $download);
419 $finalJobqueue[] = $jobQueue->getArray();
421 $job =
new ShowJob($jobValObj[
'job'][
'jobId'],
422 $jobValObj[
'job'][
'jobName'], $finalJobqueue,
423 $jobValObj[
'upload'][
'uploadId']);
424 $allJobsHistory[] = $job->getArray();
426 return $response->withJson($allJobsHistory, 200);
435 private function getJobQueue($allJobPks)
437 $showJobsDao = $this->restHelper->getShowJobDao();
438 $jobsInfo = $showJobsDao->getJobInfo($allJobPks);
439 usort($jobsInfo, [$this,
"compareJobsInfo"]);
445 $ajaxShowJobs = $this->restHelper->getPlugin(
'ajaxShowJobs');
446 $showJobData = $ajaxShowJobs->getShowJobsForEachJob($jobsInfo,
true);
459 $jobQueue = $this->getJobQueue([$job->getId()]);
460 $finalJobqueue = array();
461 foreach ($jobQueue[0][
'job'][
'jobQueue'] as $jqVal) {
463 if ($jqVal[
'depends'][0] !=
null) {
464 $depends = $jqVal[
'depends'];
467 if (!empty($jqVal[
'download'])) {
469 "text" => $jqVal[
"download"],
474 $singleJobQueue =
new JobQueue($jqVal[
'jq_pk'], $jqVal[
'jq_type'],
475 $jqVal[
'jq_starttime'], $jqVal[
'jq_endtime'], $jqVal[
'jq_endtext'],
476 $jqVal[
'jq_itemsprocessed'], $jqVal[
'jq_log'], $depends,
477 $jqVal[
'itemsPerSec'], $jqVal[
'canDoActions'], $jqVal[
'isInProgress'],
478 $jqVal[
'isReady'], $download);
479 $finalJobqueue[] = $singleJobQueue->getArray();
481 $job->setJobQueue($finalJobqueue);
492 return $JobsInfo2[
"job"][
"job_pk"] - $JobsInfo1[
"job"][
"job_pk"];
503 public function getJobStatistics($request, $response, $args)
507 $statisticsPlugin = $this->restHelper->getPlugin(
'dashboard-statistics');
508 $res = $statisticsPlugin->CountAllJobs(
true);
509 return $response->withJson($res, 200);
521 public function getAllServerJobsStatus($request, $response, $args)
525 $allJobStatusPlugin = $this->restHelper->getPlugin(
'ajax_all_job_status');
526 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
527 $res = $allJobStatusPlugin->handle($symfonyRequest);
528 return $response->withJson(json_decode($res->getContent(),
true), 200);
539 public function getSchedulerJobOptionsByOperation($request, $response, $args)
542 $operation = $args[
'operationName'];
544 $adminSchedulerPlugin = $this->restHelper->getPlugin(
'admin_scheduler');
546 if (!in_array($operation, array_keys($adminSchedulerPlugin->operation_array))) {
547 $allowedOperations = implode(
', ', array_keys($adminSchedulerPlugin->operation_array));
548 throw new HttpBadRequestException(
"Operation '$operation' not allowed." .
549 " Allowed operations are: $allowedOperations");
553 $schedulerPlugin = $this->restHelper->getPlugin(
'ajax_admin_scheduler');
554 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
555 $symfonyRequest->request->set(
'operation', $operation);
556 $symfonyRequest->request->set(
'fromRest',
true);
557 $res = $schedulerPlugin->handle($symfonyRequest);
558 return $response->withJson($res, 200);
570 public function handleRunSchedulerOption($request, $response, $args)
574 $query = $request->getQueryParams();
576 $operation = $body[
'operation'];
578 $adminSchedulerPlugin = $this->restHelper->getPlugin(
'admin_scheduler');
580 if (!in_array($operation, array_keys($adminSchedulerPlugin->operation_array))) {
581 $allowedOperations = implode(
', ', array_keys($adminSchedulerPlugin->operation_array));
582 throw new HttpBadRequestException(
"Operation '$operation' not allowed." .
583 " Allowed operations are: $allowedOperations");
587 $schedulerPlugin = $this->restHelper->getPlugin(
'ajax_admin_scheduler');
588 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
589 $symfonyRequest->request->set(
'operation', $operation);
590 $symfonyRequest->request->set(
'fromRest',
true);
591 $data = $schedulerPlugin->handle($symfonyRequest);
593 if ($operation ==
'status' || $operation ==
'verbose') {
594 if (!isset($query[
'job']) || !in_array($query[
'job'], $data[
'jobList'])) {
595 $allowedJobs = implode(
', ', $data[
'jobList']);
596 throw new HttpBadRequestException(
"Job '{$query['job']}' not " .
597 "allowed. Allowed jobs are: $allowedJobs");
599 if (($operation ==
'verbose') && (!isset($query[
'level']) || !in_array($query[
'level'], $data[
'verboseList']))) {
600 $allowedLevels = implode(
', ', $data[
'verboseList']);
601 throw new HttpBadRequestException(
"Level '{$query['level']}' not " .
602 "allowed. Allowed levels are: $allowedLevels");
604 } elseif ($operation ==
'priority' && (!isset($query[
'priority']) || !in_array($query[
'priority'], $data[
'priorityList']))) {
605 $allowedPriorities = implode(
', ', $data[
'priorityList']);
606 throw new HttpBadRequestException(
"Priority '{$query['priority']}' not " .
607 "allowed. Allowed priorities are: $allowedPriorities");
610 if ($operation ==
'status') {
611 $query[
'priority'] =
null;
612 $query[
'level'] =
null;
613 }
else if ($operation ==
'priority') {
614 $query[
'job'] =
null;
615 $query[
'level'] =
null;
616 }
else if ($operation ==
'verbose') {
617 $query[
'priority'] =
null;
619 $query[
'job'] =
null;
620 $query[
'priority'] =
null;
621 $query[
'level'] =
null;
624 $response_from_scheduler = $adminSchedulerPlugin->OperationSubmit(
625 $operation, array_search($query[
'job'], $data[
'jobList']),
626 $query[
'priority'], $query[
'level']);
627 $operation_text = $adminSchedulerPlugin->GetOperationText($operation);
631 if (!empty($adminSchedulerPlugin->error_info)) {
633 $status_msg .=
"$operation_text $text.";
634 throw new HttpInternalServerErrorException($status_msg . $report);
636 $text = _(
"successfully");
637 $status_msg .=
"$operation_text $text.";
638 if (! empty($response_from_scheduler)) {
639 $report .= $response_from_scheduler;
642 $info =
new Info(200, $status_msg. $report, InfoType::INFO);
643 return $response->withJson($info->getArray(), $info->getCode());
Controller for Job model.
createJob($request, $response, $args)
getJobs($request, $response, $args)
getFilteredResults($uploadId, $status, $request, $response, $sort, $limit, $page, $apiVersion)
getAllResults($id, $status, $request, $response, $sort, $limit, $page, $apiVersion)
deleteJob($request, $response, $args)
compareJobsInfo($JobsInfo1, $JobsInfo2)
Sort compare function to order $JobsInfo by job_pk.
getAllUserResults($userId, $status, $request, $response, $sort, $limit, $page, $apiVersion)
addJobQueue(&$job, $request=null)
getUploadEtaInSeconds($jobId, $uploadId)
getAllJobs($request, $response, $args)
static buildDownloadPath($request, $jobId)
Base controller for REST calls.
getParsedBody(ServerRequestInterface $request)
Parse request body as JSON and return associative PHP array.
Override Slim response for withJson function.
Handle new file uploads from Slim framework and move to FOSSology.
static getVersion(ServerRequestInterface $request)
Different type of infos provided by REST.
Info model to contain general error and return values.
Model class to hold JobQueue info.
Model class to hold ShowJob info.
fo_communicate_with_scheduler($input, &$output, &$error_msg)
Communicate with scheduler, send commands to the scheduler, then get the output.