Passed
Push — hans/7even ( 272ce5...8fdec5 )
by Simon
05:56
created

SolrIndexTask   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 379
Duplicated Lines 0 %

Test Coverage

Coverage 68.7%

Importance

Changes 42
Bugs 4 Features 0
Metric Value
eloc 125
c 42
b 4
f 0
dl 0
loc 379
ccs 90
cts 131
cp 0.687
rs 9.28
wmc 39

14 Methods

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