FOSSology  4.4.0
Open Source License Compliance by Open Source Software
common-job.php
Go to the documentation of this file.
1 <?php
2 
7 /*
8  SPDX-FileCopyrightText: © 2008-2015 Hewlett-Packard Development Company, L.P.
9  SPDX-FileCopyrightText: © 2015, 2018 Siemens AG
10 
11  SPDX-License-Identifier: LGPL-2.1-only
12 */
56 function JobAddUpload($userId, $groupId, $job_name, $filename, $desc, $UploadMode, $folder_pk, $public_perm=Auth::PERM_NONE, $setGlobal=0)
57 {
58  global $container;
59 
60  $dbManager = $container->get('db.manager');
61  /* check all required inputs */
62  if (empty($userId) || empty($job_name) || empty($filename) ||
63  empty($UploadMode) || empty($folder_pk)) {
64  return;
65  }
66 
67  $row = $dbManager->getSingleRow("INSERT INTO upload
68  (upload_desc,upload_filename,user_fk,upload_mode,upload_origin,public_perm) VALUES ($1,$2,$3,$4,$5,$6) RETURNING upload_pk",
69  array($desc,$job_name,$userId,$UploadMode,$filename, $public_perm),__METHOD__.'.insert.upload');
70  $uploadId = $row['upload_pk'];
71 
72  $dbManager->getSingleRow("INSERT INTO foldercontents (parent_fk,foldercontents_mode,child_id) VALUES ($1,$2,$3)",
73  array($folder_pk,FolderDao::MODE_UPLOAD,$uploadId),'insert.foldercontents');
74 
75  // Force insertion
76  if ($setGlobal != 1) {
77  $setGlobal = 0;
78  }
79  /* @var UploadDao $uploadDao */
80  $uploadDao = $GLOBALS['container']->get('dao.upload');
81  $uploadDao->getGlobalDecisionSettingsFromInfo($uploadId, $setGlobal);
82 
86  if (empty($groupId)) {
87  $usersRow = $dbManager->getSingleRow('SELECT * FROM users WHERE user_pk=$1',
88  array($userId), __METHOD__.'.select.user');
89  $groupId = $usersRow['group_fk'];
90  }
91  $perm_admin = Auth::PERM_ADMIN;
92 
93  $dbManager->getSingleRow("INSERT INTO perm_upload (perm, upload_fk, group_fk) VALUES ($1,$2,$3)",
94  array($perm_admin, $uploadId, $groupId),'insert.perm_upload');
95 
96  return ($uploadId);
97 }
98 
99 
111 function JobAddJob($userId, $groupId, $job_name, $upload_pk=0, $priority=0)
112 {
113  global $container;
114 
116  $dbManager = $container->get('db.manager');
117 
118  $upload_pk_val = empty($upload_pk) ? null : $upload_pk;
119 
120  $params = array($userId, $priority, $job_name, $upload_pk_val);
121  $stmtName = __METHOD__;
122  if (empty($groupId)) {
123  $stmtName .= "noGrp";
124  $groupPkVal = "(SELECT group_fk FROM users WHERE user_pk = $1)";
125  } else {
126  $params[] = $groupId;
127  $groupPkVal = "$". count($params);
128  }
129 
130  $row = $dbManager->getSingleRow(
131  "INSERT INTO job
132  (job_user_fk,job_group_fk,job_queued,job_priority,job_name,job_upload_fk) VALUES
133  ($1,$groupPkVal,now(),$2,$3,$4) RETURNING job_pk",
134  $params,
135  $stmtName
136  );
137 
138  return intval($row['job_pk']);
139 } // JobAddJob()
140 
141 
157 function JobQueueAdd($job_pk, $jq_type, $jq_args, $jq_runonpfile, $Depends, $host = NULL, $jq_cmd_args=NULL)
158 {
159  global $PG_CONN;
160  $jq_args = pg_escape_string($jq_args);
161  $jq_cmd_args = pg_escape_string($jq_cmd_args);
162 
163  /* Make sure all dependencies exist */
164  if (is_array($Depends)) {
165  foreach ($Depends as $Dependency) {
166  if (empty($Dependency)) {
167  continue;
168  }
169 
170  $sql = "SELECT jq_pk FROM jobqueue WHERE jq_pk = '$Dependency'";
171  $result = pg_query($PG_CONN, $sql);
172  DBCheckResult($result, $sql, __FILE__, __LINE__);
173  $MissingDep = (pg_num_rows($result) == 0);
174  pg_free_result($result);
175 
176  if ($MissingDep) {
177  return;
178  }
179  }
180  }
181 
182  $sqlBegin = "BEGIN";
183  $result = pg_query($PG_CONN, $sqlBegin);
184  DBCheckResult($result, $sqlBegin, __FILE__, __LINE__);
185  pg_free_result($result);
186 
187  /* Add the job */
188  $sql = "INSERT INTO jobqueue ";
189  $sql.= "(jq_job_fk,jq_type,jq_args,jq_runonpfile,jq_starttime,jq_endtime,jq_end_bits,jq_host,jq_cmd_args) VALUES ";
190  $sql.= "('$job_pk','$jq_type','$jq_args',";
191  $sql .= (empty($jq_runonpfile)) ? "NULL" : "'$jq_runonpfile'";
192  $sql.= ",NULL,NULL,0,";
193  $sql .= $host ? "'$host'," : "NULL,";
194  $sql .= $jq_cmd_args ? "'$jq_cmd_args')" : "NULL)";
195 
196  $result = pg_query($PG_CONN, $sql);
197  DBCheckResult($result, $sql, __FILE__, __LINE__);
198  pg_free_result($result);
199 
200  /* Find the jobqueue that was just added */
201  $jq_pk = GetLastSeq("jobqueue_jq_pk_seq", "jobqueue");
202  if (empty($jq_pk)) {
203  $sql = "ROLLBACK";
204  $result = pg_query($PG_CONN, $sql);
205  DBCheckResult($result, $sql, __FILE__, __LINE__);
206  pg_free_result($result);
207  return;
208  }
209 
210  /* Add dependencies */
211  if (is_array($Depends)) {
212  foreach ($Depends as $Dependency) {
213  if (empty($Dependency)) {
214  continue;
215  }
216  $sql = "INSERT INTO jobdepends (jdep_jq_fk,jdep_jq_depends_fk) VALUES ('$jq_pk','$Dependency')";
217  $result = pg_query($PG_CONN, $sql);
218  DBCheckResult($result, $sql, __FILE__, __LINE__);
219  pg_free_result($result);
220  }
221  }
222 
223  /* Commit the jobqueue and jobdepends changes */
224  $sql = "COMMIT";
225  $result = pg_query($PG_CONN, $sql);
226  DBCheckResult($result, $sql, __FILE__, __LINE__);
227  pg_free_result($result);
228 
229  return $jq_pk;
230 } // JobQueueAdd()
231 
232 
244 function GetJobList($status)
245 {
246  /* Gets the list of jobqueue records with the requested $status */
247  global $PG_CONN;
248  if (empty($status)) {
249  return;
250  }
251  $sql = "SELECT jq_pk FROM jobqueue WHERE jq_endtext like '%$status%' order by jq_pk;";
252  $result = pg_query($PG_CONN, $sql);
253  DBCheckResult($result, $sql, __FILE__, __LINE__);
254  $job_array = pg_fetch_all_columns($result, 0);
255  pg_free_result($result);
256  return $job_array;
257 }
258 
268 function QueueUploadsOnAgents($upload_pk_list, $agent_list, $Verbose)
269 {
270  global $Plugins;
271  global $PG_CONN;
272 
273  /* Get the users.default_bucketpool_fk */
274  $user_pk = Auth::getUserId();
275  $group_pk = Auth::getGroupId();
276 
277  if (empty($upload_pk_list)) {
278  return;
279  }
280  // Schedule them
281  $agent_count = count($agent_list);
282  foreach (explode(",", $upload_pk_list) as $upload_pk) {
283  if (empty($upload_pk)) {
284  continue;
285  }
286 
287  // Create a job for the upload
288  $where = "where upload_pk ='$upload_pk'";
289  $UploadRec = GetSingleRec("upload", $where);
290  if (empty($UploadRec)) {
291  echo "ERROR: unknown upload_pk: $upload_pk\n";
292  continue;
293  }
294 
295  $ShortName = $UploadRec['upload_filename'];
296 
297  /* Create Job */
298  $job_pk = JobAddJob($user_pk, $group_pk, $ShortName, $upload_pk);
299 
300  // don't exit on AgentAdd failure, or all the agents requested will
301  // not get scheduled.
302  for ($ac = 0; $ac < $agent_count; $ac ++) {
303  $agentname = $agent_list[$ac]->URI;
304  if (! empty($agentname)) {
305  $Agent = & $Plugins[plugin_find_id($agentname)];
306  $Dependencies = [];
307  $ErrorMsg = "already queued!";
308  $agent_jq_pk = $Agent->AgentAdd($job_pk, $upload_pk, $ErrorMsg,
309  $Dependencies);
310  if ($agent_jq_pk <= 0) {
311  echo "WARNING: Scheduling failed for Agent $agentname, upload_pk is: $upload_pk, job_pk is:$job_pk\n";
312  echo "WARNING message: $ErrorMsg\n";
313  } else if ($Verbose) {
314  $SQL = "SELECT upload_filename FROM upload where upload_pk = $upload_pk";
315  $result = pg_query($PG_CONN, $SQL);
316  DBCheckResult($result, $SQL, __FILE__, __LINE__);
317  $row = pg_fetch_assoc($result);
318  pg_free_result($result);
319  print
320  "$agentname is queued to run on $upload_pk:$row[upload_filename].\n";
321  }
322  }
323  } /* for $ac */
324  } /* for each $upload_pk */
325 } /* QueueUploadsOnAgents() */
326 
333 function QueueUploadsOnDelagents($upload_pk_list)
334 {
335  /* Get the users.default_bucketpool_fk */
336  $user_pk = Auth::getUserId();
337  $group_pk = Auth::getGroupId();
338 
339  if (! empty($upload_pk_list)) {
340  foreach (explode(",", $upload_pk_list) as $upload_pk) {
341  if (empty($upload_pk)) {
342  continue;
343  }
344 
345  // Create a job for the upload
346  $jobpk = JobAddJob($user_pk, $group_pk, "Delete", $upload_pk);
347  if (empty($jobpk) || ($jobpk < 0)) {
348  echo "WARNING: Failed to schedule Delagent for Upload $upload_pk";
349  }
350  $jqargs = "DELETE UPLOAD $upload_pk";
351  $jobqueuepk = JobQueueAdd($jobpk, "delagent", $jqargs, NULL, NULL);
352  if (empty($jobqueuepk)) {
353  echo "WARNING: Failed to schedule Delagent for Upload $upload_pk";
354  }
355  print "Delagent is queued to run on Upload: $upload_pk.\n";
356  } /* for each $upload_pk */
357  } // if $upload_pk is defined
358  /* Tell the scheduler to check the queue. */
359  $success = fo_communicate_with_scheduler("database", $output, $error_msg);
360  if (!$success) {
361  echo $error_msg . "\n" . $output;
362  }
363 }
364 
378 function IsAlreadyScheduled($job_pk, $AgentName, $upload_pk)
379 {
380  global $PG_CONN;
381 
382  $jq_pk = 0;
383 
384  /*
385  * check if the upload_pk is currently in the job queue being processed when
386  * agent name is ununpack or adj2nest
387  */
388  /*
389  * it is unneccessary to reschedule ununpack and adj2nest, one time is enough
390  */
391  if ($AgentName == "ununpack" || $AgentName == "adj2nest") {
392  $sql = "SELECT jq_pk FROM jobqueue, job where job_pk=jq_job_fk " .
393  "AND jq_type='$AgentName' and job_upload_fk = $upload_pk";
394  } else {
395  /* check if the upload_pk is currently in the job queue being processed */
396  $sql = "SELECT jq_pk FROM jobqueue, job where job_pk=jq_job_fk AND jq_type='$AgentName' and job_pk=$job_pk";
397  }
398  $result = pg_query($PG_CONN, $sql);
399  DBCheckResult($result, $sql, __FILE__, __LINE__);
400  if (pg_num_rows($result) > 0) {
401  $row = pg_fetch_assoc($result);
402  $jq_pk = $row["jq_pk"];
403  }
404  pg_free_result($result);
405  return $jq_pk;
406 } // IsAlreadyScheduled()
407 
408 
433 function CommonAgentAdd($plugin, $job_pk, $upload_pk, &$ErrorMsg, $Dependencies, $jqargs = "", $jq_cmd_args = NULL)
434 {
435  global $Plugins;
436  $Deps = array();
437  $DependsEmpty = array();
438 
439  /* check if the latest agent has already been run */
440  if ($plugin->AgentHasResults($upload_pk) == 1) {
441  return 0;
442  }
443 
444  /* if it is already scheduled, then return success */
445  if (($jq_pk = IsAlreadyScheduled($job_pk, $plugin->AgentName, $upload_pk)) != 0) {
446  return $jq_pk;
447  }
448 
449  /* queue up dependencies */
450  foreach ($Dependencies as $Dependency) {
451  if (is_array($Dependency)) {
452  $PluginName = $Dependency['name'];
453  $DepArgs = $Dependency['args'];
454  } else {
455  $PluginName = $Dependency;
456  $DepArgs = null;
457  }
458  $DepPlugin = plugin_find($PluginName);
459  if ($DepPlugin === null) {
460  $ErrorMsg = "Invalid plugin name: $PluginName, (CommonAgentAdd())";
461  return - 1;
462  }
463  if (($Deps[] = $DepPlugin->AgentAdd($job_pk, $upload_pk, $ErrorMsg, $DependsEmpty, $DepArgs)) == - 1) {
464  return - 1;
465  }
466  }
467  /* schedule AgentName */
468  if (empty($jqargs)) {
469  $jqargs = $upload_pk;
470  }
471  $jq_pk = JobQueueAdd($job_pk, $plugin->AgentName, $jqargs, "", $Deps, NULL,
472  $jq_cmd_args);
473  if (empty($jq_pk)) {
474  $ErrorMsg = _(
475  "Failed to insert agent $plugin->AgentName into job queue. jqargs: $jqargs");
476  return (-1);
477  }
478  /* Tell the scheduler to check the queue. */
479  $success = fo_communicate_with_scheduler("database", $output, $error_msg);
480  if (!$success) {
481  $ErrorMsg = $error_msg . "\n" . $output;
482  }
483 
484  return ($jq_pk);
485 }
486 
498 function isAlreadyRunning($agentName, $upload_pk)
499 {
500  global $PG_CONN;
501 
502  $jq_pk = 0;
503 
504  $sql = "SELECT jq_pk FROM jobqueue INNER JOIN job ON job_pk = jq_job_fk "
505  . "WHERE jq_type='$agentName' AND job_upload_fk = $upload_pk "
506  . "AND jq_end_bits = 0";
507  $result = pg_query($PG_CONN, $sql);
508  DBCheckResult($result, $sql, __FILE__, __LINE__);
509  if (pg_num_rows($result) > 0) {
510  $row = pg_fetch_assoc($result);
511  $jq_pk = $row["jq_pk"];
512  }
513  pg_free_result($result);
514  return intval($jq_pk);
515 } // isAlreadyRunning()
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
DBCheckResult($result, $sql, $filenm, $lineno)
Check the postgres result for unexpected errors. If found, treat them as fatal.
Definition: common-db.php:187
GetLastSeq($seqname, $tablename)
Get last sequence number.
Definition: common-db.php:293
GetSingleRec($Table, $Where="")
Retrieve a single database record.
Definition: common-db.php:91
isAlreadyRunning($agentName, $upload_pk)
Check if an agent is already running in a job.
Definition: common-job.php:498
CommonAgentAdd($plugin, $job_pk, $upload_pk, &$ErrorMsg, $Dependencies, $jqargs="", $jq_cmd_args=NULL)
Queue an agent. This is a simple version of AgentAdd() that can be used by multiple plugins that only...
Definition: common-job.php:433
QueueUploadsOnDelagents($upload_pk_list)
Schedule delagent on upload ids.
Definition: common-job.php:333
QueueUploadsOnAgents($upload_pk_list, $agent_list, $Verbose)
Schedule agent tasks on upload ids.
Definition: common-job.php:268
GetJobList($status)
Gets the list of jobqueue records with the requested $status.
Definition: common-job.php:244
JobQueueAdd($job_pk, $jq_type, $jq_args, $jq_runonpfile, $Depends, $host=NULL, $jq_cmd_args=NULL)
Insert a jobqueue + jobdepends records.
Definition: common-job.php:157
JobAddUpload($userId, $groupId, $job_name, $filename, $desc, $UploadMode, $folder_pk, $public_perm=Auth::PERM_NONE, $setGlobal=0)
Insert a new upload record, and update the foldercontents table.
Definition: common-job.php:56
IsAlreadyScheduled($job_pk, $AgentName, $upload_pk)
Check if an agent is already scheduled in a job.
Definition: common-job.php:378
plugin_find($pluginName)
Given the official name of a plugin, return the $Plugins object.
fo_communicate_with_scheduler($input, &$output, &$error_msg)
Communicate with scheduler, send commands to the scheduler, then get the output.
#define PERM_ADMIN
Administrator.
Definition: libfossology.h:34
#define PERM_NONE
User has no permission (not logged in)
Definition: libfossology.h:31
foreach($Options as $Option=> $OptVal) if(0==$reference_flag &&0==$nomos_flag) $PG_CONN