File: /var/www/limestate-admin/app/Console/Commands/ElasticIndexCheck.php
<?php
namespace App\Console\Commands;
use App\Services\ElasticIndexService;
use Elastic\Elasticsearch\ClientBuilder;
use Illuminate\Console\Command;
use Symfony\Component\Console\Command\Command as CommandAlias;
use Throwable;
class ElasticIndexCheck extends Command
{
protected $signature = 'elastic:index-check';
protected $description = 'Пересчитываем индекс Elastic если он очистился';
private array $indexNotExists = [];
private function needReindex($indicesData): bool
{
$needReindex = false;
$indexNotExists = [ElasticIndexService::INDEX_COMPLEXES, ElasticIndexService::INDEX_SECOND, ElasticIndexService::INDEX_FLATS];
if (empty($indicesData)) {
$this->warn('Индексов нет');
$needReindex = true;
} else {
$this->info('Проверяем индексы');
foreach ($indicesData as $row) {
$this->line('Проверяем ' . $row->index);
if (!in_array($row->index, $indexNotExists)) {
$this->line('этот индекс нас не интересует');
continue;
}
if ($row->health !== 'green' || $row->{'docs.count'} < 1) {
$this->warn('Индекс ' . $row->index . ' не прошел проверку');
$needReindex = true;
continue;
}
$this->indexNotExists = array_diff($indexNotExists, [$row->index]);
}
}
return $needReindex;
}
public function handle(ElasticIndexService $service): int
{
$this->info($this->description);
$host = config('elastic.host');
try {
$params = ['hosts' => [$host], 'retries' => 2];
$client = ClientBuilder::fromConfig($params, true);
$res = $client->cat()->indices(['format' => 'json']);
if (200 !== $res->getStatusCode()) {
$this->error('Elasticsearch ответил ошибкой: ' . $res->getStatusCode());
return CommandAlias::FAILURE;
}
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return CommandAlias::FAILURE;
}
$indicesData = json_decode($res);
$needReindex = $this->needReindex($indicesData);
$this->newLine();
if ($needReindex || !empty($this->indexNotExists)) {
$this->warn('Запускаем пересчёт');
try {
$service->setIsCli();
$service->complexes();
$service->second();
$service->flats();
} catch (Throwable $exception) {
$this->error($exception->getMessage());
$this->error($exception->getTraceAsString());
return CommandAlias::FAILURE;
}
} else {
$this->info('С индексами всё в порядке');
}
return CommandAlias::SUCCESS;
}
}