Passed
Push — hans/logtests ( 76c086...71695d )
by Simon
06:24 queued 02:27
created

SolrIndexTask::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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