Passed
Push — hans/bugfix ( 237ebf...bcf2d7 )
by Simon
11:21 queued 09:02
created

SolrIndexTask::indexStateClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 2
rs 10
1
<?php
2
/**
3
 * Class SolrIndexTask|Firesphere\SolrSearch\Tasks\SolrIndexTask Index Solr cores
4
 *
5
 * @package Firesphere\SolrSearch\Tasks
6
 * @author Simon `Firesphere` Erkelens; Marco `Sheepy` Hermo
7
 * @copyright Copyright (c) 2018 - now() Firesphere & Sheepy
8
 */
9
10
namespace Firesphere\SolrSearch\Tasks;
11
12
use Exception;
13
use Firesphere\SolrSearch\Factories\DocumentFactory;
14
use Firesphere\SolrSearch\Helpers\SolrLogger;
15
use Firesphere\SolrSearch\Indexes\BaseIndex;
16
use Firesphere\SolrSearch\Services\SolrCoreService;
17
use Firesphere\SolrSearch\States\SiteState;
18
use Firesphere\SolrSearch\Traits\LoggerTrait;
19
use Firesphere\SolrSearch\Traits\SolrIndexTrait;
20
use GuzzleHttp\Exception\GuzzleException;
21
use Psr\Log\LoggerInterface;
22
use ReflectionException;
23
use SilverStripe\Control\Controller;
24
use SilverStripe\Control\Director;
25
use SilverStripe\Control\HTTPRequest;
26
use SilverStripe\Core\Injector\Injector;
27
use SilverStripe\Dev\BuildTask;
28
use SilverStripe\ORM\ArrayList;
29
use SilverStripe\ORM\DataList;
30
use SilverStripe\ORM\DataObject;
31
use SilverStripe\ORM\DB;
32
use SilverStripe\ORM\SS_List;
33
use SilverStripe\ORM\ValidationException;
34
use SilverStripe\Versioned\Versioned;
35
36
/**
37
 * Class SolrIndexTask
38
 *
39
 * @description Index items to Solr through a tasks
40
 * @package Firesphere\SolrSearch\Tasks
41
 */
42
class SolrIndexTask extends BuildTask
43
{
44
    use LoggerTrait;
45
    use SolrIndexTrait;
46
    /**
47
     * URLSegment of this task
48
     *
49
     * @var string
50
     */
51
    private static $segment = 'SolrIndexTask';
52
    /**
53
     * Store the current states for all instances of SiteState
54
     *
55
     * @var array
56
     */
57
    public $currentStates;
58
    /**
59
     * My name
60
     *
61
     * @var string
62
     */
63
    protected $title = 'Solr Index update';
64
    /**
65
     * What do I do?
66
     *
67
     * @var string
68
     */
69
    protected $description = 'Add or update documents to an existing Solr core.';
70
71
    /**
72
     * SolrIndexTask constructor. Sets up the document factory
73
     *
74
     * @throws ReflectionException
75
     */
76 16
    public function __construct()
77
    {
78 16
        parent::__construct();
79
        // Only index live items.
80
        // The old FTS module also indexed Draft items. This is unnecessary
81
        // If versioned is needed, a separate Versioned Search module is required
82 16
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
83 16
        $this->setService(Injector::inst()->get(SolrCoreService::class));
84 16
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
85 16
        $this->setDebug(Director::isDev() || Director::is_cli());
86 16
        $this->setBatchLength(DocumentFactory::config()->get('batchLength'));
87 16
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
88 16
        $this->setCores($cores);
89 16
        $currentStates = SiteState::currentStates();
90 16
        SiteState::setDefaultStates($currentStates);
91 16
    }
92
93
    /**
94
     * Implement this method in the task subclass to
95
     * execute via the TaskRunner
96
     *
97
     * @param HTTPRequest $request Current request
98
     * @return int|bool
99
     * @throws Exception
100
     * @throws GuzzleException
101
     */
102 13
    public function run($request)
103
    {
104 13
        $start = time();
105 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
106 13
        list($vars, $group, $isGroup) = $this->taskSetup($request);
107 13
        $groups = 0;
108 13
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
109
110 13
        foreach ($indexes as $indexName) {
111
            /** @var BaseIndex $index */
112 13
            $index = Injector::inst()->get($indexName, false);
113 13
            $this->setIndex($index);
114
115 13
            $indexClasses = $this->index->getClasses();
116 13
            $classes = $this->getClasses($vars, $indexClasses);
117 13
            if (!count($classes)) {
118 10
                continue;
119
            }
120
121 13
            $this->clearIndex($vars);
122
123 13
            $groups = $this->indexClassForIndex($classes, $isGroup, $group);
124
        }
125
126 13
        $this->getLogger()->info(gmdate('Y-m-d H:i:s'));
127 13
        $time = gmdate('H:i:s', (time() - $start));
128 13
        $this->getLogger()->info(sprintf('Time taken: %s', $time));
129
130 13
        return $groups;
131
    }
132
133
    /**
134
     * Set up the requirements for this task
135
     *
136
     * @param HTTPRequest $request Current request
137
     * @return array
138
     */
139 13
    protected function taskSetup($request): array
140
    {
141 13
        $vars = $request->getVars();
142 13
        $debug = $this->isDebug() || isset($vars['debug']);
143
        // Forcefully set the debugging to whatever the outcome of the above is
144 13
        $this->setDebug($debug, true);
145 13
        $group = $vars['group'] ?? 0;
146 13
        $start = $vars['start'] ?? 0;
147 13
        $group = ($start > $group) ? $start : $group;
148 13
        $isGroup = isset($vars['group']);
149
150 13
        return [$vars, $group, $isGroup];
151
    }
152
153
    /**
154
     * get the classes to run for this task execution
155
     *
156
     * @param array $vars URL GET Parameters
157
     * @param array $classes Classes to index
158
     * @return bool|array
159
     */
160 13
    protected function getClasses($vars, array $classes): array
161
    {
162 13
        if (isset($vars['class'])) {
163 1
            return array_intersect($classes, [$vars['class']]);
164
        }
165
166 12
        return $classes;
167
    }
168
169
    /**
170
     * Clear the given index if a full re-index is needed
171
     *
172
     * @param array $vars URL GET Parameters
173
     * @throws Exception
174
     */
175 13
    public function clearIndex($vars)
176
    {
177 13
        if (!empty($vars['clear'])) {
178 1
            $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName()));
179 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);
180
        }
181 13
    }
182
183
    /**
184
     * Index the classes for a specific index
185
     *
186
     * @param array $classes Classes that need indexing
187
     * @param bool $isGroup Indexing a specific group?
188
     * @param int $group Group to index
189
     * @return int
190
     * @throws Exception
191
     * @throws GuzzleException
192
     */
193 13
    protected function indexClassForIndex($classes, $isGroup, $group): int
194
    {
195 13
        $groups = 0;
196 13
        foreach ($classes as $class) {
197 13
            $groups = $this->indexClass($isGroup, $class, $group);
198
        }
199
200 13
        return $groups;
201
    }
202
203
    /**
204
     * Index a single class for a given index. {@link static::indexClassForIndex()}
205
     *
206
     * @param bool $isGroup Is a specific group indexed
207
     * @param string $class Class to index
208
     * @param int $group Group to index
209
     * @return int
210
     * @throws GuzzleException
211
     * @throws ValidationException
212
     */
213 13
    private function indexClass($isGroup, $class, int $group): int
214
    {
215 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $this->getIndex()->getIndexName()));
216 13
        list($totalGroups, $groups) = $this->getGroupSettings($isGroup, $class, $group);
217 13
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
218
        do { // Run from oldest to newest
219
            try {
220 13
                if ($this->hasPCNTL()) {
221
                    // @codeCoverageIgnoreStart
222
                    $group = $this->spawnChildren($class, $group, $groups);
223
                // @codeCoverageIgnoreEnd
224
                } else {
225 13
                    $this->doReindex($group, $class);
226
                }
227 13
                $group++;
228
            } catch (Exception $error) {
229
                // @codeCoverageIgnoreStart
230
                $this->logException($this->index->getIndexName(), $group, $error);
231
                $group++;
232
                continue;
233
                // @codeCoverageIgnoreEnd
234
            }
235 13
        } while ($group <= $groups);
236
237 13
        return $totalGroups;
238
    }
239
240
    /**
241
     * Check the amount of groups and the total against the isGroup check.
242
     *
243
     * @param bool $isGroup Is it a specific group
244
     * @param string $class Class to check
245
     * @param int $group Current group to index
246
     * @return array
247
     */
248 13
    private function getGroupSettings($isGroup, $class, int $group): array
249
    {
250 13
        $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());
251 13
        $groups = $isGroup ? ($group + $this->getCores() - 1) : $totalGroups;
252
253 13
        return [$totalGroups, $groups];
254
    }
255
256
    /**
257
     * Check if PCNTL is available and/or useable.
258
     * The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
259
     * The pcntl parameter check is for unit tests, but PHPUnit does not support PCNTL (yet)
260
     *
261
     * @return bool
262
     */
263 13
    private function hasPCNTL()
264
    {
265 13
        return Director::is_cli() &&
266 13
            function_exists('pcntl_fork') &&
267
            (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl' ||
268 13
                !Controller::curr()->getRequest()->getVar('unittest'));
269
    }
270
271
    /**
272
     * For each core, spawn a child process that will handle a separate group.
273
     * This speeds up indexing through CLI massively.
274
     *
275
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
276
     * @param string $class Class to index
277
     * @param int $group Group to index
278
     * @param int $groups Total amount of groups
279
     * @return int Last group indexed
280
     * @throws Exception
281
     * @throws GuzzleException
282
     */
283
    private function spawnChildren($class, int $group, int $groups): int
284
    {
285
        $start = $group;
286
        $pids = [];
287
        $cores = $this->getCores();
288
        // for each core, start a grouped indexing
289
        for ($i = 0; $i < $cores; $i++) {
290
            $start = $group + $i;
291
            if ($start < $groups) {
292
                $this->runForkedChild($class, $pids, $start);
293
            }
294
        }
295
        // Wait for each child to finish
296
        // It needs to wait for them independently,
297
        // or it runs out of memory for some reason
298
        foreach ($pids as $pid) {
299
            pcntl_waitpid($pid, $status);
300
        }
301
        $commit = $this->index->getClient()->createUpdate();
302
        $commit->addCommit();
303
304
        $this->index->getClient()->update($commit);
305
306
        return $start;
307
    }
308
309
    /**
310
     * Create a fork and run the child
311
     *
312
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
313
     * @param string $class Class to index
314
     * @param array $pids Array of all the child Process IDs
315
     * @param int $start Start point for the objects
316
     * @return void
317
     * @throws GuzzleException
318
     * @throws ValidationException
319
     */
320
    private function runForkedChild($class, array &$pids, int $start): void
321
    {
322
        $pid = pcntl_fork();
323
        // PID needs to be pushed before anything else, for some reason
324
        $pids[] = $pid;
325
        $config = DB::getConfig();
326
        DB::connect($config);
327
        $this->runChild($class, $pid, $start);
328
    }
329
330
    /**
331
     * Ren a single child index operation
332
     *
333
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
334
     * @param string $class Class to index
335
     * @param int $pid PID of the child
336
     * @param int $start Position to start
337
     * @throws GuzzleException
338
     * @throws ValidationException
339
     * @throws Exception
340
     */
341
    private function runChild($class, int $pid, int $start): void
342
    {
343
        if ($pid === 0) {
344
            try {
345
                $this->doReindex($start, $class, $pid);
346
            } catch (Exception $error) {
347
                SolrLogger::logMessage('ERROR', $error, $this->index->getIndexName());
348
                $msg = sprintf(
349
                    'Something went wrong while indexing %s on %s, see the logs for details',
350
                    $start,
351
                    $this->index->getIndexName()
352
                );
353
                if ($pid !== false) {
354
                    exit(0);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
355
                }
356
                 throw new Exception($msg);
357
            }
358
        }
359
    }
360
361
    /**
362
     * Reindex the given group, for each state
363
     *
364
     * @param int $group Group to index
365
     * @param string $class Class to index
366
     * @param bool|int $pid Are we a child process or not
367
     * @throws Exception
368
     */
369 13
    private function doReindex($group, $class, $pid = false)
370
    {
371 13
        $start = time();
372 13
        foreach (SiteState::getStates() as $state) {
373 13
            if ($state !== 'default' && !empty($state)) {
374
                SiteState::withState($state);
375
            }
376 13
            $this->indexStateClass($group, $class);
377
        }
378
379 13
        SiteState::withState(SiteState::DEFAULT_STATE);
380 13
        $end = gmdate('i:s', time() - $start);
381 13
        $this->getLogger()->info(sprintf('Indexed group %s in %s', $group, $end));
382
383
        // @codeCoverageIgnoreStart
384
        if ($pid !== false) {
385
            exit(0);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
386
        }
387
        // @codeCoverageIgnoreEnd
388 13
    }
389
390
    /**
391
     * Index a group of a class for a specific state and index
392
     *
393
     * @param string $group Group to index
394
     * @param string $class Class to index
395
     * @throws Exception
396
     */
397 13
    private function indexStateClass($group, $class): void
398
    {
399
        // Generate filtered list of local records
400 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
401
        /** @var DataList|DataObject[] $items */
402 13
        $items = DataObject::get($baseClass)
403 13
            ->sort('ID ASC')
404 13
            ->limit($this->getBatchLength(), ($group * $this->getBatchLength()));
405 13
        if ($items->count()) {
406 1
            $this->updateIndex($items);
407
        }
408 13
    }
409
410
    /**
411
     * Execute the update on the client
412
     *
413
     * @param SS_List $items Items to index
414
     * @throws Exception
415
     */
416 1
    private function updateIndex($items): void
417
    {
418 1
        $index = $this->getIndex();
419 1
        $client = $index->getClient();
420 1
        $update = $client->createUpdate();
421 1
        $this->service->setDebug($this->debug);
422 1
        $this->service->updateIndex($index, $items, $update);
423 1
        $client->update($update);
424 1
    }
425
426
    /**
427
     * Log an exception if it happens. Most are catched, these logs are for the developers
428
     * to identify problems and fix them.
429
     *
430
     * @codeCoverageIgnore This is actually tested through reflection
431
     * @param string $index Index that is currently running
432
     * @param int $group Group currently attempted to index
433
     * @param Exception $exception Exception that's been thrown
434
     * @throws GuzzleException
435
     * @throws ValidationException
436
     */
437
    private function logException($index, int $group, Exception $exception): void
438
    {
439
        $this->getLogger()->error($exception->getMessage());
440
        $msg = sprintf(
441
            'Error indexing core %s on group %s,' . PHP_EOL .
442
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
443
            $index,
444
            $group
445
        );
446
        SolrLogger::logMessage('ERROR', $msg, $index);
447
    }
448
}
449