Passed
Push — hans/code-cleanup ( 7f6349...96a9e1 )
by Simon
06:38
created

SolrIndexTask   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 408
Duplicated Lines 0 %

Test Coverage

Coverage 65.22%

Importance

Changes 43
Bugs 4 Features 0
Metric Value
eloc 128
c 43
b 4
f 0
dl 0
loc 408
ccs 90
cts 138
cp 0.6522
rs 9.1199
wmc 41

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setDebug() 0 5 1
B indexClass() 0 27 7
A clearIndex() 0 5 2
A run() 0 27 3
A indexClassForIndex() 0 8 2
A getClasses() 0 7 2
A setService() 0 5 1
A taskSetup() 0 10 3
A __construct() 0 12 2
A runChild() 0 13 3
A stateReindex() 0 10 2
A spawnChildren() 0 24 5
A runForkedChild() 0 8 1
A updateIndex() 0 7 1
A logException() 0 10 1
A doReindex() 0 14 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
4
namespace Firesphere\SolrSearch\Tasks;
5
6
use Exception;
7
use Firesphere\SolrSearch\Factories\DocumentFactory;
8
use Firesphere\SolrSearch\Helpers\SolrLogger;
9
use Firesphere\SolrSearch\Indexes\BaseIndex;
10
use Firesphere\SolrSearch\Services\SolrCoreService;
11
use Firesphere\SolrSearch\States\SiteState;
12
use Firesphere\SolrSearch\Traits\LoggerTrait;
13
use GuzzleHttp\Exception\GuzzleException;
14
use Psr\Log\LoggerInterface;
15
use ReflectionException;
16
use SilverStripe\Control\Controller;
17
use SilverStripe\Control\Director;
18
use SilverStripe\Control\HTTPRequest;
19
use SilverStripe\Core\Injector\Injector;
20
use SilverStripe\Dev\BuildTask;
21
use SilverStripe\ORM\ArrayList;
22
use SilverStripe\ORM\DataList;
23
use SilverStripe\ORM\DataObject;
24
use SilverStripe\ORM\DB;
25
use SilverStripe\ORM\ValidationException;
26
use SilverStripe\Versioned\Versioned;
27
28
/**
29
 * Class SolrIndexTask
30
 *
31
 * @description Index items to Solr through a tasks
32
 * @package Firesphere\SolrSearch\Tasks
33
 */
34
class SolrIndexTask extends BuildTask
35
{
36
    use LoggerTrait;
37
    /**
38
     * URLSegment of this task
39
     *
40
     * @var string
41
     */
42
    private static $segment = 'SolrIndexTask';
43
    /**
44
     * Store the current states for all instances of SiteState
45
     *
46
     * @var array
47
     */
48
    public $currentStates;
49
    /**
50
     * My name
51
     *
52
     * @var string
53
     */
54
    protected $title = 'Solr Index update';
55
    /**
56
     * What do I do?
57
     *
58
     * @var string
59
     */
60
    protected $description = 'Add or update documents to an existing Solr core.';
61
    /**
62
     * Debug mode enabled, default false
63
     *
64
     * @var bool
65
     */
66
    protected $debug = false;
67
    /**
68
     * Singleton of {@link SolrCoreService}
69
     *
70
     * @var SolrCoreService
71
     */
72
    protected $service;
73
74
    /**
75
     * Default batch length
76
     *
77
     * @var int
78
     */
79
    protected $batchLength = 1;
80
81
    /**
82
     * SolrIndexTask constructor. Sets up the document factory
83
     *
84
     * @throws ReflectionException
85
     */
86 14
    public function __construct()
87
    {
88 14
        parent::__construct();
89
        // Only index live items.
90
        // The old FTS module also indexed Draft items. This is unnecessary
91 14
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
92
        // If versioned is needed, a separate Versioned Search module is required
93 14
        $this->setService(Injector::inst()->get(SolrCoreService::class));
94 14
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
95 14
        $this->setDebug(Director::isDev() || Director::is_cli());
96 14
        $currentStates = SiteState::currentStates();
97 14
        SiteState::setDefaultStates($currentStates);
98 14
    }
99
100
    /**
101
     * Set the {@link SolrCoreService}
102
     *
103
     * @param SolrCoreService $service
104
     * @return SolrIndexTask
105
     */
106 14
    public function setService(SolrCoreService $service): SolrIndexTask
107
    {
108 14
        $this->service = $service;
109
110 14
        return $this;
111
    }
112
113
    /**
114
     * Set the debug mode
115
     *
116
     * @param bool $debug
117
     * @return SolrIndexTask
118
     */
119 14
    public function setDebug(bool $debug): SolrIndexTask
120
    {
121 14
        $this->debug = $debug;
122
123 14
        return $this;
124
    }
125
126
    /**
127
     * Implement this method in the task subclass to
128
     * execute via the TaskRunner
129
     *
130
     * @param HTTPRequest $request
131
     * @return int|bool
132
     * @throws Exception
133
     * @throws GuzzleException
134
     */
135 13
    public function run($request)
136
    {
137 13
        $start = time();
138 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
139 13
        list($vars, $group, $isGroup) = $this->taskSetup($request);
140 13
        $groups = 0;
141 13
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
142
143 13
        foreach ($indexes as $indexName) {
144
            /** @var BaseIndex $index */
145 13
            $index = Injector::inst()->get($indexName, false);
146
147 13
            $indexClasses = $index->getClasses();
148 13
            $classes = $this->getClasses($vars, $indexClasses);
149 13
            if (!count($classes)) {
150 10
                continue;
151
            }
152
153 13
            $this->clearIndex($vars, $index);
154
155 13
            $groups = $this->indexClassForIndex($classes, $isGroup, $index, $group);
156
        }
157
158 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
159 13
        $this->getLogger()->info(sprintf('Time taken: %s minutes', (time() - $start) / 60));
160
161 13
        return $groups;
162
    }
163
164
    /**
165
     * Set up the requirements for this task
166
     *
167
     * @param HTTPRequest $request
168
     * @return array
169
     */
170 13
    protected function taskSetup($request): array
171
    {
172 13
        $vars = $request->getVars();
173 13
        $this->debug = $this->debug || isset($vars['debug']);
174 13
        $group = $vars['group'] ?? 0;
175 13
        $start = $vars['start'] ?? 0;
176 13
        $group = ($start > $group) ? $start : $group;
177 13
        $isGroup = isset($vars['group']);
178
179 13
        return [$vars, $group, $isGroup];
180
    }
181
182
    /**
183
     * get the classes to run for this task execution
184
     *
185
     * @param $vars
186
     * @param array $classes
187
     * @return bool|array
188
     */
189 13
    protected function getClasses($vars, array $classes): array
190
    {
191 13
        if (isset($vars['class'])) {
192 1
            return array_intersect($classes, [$vars['class']]);
193
        }
194
195 12
        return $classes;
196
    }
197
198
    /**
199
     * Clear the given index if a full re-index is needed
200
     *
201
     * @param $vars
202
     * @param BaseIndex $index
203
     * @throws Exception
204
     */
205 13
    public function clearIndex($vars, BaseIndex $index)
206
    {
207 13
        if (!empty($vars['clear'])) {
208 1
            $this->getLogger()->info(sprintf('Clearing index %s', $index->getIndexName()));
209 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $index);
210
        }
211 13
    }
212
213
    /**
214
     * Index the classes for a specific index
215
     *
216
     * @param $classes
217
     * @param $isGroup
218
     * @param BaseIndex $index
219
     * @param $group
220
     * @return int
221
     * @throws Exception
222
     * @throws GuzzleException
223
     */
224 13
    protected function indexClassForIndex($classes, $isGroup, BaseIndex $index, $group): int
225
    {
226 13
        $groups = 0;
227 13
        foreach ($classes as $class) {
228 13
            $groups = $this->indexClass($isGroup, $class, $index, $group);
229
        }
230
231 13
        return $groups;
232
    }
233
234
    /**
235
     * Index a single class for a given index. {@link static::indexClassForIndex()}
236
     *
237
     * @param bool $isGroup
238
     * @param string $class
239
     * @param BaseIndex $index
240
     * @param int $group
241
     * @return int
242
     * @throws GuzzleException
243
     * @throws ValidationException
244
     */
245 13
    private function indexClass($isGroup, $class, BaseIndex $index, int $group): int
246
    {
247 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $index->getIndexName()));
248 13
        $this->batchLength = DocumentFactory::config()->get('batchLength');
249 13
        $totalGroups = (int)ceil($class::get()->count() / $this->batchLength);
250 13
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
251 13
        $groups = $isGroup ? ($group + $cores - 1) : $totalGroups;
252 13
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
253
        do { // Run from oldest to newest
254
            try {
255
                // The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
256 13
                if (function_exists('pcntl_fork') &&
257 13
                    !Controller::curr()->getRequest()->getVar('unittest')
258
                ) {
259
                    $group = $this->spawnChildren($class, $index, $group, $cores, $groups);
260
                } else {
261 13
                    $this->doReindex($group, $class, $index);
262
                }
263
            } catch (Exception $error) {
264
                $this->logException($index->getIndexName(), $group, $error);
265
                $group++;
266
                continue;
267
            }
268 13
            $group++;
269 13
        } while ($group <= $groups);
270
271 13
        return $totalGroups;
272
    }
273
274
    /**
275
     * For each core, spawn a child process that will handle a separate group.
276
     * This speeds up indexing through CLI massively.
277
     *
278
     * @param string $class
279
     * @param BaseIndex $index
280
     * @param int $group
281
     * @param int $cores
282
     * @param int $groups
283
     * @return int
284
     * @throws Exception
285
     * @throws GuzzleException
286
     */
287
    private function spawnChildren($class, BaseIndex $index, int $group, int $cores, int $groups): int
288
    {
289
        $start = $group;
290
        $pids = [];
291
        // for each core, start a grouped indexing
292
        for ($i = 0; $i < $cores; $i++) {
293
            $start = $group + $i;
294
            if ($start < $groups) {
295
                $this->runForkedChild($class, $index, $pids, $i, $start);
296
            }
297
        }
298
        // Wait for each child to finish
299
        foreach ($pids as $key => $pid) {
300
            pcntl_waitpid($pid, $status);
301
            if ($status === 0) {
302
                unset($pids[$key]);
303
            }
304
        }
305
        $commit = $index->getClient()->createUpdate();
306
        $commit->addCommit();
307
308
        $index->getClient()->update($commit);
309
310
        return $start;
311
    }
312
313
    /**
314
     * @param $class
315
     * @param BaseIndex $index
316
     * @param array $pids
317
     * @param int $i
318
     * @param int $start
319
     * @return void
320
     * @throws GuzzleException
321
     * @throws ValidationException
322
     */
323
    private function runForkedChild($class, BaseIndex $index, array &$pids, int $i, int $start): void
324
    {
325
        $pid = pcntl_fork();
326
        // PID needs to be pushed before anything else, for some reason
327
        $pids[$i] = $pid;
328
        $config = DB::getConfig();
329
        DB::connect($config);
330
        $this->runChild($class, $index, $pid, $start);
331
    }
332
333
    /**
334
     * @param $class
335
     * @param BaseIndex $index
336
     * @param int $pid
337
     * @param int $start
338
     * @throws GuzzleException
339
     * @throws ValidationException
340
     * @throws Exception
341
     */
342
    private function runChild($class, BaseIndex $index, int $pid, int $start): void
343
    {
344
        if (!$pid) {
345
            try {
346
                $this->doReindex($start, $class, $index, true);
347
            } catch (Exception $e) {
348
                SolrLogger::logMessage('ERROR', $e, $index->getIndexName());
349
                $msg = sprintf(
350
                    'Something went wrong while indexing %s on %s, see the logs for details',
351
                    $start,
352
                    $index->getIndexName()
353
                );
354
                throw new Exception($msg);
355
            }
356
        }
357
    }
358
359
    /**
360
     * Reindex the given group, for each state
361
     *
362
     * @param int $group
363
     * @param string $class
364
     * @param BaseIndex $index
365
     * @param bool $pcntl
366
     * @throws Exception
367
     */
368 13
    private function doReindex($group, $class, BaseIndex $index, $pcntl = false)
369
    {
370 13
        foreach (SiteState::getStates() as $state) {
371 13
            if ($state !== 'default' && !empty($state)) {
372
                SiteState::withState($state);
373
            }
374 13
            $this->stateReindex($group, $class, $index);
375
        }
376
377 13
        SiteState::withState(SiteState::DEFAULT_STATE);
378 13
        $this->getLogger()->info(sprintf('Indexed group %s', $group));
379
380 13
        if ($pcntl) {
381
            exit(0);
1 ignored issue
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...
382
        }
383 13
    }
384
385
    /**
386
     * Index a group of a class for a specific state and index
387
     *
388
     * @param $group
389
     * @param $class
390
     * @param BaseIndex $index
391
     * @throws Exception
392
     */
393 13
    private function stateReindex($group, $class, BaseIndex $index): void
394
    {
395
        // Generate filtered list of local records
396 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
397
        /** @var DataList|DataObject[] $items */
398 13
        $items = DataObject::get($baseClass)
399 13
            ->sort('ID ASC')
400 13
            ->limit($this->batchLength, ($group * $this->batchLength));
401 13
        if ($items->count()) {
402 1
            $this->updateIndex($index, $items);
403
        }
404 13
    }
405
406
    /**
407
     * Execute the update on the client
408
     *
409
     * @param BaseIndex $index
410
     * @param $items
411
     * @throws Exception
412
     */
413 1
    private function updateIndex(BaseIndex $index, $items): void
414
    {
415 1
        $client = $index->getClient();
416 1
        $update = $client->createUpdate();
417 1
        $this->service->setInDebugMode($this->debug);
418 1
        $this->service->updateIndex($index, $items, $update);
419 1
        $client->update($update);
420 1
    }
421
422
    /**
423
     * Log an exception if it happens. Most are catched, these logs are for the developers
424
     * to identify problems and fix them.
425
     *
426
     * @param string $index
427
     * @param int $group
428
     * @param Exception $exception
429
     * @throws GuzzleException
430
     * @throws ValidationException
431
     */
432
    private function logException($index, int $group, Exception $exception): void
433
    {
434
        $this->getLogger()->error($exception->getMessage());
435
        $msg = sprintf(
436
            'Error indexing core %s on group %s,' . PHP_EOL .
437
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
438
            $index,
439
            $group
440
        );
441
        SolrLogger::logMessage('ERROR', $msg, $index);
442
    }
443
}
444