Passed
Push — hans/cow-is-animal ( cb2f8e...10edfb )
by Simon
06:23 queued 03:17
created

SolrIndexTask   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 366
Duplicated Lines 0 %

Test Coverage

Coverage 72%

Importance

Changes 41
Bugs 4 Features 0
Metric Value
eloc 118
dl 0
loc 366
ccs 90
cts 125
cp 0.72
rs 9.36
c 41
b 4
f 0
wmc 38

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