GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 87f38d...2faa62 )
by Daniel
02:12
created

QueuedJobService::queueJob()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 28
nc 7
nop 4
1
<?php
2
3
namespace Symbiote\QueuedJobs\Services;
4
5
use Exception;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Control\Director;
8
use SilverStripe\Control\Email\Email;
9
use SilverStripe\Control\Session;
10
use SilverStripe\Core\Config\Config;
11
use SilverStripe\Core\Config\Configurable;
12
use SilverStripe\Core\Convert;
13
use SilverStripe\Core\Extensible;
14
use SilverStripe\Core\Injector\Injectable;
15
use SilverStripe\Core\Injector\Injector;
16
use SilverStripe\Dev\SapphireTest;
17
use SilverStripe\ORM\DataList;
18
use SilverStripe\ORM\DataObject;
19
use SilverStripe\ORM\DB;
20
use SilverStripe\ORM\FieldType\DBDatetime;
21
use SilverStripe\Security\Member;
22
use SilverStripe\Security\Permission;
23
use SilverStripe\Security\Security;
24
use Psr\Log\LoggerInterface;
25
use SilverStripe\Subsites\Model\Subsite;
26
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
27
use Symbiote\QueuedJobs\QJUtils;
28
29
/**
30
 * A service that can be used for starting, stopping and listing queued jobs.
31
 *
32
 * When a job is first added, it is initialised, its job type determined, then persisted to the database
33
 *
34
 * When the queues are scanned, a job is reloaded and processed. Ignoring the persistence and reloading, it looks
35
 * something like
36
 *
37
 * job->getJobType();
38
 * job->getJobData();
39
 * data->write();
40
 * job->setup();
41
 * while !job->isComplete
42
 *  job->process();
43
 *  job->getJobData();
44
 *  data->write();
45
 *
46
 *
47
 * @author Marcus Nyeholt <[email protected]>
48
 * @license BSD http://silverstripe.org/bsd-license/
49
 */
50
class QueuedJobService
51
{
52
    use Configurable;
53
    use Injectable;
54
    use Extensible;
55
56
    /**
57
     * @config
58
     * @var int
59
     */
60
    private static $stall_threshold = 3;
0 ignored issues
show
Unused Code introduced by
The property $stall_threshold is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
61
62
    /**
63
     * How much ram will we allow before pausing and releasing the memory?
64
     *
65
     * For instance, set to 268435456 (256MB) to pause this process if used memory exceeds
66
     * this value. This needs to be set to a value lower than the php_ini max_memory as
67
     * the system will otherwise crash before shutdown can be handled gracefully.
68
     *
69
     * This was increased to 256MB for SilverStripe 4.x as framework uses more memory than 3.x
70
     *
71
     * @var int
72
     * @config
73
     */
74
    private static $memory_limit = 268435456;
0 ignored issues
show
Unused Code introduced by
The property $memory_limit is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
75
76
    /**
77
     * Optional time limit (in seconds) to run the service before restarting to release resources.
78
     *
79
     * Defaults to no limit.
80
     *
81
     * @var int
82
     * @config
83
     */
84
    private static $time_limit = 0;
0 ignored issues
show
Unused Code introduced by
The property $time_limit is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
85
86
    /**
87
     * Timestamp (in seconds) when the queue was started
88
     *
89
     * @var int
90
     */
91
    protected $startedAt = 0;
92
93
    /**
94
     * Should "immediate" jobs be managed using the shutdown function?
95
     *
96
     * It is recommended you set up an inotify watch and use that for
97
     * triggering immediate jobs. See the wiki for more information
98
     *
99
     * @var boolean
100
     * @config
101
     */
102
    private static $use_shutdown_function = true;
0 ignored issues
show
Unused Code introduced by
The property $use_shutdown_function is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
103
104
    /**
105
     * The location for immediate jobs to be stored in
106
     *
107
     * @var string
108
     * @config
109
     */
110
    private static $cache_dir = 'queuedjobs';
0 ignored issues
show
Unused Code introduced by
The property $cache_dir is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
111
112
    /**
113
     * @var DefaultQueueHandler
114
     */
115
    public $queueHandler;
116
117
    /**
118
     *
119
     * @var TaskRunnerEngine
120
     */
121
    public $queueRunner;
122
123
    /**
124
     * Config controlled list of default/required jobs
125
     * @var array
126
     */
127
    public $defaultJobs = [];
128
129
    /**
130
     * Register our shutdown handler
131
     */
132
    public function __construct()
133
    {
134
        // bind a shutdown function to process all 'immediate' queued jobs if needed, but only in CLI mode
135
        if (static::config()->get('use_shutdown_function') && Director::is_cli()) {
136
            register_shutdown_function(array($this, 'onShutdown'));
137
        }
138
        if (Config::inst()->get(Email::class, 'queued_job_admin_email') == '') {
139
            Config::modify()->set(
140
                Email::class,
141
                'queued_job_admin_email',
142
                Config::inst()->get(Email::class, 'admin_email')
143
            );
144
        }
145
    }
146
147
    /**
148
     * Adds a job to the queue to be started
149
     *
150
     * Relevant data about the job will be persisted using a QueuedJobDescriptor
151
     *
152
     * @param QueuedJob $job
153
     *          The job to start.
154
     * @param $startAfter
155
     *          The date (in Y-m-d H:i:s format) to start execution after
156
     * @param int $userId
157
     *          The ID of a user to execute the job as. Defaults to the current user
158
     * @return int
159
     */
160
    public function queueJob(QueuedJob $job, $startAfter = null, $userId = null, $queueName = null)
161
    {
162
        $signature = $job->getSignature();
163
164
        // see if we already have this job in a queue
165
        $filter = array(
166
            'Signature' => $signature,
167
            'JobStatus' => array(
168
                QueuedJob::STATUS_NEW,
169
                QueuedJob::STATUS_INIT,
170
            )
171
        );
172
173
        $existing = DataList::create(QueuedJobDescriptor::class)
174
            ->filter($filter)
175
            ->first();
176
177
        if ($existing && $existing->ID) {
178
            return $existing->ID;
179
        }
180
181
        $jobDescriptor = new QueuedJobDescriptor();
182
        $jobDescriptor->JobTitle = $job->getTitle();
183
        $jobDescriptor->JobType = $queueName ? $queueName : $job->getJobType();
184
        $jobDescriptor->Signature = $signature;
185
        $jobDescriptor->Implementation = get_class($job);
186
        $jobDescriptor->StartAfter = $startAfter;
187
188
        $runAsID = 0;
189
        if ($userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
190
            $runAsID = $userId;
191
        } elseif (Security::getCurrentUser() && Security::getCurrentUser()->exists()) {
192
            $runAsID = Security::getCurrentUser()->ID;
193
        }
194
        $jobDescriptor->RunAsID = $runAsID;
0 ignored issues
show
Documentation introduced by
The property RunAsID does not exist on object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
195
196
        // copy data
197
        $this->copyJobToDescriptor($job, $jobDescriptor);
0 ignored issues
show
Documentation introduced by
$jobDescriptor is of type object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>, but the function expects a object<Symbiote\QueuedJo...Services\JobDescriptor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
198
199
        $jobDescriptor->write();
200
201
        $this->startJob($jobDescriptor, $startAfter);
0 ignored issues
show
Documentation introduced by
$jobDescriptor is of type object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>, but the function expects a object<Symbiote\QueuedJo...Services\JobDescriptor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
202
203
        return $jobDescriptor->ID;
204
    }
205
206
    /**
207
     * Start a job (or however the queue handler determines it should be started)
208
     *
209
     * @param JobDescriptor $jobDescriptor
210
     * @param date $startAfter
211
     */
212
    public function startJob($jobDescriptor, $startAfter = null)
213
    {
214
        if ($startAfter && strtotime($startAfter) > time()) {
215
            $this->queueHandler->scheduleJob($jobDescriptor, $startAfter);
216
        } else {
217
            // immediately start it on the queue, however that works
218
            $this->queueHandler->startJobOnQueue($jobDescriptor);
219
        }
220
    }
221
222
    /**
223
     * Copies data from a job into a descriptor for persisting
224
     *
225
     * @param QueuedJob $job
226
     * @param JobDescriptor $jobDescriptor
227
     */
228
    protected function copyJobToDescriptor($job, $jobDescriptor)
229
    {
230
        $data = $job->getJobData();
231
232
        $jobDescriptor->TotalSteps = $data->totalSteps;
233
        $jobDescriptor->StepsProcessed = $data->currentStep;
234
        if ($data->isComplete) {
235
            $jobDescriptor->JobStatus = QueuedJob::STATUS_COMPLETE;
236
            $jobDescriptor->JobFinished = date('Y-m-d H:i:s');
237
        }
238
239
        $jobDescriptor->SavedJobData = serialize($data->jobData);
240
        $jobDescriptor->SavedJobMessages = serialize($data->messages);
241
    }
242
243
    /**
244
     * @param QueuedJobDescriptor $jobDescriptor
245
     * @param QueuedJob $job
246
     */
247
    protected function copyDescriptorToJob($jobDescriptor, $job)
248
    {
249
        $jobData = null;
0 ignored issues
show
Unused Code introduced by
$jobData is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
250
        $messages = null;
0 ignored issues
show
Unused Code introduced by
$messages is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
251
252
        // switching to php's serialize methods... not sure why this wasn't done from the start!
253
        $jobData = @unserialize($jobDescriptor->SavedJobData);
254
        $messages = @unserialize($jobDescriptor->SavedJobMessages);
255
256
        if (!$jobData) {
257
            // SS's convert:: function doesn't do this detection for us!!
258
            if (function_exists('json_decode')) {
259
                $jobData = json_decode($jobDescriptor->SavedJobData);
260
                $messages = json_decode($jobDescriptor->SavedJobMessages);
261
            } else {
262
                $jobData = Convert::json2obj($jobDescriptor->SavedJobData);
263
                $messages = Convert::json2obj($jobDescriptor->SavedJobMessages);
264
            }
265
        }
266
267
        $job->setJobData(
268
            $jobDescriptor->TotalSteps,
269
            $jobDescriptor->StepsProcessed,
270
            $jobDescriptor->JobStatus == QueuedJob::STATUS_COMPLETE,
271
            $jobData,
272
            $messages
273
        );
274
    }
275
276
    /**
277
     * Check the current job queues and see if any of the jobs currently in there should be started. If so,
278
     * return the next job that should be executed
279
     *
280
     * @param string $type Job type
281
     * @return QueuedJobDescriptor
282
     */
283
    public function getNextPendingJob($type = null)
284
    {
285
        // Filter jobs by type
286
        $type = $type ?: QueuedJob::QUEUED;
287
        $list = QueuedJobDescriptor::get()
288
            ->filter('JobType', $type)
289
            ->sort('ID', 'ASC');
290
291
        // see if there's any blocked jobs that need to be resumed
292
        $waitingJob = $list
293
            ->filter('JobStatus', QueuedJob::STATUS_WAIT)
294
            ->first();
295
        if ($waitingJob) {
296
            return $waitingJob;
297
        }
298
299
        // If there's an existing job either running or pending, the lets just return false to indicate
300
        // that we're still executing
301
        $runningJob = $list
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $runningJob is correct as $list->filter('JobStatus...::STATUS_RUN))->first() (which targets SilverStripe\ORM\DataList::first()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
302
            ->filter('JobStatus', array(QueuedJob::STATUS_INIT, QueuedJob::STATUS_RUN))
303
            ->first();
304
        if ($runningJob) {
305
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Symbiote\QueuedJobs\Serv...vice::getNextPendingJob of type Symbiote\QueuedJobs\Data...ueuedJobDescriptor|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
306
        }
307
308
        // Otherwise, lets find any 'new' jobs that are waiting to execute
309
        $newJob = $list
310
            ->filter('JobStatus', QueuedJob::STATUS_NEW)
311
            ->where(sprintf(
312
                '"StartAfter" < \'%s\' OR "StartAfter" IS NULL',
313
                DBDatetime::now()->getValue()
314
            ))
315
            ->first();
316
317
        return $newJob;
318
    }
319
320
    /**
321
     * Runs an explicit check on all currently running jobs to make sure their "processed" count is incrementing
322
     * between each run. If it's not, then we need to flag it as paused due to an error.
323
     *
324
     * This typically happens when a PHP fatal error is thrown, which can't be picked up by the error
325
     * handler or exception checker; in this case, we detect these stalled jobs later and fix (try) to
326
     * fix them
327
     *
328
     * @param int $queue The queue to check against
329
     */
330
    public function checkJobHealth($queue = null)
331
    {
332
        $queue = $queue ?: QueuedJob::QUEUED;
333
        // Select all jobs currently marked as running
334
        $runningJobs = QueuedJobDescriptor::get()
335
            ->filter(array(
336
                'JobStatus' => array(
337
                    QueuedJob::STATUS_RUN,
338
                    QueuedJob::STATUS_INIT,
339
                ),
340
                'JobType' => $queue,
341
            ));
342
343
        // If no steps have been processed since the last run, consider it a broken job
344
        // Only check jobs that have been viewed before. LastProcessedCount defaults to -1 on new jobs.
345
        $stalledJobs = $runningJobs
346
            ->filter('LastProcessedCount:GreaterThanOrEqual', 0)
347
            ->where('"StepsProcessed" = "LastProcessedCount"');
348
        foreach ($stalledJobs as $stalledJob) {
349
            $this->restartStalledJob($stalledJob);
350
        }
351
352
        // now, find those that need to be marked before the next check
353
        // foreach job, mark it as having been incremented
354
        foreach ($runningJobs as $job) {
355
            $job->LastProcessedCount = $job->StepsProcessed;
356
            $job->write();
357
        }
358
359
        // finally, find the list of broken jobs and send an email if there's some found
360
        $brokenJobs = QueuedJobDescriptor::get()->filter('JobStatus', QueuedJob::STATUS_BROKEN);
361 View Code Duplication
        if ($brokenJobs && $brokenJobs->count()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
362
            $this->getLogger()->error(
363
                print_r(
364
                    array(
365
                        'errno' => 0,
366
                        'errstr' => 'Broken jobs were found in the job queue',
367
                        'errfile' => __FILE__,
368
                        'errline' => __LINE__,
369
                        'errcontext' => array()
370
                    ),
371
                    true
372
                )
373
            );
374
        }
375
    }
376
377
    /**
378
     * Checks through ll the scheduled jobs that are expected to exist
379
     */
380
    public function checkDefaultJobs($queue = null)
381
    {
382
        $queue = $queue ?: QueuedJob::QUEUED;
0 ignored issues
show
Unused Code introduced by
$queue is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
383
        if (count($this->defaultJobs)) {
384
            $activeJobs = QueuedJobDescriptor::get()->filter(
385
                'JobStatus',
386
                array(
387
                    QueuedJob::STATUS_NEW,
388
                    QueuedJob::STATUS_INIT,
389
                    QueuedJob::STATUS_RUN,
390
                    QueuedJob::STATUS_WAIT,
391
                    QueuedJob::STATUS_PAUSED,
392
                )
393
            );
394
            foreach ($this->defaultJobs as $title => $jobConfig) {
395
                if (!isset($jobConfig['filter']) || !isset($jobConfig['type'])) {
396
                    $this->getLogger()->error("Default Job config: $title incorrectly set up. Please check the readme for examples");
397
                    continue;
398
                }
399
                $job = $activeJobs->filter(array_merge(
400
                    array('Implementation' => $jobConfig['type']),
401
                    $jobConfig['filter']
402
                ));
403
                if (!$job->count()) {
404
                    $this->getLogger()->error("Default Job config: $title was missing from Queue");
405
                    Email::create()
406
                        ->setTo(isset($jobConfig['email']) ? $jobConfig['email'] : Config::inst()->get('Email', 'queued_job_admin_email'))
407
                        ->setFrom(Config::inst()->get('Email', 'queued_job_admin_email'))
408
                        ->setSubject('Default Job "' . $title . '" missing')
409
                        ->setData($jobConfig)
410
                        ->addData('Title', $title)
411
                        ->addData('Site', Director::absoluteBaseURL())
0 ignored issues
show
Security Bug introduced by
It seems like \SilverStripe\Control\Director::absoluteBaseURL() targeting SilverStripe\Control\Director::absoluteBaseURL() can also be of type false; however, SilverStripe\Control\Email\Email::addData() does only seem to accept string|null, did you maybe forget to handle an error condition?
Loading history...
412
                        ->setHTMLTemplate('QueuedJobsDefaultJob')
413
                        ->send();
414
                    if (isset($jobConfig['recreate']) && $jobConfig['recreate']) {
415
                        if (!array_key_exists('construct', $jobConfig) || !isset($jobConfig['startDateFormat']) || !isset($jobConfig['startTimeString'])) {
416
                            $this->getLogger()->error("Default Job config: $title incorrectly set up. Please check the readme for examples");
417
                            continue;
418
                        }
419
                        singleton('Symbiote\\QueuedJobs\\Services\\QueuedJobService')->queueJob(
420
                            Injector::inst()->createWithArgs($jobConfig['type'], $jobConfig['construct']),
421
                            date($jobConfig['startDateFormat'], strtotime($jobConfig['startTimeString']))
422
                        );
423
                        $this->getLogger()->error("Default Job config: $title has been re-added to the Queue");
424
                    }
425
                }
426
            }
427
        }
428
    }
429
430
    /**
431
     * Attempt to restart a stalled job
432
     *
433
     * @param QueuedJobDescriptor $stalledJob
434
     * @return bool True if the job was successfully restarted
435
     */
436
    protected function restartStalledJob($stalledJob)
437
    {
438
        if ($stalledJob->ResumeCounts < static::config()->get('stall_threshold')) {
439
            $stalledJob->restart();
440
            $message = _t(
441
                __CLASS__ . '.STALLED_JOB_RESTART_MSG',
442
                'A job named {name} appears to have stalled. It will be stopped and restarted, please login to make sure it has continued',
443
                ['name' => $stalledJob->JobTitle]
444
            );
445
        } else {
446
            $stalledJob->pause();
447
            $message = _t(
448
                __CLASS__ . '.STALLED_JOB_MSG',
449
                'A job named {name} appears to have stalled. It has been paused, please login to check it',
450
                ['name' => $stalledJob->JobTitle]
451
            );
452
        }
453
454
        $this->getLogger()->error($message);
455
        $from = Config::inst()->get(Email::class, 'admin_email');
456
        $to = Config::inst()->get(Email::class, 'queued_job_admin_email');
457
        $subject = _t(__CLASS__ . '.STALLED_JOB', 'Stalled job');
458
        $mail = new Email($from, $to, $subject, $message);
459
        $mail->send();
460
    }
461
462
    /**
463
     * Prepares the given jobDescriptor for execution. Returns the job that
464
     * will actually be run in a state ready for executing.
465
     *
466
     * Note that this is called each time a job is picked up to be executed from the cron
467
     * job - meaning that jobs that are paused and restarted will have 'setup()' called on them again,
468
     * so your job MUST detect that and act accordingly.
469
     *
470
     * @param QueuedJobDescriptor $jobDescriptor
471
     *          The Job descriptor of a job to prepare for execution
472
     *
473
     * @return QueuedJob|boolean
474
     */
475
    protected function initialiseJob(QueuedJobDescriptor $jobDescriptor)
476
    {
477
        // create the job class
478
        $impl = $jobDescriptor->Implementation;
479
        $job = Injector::inst()->create($impl);
480
        /* @var $job QueuedJob */
481
        if (!$job) {
482
            throw new Exception("Implementation $impl no longer exists");
483
        }
484
485
        $jobDescriptor->JobStatus = QueuedJob::STATUS_INIT;
486
        $jobDescriptor->write();
487
488
        // make sure the data is there
489
        $this->copyDescriptorToJob($jobDescriptor, $job);
490
491
        // see if it needs 'setup' or 'restart' called
492
        if ($jobDescriptor->StepsProcessed <= 0) {
493
            $job->setup();
494
        } else {
495
            $job->prepareForRestart();
496
        }
497
498
        // make sure the descriptor is up to date with anything changed
499
        $this->copyJobToDescriptor($job, $jobDescriptor);
0 ignored issues
show
Documentation introduced by
$jobDescriptor is of type object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>, but the function expects a object<Symbiote\QueuedJo...Services\JobDescriptor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
500
        $jobDescriptor->write();
501
502
        return $job;
503
    }
504
505
    /**
506
     * Given a {@link QueuedJobDescriptor} mark the job as initialised. Works sort of like a mutex.
507
     * Currently a database lock isn't entirely achievable, due to database adapters not supporting locks.
508
     * This may still have a race condition, but this should minimise the possibility.
509
     * Side effect is the job status will be changed to "Initialised".
510
     *
511
     * Assumption is the job has a status of "Queued" or "Wait".
512
     *
513
     * @param QueuedJobDescriptor $jobDescriptor
514
     * @return boolean
515
     */
516
    protected function grabMutex(QueuedJobDescriptor $jobDescriptor)
517
    {
518
        // write the status and determine if any rows were affected, for protection against a
519
        // potential race condition where two or more processes init the same job at once.
520
        // This deliberately does not use write() as that would always update LastEdited
521
        // and thus the row would always be affected.
522
        try {
523
            DB::query(sprintf(
524
                'UPDATE "QueuedJobDescriptor" SET "JobStatus" = \'%s\' WHERE "ID" = %s',
525
                QueuedJob::STATUS_INIT,
526
                $jobDescriptor->ID
527
            ));
528
        } catch (Exception $e) {
529
            return false;
530
        }
531
532
        if (DB::getConn()->affectedRows() === 0 && $jobDescriptor->JobStatus !== QueuedJob::STATUS_INIT) {
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\ORM\DB::getConn() has been deprecated with message: since version 4.0 Use DB::get_conn instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
533
            return false;
534
        }
535
536
        return true;
537
    }
538
539
    /**
540
     * Start the actual execution of a job.
541
     * The assumption is the jobID refers to a {@link QueuedJobDescriptor} that is status set as "Queued".
542
     *
543
     * This method will continue executing until the job says it's completed
544
     *
545
     * @param int $jobId
546
     *          The ID of the job to start executing
547
     * @return boolean
548
     */
549
    public function runJob($jobId)
0 ignored issues
show
Coding Style introduced by
runJob uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
550
    {
551
        // first retrieve the descriptor
552
        $jobDescriptor = DataObject::get_by_id(
553
            QueuedJobDescriptor::class,
554
            (int) $jobId
555
        );
556
        if (!$jobDescriptor) {
557
            throw new Exception("$jobId is invalid");
558
        }
559
560
        // now lets see whether we have a current user to run as. Typically, if the job is executing via the CLI,
561
        // we want it to actually execute as the RunAs user - however, if running via the web (which is rare...), we
562
        // want to ensure that the current user has admin privileges before switching. Otherwise, we just run it
563
        // as the currently logged in user and hope for the best
564
565
        // We need to use $_SESSION directly because SS ties the session to a controller that no longer exists at
566
        // this point of execution in some circumstances
567
        $originalUserID = isset($_SESSION['loggedInAs']) ? $_SESSION['loggedInAs'] : 0;
568
        $originalUser = $originalUserID
569
            ? DataObject::get_by_id(Member::class, $originalUserID)
570
            : null;
571
        $runAsUser = null;
572
573
        // If the Job has requested that we run it as a particular user, then we should try and do that.
574
        if ($jobDescriptor->RunAs() !== null) {
575
            $runAsUser = $this->setRunAsUser($jobDescriptor->RunAs(), $originalUser);
0 ignored issues
show
Bug introduced by
It seems like $originalUser defined by $originalUserID ? \Silve...$originalUserID) : null on line 568 can also be of type object<SilverStripe\ORM\DataObject>; however, Symbiote\QueuedJobs\Serv...Service::setRunAsUser() does only seem to accept null|object<SilverStripe\Security\Member>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
576
        }
577
578
        // set up a custom error handler for this processing
579
        $errorHandler = new JobErrorHandler();
580
581
        $job = null;
582
583
        $broken = false;
584
585
        // Push a config context onto the stack for the duration of this job run.
586
        Config::nest();
587
588
        if ($this->grabMutex($jobDescriptor)) {
0 ignored issues
show
Compatibility introduced by
$jobDescriptor of type object<SilverStripe\ORM\DataObject> is not a sub-type of object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>. It seems like you assume a child class of the class SilverStripe\ORM\DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
589
            try {
590
                $job = $this->initialiseJob($jobDescriptor);
0 ignored issues
show
Compatibility introduced by
$jobDescriptor of type object<SilverStripe\ORM\DataObject> is not a sub-type of object<Symbiote\QueuedJo...ts\QueuedJobDescriptor>. It seems like you assume a child class of the class SilverStripe\ORM\DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
591
592
                // get the job ready to begin.
593
                if (!$jobDescriptor->JobStarted) {
594
                    $jobDescriptor->JobStarted = date('Y-m-d H:i:s');
595
                } else {
596
                    $jobDescriptor->JobRestarted = date('Y-m-d H:i:s');
597
                }
598
599
                // Only write to job as "Running" if 'isComplete' was NOT set to true
600
                // during setup() or prepareForRestart()
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
601
                if (!$job->jobFinished()) {
602
                    $jobDescriptor->JobStatus = QueuedJob::STATUS_RUN;
603
                    $jobDescriptor->write();
604
                }
605
606
                $lastStepProcessed = 0;
607
                // have we stalled at all?
608
                $stallCount = 0;
609
610
                if ($job->SubsiteID && class_exists(Subsite::class)) {
611
                    Subsite::changeSubsite($job->SubsiteID);
612
613
                    // lets set the base URL as far as Director is concerned so that our URLs are correct
614
                    $subsite = DataObject::get_by_id(Subsite::class, $job->SubsiteID);
615
                    if ($subsite && $subsite->exists()) {
616
                        $domain = $subsite->domain();
617
                        $base = rtrim(Director::protocol() . $domain, '/') . '/';
618
619
                        Config::modify()->set(Director::class, 'alternate_base_url', $base);
620
                    }
621
                }
622
623
                // while not finished
624
                while (!$job->jobFinished() && !$broken) {
625
                    // see that we haven't been set to 'paused' or otherwise by another process
626
                    $jobDescriptor = DataObject::get_by_id(
627
                        QueuedJobDescriptor::class,
628
                        (int) $jobId
629
                    );
630
                    if (!$jobDescriptor || !$jobDescriptor->exists()) {
631
                        $broken = true;
632
                        $this->getLogger()->error(
633
                            print_r(
634
                                array(
635
                                    'errno' => 0,
636
                                    'errstr' => 'Job descriptor ' . $jobId . ' could not be found',
637
                                    'errfile' => __FILE__,
638
                                    'errline' => __LINE__,
639
                                    'errcontext' => array()
640
                                ),
641
                                true
642
                            )
643
                        );
644
                        break;
645
                    }
646
                    if ($jobDescriptor->JobStatus != QueuedJob::STATUS_RUN) {
647
                        // we've been paused by something, so we'll just exit
648
                        $job->addMessage(
649
                            _t(__CLASS__ . '.JOB_PAUSED', 'Job paused at {time}', ['time' => date('Y-m-d H:i:s')])
650
                        );
651
                        $broken = true;
652
                    }
653
654
                    if (!$broken) {
655
                        // Collect output as job messages as well as sending it to the screen
656
                        $obLogger = function ($buffer, $phase) use ($job, $jobDescriptor) {
0 ignored issues
show
Unused Code introduced by
The parameter $phase is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
657
                            $job->addMessage($buffer);
658
                            if ($jobDescriptor) {
659
                                $this->copyJobToDescriptor($job, $jobDescriptor);
0 ignored issues
show
Documentation introduced by
$jobDescriptor is of type object<SilverStripe\ORM\DataObject>, but the function expects a object<Symbiote\QueuedJo...Services\JobDescriptor>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
660
                                $jobDescriptor->write();
661
                            }
662
                            return $buffer;
663
                        };
664
                        ob_start($obLogger, 256);
665
666
                        try {
667
                            $job->process();
668
                        } catch (Exception $e) {
669
                            // okay, we'll just catch this exception for now
670
                            $job->addMessage(
671
                                _t(
672
                                    __CLASS__ . '.JOB_EXCEPT',
673
                                    'Job caused exception {message} in {file} at line {line}',
674
                                    [
675
                                        'message' => $e->getMessage(),
676
                                        'file' => $e->getFile(),
677
                                        'line' => $e->getLine(),
678
                                    ]
679
                                ),
680
                                'ERROR'
681
                            );
682
                            $this->getLogger()->error($e->getMessage());
683
                            $jobDescriptor->JobStatus =  QueuedJob::STATUS_BROKEN;
684
                            $this->extend('updateJobDescriptorAndJobOnException', $jobDescriptor, $job, $e);
685
                        }
686
687
                        ob_end_flush();
688
689
                        // now check the job state
690
                        $data = $job->getJobData();
691
                        if ($data->currentStep == $lastStepProcessed) {
692
                            $stallCount++;
693
                        }
694
695
                        if ($stallCount > static::config()->get('stall_threshold')) {
696
                            $broken = true;
697
                            $job->addMessage(
698
                                _t(
699
                                    __CLASS__ . '.JOB_STALLED',
700
                                    'Job stalled after {attempts} attempts - please check',
701
                                    ['attempts' => $stallCount]
702
                                ),
703
                                'ERROR'
704
                            );
705
                            $jobDescriptor->JobStatus =  QueuedJob::STATUS_BROKEN;
706
                        }
707
708
                        // now we'll be good and check our memory usage. If it is too high, we'll set the job to
709
                        // a 'Waiting' state, and let the next processing run pick up the job.
710
                        if ($this->isMemoryTooHigh()) {
711
                            $job->addMessage(
712
                                _t(
713
                                    __CLASS__ . '.MEMORY_RELEASE',
714
                                    'Job releasing memory and waiting ({used} used)',
715
                                    ['used' => $this->humanReadable($this->getMemoryUsage())]
716
                                )
717
                            );
718
                            if ($jobDescriptor->JobStatus != QueuedJob::STATUS_BROKEN) {
719
                                $jobDescriptor->JobStatus = QueuedJob::STATUS_WAIT;
720
                            }
721
                            $broken = true;
722
                        }
723
724
                        // Also check if we are running too long
725
                        if ($this->hasPassedTimeLimit()) {
726
                            $job->addMessage(_t(
727
                                __CLASS__ . '.TIME_LIMIT',
728
                                'Queue has passed time limit and will restart before continuing'
729
                            ));
730
                            if ($jobDescriptor->JobStatus != QueuedJob::STATUS_BROKEN) {
731
                                $jobDescriptor->JobStatus = QueuedJob::STATUS_WAIT;
732
                            }
733
                            $broken = true;
734
                        }
735
                    }
736
737
                    if ($jobDescriptor) {
738
                        $this->copyJobToDescriptor($job, $jobDescriptor);
739
                        $jobDescriptor->write();
740 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
741
                        $this->getLogger()->error(
742
                            print_r(
743
                                array(
744
                                    'errno' => 0,
745
                                    'errstr' => 'Job descriptor has been set to null',
746
                                    'errfile' => __FILE__,
747
                                    'errline' => __LINE__,
748
                                    'errcontext' => array()
749
                                ),
750
                                true
751
                            )
752
                        );
753
                        $broken = true;
754
                    }
755
                }
756
757
                // a last final save. The job is complete by now
758
                if ($jobDescriptor) {
759
                    $jobDescriptor->write();
760
                }
761
762
                if ($job->jobFinished()) {
763
                    $job->afterComplete();
764
                    $jobDescriptor->cleanupJob();
765
                }
766
            } catch (Exception $e) {
767
                // okay, we'll just catch this exception for now
768
                $this->getLogger()->error($e->getMessage());
769
                $jobDescriptor->JobStatus =  QueuedJob::STATUS_BROKEN;
770
                $this->extend('updateJobDescriptorAndJobOnException', $jobDescriptor, $job, $e);
771
                $jobDescriptor->write();
772
                $broken = true;
773
            }
774
        }
775
776
        $errorHandler->clear();
777
778
        Config::unnest();
779
780
        $this->unsetRunAsUser($runAsUser, $originalUser);
0 ignored issues
show
Bug introduced by
It seems like $originalUser defined by $originalUserID ? \Silve...$originalUserID) : null on line 568 can also be of type object<SilverStripe\ORM\DataObject>; however, Symbiote\QueuedJobs\Serv...rvice::unsetRunAsUser() does only seem to accept null|object<SilverStripe\Security\Member>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
781
782
        return !$broken;
783
    }
784
785
    /**
786
     * @param Member $runAsUser
787
     * @param Member|null $originalUser
788
     * @return null|Member
789
     */
790
    protected function setRunAsUser(Member $runAsUser, Member $originalUser = null)
0 ignored issues
show
Coding Style introduced by
setRunAsUser uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
791
    {
792
        // Sanity check. Can't set the user if they don't exist.
793
        if ($runAsUser === null || !$runAsUser->exists()) {
794
            return null;
795
        }
796
797
        // Don't need to set Security user if we're already logged in as that same user.
798
        if ($originalUser && $originalUser->ID === $runAsUser->ID) {
799
            return null;
800
        }
801
802
        // We are currently either not logged in at all, or we're logged in as a different user. We should switch users
803
        // so that the context within the Job is correct.
804
        if (Controller::has_curr()) {
805
            Security::setCurrentUser($runAsUser);
806
        } else {
807
            $_SESSION['loggedInAs'] = $runAsUser->ID;
808
        }
809
810
        // This is an explicit coupling brought about by SS not having a nice way of mocking a user, as it requires
811
        // session nastiness
812
        if (class_exists('SecurityContext')) {
813
            singleton('SecurityContext')->setMember($runAsUser);
814
        }
815
816
        return $runAsUser;
817
    }
818
819
    /**
820
     * @param Member|null $runAsUser
821
     * @param Member|null $originalUser
822
     */
823
    protected function unsetRunAsUser(Member $runAsUser = null, Member $originalUser = null)
0 ignored issues
show
Coding Style introduced by
unsetRunAsUser uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
824
    {
825
        // No runAsUser was set, so we don't need to do anything.
826
        if ($runAsUser === null) {
827
            return;
828
        }
829
830
        // There was no originalUser, so we should make sure that we set the user back to null.
831
        if (!$originalUser) {
832
            if (Controller::has_curr()) {
833
                Security::setCurrentUser(null);
834
            } else {
835
                $_SESSION['loggedInAs'] = null;
836
            }
837
        }
838
839
        // Okay let's reset our user.
840
        if (Controller::has_curr()) {
841
            Security::setCurrentUser($originalUser);
842
        } else {
843
            $_SESSION['loggedInAs'] = $originalUser->ID;
844
        }
845
    }
846
847
    /**
848
     * Start timer
849
     */
850
    protected function markStarted()
851
    {
852
        if ($this->startedAt) {
853
            $this->startedAt = DBDatetime::now()->Format('U');
0 ignored issues
show
Documentation Bug introduced by
It seems like \SilverStripe\ORM\FieldT...ime::now()->Format('U') can also be of type string. However, the property $startedAt is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
854
        }
855
    }
856
857
    /**
858
     * Is execution time too long?
859
     *
860
     * @return bool True if the script has passed the configured time_limit
861
     */
862
    protected function hasPassedTimeLimit()
863
    {
864
        // Ensure a limit exists
865
        $limit = static::config()->get('time_limit');
866
        if (!$limit) {
867
            return false;
868
        }
869
870
        // Ensure started date is set
871
        $this->markStarted();
872
873
        // Check duration
874
        $now = DBDatetime::now()->Format('U');
875
        return $now > $this->startedAt + $limit;
876
    }
877
878
    /**
879
     * Is memory usage too high?
880
     *
881
     * @return bool
882
     */
883
    protected function isMemoryTooHigh()
884
    {
885
        $used = $this->getMemoryUsage();
886
        $limit = $this->getMemoryLimit();
887
        return $limit && ($used > $limit);
888
    }
889
890
    /**
891
     * Get peak memory usage of this application
892
     *
893
     * @return float
894
     */
895
    protected function getMemoryUsage()
896
    {
897
        // Note we use real_usage = false
898
        // http://stackoverflow.com/questions/15745385/memory-get-peak-usage-with-real-usage
899
        // Also we use the safer peak memory usage
900
        return (float)memory_get_peak_usage(false);
901
    }
902
903
    /**
904
     * Determines the memory limit (in bytes) for this application
905
     * Limits to the smaller of memory_limit configured via php.ini or silverstripe config
906
     *
907
     * @return float Memory limit in bytes
908
     */
909
    protected function getMemoryLimit()
910
    {
911
        // Limit to smaller of explicit limit or php memory limit
912
        $limit = $this->parseMemory(static::config()->get('memory_limit'));
913
        if ($limit) {
914
            return $limit;
915
        }
916
917
        // Fallback to php memory limit
918
        $phpLimit = $this->getPHPMemoryLimit();
919
        if ($phpLimit) {
920
            return $phpLimit;
921
        }
922
    }
923
924
    /**
925
     * Calculate the current memory limit of the server
926
     *
927
     * @return float
928
     */
929
    protected function getPHPMemoryLimit()
930
    {
931
        return $this->parseMemory(trim(ini_get("memory_limit")));
932
    }
933
934
    /**
935
     * Convert memory limit string to bytes.
936
     * Based on implementation in install.php5
937
     *
938
     * @param string $memString
939
     * @return float
940
     */
941
    protected function parseMemory($memString)
942
    {
943
        switch (strtolower(substr($memString, -1))) {
944
            case "b":
945
                return round(substr($memString, 0, -1));
946
            case "k":
947
                return round(substr($memString, 0, -1) * 1024);
948
            case "m":
949
                return round(substr($memString, 0, -1) * 1024 * 1024);
950
            case "g":
951
                return round(substr($memString, 0, -1) * 1024 * 1024 * 1024);
952
            default:
953
                return round($memString);
954
        }
955
    }
956
957
    protected function humanReadable($size)
958
    {
959
        $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
960
        return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
961
    }
962
963
964
    /**
965
     * Gets a list of all the current jobs (or jobs that have recently finished)
966
     *
967
     * @param string $type
968
     *          if we're after a particular job list
969
     * @param int $includeUpUntil
970
     *          The number of seconds to include jobs that have just finished, allowing a job list to be built that
971
     *          includes recently finished jobs
972
     * @return QueuedJobDescriptor
973
     */
974
    public function getJobList($type = null, $includeUpUntil = 0)
975
    {
976
        return DataObject::get(
977
            QueuedJobDescriptor::class,
978
            $this->getJobListFilter($type, $includeUpUntil)
979
        );
980
    }
981
982
    /**
983
     * Return the SQL filter used to get the job list - this is used by the UI for displaying the job list...
984
     *
985
     * @param string $type
986
     *          if we're after a particular job list
987
     * @param int $includeUpUntil
988
     *          The number of seconds to include jobs that have just finished, allowing a job list to be built that
989
     *          includes recently finished jobs
990
     * @return string
991
     */
992
    public function getJobListFilter($type = null, $includeUpUntil = 0)
993
    {
994
        $util = singleton(QJUtils::class);
995
996
        $filter = array('JobStatus <>' => QueuedJob::STATUS_COMPLETE);
997
        if ($includeUpUntil) {
998
            $filter['JobFinished > '] = date('Y-m-d H:i:s', time() - $includeUpUntil);
999
        }
1000
1001
        $filter = $util->dbQuote($filter, ' OR ');
1002
1003
        if ($type) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1004
            $filter = $util->dbQuote(array('JobType =' => (string) $type)). ' AND ('.$filter.')';
1005
        }
1006
1007
        return $filter;
1008
    }
1009
1010
    /**
1011
     * Process the job queue with the current queue runner
1012
     *
1013
     * @param string $queue
1014
     */
1015
    public function runQueue($queue)
1016
    {
1017
        $this->checkJobHealth($queue);
1018
        $this->checkdefaultJobs($queue);
1019
        $this->queueRunner->runQueue($queue);
1020
    }
1021
1022
    /**
1023
     * Process all jobs from a given queue
1024
     *
1025
     * @param string $name The job queue to completely process
1026
     */
1027
    public function processJobQueue($name)
1028
    {
1029
        // Start timer to measure lifetime
1030
        $this->markStarted();
1031
1032
        // Begin main loop
1033
        do {
1034
            if (class_exists('Subsite')) {
1035
                // clear subsite back to default to prevent any subsite changes from leaking to
1036
                // subsequent actions
1037
                /**
1038
                 * @todo Check for 4.x compatibility with Subsites once namespacing is implemented
1039
                 */
1040
                \Subsite::changeSubsite(0);
1041
            }
1042
1043
            $job = $this->getNextPendingJob($name);
1044
            if ($job) {
1045
                $success = $this->runJob($job->ID);
1046
                if (!$success) {
1047
                    // make sure job is null so it doesn't continue the current
1048
                    // processing loop. Next queue executor can pick up where
1049
                    // things left off
1050
                    $job = null;
1051
                }
1052
            }
1053
        } while ($job);
1054
    }
1055
1056
    /**
1057
     * When PHP shuts down, we want to process all of the immediate queue items
1058
     *
1059
     * We use the 'getNextPendingJob' method, instead of just iterating the queue, to ensure
1060
     * we ignore paused or stalled jobs.
1061
     */
1062
    public function onShutdown()
1063
    {
1064
        $this->processJobQueue(QueuedJob::IMMEDIATE);
1065
    }
1066
1067
    /**
1068
     * Get a logger
1069
     * @return LoggerInterface
1070
     */
1071
    public function getLogger()
1072
    {
1073
        return Injector::inst()->get(LoggerInterface::class);
1074
    }
1075
}
1076