Passed
Push — feature/Logging ( f3941b...f314df )
by Simon
06:52
created

SolrIndexTask::logException()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

269
                'Index' => 'x:' . /** @scrutinizer ignore-type */ $index,
Loading history...
270
                'Level' => 'ERROR'
271
            ])
272
            ->sort('Created ASC')
273
            ->first();
274
        Debug::dump(sprintf(
275
            "Error loading core %s on group %s,\n" .
276
            "Please log in to the CMS to find out more about Configuration errors\n" .
277
            'Last known error: %s',
278
            $index,
0 ignored issues
show
Bug introduced by
$index of type Firesphere\SolrSearch\Indexes\BaseIndex is incompatible with the type string expected by parameter $args of sprintf(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

278
            /** @scrutinizer ignore-type */ $index,
Loading history...
279
            $group,
280
            ($lastError === null) ? 'Unknown' : $lastError->getLastErrorLine()
281
        ));
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return integer. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
282
    }
283
}
284