Update source into github

This commit is contained in:
pbao9
2025-07-24 16:18:27 +07:00
parent 41419358dd
commit 69851ac7bc
2642 changed files with 284095 additions and 0 deletions
@@ -0,0 +1,54 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class CheckIPAddress implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
protected array $info;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$virtual_info,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
$this->info = $virtual_info;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$DetailVirtualMachine = $this->serviceVCenter->GetIPAddressVirtualMachine($this->vmware_id);
if ($DetailVirtualMachine['error']) {
throw new \Exception(json_encode($DetailVirtualMachine['message']));
}
if (!$DetailVirtualMachine['data']['ip_address'] === $this->data->IpAddress->ip) {
throw new \Exception(json_encode($DetailVirtualMachine['message']));
}
$jobs_configDB = new ConfigDatabase($this->data,$this->info);
dispatch($jobs_configDB)->delay(now()->addSeconds(5));
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class CheckStatusVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$status = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
if ($status['error'] === true) {
throw new \Exception(json_encode($status['message']));
}
if ($status['data']['operations_ready'] === false) {
do {
sleep(10);
$status = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
} while ($status['data']['operations_ready'] !== true);
}
$jobs_configNetwork = new GetNetworkVirtualMachine($this->vmware_id,$this->data,$this->serviceVCenter);
dispatch($jobs_configNetwork)->delay(now()->addSeconds(5));
}
}
@@ -0,0 +1,124 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Facade\HelperFacade as Helper;
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 ConfigCLICommand implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$PasswordVirtualMachine = Helper::general_password();
$usersName = '';
$port = '';
// Lưu password vào database ngay khi tạo
try {
$vm = \App\Models\ModuleVmware::where('vmware_id', $this->vmware_id)->first();
if ($vm) {
$vm->update(['password' => \App\Http\Facade\SignRSA::EncryptFunc($PasswordVirtualMachine)]);
Log::info('✅ Đã lưu password vào database', [
'vm_id' => $this->vmware_id,
'password' => $PasswordVirtualMachine
]);
}
} catch (\Exception $e) {
Log::error('❌ Lỗi khi lưu password: ' . $e->getMessage());
}
switch (true) {
case (str_contains($this->data->Os->OsGroup->name, "Windows") && str_contains($this->data->Os->version, 10)):
$usersName = 'administrator';
$port = 533892;
$this->serviceVCenter->ConfigWindowsVersion10($this->vmware_id, $this->data, $PasswordVirtualMachine);
break;
case (str_contains($this->data->Os->OsGroup->name, "Windows")):
$usersName = 'administrator';
$port = 53389;
$this->serviceVCenter->ConfigWindowsServer($this->vmware_id, $this->data,
$PasswordVirtualMachine);
break;
case (str_contains($this->data->Os->OsGroup->name, "CentOS") && str_contains($this->data->Os->version, 7)):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigCentOSVersion7($this->vmware_id, $this->data,
$PasswordVirtualMachine);
break;
case (str_contains($this->data->Os->OsGroup->name, "CentOS") && str_contains($this->data->Os->version, 8)):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigCentOSVersion8($this->vmware_id, $this->data,
$PasswordVirtualMachine);
break;
case (str_contains($this->data->Os->OsGroup->name, "Ubuntu")):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigVirtualMachineUbuntu($this->vmware_id, $this->data,
$PasswordVirtualMachine);
break;
case (str_contains($this->data->Os->OsGroup->name, "Rocky")):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigRockyLinuxVersion9($this->vmware_id, $this->data,
$PasswordVirtualMachine);
break;
}
sleep(20);
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
if ($VirtualMachine['data']['operations_ready'] === false) {
do {
sleep(10);
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
Log::channel('Custom')->info(json_encode($VirtualMachine));
} while ($VirtualMachine['data']['operations_ready'] !== true);
}
if (str_contains($this->data->Os->OsGroup->name, "Windows"))
{
$this->serviceVCenter->ConfigFixWindowsClick($this->vmware_id, $this->data);
}
$jobs_CheckIP = new CheckIPAddress($this->vmware_id,$this->data,['user' => $usersName,'password' => $PasswordVirtualMachine,'port' => $port],$this->serviceVCenter);
dispatch($jobs_CheckIP)->delay(now()->addSeconds(5));
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Events\Create_VirtualMachine_Success;
use App\Http\Facade\SignRSA;
use App\Http\Facade\HelperFacade as Helper;
use App\Http\Services\Telegram;
use App\Jobs\Mail\SendInformationVirtualMachine;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ConfigDatabase implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data;
protected $info;
protected $telegram;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data,$info)
{
$this->data = $data;
$this->info = $info;
$this->telegram = new Telegram();
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->data->update([
'name' => $this->data->ipaddress->ip . '_' . $this->data->cannotustomer->firstname,
'port' => $this->info['port'],
'user' => $this->info['user'],
'password' => SignRSA::EncryptFunc($this->info['password']),
'status' => 1
]);
$this->data->ipAddress->update([
'vm_name' => $this->data->IpAddress->ip . '_' . $this->data->Customer->firstname,
'status' => 1
]);
$setting = Setting::where('key', 'setting')->first();
$data = [
'company_name' => json_decode($setting->value)->company,
'company_logo' => json_decode($setting->value)->logo,
'client_name' => $this->data->Customer->firstname . " " . $this->data->Customer->lastname,
'product_name' => $this->data->GetInvoiceItem()->GetItemProduct()->name,
'product_billing' => Helper::billing_cycle($this->data->GetInvoiceItem()->billing),
'product_price' => number_format($this->data->GetInvoiceItem()->amount, 0, ',', '.'),
'service_host' => $this->data->IpAddress->ip,
'service_username' => $this->info['user'],
'service_port' => $this->info['port'],
'service_password' => $this->info['password'],
'os_name' => $this->data->Os->OsGroup->name . " " . $this->data->Os->version,
'service_due_exp' => Carbon::parse($this->data->next_due_date)->format('d/m/Y')
];
$mail = new SendInformationVirtualMachine($data, $this->data->Customer);
dispatch($mail)->delay(now()->addSeconds(5));
Event(new Create_VirtualMachine_Success("Máy chủ của bạn đã được khởi tạo thành công!",
$this->data->customer->id));
$this->telegram->SendInformation($this->data, $this->info['user'], $this->info['password'], $this->info['port']);
}
}
@@ -0,0 +1,115 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Services\Telegram;
use App\Http\Services\vCenter as ServiceVCenter;
use App\Models\ModuleVmware;
use Carbon\Carbon;
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;
use Illuminate\Support\Str;
use Throwable;
class CreateVMJobs implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data = null;
protected $push = null;
protected $telegram = null;
public int $tries = 1;
public $message = "";
public $timeout = 0;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($product = 0)
{
$this->data = $product;
$this->telegram = new Telegram;
}
public function handle(ServiceVCenter $serviceVCenter)
{
$product = ModuleVmware::with([
'Order.OrderItem',
'Customer',
'IpAddress.Network',
'IpAddress.Host.OneDatastore',
'IpAddress.Host.Datacenter.vCenter','Os.OsGroup'
])->find($this->data);
$serviceVCenter->token = $product->IpAddress->Host->Datacenter->vCenter->token;
$serviceVCenter->apiUri = $product->IpAddress->Host->Datacenter->vCenter->host;
$CheckToken = $serviceVCenter->checkApiExits();
if (! $CheckToken)
{
$token = $serviceVCenter->loginServer($product->IpAddress->Host->Datacenter->vCenter);
if ($token)
{
$product->IpAddress->Host->Datacenter->vCenter->update(['token' => $token]);
$serviceVCenter->token = $token;
}
}
$name = $product->IpAddress->ip . '_' . str_replace('-','_',Str::slug($product->Customer->firstname));
$jobs_check = new GetVirtualMachine($name,$product,$serviceVCenter);
$vmware_id = $jobs_check->handle();
if ($vmware_id === false)
{
Log::channel('detail')->info("Bắt đầu tạo: " . time());
$vmware_id = $serviceVCenter->CreateVirtualMachine($product);
Log::channel('detail')->info("Kết thúc: " . time());
if (isset($vmware_id['error']) && $vmware_id['error'] === false) {
$vmware_id = $vmware_id['data'];
}
}
if ($vmware_id && is_string($vmware_id)) {
$product->update(['vmware_id' => $vmware_id]);
$jobs_GetStatus = new CheckStatusVirtualMachine($vmware_id,$product,$serviceVCenter);
dispatch($jobs_GetStatus)->delay(now()->addSeconds(30));
} else {
$this->message = "Notification: " . json_encode($vmware_id);
throw new \Exception(json_encode($vmware_id));
}
}
public function failed(Throwable $exception): void
{
Log::channel('Custom')->info("\r\n");
Log::channel('Custom')->info("=================================");
Log::channel('Custom')->info("Thông báo lỗi lúc: " .Carbon::now());
Log::channel('Custom')->info("Notification Create VirtualMachine: ");
Log::channel('Custom')->info("========");
Log::channel('Custom')->info($exception->getMessage());
Log::channel('Custom')->info("=================================");
$this->telegram->SendErrorMessage($exception->getMessage());
}
}
@@ -0,0 +1,404 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Facade\SignRSA;
use App\Http\Services\Discord;
use App\Http\Services\vCenter;
use App\Jobs\Mail\Customer\VMCreationFailedJob;
use App\Models\OrderItem;
use App\Models\Os;
use App\Services\VMDataService;
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 CreateVirtualMachineJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public OrderItem $item;
public bool $isRetry = false;
/**
* Create a new job instance.
*/
public function __construct(OrderItem $item, bool $isRetry = false)
{
$this->item = $item;
$this->isRetry = $isRetry;
}
/**
* Execute the job.
*/
public function handle(vCenter $vCenter, Discord $discord, VMDataService $vmDataService)
{
try {
$product = $this->item->getProductAttribute(); // dùng helper trong OrderItem
if (!$product) {
$errorMessage = "Không tìm thấy sản phẩm từ OrderItem #{$this->item->id}";
Log::warning($errorMessage);
$discord->SendErrorMessage($errorMessage, 'CreateVirtualMachineJob - Missing Product');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return false;
}
$host = $product->host; // từ module_host_id
$datacenter = $host?->datacenter;
$vcenter = $datacenter?->vcenter;
$osModel = Os::find($this->item->os_id);
$template = $osModel?->template_id;
if (!$vcenter || !$host || !$datacenter) {
$errorMessage = "Thiếu thông tin host/datacenter/vcenter từ sản phẩm ID #{$product->id}";
Log::error($errorMessage);
$discord->SendErrorMessage([
'error' => $errorMessage,
'product_id' => $product->id,
'order_item_id' => $this->item->id,
'host_id' => $host?->id,
'datacenter_id' => $datacenter?->id,
'vcenter_id' => $vcenter?->id
], 'CreateVirtualMachineJob - Missing Infrastructure');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return;
}
// Login to vCenter
if (!$vCenter->loginServer($vcenter)) {
$errorMessage = "Login vào vCenter thất bại với host: {$vcenter->host}";
Log::error($errorMessage);
$discord->SendErrorMessage([
'error' => $errorMessage,
'vcenter_host' => $vcenter->host,
'vcenter_user' => $vcenter->user,
'product_id' => $product->id,
'order_item_id' => $this->item->id
], 'CreateVirtualMachineJob - vCenter Login Failed');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return false;
}
// Lấy thông tin addon (CPU, RAM)
$addonData = [
'cpu' => 0,
'ram' => 0,
'disk' => 0
];
// Lấy addon từ order item
if ($this->item->addons) {
Log::info("🔍 Tìm thấy addons cho order item", [
'order_item_id' => $this->item->id,
'addons_count' => $this->item->addons->count(),
'addons' => $this->item->addons->map(function($addon) {
return [
'id' => $addon->id,
'addon_id' => $addon->addon_id,
'qty' => $addon->qty,
'price' => $addon->price,
'addon_name' => $addon->addonItems?->name ?? 'Unknown'
];
})
]);
foreach ($this->item->addons as $orderAddon) {
$addon = $orderAddon->addonItems;
if (!$addon) {
Log::warning("⚠️ Addon không tìm thấy addonItems", [
'order_addon_id' => $orderAddon->id,
'addon_id' => $orderAddon->addon_id
]);
continue;
}
$addonName = strtolower(trim($addon->name));
$quantity = (int) $orderAddon->qty;
Log::info("🔍 Xử lý addon", [
'addon_name' => $addon->name,
'addon_name_lower' => $addonName,
'quantity' => $quantity,
'addon_id' => $addon->id
]);
switch ($addonName) {
case 'cpu':
$addonData['cpu'] += $quantity;
Log::info("✅ Thêm CPU addon: +{$quantity}");
break;
case 'ram':
$addonData['ram'] += $quantity;
Log::info("✅ Thêm RAM addon: +{$quantity}GB");
break;
case 'disk':
case 'ssd':
$addonData['disk'] += $quantity;
Log::info("✅ Thêm Disk addon: +{$quantity}GB");
break;
default:
Log::warning("⚠️ Addon không được nhận diện: {$addonName}");
break;
}
}
} else {
Log::info("ℹ️ Không có addons cho order item {$this->item->id}");
}
Log::info('📊 Thông tin addon được xử lý', [
'order_item_id' => $this->item->id,
'addon_data' => $addonData,
'addons_count' => $this->item->addons?->count() ?? 0,
'has_addons' => !empty($addonData) && array_sum($addonData) > 0
]);
$result = $vCenter->CreateVirtualMachine([
'item' => $this->item,
'host' => $host,
'datacenter' => $datacenter,
'vcenter' => $vcenter,
'template' => $template,
'addon' => $addonData,
]);
Log::info('Thông tin vCenter khi tạo máy ảo', [
'product' => $product,
'item' => $this->item,
'host_id' => $host?->id,
'host_name' => $host?->name,
'host_vcenter_id' => $host?->vcenter_id,
'datacenter_id' => $datacenter?->id,
'datacenter_name' => $datacenter?->name,
'datacenter_vcenter_id' => $datacenter?->vcenter_id,
'vcenter' => $vcenter,
'vcenter_id' => $vcenter?->id,
'vcenter_host' => $vcenter?->host,
'vcenter_user' => $vcenter?->user,
'vcenter_password' => SignRSA::DecryptFunc($vcenter?->password)
]);
if (is_array($result) && ($result['error'] ?? false)) {
$errorMessage = 'Tạo máy ảo thất bại: ' . json_encode($result);
Log::warning($errorMessage);
$discord->SendErrorMessage([
'error' => $result['error'] ?? 'Unknown error',
'result' => $result,
'product_id' => $product->id,
'order_item_id' => $this->item->id,
'host_name' => $host?->name,
'datacenter_name' => $datacenter?->name,
'vcenter_host' => $vcenter?->host
], 'CreateVirtualMachineJob - VM Creation Failed');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return false;
} elseif ($result === 'Login_Again') {
$errorMessage = 'Tạo máy ảo thất bại: cần đăng nhập lại.';
Log::error($errorMessage);
$discord->SendErrorMessage([
'error' => $errorMessage,
'product_id' => $product->id,
'order_item_id' => $this->item->id,
'vcenter_host' => $vcenter?->host
], 'CreateVirtualMachineJob - vCenter Re-login Required');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return false;
} else {
Log::info('Tạo máy ảo thành công: ' . json_encode($result));
// Lấy vm_id từ kết quả
$vmId = is_array($result) ? ($result['data'] ?? 'unknown') : $result;
if ($vmId !== 'unknown' && $vmId !== 'UNKNOWN') {
try {
// Lưu vm_id vào bảng invoice
$invoice = \App\Models\Invoice::where('order_id', $this->item->order->id)->first();
if ($invoice) {
$invoice->update(['vm_id' => $vmId]);
Log::info('✅ Đã lưu vm_id vào bảng invoice', [
'vm_id' => $vmId,
'invoice_id' => $invoice->id,
'order_id' => $this->item->order->id
]);
} else {
Log::warning('⚠️ Không tìm thấy invoice cho order', [
'order_id' => $this->item->order->id,
'vm_id' => $vmId
]);
}
// Start VM ngay sau khi tạo thành công
Log::info('🚀 Bắt đầu khởi động VM sau khi tạo thành công', [
'vm_id' => $vmId,
'order_item_id' => $this->item->id
]);
$startResult = $vCenter->StartVirtualMachine($vmId);
if ($startResult === 'Login_Again') {
// Thử đăng nhập lại và start VM
Log::info('🔄 Thử đăng nhập lại vCenter để start VM', [
'vm_id' => $vmId,
'vcenter_host' => $vcenter->host
]);
if ($vCenter->loginServer($vcenter)) {
$startResult = $vCenter->StartVirtualMachine($vmId);
Log::info('✅ Đăng nhập lại thành công, thử start VM lần nữa', [
'vm_id' => $vmId,
'start_result' => $startResult
]);
} else {
Log::error('❌ Không thể đăng nhập lại vCenter để start VM', [
'vm_id' => $vmId,
'vcenter_host' => $vcenter->host
]);
}
}
if (is_array($startResult) && $startResult['error'] === false) {
Log::info('✅ Khởi động VM thành công', [
'vm_id' => $vmId,
'order_item_id' => $this->item->id,
'result' => $startResult['data']
]);
// Dispatch ConfigCLICommand để cấu hình VM và lấy password
$configJob = new ConfigCLICommand($vmId, $this->item, $vCenter);
dispatch($configJob)->delay(now()->addMinutes(2)); // Chờ 2 phút để VM boot hoàn toàn
Log::info('✅ Đã dispatch ConfigCLICommand job', [
'vm_id' => $vmId,
'order_item_id' => $this->item->id
]);
} else {
Log::warning('⚠️ Khởi động VM thất bại', [
'vm_id' => $vmId,
'order_item_id' => $this->item->id,
'error' => $startResult['data']
]);
}
// Lưu dữ liệu VM và IP address vào database
$ipAddresses = [];
if (is_array($result)) {
$ipAddresses = $result['ip_addresses'] ?? [];
}
$saveResult = $vmDataService->saveVMData($this->item, $vmId, $ipAddresses);
if ($saveResult['success']) {
Log::info('✅ Lưu dữ liệu VM và IP address thành công', [
'vm_id' => $saveResult['vm']->id,
'vmware_id' => $vmId,
'ip_address_id' => $saveResult['ip_address']->id,
'order_item_id' => $this->item->id
]);
} else {
Log::error('❌ Lỗi khi lưu dữ liệu VM và IP address', [
'vmware_id' => $vmId,
'error' => $saveResult['message'],
'order_item_id' => $this->item->id
]);
}
} catch (\Exception $e) {
Log::error('❌ Lỗi khi lưu dữ liệu VM hoặc start VM: ' . $e->getMessage(), [
'vm_id' => $vmId,
'order_id' => $this->item->order->id,
'trace' => $e->getTraceAsString()
]);
}
}
// Log thông tin addon đã được áp dụng
if (!empty($addonData) && array_sum($addonData) > 0) {
Log::info('Addon đã được áp dụng thành công', [
'vm_id' => $vmId,
'addon_data' => $addonData,
'order_item_id' => $this->item->id
]);
}
// Gửi thông báo thành công
$discord->SendJobRunInfo(
'CreateVirtualMachineJob',
'success',
[
'product_id' => $product->id,
'order_item_id' => $this->item->id,
'result' => $result,
'addon_applied' => !empty($addonData) && array_sum($addonData) > 0,
'vm_id_saved' => $vmId !== 'unknown' && $vmId !== 'UNKNOWN',
'vm_started' => isset($startResult) && is_array($startResult) && $startResult['error'] === false
]
);
return true;
}
} catch (\Throwable $e) {
$errorMessage = 'Lỗi khi tạo máy ảo (Job): ' . $e->getMessage();
Log::error($errorMessage, [
'exception' => $e,
'order_item_id' => $this->item->id,
'trace' => $e->getTraceAsString()
]);
$discord->SendErrorMessage([
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'order_item_id' => $this->item->id,
'trace' => substr($e->getTraceAsString(), 0, 500) // Giới hạn độ dài trace
], 'CreateVirtualMachineJob - Exception');
if (!$this->isRetry) {
$this->sendFailureNotification($errorMessage);
}
return false;
}
}
/**
* Send failure notification to customer
*/
private function sendFailureNotification(string $errorMessage): void
{
try {
$customer = $this->item->order->customer;
$product = $this->item->getProductAttribute();
VMCreationFailedJob::dispatch([
'customer_email' => $customer->email,
'customer_name' => trim($customer->firstname . ' ' . $customer->lastname),
'product_name' => $product?->name ?? 'Unknown Product',
'order_id' => $this->item->order->id,
'order_num' => $this->item->order->order_num,
'error_message' => $errorMessage,
'order_item_id' => $this->item->id
]);
} catch (\Throwable $e) {
Log::error('Không thể gửi email thông báo lỗi VM: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class GetNetworkVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data, $service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$NetworkForVirtualMachine = $this->serviceVCenter->GetNetworkVirtualMachine($this->vmware_id);
if ($NetworkForVirtualMachine['error']) {
throw new \Exception(json_encode($NetworkForVirtualMachine['message']));
}
$Network = $this->data->IpAddress->Network->network;
if ($Network !== $NetworkForVirtualMachine['data']['network']) {
$ConfigNetwork = [
"spec" => [
"backing" => [
"type" => $this->data->IpAddress->Network->type,
"network" => $this->data->IpAddress->Network->network
]
]
];
$this->serviceVCenter->ConfigNetworkVirtualMachine($this->vmware_id,$ConfigNetwork);
}
$jobs_configCLI = new ConfigCLICommand($this->vmware_id,$this->data,$this->serviceVCenter);
dispatch($jobs_configCLI)->delay(now()->addSeconds(5));
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Services\vCenter as ServiceVCenter;
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 GetVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $name;
protected $data;
protected $response = '';
protected ServiceVCenter $serviceVCenter;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($name = '', $data,$service)
{
//
$this->name = $name;
$this->data = $data;
$this->serviceVCenter = $service;
}
/**
* Execute the job.
*
* @return bool|string
*/
public function handle()
{
$vmware_id = $this->serviceVCenter->FindVirtualMachine($this->name);
Log::channel('detail')->info("==================");
Log::channel('detail')->info($vmware_id);
return $vmware_id;
}
public function failed(\Throwable $error)
{
Log::channel('error')->info($error->getMessage());
}
}