Cancelled
Push — hans/its-the-same ( 5e726a...539df6 )
by Simon
04:41
created

SolrIndexTask   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 399
Duplicated Lines 0 %

Test Coverage

Coverage 96.84%

Importance

Changes 38
Bugs 5 Features 0
Metric Value
eloc 131
c 38
b 5
f 0
dl 0
loc 399
ccs 92
cts 95
cp 0.9684
rs 8.96
wmc 43

16 Methods

Rating   Name   Duplication   Size   Complexity  
A clearIndex() 0 5 2
A indexClassForIndex() 0 8 2
A getClasses() 0 7 2
A stateReindex() 0 10 2
A __construct() 0 15 3
A hasPCNTL() 0 6 4
A indexClass() 0 25 4
A run() 0 28 3
A spawnChildren() 0 25 5
A runForkedChild() 0 8 1
A taskSetup() 0 10 3
A getGroupSettings() 0 6 2
A runChild() 0 13 3
A updateIndex() 0 8 1
A logException() 0 10 1
A doReindex() 0 15 5

How to fix   Complexity   

Complex Class

Complex classes like SolrIndexTask often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SolrIndexTask, and based on these observations, apply Extract Interface, too.

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 15
    public function __construct()
77
    {
78 15
        parent::__construct();
79
        // Only index live items.
80
        // The old FTS module also indexed Draft items. This is unnecessary
81 15
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
82
        // If versioned is needed, a separate Versioned Search module is required
83 15
        $this->setService(Injector::inst()->get(SolrCoreService::class));
84 15
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
85 15
        $this->setDebug(Director::isDev() || Director::is_cli());
86 15
        $this->setBatchLength(DocumentFactory::config()->get('batchLength'));
87 15
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
88 15
        $this->setCores($cores);
89 15
        $currentStates = SiteState::currentStates();
90 15
        SiteState::setDefaultStates($currentStates);
91 15
    }
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
        $this->debug = $this->debug || isset($vars['debug']);
142 13
        $group = $vars['group'] ?? 0;
143 13
        $start = $vars['start'] ?? 0;
144 13
        $group = ($start > $group) ? $start : $group;
145 13
        $isGroup = isset($vars['group']);
146
147 13
        return [$vars, $group, $isGroup];
148
    }
149
150
    /**
151
     * get the classes to run for this task execution
152
     *
153
     * @param array $vars URL GET Parameters
154
     * @param array $classes Classes to index
155
     * @return bool|array
156
     */
157 13
    protected function getClasses($vars, array $classes): array
158
    {
159 13
        if (isset($vars['class'])) {
160 1
            return array_intersect($classes, [$vars['class']]);
161
        }
162
163 12
        return $classes;
164
    }
165
166
    /**
167
     * Clear the given index if a full re-index is needed
168
     *
169
     * @param array $vars URL GET Parameters
170
     * @throws Exception
171
     */
172 13
    public function clearIndex($vars)
173
    {
174 13
        if (!empty($vars['clear'])) {
175 1
            $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName()));
176 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);
177
        }
178 13
    }
179
180
    /**
181
     * Index the classes for a specific index
182
     *
183
     * @param array $classes Classes that need indexing
184
     * @param bool $isGroup Indexing a specific group?
185
     * @param int $group Group to index
186
     * @return int
187
     * @throws Exception
188
     * @throws GuzzleException
189
     */
190 13
    protected function indexClassForIndex($classes, $isGroup, $group): int
191
    {
192 13
        $groups = 0;
193 13
        foreach ($classes as $class) {
194 13
            $groups = $this->indexClass($isGroup, $class, $group);
195
        }
196
197 13
        return $groups;
198
    }
199
200
    /**
201
     * Index a single class for a given index. {@link static::indexClassForIndex()}
202
     *
203
     * @param bool $isGroup Is a specific group indexed
204
     * @param string $class Class to index
205
     * @param int $group Group to index
206
     * @return int
207
     * @throws GuzzleException
208
     * @throws ValidationException
209
     */
210 13
    private function indexClass($isGroup, $class, int $group): int
211
    {
212 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $this->getIndex()->getIndexName()));
213 13
        list($totalGroups, $groups) = $this->getGroupSettings($isGroup, $class, $group);
214 13
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
215
        do { // Run from oldest to newest
216
            try {
217 13
                if ($this->hasPCNTL()) {
218
                    // @codeCoverageIgnoreStart
219
                    $group = $this->spawnChildren($class, $group, $groups);
220
                    // @codeCoverageIgnoreEnd
221
                } else {
222 13
                    $this->doReindex($group, $class);
223
                }
224 13
                $group++;
225
            } catch (Exception $error) {
226
                // @codeCoverageIgnoreStart
227
                $this->logException($this->index->getIndexName(), $group, $error);
228
                $group++;
229
                continue;
230
                // @codeCoverageIgnoreEnd
231
            }
232 13
        } while ($group <= $groups);
233
234 13
        return $totalGroups;
235
    }
236
237
    /**
238
     * Check the amount of groups and the total against the isGroup check.
239
     *
240
     * @param bool $isGroup Is it a specific group
241
     * @param string $class Class to check
242
     * @param int $group Current group to index
243
     * @return array
244
     */
245 13
    private function getGroupSettings($isGroup, $class, int $group): array
246
    {
247 13
        $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());
248 13
        $groups = $isGroup ? ($group + $this->getCores() - 1) : $totalGroups;
249
250 13
        return [$totalGroups, $groups];
251
    }
252
253
    /**
254
     * Check if PCNTL is available and/or useable.
255
     * The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
256
     * The pcntl parameter check is for unit tests, but PHPUnit does not support PCNTL (yet)
257
     *
258
     * @return bool
259
     */
260 13
    private function hasPCNTL()
261
    {
262 13
        return Director::is_cli() &&
263 13
            function_exists('pcntl_fork') &&
264
            (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl' ||
265 13
                !Controller::curr()->getRequest()->getVar('unittest'));
266
    }
267
268
    /**
269
     * For each core, spawn a child process that will handle a separate group.
270
     * This speeds up indexing through CLI massively.
271
     *
272
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
273
     * @param string $class Class to index
274
     * @param int $group Group to index
275
     * @param int $groups Total amount of groups
276
     * @return int Last group indexed
277
     * @throws Exception
278
     * @throws GuzzleException
279
     */
280
    private function spawnChildren($class, int $group, int $groups): int
281
    {
282
        $start = $group;
283
        $pids = [];
284
        $cores = $this->getCores();
285
        // for each core, start a grouped indexing
286
        for ($i = 0; $i < $cores; $i++) {
287
            $start = $group + $i;
288
            if ($start < $groups) {
289
                $this->runForkedChild($class, $pids, $i, $start);
290
            }
291
        }
292
        // Wait for each child to finish
293
        foreach ($pids as $key => $pid) {
294
            pcntl_waitpid($pid, $status);
295
            if ($status === 0) {
296
                unset($pids[$key]);
297
            }
298
        }
299
        $commit = $this->index->getClient()->createUpdate();
300
        $commit->addCommit();
301
302
        $this->index->getClient()->update($commit);
303
304
        return $start;
305
    }
306
307
    /**
308
     * Create a fork and run the child
309
     *
310
     * @codeCoverageIgnore Can't be tested because PCNTL is not available
311
     * @param string $class Class to index
312
     * @param array $pids Array of all the child Process IDs
313
     * @param int $coreNumber Core number
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 $coreNumber, int $start): void
320
    {
321
        $pid = pcntl_fork();
322
        // PID needs to be pushed before anything else, for some reason
323
        $pids[$coreNumber] = $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
        if (!$pid) {
343
            try {
344
                $this->doReindex($start, $class, $pid);
345
            } catch (Exception $error) {
346
                SolrLogger::logMessage('ERROR', $error, $this->index->getIndexName());
347
                $msg = sprintf(
348
                    'Something went wrong while indexing %s on %s, see the logs for details',
349
                    $start,
350
                    $this->index->getIndexName()
351
                );
352
                throw new Exception($msg);
353
            }
354
        }
355
    }
356
357
    /**
358
     * Reindex the given group, for each state
359
     *
360
     * @param int $group Group to index
361
     * @param string $class Class to index
362
     * @param bool|int $pcntl Are we a child process or not
363
     * @throws Exception
364
     */
365 13
    private function doReindex($group, $class, $pcntl = false)
366
    {
367 13
        foreach (SiteState::getStates() as $state) {
368 13
            if ($state !== 'default' && !empty($state)) {
369
                SiteState::withState($state);
370
            }
371 13
            $this->stateReindex($group, $class);
372
        }
373
374 13
        SiteState::withState(SiteState::DEFAULT_STATE);
375 13
        $this->getLogger()->info(sprintf('Indexed group %s', $group));
376
377
        // @codeCoverageIgnoreStart
378
        if ($pcntl !== false) {
379
            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...
380
        }
381
        // @codeCoverageIgnoreEnd
382 13
    }
383
384
    /**
385
     * Index a group of a class for a specific state and index
386
     *
387
     * @param string $group Group to index
388
     * @param string $class Class to index
389
     * @throws Exception
390
     */
391 13
    private function stateReindex($group, $class): void
392
    {
393
        // Generate filtered list of local records
394 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
395
        /** @var DataList|DataObject[] $items */
396 13
        $items = DataObject::get($baseClass)
397 13
            ->sort('ID ASC')
398 13
            ->limit($this->getBatchLength(), ($group * $this->getBatchLength()));
399 13
        if ($items->count()) {
400 1
            $this->updateIndex($items);
401
        }
402 13
    }
403
404
    /**
405
     * Execute the update on the client
406
     *
407
     * @param SS_List $items Items to index
408
     * @throws Exception
409
     */
410 1
    private function updateIndex($items): void
411
    {
412 1
        $index = $this->getIndex();
413 1
        $client = $index->getClient();
414 1
        $update = $client->createUpdate();
415 1
        $this->service->setInDebugMode($this->debug);
416 1
        $this->service->updateIndex($index, $items, $update);
417 1
        $client->update($update);
418 1
    }
419
420
    /**
421
     * Log an exception if it happens. Most are catched, these logs are for the developers
422
     * to identify problems and fix them.
423
     *
424
     * @codeCoverageIgnore This is actually tested through reflection
425
     * @param string $index Index that is currently running
426
     * @param int $group Group currently attempted to index
427
     * @param Exception $exception Exception that's been thrown
428
     * @throws GuzzleException
429
     * @throws ValidationException
430
     */
431
    private function logException($index, int $group, Exception $exception): void
432
    {
433
        $this->getLogger()->error($exception->getMessage());
434
        $msg = sprintf(
435
            'Error indexing core %s on group %s,' . PHP_EOL .
436
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
437
            $index,
438
            $group
439
        );
440
        SolrLogger::logMessage('ERROR', $msg, $index);
441
    }
442
}
443