106 lines
3.1 KiB
PHP
106 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs\VirtualMachine\Snapshot;
|
|
|
|
use App\Events\NotificationStatus;
|
|
use App\Http\Services\Telegram;
|
|
use App\Http\Services\vCenter as ServiceVCenter;
|
|
use App\Models\ModuleSnapshot;
|
|
use App\Models\ModuleSnapshotLimit;
|
|
use App\Models\ModuleVmware;
|
|
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 CreateSnapshot implements ShouldQueue
|
|
{
|
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
|
public function __construct(
|
|
public int $snapshotId
|
|
) {}
|
|
|
|
public function handle(ServiceVCenter $serviceVCenter)
|
|
{
|
|
$snapshot = ModuleSnapshot::with('vm.ipAddress.host.datacenter.vCenter')
|
|
->find($this->snapshotId);
|
|
|
|
if (!$snapshot) {
|
|
return;
|
|
}
|
|
|
|
$snapshot->update(['status' => 'processing']);
|
|
|
|
$product = $snapshot->vm;
|
|
$vcenter = $product->ipAddress->host->datacenter->vCenter;
|
|
|
|
try {
|
|
// Config vCenter
|
|
$serviceVCenter->token = $vcenter->token;
|
|
$serviceVCenter->apiUri = $vcenter->host;
|
|
|
|
// Call vCenter
|
|
$result = $serviceVCenter->CreateSnapShot($product);
|
|
|
|
if ($result === 'Login_Again') {
|
|
$token = $serviceVCenter->loginServer($vcenter);
|
|
if (!$token) {
|
|
throw new \Exception('Không thể login lại vCenter');
|
|
}
|
|
|
|
$vcenter->update(['token' => $token]);
|
|
$serviceVCenter->token = $token;
|
|
$result = $serviceVCenter->CreateSnapShot($product);
|
|
}
|
|
|
|
if (is_array($result) && ($result['error'] ?? false)) {
|
|
throw new \Exception($result['message'] ?? 'Lỗi tạo snapshot');
|
|
}
|
|
|
|
// Update DB SUCCESS
|
|
$snapshot->update([
|
|
'name' => $result['name'] ?? $snapshot->name,
|
|
'status' => 'success',
|
|
'snapshot_ref' => $result['snapshot_id'] ?? null,
|
|
'vcenter_task_id' => $result['task_id'] ?? null,
|
|
]);
|
|
|
|
// Increment quota CHỈ khi success
|
|
ModuleSnapshotLimit::where('customer_id', $snapshot->customer_id)
|
|
->increment('used');
|
|
|
|
event(new NotificationStatus(
|
|
"Snapshot {$snapshot->name} tạo thành công",
|
|
true
|
|
));
|
|
} catch (\Throwable $e) {
|
|
$snapshot->update([
|
|
'status' => 'failed',
|
|
'error_message' => $e->getMessage(),
|
|
]);
|
|
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
public function failed(\Throwable $exception)
|
|
{
|
|
$snapshot = ModuleSnapshot::find($this->snapshotId);
|
|
|
|
if ($snapshot) {
|
|
$snapshot->update([
|
|
'status' => 'failed',
|
|
'error_message' => $exception->getMessage(),
|
|
]);
|
|
}
|
|
|
|
event(new NotificationStatus(
|
|
"Snapshot thất bại: {$exception->getMessage()}",
|
|
false
|
|
));
|
|
}
|
|
}
|