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