Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix jobs locking #1118

Merged
merged 2 commits into from
Apr 9, 2019
Merged
Changes from 1 commit
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
49 changes: 25 additions & 24 deletions app/code/community/Algolia/Algoliasearch/Model/Queue.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ public function run($maxJobs)
$model->{$method}(new Varien_Object($job['data']));

// Delete one by one
$where = $this->db->quoteInto('job_id IN (?)', $job['merged_ids']);
$this->db->delete($this->table, $where);
$this->db->delete($this->table, array('job_id IN (?)' => $job['merged_ids']));


$this->logRecord['processed_jobs'] += count($job['merged_ids']);
} catch (\Exception $e) {
Expand Down Expand Up @@ -227,11 +227,6 @@ private function getJobs($maxJobs, $pid)
break;
}

// If $jobs is empty, it's the first run
if (empty($jobs)) {
$firstJobId = $rawJobs[0]['job_id'];
}

$rawJobs = $this->prepareJobs($rawJobs);
$rawJobs = array_merge($jobs, $rawJobs);
$rawJobs = $this->mergeJobs($rawJobs);
Expand Down Expand Up @@ -262,14 +257,7 @@ private function getJobs($maxJobs, $pid)
}
}

if (isset($firstJobId)) {
$lastJobId = $this->maxValueInArray($jobs, 'job_id');

// Reserve all new jobs since last run
$this->db->query("UPDATE {$this->db->quoteIdentifier($this->table, true)}
SET pid = " . $pid . '
WHERE job_id >= ' . $firstJobId . " AND job_id <= $lastJobId");
}
$this->lockJobs($jobs);

$this->db->commit();
} catch (\Exception $e) {
Expand Down Expand Up @@ -439,19 +427,32 @@ private function arrayMultisort()
return array_pop($args);
}

private function maxValueInArray($array, $keyToSearch)
/**
* @param array $jobs
*/
private function lockJobs($jobs)
{
$currentMax = null;
$jobsIds = $this->getJobsIdsFromMergedJobs($jobs);

foreach ($array as $arr) {
foreach ($arr as $key => $value) {
if ($key == $keyToSearch && ($value >= $currentMax)) {
$currentMax = $value;
}
}
if ($jobsIds !== array()) {
$pid = getmypid();
$this->db->update($this->table, array('pid' => $pid), array('job_id IN (?)' => $jobsIds));
}
}

/**
* @param array $mergedJobs
*
* @return string[]
*/
private function getJobsIdsFromMergedJobs($mergedJobs)
{
$jobsIds = array();
foreach ($mergedJobs as $job) {
$jobsIds = array_merge($jobsIds, $job['merged_ids']);
}

return $currentMax;
return $jobsIds;
}

private function clearOldLogRecords()
Expand Down