Passed
Push — hans/authentication ( f88d5d...b8d786 )
by Simon
05:24
created

SolrIndexTask::indexClass()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 10
Bugs 3 Features 0
Metric Value
cc 4
eloc 16
c 10
b 3
f 0
nc 5
nop 3
dl 0
loc 25
ccs 9
cts 10
cp 0.9
crap 4.016
rs 9.7333
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
    /**
48
     * URLSegment of this task
49
     *
50
     * @var string
51
     */
52
    private static $segment = 'SolrIndexTask';
53
    /**
54
     * Store the current states for all instances of SiteState
55
     *
56
     * @var array
57
     */
58
    public $currentStates;
59
    /**
60
     * My name
61
     *
62
     * @var string
63
     */
64
    protected $title = 'Solr Index update';
65
    /**
66
     * What do I do?
67
     *
68
     * @var string
69
     */
70
    protected $description = 'Add or update documents to an existing Solr core.';
71
72
    /**
73
     * SolrIndexTask constructor. Sets up the document factory
74
     *
75
     * @throws ReflectionException
76
     */
77 16
    public function __construct()
78
    {
79 16
        parent::__construct();
80
        // Only index live items.
81
        // The old FTS module also indexed Draft items. This is unnecessary
82
        // If versioned is needed, a separate Versioned Search module is required
83 16
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
84 16
        $this->setService(Injector::inst()->get(SolrCoreService::class));
85 16
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
86 16
        $this->setDebug(Director::isDev() || Director::is_cli());
87 16
        $this->setBatchLength(DocumentFactory::config()->get('batchLength'));
88 16
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
89 16
        $this->setCores($cores);
90 16
        $currentStates = SiteState::currentStates();
91 16
        SiteState::setDefaultStates($currentStates);
92 16
    }
93
94
    /**
95
     * Implement this method in the task subclass to
96
     * execute via the TaskRunner
97
     *
98
     * @param HTTPRequest $request Current request
99
     * @return int|bool
100
     * @throws Exception
101
     * @throws GuzzleException
102
     */
103 13
    public function run($request)
104
    {
105 13
        $start = time();
106 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
107 13
        list($vars, $group, $isGroup) = $this->taskSetup($request);
108 13
        $groups = 0;
109 13
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
110
111 13
        foreach ($indexes as $indexName) {
112
            /** @var BaseIndex $index */
113 13
            $index = Injector::inst()->get($indexName, false);
114 13
            $this->setIndex($index);
115
116 13
            $indexClasses = $this->index->getClasses();
117 13
            $classes = $this->getClasses($vars, $indexClasses);
118 13
            if (!count($classes)) {
119 10
                continue;
120
            }
121
122 13
            $this->clearIndex($vars);
123
124 13
            $groups = $this->indexClassForIndex($classes, $isGroup, $group);
125
        }
126
127 13
        $this->getLogger()->info(gmdate('Y-m-d H:i:s'));
128 13
        $time = gmdate('H:i:s', (time() - $start));
129 13
        $this->getLogger()->info(sprintf('Time taken: %s', $time));
130
131 13
        return $groups;
132
    }
133
134
    /**
135
     * Set up the requirements for this task
136
     *
137
     * @param HTTPRequest $request Current request
138
     * @return array
139
     */
140 13
    protected function taskSetup($request): array
141
    {
142 13
        $vars = $request->getVars();
143 13
        $debug = $this->isDebug() || isset($vars['debug']);
144
        // Forcefully set the debugging to whatever the outcome of the above is
145 13
        $this->setDebug($debug, true);
146 13
        $group = $vars['group'] ?? 0;
147 13
        $start = $vars['start'] ?? 0;
148 13
        $group = ($start > $group) ? $start : $group;
149 13
        $isGroup = isset($vars['group']);
150
151 13
        return [$vars, $group, $isGroup];
152
    }
153
154
    /**
155
     * get the classes to run for this task execution
156
     *
157
     * @param array $vars URL GET Parameters
158
     * @param array $classes Classes to index
159
     * @return bool|array
160
     */
161 13
    protected function getClasses($vars, array $classes): array
162
    {
163 13
        if (isset($vars['class'])) {
164 1
            return array_intersect($classes, [$vars['class']]);
165
        }
166
167 12
        return $classes;
168
    }
169
170
    /**
171
     * Clear the given index if a full re-index is needed
172
     *
173
     * @param array $vars URL GET Parameters
174
     * @throws Exception
175
     */
176 13
    public function clearIndex($vars)
177
    {
178 13
        if (!empty($vars['clear'])) {
179 1
            $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName()));
180 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);
181
        }
182 13
    }
183
184
    /**
185
     * Index the classes for a specific index
186
     *
187
     * @param array $classes Classes that need indexing
188
     * @param bool $isGroup Indexing a specific group?
189
     * @param int $group Group to index
190
     * @return int
191
     * @throws Exception
192
     * @throws GuzzleException
193
     */
194 13
    protected function indexClassForIndex($classes, $isGroup, $group): int
195
    {
196 13
        $groups = 0;
197 13
        foreach ($classes as $class) {
198 13
            $groups = $this->indexClass($isGroup, $class, $group);
199
        }
200
201 13
        return $groups;
202
    }
203
204
    /**
205
     * Index a single class for a given index. {@link static::indexClassForIndex()}
206
     *
207
     * @param bool $isGroup Is a specific group indexed
208
     * @param string $class Class to index
209
     * @param int $group Group to index
210
     * @return int
211
     * @throws GuzzleException
212
     * @throws ValidationException
213
     */
214 13
    private function indexClass($isGroup, $class, int $group): int
215
    {
216 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $this->getIndex()->getIndexName()));
217 13
        list($totalGroups, $groups) = $this->getGroupSettings($isGroup, $class, $group);
218 13
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
219
        do { // Run from oldest to newest
220
            try {
221 13
                if ($this->hasPCNTL()) {
222
                    // @codeCoverageIgnoreStart
223
                    $group = $this->spawnChildren($class, $group, $groups);
224
                    // @codeCoverageIgnoreEnd
225
                } else {
226 13
                    $this->doReindex($group, $class);
227
                }
228 13
                $group++;
229
            } catch (Exception $error) {
230
                // @codeCoverageIgnoreStart
231
                $this->logException($this->index->getIndexName(), $group, $error);
232
                $group++;
233
                continue;
234
                // @codeCoverageIgnoreEnd
235
            }
236 13
        } while ($group <= $groups);
237
238 13
        return $totalGroups;
239
    }
240
241
    /**
242
     * Check the amount of groups and the total against the isGroup check.
243
     *
244
     * @param bool $isGroup Is it a specific group
245
     * @param string $class Class to check
246
     * @param int $group Current group to index
247
     * @return array
248
     */
249 13
    private function getGroupSettings($isGroup, $class, int $group): array
250
    {
251 13
        $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());
252 13
        $groups = $isGroup ? ($group + $this->getCores() - 1) : $totalGroups;
253
254 13
        return [$totalGroups, $groups];
255
    }
256
257
    /**
258
     * Check if PCNTL is available and/or useable.
259
     * The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
260
     * The pcntl parameter check is for unit tests, but PHPUnit does not support PCNTL (yet)
261
     *
262
     * @return bool
263
     */
264 13
    private function hasPCNTL()
265
    {
266 13
        return Director::is_cli() &&
267 13
            function_exists('pcntl_fork') &&
268
            (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl' ||
269 13
                !Controller::curr()->getRequest()->getVar('unittest'));
270
    }
271
272
    /**
273
     * For each core, spawn a child process that will handle a separate group.
274
     * This speeds up indexing through CLI massively.
275
     *
276
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
277
     * @param string $class Class to index
278
     * @param int $group Group to index
279
     * @param int $groups Total amount of groups
280
     * @return int Last group indexed
281
     * @throws Exception
282
     * @throws GuzzleException
283
     */
284
    private function spawnChildren($class, int $group, int $groups): int
285
    {
286
        $start = $group;
287
        $pids = [];
288
        $cores = $this->getCores();
289
        // for each core, start a grouped indexing
290
        for ($i = 0; $i < $cores; $i++) {
291
            $start = $group + $i;
292
            if ($start < $groups) {
293
                $this->runForkedChild($class, $pids, $start);
294
            }
295
        }
296
        // Wait for each child to finish
297
        // It needs to wait for them independently,
298
        // or it runs out of memory for some reason
299
        foreach ($pids as $pid) {
300
            pcntl_waitpid($pid, $status);
301
        }
302
        $commit = $this->index->getClient()->createUpdate();
303
        $commit->addCommit();
304
305
        $this->index->getClient()->update($commit);
306
307
        return $start;
308
    }
309
310
    /**
311
     * Create a fork and run the child
312
     *
313
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
314
     * @param string $class Class to index
315
     * @param array $pids Array of all the child Process IDs
316
     * @param int $start Start point for the objects
317
     * @return void
318
     * @throws GuzzleException
319
     * @throws ValidationException
320
     */
321
    private function runForkedChild($class, array &$pids, int $start): void
322
    {
323
        $pid = pcntl_fork();
324
        // PID needs to be pushed before anything else, for some reason
325
        $pids[] = $pid;
326
        $config = DB::getConfig();
327
        DB::connect($config);
328
        $this->runChild($class, $pid, $start);
329
    }
330
331
    /**
332
     * Ren a single child index operation
333
     *
334
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
335
     * @param string $class Class to index
336
     * @param int $pid PID of the child
337
     * @param int $start Position to start
338
     * @throws GuzzleException
339
     * @throws ValidationException
340
     * @throws Exception
341
     */
342
    private function runChild($class, int $pid, int $start): void
343
    {
344
        if ($pid === 0) {
345
            try {
346
                $this->doReindex($start, $class, $pid);
347
            } catch (Exception $error) {
348
                SolrLogger::logMessage('ERROR', $error);
349
                $msg = sprintf(
350
                    'Something went wrong while indexing %s on %s, see the logs for details',
351
                    $start,
352
                    $this->index->getIndexName()
353
                );
354
                if ($pid !== false) {
355
                    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...
356
                }
357
                throw new Exception($msg);
358
            }
359
        }
360
    }
361
362
    /**
363
     * Reindex the given group, for each state
364
     *
365
     * @param int $group Group to index
366
     * @param string $class Class to index
367
     * @param bool|int $pid Are we a child process or not
368
     * @throws Exception
369
     */
370 13
    private function doReindex($group, $class, $pid = false)
371
    {
372 13
        $start = time();
373 13
        foreach (SiteState::getStates() as $state) {
374 13
            if ($state !== SiteState::DEFAULT_STATE && !empty($state)) {
375
                SiteState::withState($state);
376
            }
377 13
            $this->indexStateClass($group, $class);
378
        }
379
380 13
        SiteState::withState(SiteState::DEFAULT_STATE);
381 13
        $end = gmdate('i:s', time() - $start);
382 13
        $this->getLogger()->info(sprintf('Indexed group %s in %s', $group, $end));
383
384
        // @codeCoverageIgnoreStart
385
        if ($pid !== false) {
386
            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...
387
        }
388
        // @codeCoverageIgnoreEnd
389 13
    }
390
391
    /**
392
     * Index a group of a class for a specific state and index
393
     *
394
     * @param string $group Group to index
395
     * @param string $class Class to index
396
     * @throws Exception
397
     */
398 13
    private function indexStateClass($group, $class): void
399
    {
400
        // Generate filtered list of local records
401 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
402
        /** @var DataList|DataObject[] $items */
403 13
        $items = DataObject::get($baseClass)
404 13
            ->sort('ID ASC')
405 13
            ->limit($this->getBatchLength(), ($group * $this->getBatchLength()));
406 13
        if ($items->count()) {
407 1
            $this->updateIndex($items);
408
        }
409 13
    }
410
411
    /**
412
     * Execute the update on the client
413
     *
414
     * @param SS_List $items Items to index
415
     * @throws Exception
416
     */
417 1
    private function updateIndex($items): void
418
    {
419 1
        $index = $this->getIndex();
420 1
        $client = $index->getClient();
421 1
        $update = $client->createUpdate();
422 1
        $this->service->setDebug($this->debug);
423 1
        $this->service->updateIndex($index, $items, $update);
424 1
        $client->update($update);
425 1
    }
426
427
    /**
428
     * Log an exception if it happens. Most are catched, these logs are for the developers
429
     * to identify problems and fix them.
430
     *
431
     * @codeCoverageIgnore This is actually tested through reflection
432
     * @param string $index Index that is currently running
433
     * @param int $group Group currently attempted to index
434
     * @param Exception $exception Exception that's been thrown
435
     * @throws GuzzleException
436
     * @throws ValidationException
437
     */
438
    private function logException($index, int $group, Exception $exception): void
439
    {
440
        $this->getLogger()->error($exception->getMessage());
441
        $msg = sprintf(
442
            'Error indexing core %s on group %s,' . PHP_EOL .
443
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
444
            $index,
445
            $group
446
        );
447
        SolrLogger::logMessage('ERROR', $msg);
448
    }
449
}
450