Passed
Push — hans/code-cleanup ( 5c0327...1f65bb )
by Simon
07:51 queued 05:57
created

SolrIndexTask::indexClass()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.9157

Importance

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