Passed
Push — hans/Index-all-fluent-options ( 21739c...402069 )
by Simon
06:23
created

SolrIndexTask::setDebug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 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 GuzzleHttp\Exception\GuzzleException;
14
use Psr\Log\LoggerInterface;
15
use ReflectionException;
16
use SilverStripe\Control\Director;
17
use SilverStripe\Control\HTTPRequest;
18
use SilverStripe\Core\Injector\Injector;
19
use SilverStripe\Dev\BuildTask;
20
use SilverStripe\ORM\ArrayList;
21
use SilverStripe\ORM\DataList;
22
use SilverStripe\ORM\DataObject;
23
use SilverStripe\ORM\ValidationException;
24
use SilverStripe\Versioned\Versioned;
25
26
/**
27
 * Class SolrIndexTask
28
 *
29
 * @description Index items to Solr through a tasks
30
 * @package Firesphere\SolrSearch\Tasks
31
 */
32
class SolrIndexTask extends BuildTask
33
{
34
    use LoggerTrait;
35
    /**
36
     * @var string
37
     */
38
    private static $segment = 'SolrIndexTask';
39
    /**
40
     * @var array Store the current states for all instances of SiteState
41
     */
42
    public $currentStates;
43
    /**
44
     * @var string
45
     */
46
    protected $title = 'Solr Index update';
47
    /**
48
     * @var string
49
     */
50
    protected $description = 'Add or update documents to an existing Solr core.';
51
    /**
52
     * @var bool
53
     */
54
    protected $debug = false;
55
    /**
56
     * @var SolrCoreService
57
     */
58
    protected $service;
59
60
    /**
61
     * SolrIndexTask constructor. Sets up the document factory
62
     *
63
     * @throws ReflectionException
64
     */
65 12
    public function __construct()
66
    {
67 12
        parent::__construct();
68
        // Only index live items.
69
        // The old FTS module also indexed Draft items. This is unnecessary
70 12
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
71 12
        $this->setService(Injector::inst()->get(SolrCoreService::class));
72 12
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
73 12
        $this->setDebug(Director::isDev() || Director::is_cli());
74 12
        $this->currentStates = SiteState::currentStates();
75 12
    }
76
77
    /**
78
     * @param SolrCoreService $service
79
     * @return SolrIndexTask
80
     */
81 12
    public function setService(SolrCoreService $service): SolrIndexTask
82
    {
83 12
        $this->service = $service;
84
85 12
        return $this;
86
    }
87
88
    /**
89
     * @param bool $debug
90
     * @return SolrIndexTask
91
     */
92 12
    public function setDebug(bool $debug): SolrIndexTask
93
    {
94 12
        $this->debug = $debug;
95
96 12
        return $this;
97
    }
98
99
    /**
100
     * Implement this method in the task subclass to
101
     * execute via the TaskRunner
102
     *
103
     * @param HTTPRequest $request
104
     * @return int|bool
105
     * @throws Exception
106
     * @throws GuzzleException
107
     * @todo defer to background because it may run out of memory
108
     */
109 11
    public function run($request)
110
    {
111 11
        $startTime = time();
112 11
        [$vars, $group, $isGroup] = $this->taskSetup($request);
113 11
        $groups = 0;
114 11
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
115
116 11
        foreach ($indexes as $indexName) {
117
            /** @var BaseIndex $index */
118 11
            $index = Injector::inst()->get($indexName, false);
119
120 11
            $indexClasses = $index->getClasses();
121 11
            $classes = $this->getClasses($vars, $indexClasses);
122 11
            if (!count($classes)) {
123 8
                continue;
124
            }
125
126 11
            $this->clearIndex($vars, $index);
127
128 11
            $groups = $this->indexClassForIndex($classes, $isGroup, $index, $group);
129
        }
130 11
        $this->getLogger()->info(
131 11
            sprintf('It took me %d seconds to do all the indexing%s', (time() - $startTime), PHP_EOL)
132
        );
133
        // Grab the latest logs from indexing if needed
134 11
        $solrLogger = new SolrLogger();
135 11
        $solrLogger->saveSolrLog('Config');
136
137 11
        return $groups;
138
    }
139
140
    /**
141
     * @param HTTPRequest $request
142
     * @return array
143
     */
144 11
    protected function taskSetup($request): array
145
    {
146 11
        $vars = $request->getVars();
147 11
        $this->debug = $this->debug || isset($vars['debug']);
148 11
        $group = $vars['group'] ?? 0;
149 11
        $start = $vars['start'] ?? 0;
150 11
        $group = ($start > $group) ? $start : $group;
151 11
        $isGroup = isset($vars['group']);
152
153 11
        return [$vars, $group, $isGroup];
154
    }
155
156
    /**
157
     * @param $vars
158
     * @param array $classes
159
     * @return bool|array
160
     */
161 11
    protected function getClasses($vars, array $classes): array
162
    {
163 11
        if (isset($vars['class'])) {
164 1
            return array_intersect($classes, [$vars['class']]);
165
        }
166
167 10
        return $classes;
168
    }
169
170
    /**
171
     * Clear the given index if a full re-index is needed
172
     *
173
     * @param $vars
174
     * @param BaseIndex $index
175
     * @throws Exception
176
     */
177 11
    public function clearIndex($vars, BaseIndex $index)
178
    {
179 11
        if (!empty($vars['clear'])) {
180 1
            $this->getLogger()->info(sprintf('Clearing index %s', $index->getIndexName()));
181 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $index);
182
        }
183 11
    }
184
185
    /**
186
     * @param $classes
187
     * @param $isGroup
188
     * @param BaseIndex $index
189
     * @param $group
190
     * @return int
191
     * @throws Exception
192
     * @throws GuzzleException
193
     */
194 11
    protected function indexClassForIndex($classes, $isGroup, BaseIndex $index, $group): int
195
    {
196 11
        $groups = 0;
197 11
        foreach ($classes as $class) {
198 11
            $groups = $this->indexClass($isGroup, $class, $index, $group);
199
        }
200
201 11
        return $groups;
202
    }
203
204
    /**
205
     * @param bool $isGroup
206
     * @param string $class
207
     * @param BaseIndex $index
208
     * @param int $group
209
     * @return int
210
     * @throws GuzzleException
211
     * @throws ValidationException
212
     */
213 11
    private function indexClass($isGroup, $class, BaseIndex $index, int $group): int
214
    {
215 11
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $index->getIndexName()), []);
216
217 11
        $batchLength = DocumentFactory::config()->get('batchLength');
218 11
        $groups = (int)ceil($class::get()->count() / $batchLength);
219 11
        $groups = $isGroup ? $group : $groups;
220 11
        while ($group <= $groups) { // Run from oldest to newest
221
            try {
222 11
                $this->doReindex($group, $class, $batchLength, $index);
223
            } catch (Exception $error) {
224
                $this->logException($index->getIndexName(), $group, $error);
225
                $group++;
226
                continue;
227
            }
228 11
            $group++;
229 11
            $this->getLogger()->info(sprintf('Indexed group %s', $group));
230
        }
231
232 11
        return $groups;
233
    }
234
235
    /**
236
     * Reindex the given group, for each state
237
     *
238
     * @param int $group
239
     * @param string $class
240
     * @param int $batchLength
241
     * @param BaseIndex $index
242
     * @throws Exception
243
     */
244 11
    private function doReindex($group, $class, $batchLength, BaseIndex $index): void
245
    {
246 11
        foreach (SiteState::getStates() as $state) {
247 11
            if ($state !== 'default') {
248
                SiteState::withState($state);
249
            }
250 11
            $this->stateReindex($group, $class, $batchLength, $index);
251
        }
252
253
        // Reset the variants back to it's original state for the next round
254 11
        foreach ($this->currentStates as $variant => $value) {
255 10
            singleton($variant)->activateState($value);
256
        }
257 11
    }
258
259
    /**
260
     * @param $group
261
     * @param $class
262
     * @param $batchLength
263
     * @param BaseIndex $index
264
     * @throws Exception
265
     */
266 11
    private function stateReindex($group, $class, $batchLength, BaseIndex $index): void
267
    {
268
        // Generate filtered list of local records
269 11
        $baseClass = DataObject::getSchema()->baseDataClass($class);
270
        /** @var DataList|DataObject[] $items */
271 11
        $items = DataObject::get($baseClass)
272 11
            ->sort('ID ASC')
273 11
            ->limit($batchLength, ($group * $batchLength));
274 11
        if ($items->count()) {
275 1
            $this->updateIndex($index, $items);
276
        }
277 11
    }
278
279
    /**
280
     * Execute the update on the client
281
     *
282
     * @param BaseIndex $index
283
     * @param $items
284
     * @throws Exception
285
     */
286 1
    private function updateIndex(BaseIndex $index, $items): void
287
    {
288 1
        $client = $index->getClient();
289 1
        $update = $client->createUpdate();
290 1
        $this->service->setInDebugMode($this->debug);
291 1
        $this->service->updateIndex($index, $items, $update);
292 1
        $update->addCommit();
293 1
        $client->update($update);
294 1
    }
295
296
    /**
297
     * @param string $index
298
     * @param int $group
299
     * @param Exception $exception
300
     * @throws GuzzleException
301
     * @throws ValidationException
302
     */
303
    private function logException($index, int $group, Exception $exception): void
304
    {
305
        $this->getLogger()->error($exception->getMessage());
306
        $msg = sprintf(
307
            'Error indexing core %s on group %s,' . PHP_EOL .
308
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
309
            $index,
310
            $group
311
        );
312
        SolrLogger::logMessage('ERROR', $msg, $index);
313
    }
314
}
315