Files
portal-api/app/Jobs/VirtualMachine/Sync/SyncHost.php
T

127 lines
4.2 KiB
PHP

<?php
namespace App\Jobs\VirtualMachine\Sync;
use App\Http\Services\Telegram;
use App\Http\Services\vCenter as ServiceVCenter;
use App\Models\ModuleDatacenter;
use App\Models\ModuleHost;
use App\Models\vCenter;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class SyncHost implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $vCenter = null;
protected $data = null;
protected Telegram $telegram;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
$this->data = vCenter::select('id', 'host', 'user', 'password', 'token')->get();
$this->vCenter = new ServiceVCenter;
$this->telegram = new Telegram();
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
// Initialize new services
$client = new \App\Http\Services\vCenter\Client();
$resourceService = new \App\Http\Services\vCenter\ResourceService($client);
$templateService = new \App\Http\Services\vCenter\TemplateService($client);
foreach ($this->data as $item) {
// Login via Client service
$token = $client->loginServer($item);
if (!$token) {
continue;
}
$dataCenter = ModuleDatacenter::where('vcenter_id', $item->id)
->select('id', 'datacenter_id')
->get();
foreach ($dataCenter as $_item) {
// Use ResourceService to get hosts
$host = $resourceService->getAllHost($_item['datacenter_id']);
if ($host === "Login_Again") {
$token = $client->loginServer($item);
if ($token) {
$host = $resourceService->getAllHost($_item['datacenter_id']);
}
}
if (!is_array($host)) {
continue; // Skip if still invalid or Login_Again
}
// Use TemplateService
$template = $templateService->getAllTemplate();
if ($host) {
foreach ($host as $_subItem) {
if (!ModuleHost::where('host_id', $_subItem['host'])->exists()) {
ModuleHost::create([
'name' => $_subItem['name'],
'host_id' => $_subItem['host'],
'module_datacenter_id' => $_item['id'],
'template' => $template[0] ?? null,
]);
}
}
}
}
}
// Notify success via Telegram
$this->telegram->SendJobRunInfo('SyncHost', 'Success', [
'message' => 'Sync host completed successfully',
'synced_vcenters' => $this->data->count(),
]);
} catch (\Throwable $exception) {
// Ghi log Laravel
Log::error('SyncHost Job failed', [
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
// Gửi log lỗi qua Telegram
$this->telegram->SendJobRunInfo('SyncHost', 'Failed', [
'error' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
]);
// Quăng lại lỗi để Laravel xử lý retry/failure
throw $exception;
}
}
public function failed(\Throwable $exception)
{
Log::error('SyncHost Job failed', [
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
}
}