Cancelled
Push — hans/code-cleanup ( 787ed2...42f8e4 )
by Simon
05:34
created

SolrIndexTask::indexClass()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8.2464

Importance

Changes 10
Bugs 3 Features 0
Metric Value
cc 7
eloc 20
c 10
b 3
f 0
nc 10
nop 3
dl 0
loc 27
ccs 12
cts 17
cp 0.7059
crap 8.2464
rs 8.6666
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 Firesphere\SolrSearch\Traits\SolrIndexTrait;
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\SS_List;
27
use SilverStripe\ORM\ValidationException;
28
use SilverStripe\Versioned\Versioned;
29
30
/**
31
 * Class SolrIndexTask
32
 *
33
 * @description Index items to Solr through a tasks
34
 * @package Firesphere\SolrSearch\Tasks
35
 */
36
class SolrIndexTask extends BuildTask
37
{
38
    use LoggerTrait;
39
    use SolrIndexTrait;
40
    /**
41
     * URLSegment of this task
42
     *
43
     * @var string
44
     */
45
    private static $segment = 'SolrIndexTask';
46
    /**
47
     * Store the current states for all instances of SiteState
48
     *
49
     * @var array
50
     */
51
    public $currentStates;
52
    /**
53
     * My name
54
     *
55
     * @var string
56
     */
57
    protected $title = 'Solr Index update';
58
    /**
59
     * What do I do?
60
     *
61
     * @var string
62
     */
63
    protected $description = 'Add or update documents to an existing Solr core.';
64
65
    /**
66
     * SolrIndexTask constructor. Sets up the document factory
67
     *
68
     * @throws ReflectionException
69
     */
70 15
    public function __construct()
71
    {
72 15
        parent::__construct();
73
        // Only index live items.
74
        // The old FTS module also indexed Draft items. This is unnecessary
75 15
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
76
        // If versioned is needed, a separate Versioned Search module is required
77 15
        $this->setService(Injector::inst()->get(SolrCoreService::class));
78 15
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
79 15
        $this->setDebug(Director::isDev() || Director::is_cli());
80 15
        $this->setBatchLength(DocumentFactory::config()->get('batchLength'));
81 15
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
82 15
        $this->setCores($cores);
83 15
        $currentStates = SiteState::currentStates();
84 15
        SiteState::setDefaultStates($currentStates);
85 15
    }
86
87
    /**
88
     * Implement this method in the task subclass to
89
     * execute via the TaskRunner
90
     *
91
     * @param HTTPRequest $request Current request
92
     * @return int|bool
93
     * @throws Exception
94
     * @throws GuzzleException
95
     */
96 13
    public function run($request)
97
    {
98 13
        $start = time();
99 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
100 13
        list($vars, $group, $isGroup) = $this->taskSetup($request);
101 13
        $groups = 0;
102 13
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
103
104 13
        foreach ($indexes as $indexName) {
105
            /** @var BaseIndex $index */
106 13
            $index = Injector::inst()->get($indexName, false);
107 13
            $this->setIndex($index);
108
109 13
            $indexClasses = $this->index->getClasses();
110 13
            $classes = $this->getClasses($vars, $indexClasses);
111 13
            if (!count($classes)) {
112 10
                continue;
113
            }
114
115 13
            $this->clearIndex($vars);
116
117 13
            $groups = $this->indexClassForIndex($classes, $isGroup, $group);
0 ignored issues
show
Bug introduced by
$isGroup of type boolean is incompatible with the type integer expected by parameter $isGroup of Firesphere\SolrSearch\Ta...k::indexClassForIndex(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
            $groups = $this->indexClassForIndex($classes, /** @scrutinizer ignore-type */ $isGroup, $group);
Loading history...
118
        }
119
120 13
        $this->getLogger()->info(date('Y-m-d H:i:s'));
121 13
        $this->getLogger()->info(sprintf('Time taken: %s minutes', (time() - $start) / 60));
122
123 13
        return $groups;
124
    }
125
126
    /**
127
     * Set up the requirements for this task
128
     *
129
     * @param HTTPRequest $request Current request
130
     * @return array
131
     */
132 13
    protected function taskSetup($request): array
133
    {
134 13
        $vars = $request->getVars();
135 13
        $this->debug = $this->debug || isset($vars['debug']);
136 13
        $group = $vars['group'] ?? 0;
137 13
        $start = $vars['start'] ?? 0;
138 13
        $group = ($start > $group) ? $start : $group;
139 13
        $isGroup = isset($vars['group']);
140
141 13
        return [$vars, $group, $isGroup];
142
    }
143
144
    /**
145
     * get the classes to run for this task execution
146
     *
147
     * @param array $vars URL GET Parameters
148
     * @param array $classes Classes to index
149
     * @return bool|array
150
     */
151 13
    protected function getClasses($vars, array $classes): array
152
    {
153 13
        if (isset($vars['class'])) {
154 1
            return array_intersect($classes, [$vars['class']]);
155
        }
156
157 12
        return $classes;
158
    }
159
160
    /**
161
     * Clear the given index if a full re-index is needed
162
     *
163
     * @param array $vars URL GET Parameters
164
     * @throws Exception
165
     */
166 13
    public function clearIndex($vars)
167
    {
168 13
        if (!empty($vars['clear'])) {
169 1
            $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName()));
170 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);
171
        }
172 13
    }
173
174
    /**
175
     * Index the classes for a specific index
176
     *
177
     * @param array $classes Classes that need indexing
178
     * @param int $isGroup Indexing a specific group?
179
     * @param int $group Group to index
180
     * @return int
181
     * @throws Exception
182
     * @throws GuzzleException
183
     */
184 13
    protected function indexClassForIndex($classes, $isGroup, $group): int
185
    {
186 13
        $groups = 0;
187 13
        foreach ($classes as $class) {
188 13
            $groups = $this->indexClass($isGroup, $class, $group);
0 ignored issues
show
Bug introduced by
$isGroup of type integer is incompatible with the type boolean expected by parameter $isGroup of Firesphere\SolrSearch\Ta...IndexTask::indexClass(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

188
            $groups = $this->indexClass(/** @scrutinizer ignore-type */ $isGroup, $class, $group);
Loading history...
189
        }
190
191 13
        return $groups;
192
    }
193
194
    /**
195
     * Index a single class for a given index. {@link static::indexClassForIndex()}
196
     *
197
     * @param bool $isGroup Is a specific group indexed
198
     * @param string $class Class to index
199
     * @param int $group Group to index
200
     * @return int
201
     * @throws GuzzleException
202
     * @throws ValidationException
203
     */
204 13
    private function indexClass($isGroup, $class, int $group): int
205
    {
206 13
        $index = $this->getIndex();
207 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $index->getIndexName()));
208 13
        $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());
209 13
        $groups = $isGroup ? ($group + $this->cores - 1) : $totalGroups;
210 13
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
211
        do { // Run from oldest to newest
212
            try {
213
                // The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
214 13
                if (function_exists('pcntl_fork') &&
215 13
                    (!Controller::curr()->getRequest()->getVar('unittest') ||
216
                    !Controller::curr()->getRequest()->getVar('unittest') === 'pcntl')
217
                ) {
218
                    $group = $this->spawnChildren($class, $group, $groups);
219 13
                } else {
220
                    $this->doReindex($group, $class);
221
                }
222
            } catch (Exception $error) {
223
                $this->logException($index->getIndexName(), $group, $error);
224
                $group++;
225
                continue;
226 13
            }
227 13
            $group++;
228
        } while ($group <= $groups);
229 13
230
        return $totalGroups;
231
    }
232
233
    /**
234
     * For each core, spawn a child process that will handle a separate group.
235
     * This speeds up indexing through CLI massively.
236
     *
237
     * @param string $class Class to index
238
     * @param int $group Group to index
239
     * @param int $groups Total amount of groups
240
     * @return int Last group indexed
241
     * @throws Exception
242
     * @throws GuzzleException
243
     */
244
    private function spawnChildren($class, int $group, int $groups): int
245
    {
246
        $start = $group;
247
        $pids = [];
248
        $cores = $this->getCores();
249
        // for each core, start a grouped indexing
250
        for ($i = 0; $i < $cores; $i++) {
251
            $start = $group + $i;
252
            if ($start < $groups) {
253
                $this->runForkedChild($class, $pids, $i, $start);
254
            }
255
        }
256
        // Wait for each child to finish
257
        foreach ($pids as $key => $pid) {
258
            pcntl_waitpid($pid, $status);
259
            if ($status === 0) {
260
                unset($pids[$key]);
261
            }
262
        }
263
        $commit = $this->index->getClient()->createUpdate();
264
        $commit->addCommit();
265
266
        $this->index->getClient()->update($commit);
267
268
        return $start;
269
    }
270
271
    /**
272
     * Create a fork and run the child
273
     *
274
     * @param string $class Class to index
275
     * @param array $pids Array of all the child Process IDs
276
     * @param int $coreNumber Core number
277
     * @param int $start Start point for the objects
278
     * @return void
279
     * @throws GuzzleException
280
     * @throws ValidationException
281
     */
282
    private function runForkedChild($class, array &$pids, int $coreNumber, int $start): void
283
    {
284
        $pid = pcntl_fork();
285
        // PID needs to be pushed before anything else, for some reason
286
        $pids[$coreNumber] = $pid;
287
        $config = DB::getConfig();
288
        DB::connect($config);
289
        $this->runChild($class, $pid, $start);
290
    }
291
292
    /**
293
     * Ren a single child index operation
294
     *
295
     * @param string $class Class to index
296
     * @param int $pid PID of the child
297
     * @param int $start Position to start
298
     * @throws GuzzleException
299
     * @throws ValidationException
300
     * @throws Exception
301
     */
302
    private function runChild($class, int $pid, int $start): void
303
    {
304
        if (!$pid) {
305
            try {
306
                $this->doReindex($start, $class, $pid);
307
            } catch (Exception $e) {
308
                SolrLogger::logMessage('ERROR', $e, $this->index->getIndexName());
309
                $msg = sprintf(
310
                    'Something went wrong while indexing %s on %s, see the logs for details',
311
                    $start,
312
                    $this->index->getIndexName()
313
                );
314
                throw new Exception($msg);
315
            }
316
        }
317
    }
318
319
    /**
320
     * Reindex the given group, for each state
321
     *
322
     * @param int $group Group to index
323
     * @param string $class Class to index
324
     * @param bool|int $pcntl Are we a child process or not
325
     * @throws Exception
326 13
     */
327
    private function doReindex($group, $class, $pcntl = false)
328 13
    {
329 13
        foreach (SiteState::getStates() as $state) {
330
            if ($state !== 'default' && !empty($state)) {
331
                SiteState::withState($state);
332 13
            }
333
            $this->stateReindex($group, $class);
334
        }
335 13
336 13
        SiteState::withState(SiteState::DEFAULT_STATE);
337
        $this->getLogger()->info(sprintf('Indexed group %s', $group));
338 13
339
        if ($pcntl !== false) {
340
            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...
341 13
        }
342
        if (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl') {
343
            throw new Exception('Catch exception for unittests');
344
        }
345
    }
346
347
    /**
348
     * Index a group of a class for a specific state and index
349
     *
350 13
     * @param string $group Group to index
351
     * @param string $class Class to index
352
     * @throws Exception
353 13
     */
354
    private function stateReindex($group, $class): void
355 13
    {
356 13
        // Generate filtered list of local records
357 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
358 13
        /** @var DataList|DataObject[] $items */
359 1
        $items = DataObject::get($baseClass)
360
            ->sort('ID ASC')
361 13
            ->limit($this->getBatchLength(), ($group * $this->getBatchLength()));
362
        if ($items->count()) {
363
            $this->updateIndex($items);
364
        }
365
    }
366
367
    /**
368
     * Execute the update on the client
369 1
     *
370
     * @param SS_List $items Items to index
371 1
     * @throws Exception
372 1
     */
373 1
    private function updateIndex($items): void
374 1
    {
375 1
        $index = $this->getIndex();
376 1
        $client = $index->getClient();
377 1
        $update = $client->createUpdate();
378
        $this->service->setInDebugMode($this->debug);
379
        $this->service->updateIndex($index, $items, $update);
380
        $client->update($update);
381
    }
382
383
    /**
384
     * Log an exception if it happens. Most are catched, these logs are for the developers
385
     * to identify problems and fix them.
386
     *
387
     * @param string $index Index that is currently running
388
     * @param int $group Group currently attempted to index
389
     * @param Exception $exception Exception that's been thrown
390
     * @throws GuzzleException
391
     * @throws ValidationException
392
     */
393
    private function logException($index, int $group, Exception $exception): void
394
    {
395
        $this->getLogger()->error($exception->getMessage());
396
        $msg = sprintf(
397
            'Error indexing core %s on group %s,' . PHP_EOL .
398
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
399
            $index,
400
            $group
401
        );
402
        SolrLogger::logMessage('ERROR', $msg, $index);
403
    }
404
}
405