Passed
Push — hans/include-sub-classes ( 25fdcc )
by Simon
08:14
created

SolrIndexTask::taskSetup()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 10
rs 10
cc 3
nc 4
nop 1
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
    public function __construct()
71
    {
72
        parent::__construct();
73
        // Only index live items.
74
        // The old FTS module also indexed Draft items. This is unnecessary
75
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
76
        // If versioned is needed, a separate Versioned Search module is required
77
        $this->setService(Injector::inst()->get(SolrCoreService::class));
78
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
79
        $this->setDebug(Director::isDev() || Director::is_cli());
80
        $this->setBatchLength(DocumentFactory::config()->get('batchLength'));
81
        $cores = SolrCoreService::config()->get('cpucores') ?: 1;
82
        $this->setCores($cores);
83
        $currentStates = SiteState::currentStates();
84
        SiteState::setDefaultStates($currentStates);
85
    }
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
    public function run($request)
97
    {
98
        $start = time();
99
        $this->getLogger()->info(date('Y-m-d H:i:s'));
100
        list($vars, $group, $isGroup) = $this->taskSetup($request);
101
        $groups = 0;
102
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
103
104
        foreach ($indexes as $indexName) {
105
            /** @var BaseIndex $index */
106
            $index = Injector::inst()->get($indexName, false);
107
            $this->setIndex($index);
108
109
            $indexClasses = $this->index->getClasses();
110
111
            $indexClasses = $this->getClassNames($indexClasses);
112
            $classes = $this->getClasses($vars, $indexClasses);
113
            if (!count($classes)) {
114
                continue;
115
            }
116
117
            $this->clearIndex($vars);
118
119
            $groups = $this->indexClassForIndex($classes, $isGroup, $group);
120
        }
121
122
        $this->getLogger()->info(date('Y-m-d H:i:s'));
123
        $this->getLogger()->info(sprintf('Time taken: %s minutes', (time() - $start) / 60));
124
125
        return $groups;
126
    }
127
128
    /**
129
     * Get the actual classes to index, to avoid array-to-string issues etc.
130
     * @param array $classes
131
     * @return array
132
     */
133
    protected function getClassNames($classes)
134
    {
135
        $return = [];
136
        foreach ($classes as $i => $classOptions) {
137
            if (is_array($classOptions)) {
138
                $return[] = array_key_first($classes[$i]);
139
            } else {
140
                $return[] = $classOptions;
141
            }
142
        }
143
144
        return $return;
145
    }
146
147
    /**
148
     * Set up the requirements for this task
149
     *
150
     * @param HTTPRequest $request Current request
151
     * @return array
152
     */
153
    protected function taskSetup($request): array
154
    {
155
        $vars = $request->getVars();
156
        $this->debug = $this->debug || isset($vars['debug']);
157
        $group = $vars['group'] ?? 0;
158
        $start = $vars['start'] ?? 0;
159
        $group = ($start > $group) ? $start : $group;
160
        $isGroup = isset($vars['group']);
161
162
        return [$vars, $group, $isGroup];
163
    }
164
165
    /**
166
     * get the classes to run for this task execution
167
     *
168
     * @param array $vars URL GET Parameters
169
     * @param array $classes Classes to index
170
     * @return bool|array
171
     */
172
    protected function getClasses($vars, array $classes): array
173
    {
174
        if (isset($vars['class'])) {
175
            return array_intersect($classes, [$vars['class']]);
176
        }
177
178
        return $classes;
179
    }
180
181
    /**
182
     * Clear the given index if a full re-index is needed
183
     *
184
     * @param array $vars URL GET Parameters
185
     * @throws Exception
186
     */
187
    public function clearIndex($vars)
188
    {
189
        if (!empty($vars['clear'])) {
190
            $this->getLogger()->info(sprintf('Clearing index %s', $this->index->getIndexName()));
191
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $this->index);
192
        }
193
    }
194
195
    /**
196
     * Index the classes for a specific index
197
     *
198
     * @param array $classes Classes that need indexing
199
     * @param bool $isGroup Indexing a specific group?
200
     * @param int $group Group to index
201
     * @return int
202
     * @throws Exception
203
     * @throws GuzzleException
204
     */
205
    protected function indexClassForIndex($classes, $isGroup, $group): int
206
    {
207
        $groups = 0;
208
        foreach ($classes as $class) {
209
            $groups = $this->indexClass($isGroup, $class, $group);
210
        }
211
212
        return $groups;
213
    }
214
215
    /**
216
     * Index a single class for a given index. {@link static::indexClassForIndex()}
217
     *
218
     * @param bool $isGroup Is a specific group indexed
219
     * @param string $class Class to index
220
     * @param int $group Group to index
221
     * @return int
222
     * @throws GuzzleException
223
     * @throws ValidationException
224
     */
225
    private function indexClass($isGroup, $class, int $group): int
226
    {
227
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $this->getIndex()->getIndexName()));
228
        list($totalGroups, $groups) = $this->getGroupSettings($isGroup, $class, $group);
229
        $this->getLogger()->info(sprintf('Total groups %s', $totalGroups));
230
        do { // Run from oldest to newest
231
            try {
232
                // The unittest param is from phpunit.xml.dist, meant to bypass the exit(0) call
233
                // The pcntl check is for unit tests, but CircleCI does not support PCNTL (yet)
234
                // @todo fix CircleCI to support PCNTL
235
                if ($this->hasPCNTL()) {
236
                    $group = $this->spawnChildren($class, $group, $groups);
237
                } else {
238
                    $this->doReindex($group, $class);
239
                }
240
                $group++;
241
            } catch (Exception $error) {
242
                $this->logException($this->index->getIndexName(), $group, $error);
243
                $group++;
244
                continue;
245
            }
246
        } while ($group <= $groups);
247
248
        return $totalGroups;
249
    }
250
251
    /**
252
     * Check the amount of groups and the total against the isGroup check.
253
     *
254
     * @param bool $isGroup Is it a specific group
255
     * @param string $class Class to check
256
     * @param int $group Current group to index
257
     * @return array
258
     */
259
    private function getGroupSettings($isGroup, $class, int $group): array
260
    {
261
        $totalGroups = (int)ceil($class::get()->count() / $this->getBatchLength());
262
        $groups = $isGroup ? ($group + $this->getCores() - 1) : $totalGroups;
263
264
        return [$totalGroups, $groups];
265
    }
266
267
    private function hasPCNTL()
268
    {
269
        return (function_exists('pcntl_fork') &&
270
            Director::is_cli() &&
271
            (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl' ||
272
                !Controller::curr()->getRequest()->getVar('unittest'))
273
        );
274
    }
275
276
    /**
277
     * For each core, spawn a child process that will handle a separate group.
278
     * This speeds up indexing through CLI massively.
279
     *
280
     * @param string $class Class to index
281
     * @param int $group Group to index
282
     * @param int $groups Total amount of groups
283
     * @return int Last group indexed
284
     * @throws Exception
285
     * @throws GuzzleException
286
     */
287
    private function spawnChildren($class, int $group, int $groups): int
288
    {
289
        $start = $group;
290
        $pids = [];
291
        $cores = $this->getCores();
292
        // for each core, start a grouped indexing
293
        for ($i = 0; $i < $cores; $i++) {
294
            $start = $group + $i;
295
            if ($start < $groups) {
296
                $this->runForkedChild($class, $pids, $i, $start);
297
            }
298
        }
299
        // Wait for each child to finish
300
        foreach ($pids as $key => $pid) {
301
            pcntl_waitpid($pid, $status);
302
            if ($status === 0) {
303
                unset($pids[$key]);
304
            }
305
        }
306
        $commit = $this->index->getClient()->createUpdate();
307
        $commit->addCommit();
308
309
        $this->index->getClient()->update($commit);
310
311
        return $start;
312
    }
313
314
    /**
315
     * Create a fork and run the child
316
     *
317
     * @param string $class Class to index
318
     * @param array $pids Array of all the child Process IDs
319
     * @param int $coreNumber Core number
320
     * @param int $start Start point for the objects
321
     * @return void
322
     * @throws GuzzleException
323
     * @throws ValidationException
324
     */
325
    private function runForkedChild($class, array &$pids, int $coreNumber, int $start): void
326
    {
327
        $pid = pcntl_fork();
328
        // PID needs to be pushed before anything else, for some reason
329
        $pids[$coreNumber] = $pid;
330
        $config = DB::getConfig();
331
        DB::connect($config);
332
        $this->runChild($class, $pid, $start);
333
    }
334
335
    /**
336
     * Ren a single child index operation
337
     *
338
     * @param string $class Class to index
339
     * @param int $pid PID of the child
340
     * @param int $start Position to start
341
     * @throws GuzzleException
342
     * @throws ValidationException
343
     * @throws Exception
344
     */
345
    private function runChild($class, int $pid, int $start): void
346
    {
347
        if (!$pid) {
348
            try {
349
                $this->doReindex($start, $class, $pid);
350
            } catch (Exception $e) {
351
                SolrLogger::logMessage('ERROR', $e, $this->index->getIndexName());
352
                $msg = sprintf(
353
                    'Something went wrong while indexing %s on %s, see the logs for details',
354
                    $start,
355
                    $this->index->getIndexName()
356
                );
357
                throw new Exception($msg);
358
            }
359
        }
360
    }
361
362
    /**
363
     * Reindex the given group, for each state
364
     *
365
     * @param int $group Group to index
366
     * @param string $class Class to index
367
     * @param bool|int $pcntl Are we a child process or not
368
     * @throws Exception
369
     */
370
    private function doReindex($group, $class, $pcntl = false)
371
    {
372
        foreach (SiteState::getStates() as $state) {
373
            if ($state !== 'default' && !empty($state)) {
374
                SiteState::withState($state);
375
            }
376
            $this->stateReindex($group, $class);
377
        }
378
379
        SiteState::withState(SiteState::DEFAULT_STATE);
380
        $this->getLogger()->info(sprintf('Indexed group %s', $group));
381
382
        if (Controller::curr()->getRequest()->getVar('unittest') === 'pcntl') {
383
            throw new Exception('Catch exception for unittests');
384
        } elseif ($pcntl !== false) {
385
            exit(0);
386
        }
387
    }
388
389
    /**
390
     * Index a group of a class for a specific state and index
391
     *
392
     * @param string $group Group to index
393
     * @param string|array $class Class to index
394
     * @throws Exception
395
     */
396
    private function stateReindex($group, $class): void
397
    {
398
        // Generate filtered list of local records
399
        $baseClass = DataObject::getSchema()->baseDataClass($class);
0 ignored issues
show
Bug introduced by
It seems like $class can also be of type array; however, parameter $class of SilverStripe\ORM\DataObjectSchema::baseDataClass() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

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

399
        $baseClass = DataObject::getSchema()->baseDataClass(/** @scrutinizer ignore-type */ $class);
Loading history...
400
        /** @var DataList|DataObject[] $items */
401
        $items = DataObject::get($baseClass)
402
            ->sort('ID ASC')
403
            ->limit($this->getBatchLength(), ($group * $this->getBatchLength()));
404
        $classes = $this->getIndex()->getClasses();
405
        $baseIndexKey = array_search($classes, $class);
0 ignored issues
show
Bug introduced by
It seems like $class can also be of type string; however, parameter $haystack of array_search() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

405
        $baseIndexKey = array_search($classes, /** @scrutinizer ignore-type */ $class);
Loading history...
406
        if (!empty($baseClass[$baseIndexKey][$class]['includeSubClasses']) &&
407
            (bool)$baseClass[$baseIndexKey][$class]['includeSubClasses'] === true
408
        ) {
409
            $items = $items->filter(['Classname' => $class]);
410
        }
411
        if ($items->count()) {
412
            $this->updateIndex($items);
413
        }
414
    }
415
416
    /**
417
     * Execute the update on the client
418
     *
419
     * @param SS_List $items Items to index
420
     * @throws Exception
421
     */
422
    private function updateIndex($items): void
423
    {
424
        $index = $this->getIndex();
425
        $client = $index->getClient();
426
        $update = $client->createUpdate();
427
        $this->service->setInDebugMode($this->debug);
428
        $this->service->updateIndex($index, $items, $update);
429
        $client->update($update);
430
    }
431
432
    /**
433
     * Log an exception if it happens. Most are catched, these logs are for the developers
434
     * to identify problems and fix them.
435
     *
436
     * @param string $index Index that is currently running
437
     * @param int $group Group currently attempted to index
438
     * @param Exception $exception Exception that's been thrown
439
     * @throws GuzzleException
440
     * @throws ValidationException
441
     */
442
    private function logException($index, int $group, Exception $exception): void
443
    {
444
        $this->getLogger()->error($exception->getMessage());
445
        $msg = sprintf(
446
            'Error indexing core %s on group %s,' . PHP_EOL .
447
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
448
            $index,
449
            $group
450
        );
451
        SolrLogger::logMessage('ERROR', $msg, $index);
452
    }
453
}
454