Passed
Push — master ( 6e4405...4199c0 )
by Marco
04:48
created

SolrIndexTask::getClasses()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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