Passed
Push — bufferfix ( 742639...c9e99b )
by Simon
05:38
created

SolrIndexTask::spawnChildren()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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