Passed
Push — hans/Index-all-fluent-options ( 3d582f...073a27 )
by Simon
08:46 queued 06:50
created

SolrIndexTask::updateIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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