-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathElasticsearch.php
429 lines (382 loc) · 15.8 KB
/
Elasticsearch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
<?php
/**
* Elasticsearch plugin for Craft CMS.
*
* @link https://www.lahautesociete.com
* @copyright Copyright (c) 2018 La Haute Société
*/
namespace lhs\elasticsearch;
use Craft;
use craft\base\Element;
use craft\base\Plugin;
use craft\commerce\elements\Product;
use craft\digitalproducts\elements\Product as DigitalProduct;
use craft\console\Application as ConsoleApplication;
use craft\elements\Asset;
use craft\elements\Entry;
use craft\events\ModelEvent;
use craft\events\PluginEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\events\RegisterUrlRulesEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\ElementHelper;
use craft\models\Section;
use craft\queue\Queue;
use craft\services\Plugins;
use craft\services\Utilities;
use craft\web\Application;
use craft\web\twig\variables\CraftVariable;
use craft\web\UrlManager;
use lhs\elasticsearch\exceptions\IndexElementException;
use lhs\elasticsearch\models\SettingsModel;
use lhs\elasticsearch\services\ElasticsearchService;
use lhs\elasticsearch\services\ElementIndexerService;
use lhs\elasticsearch\services\IndexManagementService;
use lhs\elasticsearch\services\ReindexQueueManagementService;
use lhs\elasticsearch\utilities\RefreshElasticsearchIndexUtility;
use lhs\elasticsearch\variables\ElasticsearchVariable;
use yii\base\Event;
use yii\debug\Module as DebugModule;
use yii\elasticsearch\Connection;
use yii\elasticsearch\DebugPanel;
use yii\elasticsearch\Exception;
use yii\queue\ExecEvent;
/**
* @property services\ElasticsearchService service
* @property services\ReindexQueueManagementService reindexQueueManagementService
* @property services\ElementIndexerService $elementIndexerService
* @property services\IndexManagementService $indexManagementService
* @property SettingsModel settings
* @property Connection elasticsearch
* @method SettingsModel getSettings()
*/
class Elasticsearch extends Plugin
{
public const EVENT_ERROR_NO_ATTACHMENT_PROCESSOR = 'errorNoAttachmentProcessor';
public const PLUGIN_HANDLE = 'elasticsearch';
public bool $hasCpSettings = true;
public function init(): void
{
parent::init();
$isCommerceEnabled = $this->isCommerceEnabled();
$isDigitalProductsEnabled = $this->isDigitalProductsEnabled();
$this->setComponents(
[
'service' => ElasticsearchService::class,
'reindexQueueManagementService' => ReindexQueueManagementService::class,
'elementIndexerService' => ElementIndexerService::class,
'indexManagementService' => IndexManagementService::class,
]
);
$this->initializeElasticConnector();
// Add console commands
if (Craft::$app instanceof ConsoleApplication) {
$this->controllerNamespace = 'lhs\elasticsearch\console\controllers';
}
$isCpRequest = Craft::$app->getRequest()->getIsCpRequest();
$isConsoleRequest = Craft::$app->getRequest()->getIsConsoleRequest();
if ($isCpRequest || $isConsoleRequest) {
// Remove entry from the index upon deletion
Event::on(
Entry::class,
Entry::EVENT_AFTER_DELETE,
function (Event $event) {
/** @var entry $entry */
$entry = $event->sender;
try {
$this->elementIndexerService->deleteElement($entry);
} catch (Exception $e) {
// Noop, the element must have already been deleted
}
}
);
// Remove asset from the index upon deletion
Event::on(
Asset::class,
Asset::EVENT_AFTER_DELETE,
function (Event $event) {
/** @var Asset $asset */
$asset = $event->sender;
try {
$this->elementIndexerService->deleteElement($asset);
} catch (Exception $e) {
// Noop, the element must have already been deleted
}
}
);
// Index entry, asset & products upon save (creation or update)
Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, [$this, 'onElementSaved']);
Event::on(Asset::class, Asset::EVENT_AFTER_SAVE, [$this, 'onElementSaved']);
if ($isCommerceEnabled) {
Event::on(Product::class, Product::EVENT_AFTER_SAVE, [$this, 'onElementSaved']);
if ($isDigitalProductsEnabled) {
Event::on(DigitalProduct::class, DigitalProduct::EVENT_AFTER_SAVE, [$this, 'onElementSaved']);
}
}
// Re-index all entries when plugin settings are saved
Event::on(
Plugins::class,
Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS,
function (PluginEvent $event) {
if ($event->plugin === $this) {
$this->onPluginSettingsSaved();
}
}
);
// On reindex job success, remove its id from the cache (cache is used to keep track of reindex jobs and clear those having failed before reindexing all entries)
Event::on(
Queue::class,
Queue::EVENT_AFTER_EXEC,
function (ExecEvent $event) {
$this->reindexQueueManagementService->removeJob($event->id);
}
);
// Register the plugin's CP utility
Event::on(
Utilities::class,
Utilities::EVENT_REGISTER_UTILITIES,
function (RegisterComponentTypesEvent $event) {
$event->types[] = RefreshElasticsearchIndexUtility::class;
}
);
// Register our CP routes
Event::on(
UrlManager::class,
UrlManager::EVENT_REGISTER_CP_URL_RULES,
function (RegisterUrlRulesEvent $event) {
$event->rules['elasticsearch/cp/test-connection'] = 'elasticsearch/cp/test-connection';
$event->rules['elasticsearch/cp/reindex-perform-action'] = 'elasticsearch/cp/reindex-perform-action';
}
);
// Display a flash message if the ingest attachment plugin isn't activated on the Elasticsearch instance
Event::on(
self::class,
self::EVENT_ERROR_NO_ATTACHMENT_PROCESSOR,
function () {
$application = Craft::$app;
if ($application instanceof \yii\web\Application) {
$application->getSession()->setError('The ingest-attachment plugin seems to be missing on your Elasticsearch instance.');
}
}
);
}
// Add the Elasticsearch panel to the Yii debug bar
Event::on(
Application::class,
Application::EVENT_BEFORE_REQUEST,
function () {
/** @var DebugModule|null $debugModule */
$debugModule = Craft::$app->getModule('debug');
if ($debugModule) {
$debugModule->panels['elasticsearch'] = new DebugPanel(
[
'id' => 'elasticsearch',
'module' => $debugModule,
]
);
}
}
);
// Register variables
Event::on(
CraftVariable::class,
CraftVariable::EVENT_INIT,
function (Event $event) {
/** @var CraftVariable $variable */
$variable = $event->sender;
$variable->set('elasticsearch', ElasticsearchVariable::class);
}
);
// Register our site routes (used by the console commands to reindex entries)
Event::on(
UrlManager::class,
UrlManager::EVENT_REGISTER_SITE_URL_RULES,
function (RegisterUrlRulesEvent $event) {
$event->rules['elasticsearch/get-all-elements'] = 'elasticsearch/site/get-all-elements';
$event->rules['elasticsearch/reindex-all'] = 'elasticsearch/site/reindex-all';
$event->rules['elasticsearch/reindex-element'] = 'elasticsearch/site/reindex-element';
}
);
Craft::info("{$this->name} plugin loaded", __METHOD__);
}
/**
* Creates and returns the model used to store the plugin’s settings.
*
* @return SettingsModel
*/
protected function createSettingsModel(): SettingsModel
{
return new SettingsModel();
}
/**
* Returns the rendered settings HTML, which will be inserted into the content
* block on the settings page.
*
* @return string The rendered settings HTML
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
* @throws \yii\base\Exception
*/
protected function settingsHtml(): string
{
// Get and pre-validate the settings
$settings = $this->getSettings();
//$settings->validate();
// Get the settings that are being defined by the config file
$overrides = Craft::$app->getConfig()->getConfigFromFile(strtolower($this->handle));
$sections = ArrayHelper::map(
Craft::$app->getEntries()->getAllSections(),
'id',
function (Section $section): array {
return [
'label' => Craft::t('site', $section->name),
'types' => ArrayHelper::map(
$section->getEntryTypes(),
'id',
function ($section): array {
return ['label' => Craft::t('site', $section->name)];
}
),
];
}
);
return Craft::$app->view->renderTemplate(
'elasticsearch/cp/settings',
[
'settings' => $settings,
'overrides' => array_keys($overrides),
'sections' => $sections,
]
);
}
public function beforeSaveSettings(): bool
{
$settings = $this->getSettings();
$settings->elasticsearchComponentConfig = null;
return parent::beforeSaveSettings();
}
/**
* @return Connection
* @throws \yii\base\InvalidConfigException
*/
public static function getConnection(): Connection
{
/** @noinspection PhpUnhandledExceptionInspection */
/** @var Connection $connection */
$connection = Craft::$app->get(self::PLUGIN_HANDLE);
return $connection;
}
/**
* Initialize the Elasticsearch connector
* @param SettingsModel|null $settings
* @throws \yii\base\InvalidConfigException If the configuration passed to the yii2-elasticsearch module is invalid
*/
public function initializeElasticConnector($settings = null): void
{
if ($settings === null) {
$settings = $this->getSettings();
}
if ($settings->elasticsearchComponentConfig !== null) {
$definition = $settings->elasticsearchComponentConfig;
} else {
$protocol = parse_url($settings->elasticsearchEndpoint, PHP_URL_SCHEME);
$endpointUrlWithoutProtocol = preg_replace("#^$protocol(?:://)?#", '', $settings->elasticsearchEndpoint);
$definition = [
'connectionTimeout' => 10,
'autodetectCluster' => false,
'nodes' => [
[
'protocol' => $protocol ?? 'http',
'http_address' => $endpointUrlWithoutProtocol,
'http' => ['publish_address' => $settings->elasticsearchEndpoint],
],
],
];
if ($settings->isAuthEnabled) {
$definition['auth'] = [
'username' => $settings->username,
'password' => $settings->password,
];
}
}
$definition['class'] = Connection::class;
// Fix nodes. When cluster auto detection is disabled, the Elasticsearch component crashes when closing connections…
array_walk(
$definition['nodes'],
static function (&$node) {
if (!isset($node['http'])) {
$node['http'] = [];
}
if (!isset($node['http']['publish_address'])) {
$node['http']['publish_address'] = sprintf(
'%s://%s',
$node['protocol'] ?? 'http',
$node['http_address']
);
}
}
);
/** @noinspection PhpUnhandledExceptionInspection Can't happen since a valid config array is passed */
Craft::$app->set(self::PLUGIN_HANDLE, $definition);
}
/**
* Check for presence of Craft Commerce Plugin
* @return bool
*/
public function isCommerceEnabled(): bool
{
return class_exists(\craft\commerce\Plugin::class);
}
/**
* Check for presence of Craft Digital Products Plugin
* @return bool
*/
public function isDigitalProductsEnabled(): bool
{
return class_exists(\craft\digitalproducts\Plugin::class);
}
/**
* @param ModelEvent $event
*/
public function onElementSaved(ModelEvent $event): void
{
/** @var Element $element */
$element = $event->sender;
// Handle drafts and revisions for Craft 3.2 and upper
$notDraftOrRevision = true;
$schemaVersion = Craft::$app->getInstalledSchemaVersion();
if (version_compare($schemaVersion, '3.2.0', '>=')) {
$notDraftOrRevision = !ElementHelper::isDraftOrRevision($element);
}
if ($notDraftOrRevision) {
if ($element->enabled && $element->getEnabledForSite()) {
// Only index entry items with an uri. This prevents jobs being spawned for Matrix entries in Craft 5.
if (! $element instanceof Entry || $element->uri) {
$this->reindexQueueManagementService->enqueueJob($element->id, $element->siteId, get_class($element));
}
} else {
try {
$this->elementIndexerService->deleteElement($element);
} catch (Exception $e) {
// Noop, the element must have already been deleted
}
}
}
}
protected function onPluginSettingsSaved(): void
{
/** @noinspection PhpUnhandledExceptionInspection If there was an error in the configuration, it would have prevented validation */
$this->initializeElasticConnector(); //FIXME: Check if this is needed
Craft::debug('Elasticsearch plugin settings saved => re-index all elements', __METHOD__);
try {
$this->indexManagementService->recreateIndexesForAllSites();
// Remove previous reindexing jobs as all elements will be reindexed anyway
$this->reindexQueueManagementService->clearJobs();
$this->reindexQueueManagementService->enqueueReindexJobs($this->service->getIndexableElementModels());
} catch (IndexElementException $e) {
/** @noinspection PhpUnhandledExceptionInspection This method should only be called in a web context so Craft::$app->getSession() will never throw */
Craft::$app->getSession()->setError($e->getMessage());
}
}
}