14 namespace Fossology\UI\Api\Controllers;
30 use Psr\Http\Message\ServerRequestInterface;
31 use Slim\Psr7\Request;
76 if ($apiVersion == ApiVersion::V2) {
77 $query = $request->getQueryParams();
78 $limit = $query[
'limit'] ?? 0;
79 $page = $query[
'page'] ?? 1;
81 $limit = $request->hasHeader(
'limit') ? $request->getHeaderLine(
'limit') : 0;
82 $page = $request->hasHeader(
'page') ? $request->getHeaderLine(
'page') : 1;
87 if ((! is_numeric($limit) || $limit < 0) ||
88 (! is_numeric($page) || $page < 1)) {
90 "Limit and page cannot be smaller than 1 and has to be numeric!");
93 return $this->
getAllResults($id, $request, $response, $limit, $page, $apiVersion);
105 public function getJobs($request, $response, $args)
108 $query = $request->getQueryParams();
109 $userId = $this->restHelper->getUserId();
112 if ($apiVersion == ApiVersion::V2) {
113 $limit = $query[
'limit'] ?? 0;
114 $page = $query[
'page'] ?? 1;
116 $limit = $request->hasHeader(
'limit') ? $request->getHeaderLine(
'limit') : 0;
117 $page = $request->hasHeader(
'page') ? $request->getHeaderLine(
'page') : 1;
122 if ((! is_numeric($limit) || $limit < 0) ||
123 (! is_numeric($page) || $page < 1)) {
125 "Limit and page cannot be smaller than 1 and has to be numeric!");
129 if (isset($args[
'id'])) {
130 $id = intval($args[
'id']);
131 if (! $this->dbHelper->doesIdExist(
"job",
"job_pk", $id)) {
138 return $this->
getAllResults($id, $request, $response, $limit, $page, $apiVersion);
141 if (array_key_exists(self::UPLOAD_PARAM, $query)) {
144 $request, $response, $limit, $page, $apiVersion);
147 return $this->
getAllUserResults($id, $userId, $request, $response, $limit, $page, $apiVersion);
165 if ($apiVersion == ApiVersion::V2) {
166 $query = $request->getQueryParams();
167 $folder = $query[
"folderId"] ??
null;
168 $upload = $query[
"uploadId"] ??
null;
170 $folder = $request->hasHeader(
'folderId') ? $request->getHeaderLine(
'folderId') :
null;
171 $upload = $request->hasHeader(
'uploadId') ? $request->getHeaderLine(
'uploadId') :
null;
173 if (is_numeric($folder) && is_numeric($upload) && $folder > 0 && $upload > 0) {
175 if (empty($scanOptionsJSON)) {
179 $info = $uploadHelper->handleScheduleAnalysis($upload, $folder,
180 $scanOptionsJSON,
false, $apiVersion);
181 return $response->withJson($info->getArray(), $info->getCode());
184 "Folder id and upload id should be integers!");
199 $userId = $this->restHelper->getUserId();
200 $userName = $this->restHelper->getUserDao()->getUserName($userId);
203 $jobId = intval($args[
'id']);
204 if (! $this->dbHelper->doesIdExist(
"job",
"job_pk", $jobId)) {
209 $canDeleteJob = $this->restHelper->getJobDao()->hasActionPermissionsOnJob($jobId, $userId, $this->restHelper->getGroupId());
210 if (! $canDeleteJob) {
212 "You don't have permission to delete this job.");
215 $queueId = $args[
'queue'];
218 $JobQueue = $this->restHelper->getShowJobDao()->getJobInfo([$jobId])[$jobId][
"jobqueue"];
220 if (!array_key_exists($queueId, $JobQueue)) {
222 "Job queue " . $queueId .
" doesn't exist in Job " . $jobId);
226 $dependentJobs[] = $queueId;
228 foreach ($JobQueue as $job) {
229 if (in_array($queueId, $job[
"depends"])) {
230 $dependentJobs[] = $job[
"jq_pk"];
235 foreach ($dependentJobs as $job) {
236 $Msg =
"\"" . _(
"Killed by") .
" " . $userName .
"\"";
237 $command =
"kill $job $Msg";
241 "Failed to kill job $jobId");
244 $returnVal =
new Info(200,
"Job deleted successfully", InfoType::INFO);
245 return $response->withJson($returnVal->getArray(), $returnVal->getCode());
262 list($jobs, $count) = $this->dbHelper->getUserJobs($id, $uid, $limit, $page);
264 foreach ($jobs as $job) {
266 if ($apiVersion == ApiVersion::V2) {
269 $finalJobs[] = $job->getArray($apiVersion);
272 $finalJobs = $finalJobs[0];
274 usort($finalJobs, [$this,
"sortJobsByDate"]);
276 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
290 private function getAllResults($id, $request, $response, $limit, $page, $apiVersion)
292 list($jobs, $count) = $this->dbHelper->getJobs($id, $limit, $page);
294 foreach ($jobs as $job) {
296 if ($apiVersion == ApiVersion::V2) {
299 $finalJobs[] = $job->getArray($apiVersion);
302 $finalJobs = $finalJobs[0];
304 usort($finalJobs, [$this,
"sortJobsByDate"]);
306 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
323 if (! $this->dbHelper->doesIdExist(
"upload",
"upload_pk", $uploadId)) {
327 list($jobs, $count) = $this->dbHelper->getJobs(
null, $limit, $page, $uploadId);
329 foreach ($jobs as $job) {
331 if ($apiVersion == ApiVersion::V2) {
334 $finalJobs[] = $job->getArray($apiVersion);
336 usort($finalJobs, [$this,
"sortJobsByDate"]);
337 return $response->withHeader(
"X-Total-Pages", $count)->withJson($finalJobs, 200);
347 $jobDao = $this->restHelper->getJobDao();
350 $jobqueue = $jobDao->getChlidJobStatus($job->getId());
353 $job->getUploadId()));
355 $job->setStatus($this->
getJobStatus(array_keys($jobqueue)));
367 $showJobDao = $this->restHelper->getShowJobDao();
368 $eta = $showJobDao->getEstimatedTime($jobId,
'', 0, $uploadId);
369 $eta = explode(
":", $eta);
370 if (count($eta) > 1) {
371 $eta = (intval($eta[0]) * 3600) + (intval($eta[1]) * 60) + intval($eta[2]);
386 $showJobDao = $this->restHelper->getShowJobDao();
389 foreach ($jobqueue as $jobId) {
390 $jobInfo = $showJobDao->getDataForASingleJob($jobId);
391 $endtext = $jobInfo[
'jq_endtext'];
402 if (empty($jobInfo[
'jq_endtime'])) {
410 $jobStatusString =
"";
411 if ($jobStatus & self::JOB_FAILED) {
413 $jobStatusString =
"Failed";
414 }
else if ($jobStatus & self::JOB_STARTED) {
416 $jobStatusString =
"Processing";
417 }
else if ($jobStatus & self::JOB_QUEUED) {
418 $jobStatusString =
"Queued";
421 $jobStatusString =
"Completed";
423 return $jobStatusString;
435 public function getJobsHistory($request, $response, $args)
437 $query = $request->getQueryParams();
438 if (!array_key_exists(self::UPLOAD_PARAM, $query)) {
441 $upload_fk = intval($query[self::UPLOAD_PARAM]);
449 $dbManager = $this->dbHelper->getDbManager();
452 $query =
"SELECT job_pk FROM job WHERE job_upload_fk=$1;";
453 $statement = __METHOD__.
".getJobs";
454 $result = $dbManager->getRows($query, [$upload_fk], $statement);
457 $allJobPks = array_column($result,
'job_pk');
460 $showJobData = $this->getJobQueue($allJobPks);
463 $allJobsHistory = array();
464 foreach ($showJobData as $jobValObj) {
465 $finalJobqueue = array();
466 foreach ($jobValObj[
'job'][
'jobQueue'] as $jqVal) {
468 if ($jqVal[
'depends'][0] !=
null) {
469 $depends = $jqVal[
'depends'];
472 if (!empty($jqVal[
'download'])) {
474 "text" => $jqVal[
"download"],
479 $jobQueue =
new JobQueue($jqVal[
'jq_pk'], $jqVal[
'jq_type'],
480 $jqVal[
'jq_starttime'], $jqVal[
'jq_endtime'], $jqVal[
'jq_endtext'],
481 $jqVal[
'jq_itemsprocessed'], $jqVal[
'jq_log'], $depends,
482 $jqVal[
'itemsPerSec'], $jqVal[
'canDoActions'], $jqVal[
'isInProgress'],
483 $jqVal[
'isReady'], $download);
484 $finalJobqueue[] = $jobQueue->getArray();
486 $job =
new ShowJob($jobValObj[
'job'][
'jobId'],
487 $jobValObj[
'job'][
'jobName'], $finalJobqueue,
488 $jobValObj[
'upload'][
'uploadId']);
489 $allJobsHistory[] = $job->getArray();
491 return $response->withJson($allJobsHistory, 200);
500 private function getJobQueue($allJobPks)
502 $showJobsDao = $this->restHelper->getShowJobDao();
503 $jobsInfo = $showJobsDao->getJobInfo($allJobPks);
504 usort($jobsInfo, [$this,
"compareJobsInfo"]);
510 $ajaxShowJobs = $this->restHelper->getPlugin(
'ajaxShowJobs');
511 $showJobData = $ajaxShowJobs->getShowJobsForEachJob($jobsInfo,
true);
524 $jobQueue = $this->getJobQueue([$job->getId()]);
525 $finalJobqueue = array();
526 foreach ($jobQueue[0][
'job'][
'jobQueue'] as $jqVal) {
528 if ($jqVal[
'depends'][0] !=
null) {
529 $depends = $jqVal[
'depends'];
532 if (!empty($jqVal[
'download'])) {
534 "text" => $jqVal[
"download"],
539 $singleJobQueue =
new JobQueue($jqVal[
'jq_pk'], $jqVal[
'jq_type'],
540 $jqVal[
'jq_starttime'], $jqVal[
'jq_endtime'], $jqVal[
'jq_endtext'],
541 $jqVal[
'jq_itemsprocessed'], $jqVal[
'jq_log'], $depends,
542 $jqVal[
'itemsPerSec'], $jqVal[
'canDoActions'], $jqVal[
'isInProgress'],
543 $jqVal[
'isReady'], $download);
544 $finalJobqueue[] = $singleJobQueue->getArray();
546 $job->setJobQueue($finalJobqueue);
557 return $JobsInfo2[
"job"][
"job_pk"] - $JobsInfo1[
"job"][
"job_pk"];
568 return strtotime($job2[
'queueDate']) - strtotime($job1[
'queueDate']);
579 public function getJobStatistics($request, $response, $args)
583 $statisticsPlugin = $this->restHelper->getPlugin(
'dashboard-statistics');
584 $res = $statisticsPlugin->CountAllJobs(
true);
585 return $response->withJson($res, 200);
597 public function getAllServerJobsStatus($request, $response, $args)
601 $allJobStatusPlugin = $this->restHelper->getPlugin(
'ajax_all_job_status');
602 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
603 $res = $allJobStatusPlugin->handle($symfonyRequest);
604 return $response->withJson(json_decode($res->getContent(),
true), 200);
615 public function getSchedulerJobOptionsByOperation($request, $response, $args)
618 $operation = $args[
'operationName'];
620 $adminSchedulerPlugin = $this->restHelper->getPlugin(
'admin_scheduler');
622 if (!in_array($operation, array_keys($adminSchedulerPlugin->operation_array))) {
623 $allowedOperations = implode(
', ', array_keys($adminSchedulerPlugin->operation_array));
624 throw new HttpBadRequestException(
"Operation '$operation' not allowed." .
625 " Allowed operations are: $allowedOperations");
629 $schedulerPlugin = $this->restHelper->getPlugin(
'ajax_admin_scheduler');
630 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
631 $symfonyRequest->request->set(
'operation', $operation);
632 $symfonyRequest->request->set(
'fromRest',
true);
633 $res = $schedulerPlugin->handle($symfonyRequest);
634 return $response->withJson($res, 200);
646 public function handleRunSchedulerOption($request, $response, $args)
650 $query = $request->getQueryParams();
652 $operation = $body[
'operation'];
654 $adminSchedulerPlugin = $this->restHelper->getPlugin(
'admin_scheduler');
656 if (!in_array($operation, array_keys($adminSchedulerPlugin->operation_array))) {
657 $allowedOperations = implode(
', ', array_keys($adminSchedulerPlugin->operation_array));
658 throw new HttpBadRequestException(
"Operation '$operation' not allowed." .
659 " Allowed operations are: $allowedOperations");
663 $schedulerPlugin = $this->restHelper->getPlugin(
'ajax_admin_scheduler');
664 $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
665 $symfonyRequest->request->set(
'operation', $operation);
666 $symfonyRequest->request->set(
'fromRest',
true);
667 $data = $schedulerPlugin->handle($symfonyRequest);
669 if ($operation ==
'status' || $operation ==
'verbose') {
670 if (!isset($query[
'job']) || !in_array($query[
'job'], $data[
'jobList'])) {
671 $allowedJobs = implode(
', ', $data[
'jobList']);
672 throw new HttpBadRequestException(
"Job '{$query['job']}' not " .
673 "allowed. Allowed jobs are: $allowedJobs");
675 if (($operation ==
'verbose') && (!isset($query[
'level']) || !in_array($query[
'level'], $data[
'verboseList']))) {
676 $allowedLevels = implode(
', ', $data[
'verboseList']);
677 throw new HttpBadRequestException(
"Level '{$query['level']}' not " .
678 "allowed. Allowed levels are: $allowedLevels");
680 } elseif ($operation ==
'priority' && (!isset($query[
'priority']) || !in_array($query[
'priority'], $data[
'priorityList']))) {
681 $allowedPriorities = implode(
', ', $data[
'priorityList']);
682 throw new HttpBadRequestException(
"Priority '{$query['priority']}' not " .
683 "allowed. Allowed priorities are: $allowedPriorities");
686 if ($operation ==
'status') {
687 $query[
'priority'] =
null;
688 $query[
'level'] =
null;
689 }
else if ($operation ==
'priority') {
690 $query[
'job'] =
null;
691 $query[
'level'] =
null;
692 }
else if ($operation ==
'verbose') {
693 $query[
'priority'] =
null;
695 $query[
'job'] =
null;
696 $query[
'priority'] =
null;
697 $query[
'level'] =
null;
700 $response_from_scheduler = $adminSchedulerPlugin->OperationSubmit(
701 $operation, array_search($query[
'job'], $data[
'jobList']),
702 $query[
'priority'], $query[
'level']);
703 $operation_text = $adminSchedulerPlugin->GetOperationText($operation);
707 if (!empty($adminSchedulerPlugin->error_info)) {
709 $status_msg .=
"$operation_text $text.";
710 throw new HttpInternalServerErrorException($status_msg . $report);
712 $text = _(
"successfully");
713 $status_msg .=
"$operation_text $text.";
714 if (! empty($response_from_scheduler)) {
715 $report .= $response_from_scheduler;
718 $info =
new Info(200, $status_msg. $report, InfoType::INFO);
719 return $response->withJson($info->getArray(), $info->getCode());
Controller for Job model.
getAllUserResults($id, $uid, $request, $response, $limit, $page, $apiVersion)
createJob($request, $response, $args)
getJobs($request, $response, $args)
sortJobsByDate($job1, $job2)
Sort compare function to order $JobsInfo by jobqueue start time.
getAllResults($id, $request, $response, $limit, $page, $apiVersion)
deleteJob($request, $response, $args)
getFilteredResults($uploadId, $request, $response, $limit, $page, $apiVersion)
compareJobsInfo($JobsInfo1, $JobsInfo2)
Sort compare function to order $JobsInfo by job_pk.
updateEtaAndStatus(&$job)
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.