update change password

This commit is contained in:
pbaodev
2025-08-24 22:41:15 +07:00
parent 6b358afd4b
commit 197fe413e5
19 changed files with 699 additions and 193 deletions
@@ -0,0 +1,101 @@
<?php
namespace App\Jobs\VirtualMachine\Action;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Http\Services\vCenter;
use App\Mail\VmPasswordResetSuccess;
use App\Models\ModuleVmware;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class ResetVmPasswordJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 180;
public function __construct(
public string $productId,
public string $oldPassword,
public string $newPassword,
public int $userId,
public string $email
) {}
public function handle(vCenter $serviceVCenter): void
{
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter','os.osGroup')
->where('vmware_id', $this->productId)
->where('customer_id', $this->userId)
->firstOrFail();
$osFamily = (string)($product->os->osGroup->name ?? '');
$isWindows = stripos($osFamily, 'windows') !== false;
if (!$isWindows) {
throw new \RuntimeException('Only Windows is supported by this reset job.');
}
$vmName = $product->ipAddress->vm_name
?? $product->name
?? $product->hostname
?? null;
if (!$vmName && preg_match('/^vm-\d+$/i', (string)$product->vmware_id)) {
$rawName = trim($serviceVCenter->runPsCommand("(Get-VM -Id '".addslashes($product->vmware_id)."').Name"));
if (($p = strpos($rawName, '[STDERR]')) !== false) {
$rawName = trim(substr($rawName, 0, $p));
}
$vmName = trim(preg_replace('/\s+/', ' ', $rawName));
}
if (!$vmName) {
throw new \RuntimeException('Cannot resolve VM Name on vCenter.');
}
$guestUser = 'Administrator';
$guestPassword = $this->oldPassword;
$result = $serviceVCenter->resetGuestPasswordViaPs1(
vmName: $vmName,
guestUser: $guestUser,
guestPassword: $guestPassword,
newPassword: $this->newPassword,
);
$product->update(['password' => encrypt($this->newPassword)]);
if ($result === 'Login_Fail' || $result === false || $result === null) {
throw new \RuntimeException('SSH runner login failed.');
}
if (is_string($result)) {
throw new \RuntimeException('Script returned non-JSON output: '.$result);
}
$row = $result;
if (isset($result[0])) {
$row = $result[0];
foreach ($result as $it) {
if (is_array($it) && (($it['vm'] ?? null) === $vmName)) { $row = $it; break; }
}
}
$status = strtolower($row['status'] ?? '');
if ($status !== 'ok') {
throw new \RuntimeException($row['message'] ?? 'Reset failed by script');
}
// Gửi mail thông báo
Mail::to($this->email)->send(
new VmPasswordResetSuccess(vmName: $vmName, newPassword: $this->newPassword)
);
Log::info('ResetVmPasswordJob: success', ['vm'=>$vmName]);
}
}
@@ -104,16 +104,17 @@ class CreateVirtualMachineJob implements ShouldQueue
'ram' => 0,
'disk' => 0
];
// Lấy addon từ order item
if ($this->item->addons) {
foreach ($this->item->addons as $orderAddon) {
$addon = $orderAddon->addonItems;
if (!$addon) continue;
if (!$addon)
continue;
$addonName = strtolower(trim($addon->name));
$quantity = (int) $orderAddon->qty;
switch ($addonName) {
case 'cpu':
$addonData['cpu'] += $quantity;
@@ -187,10 +188,10 @@ class CreateVirtualMachineJob implements ShouldQueue
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
@@ -212,11 +213,11 @@ class CreateVirtualMachineJob implements ShouldQueue
try {
$customer = $this->item->order->customer;
$serverName = $this->item->server_name ?? 'VM-' . $vmId;
// 1. Lấy IP available từ IPPool
$networkId = $product->ipAddress?->module_network_id ?? 1;
$availableIP = $this->getAvailableIPFromPool($networkId);
// 2. Tạo ModuleIpAddress với IP từ pool
$moduleIpAddress = ModuleIpAddress::create([
'vm_name' => $serverName,
@@ -228,7 +229,7 @@ class CreateVirtualMachineJob implements ShouldQueue
'dns' => $product->ipAddress?->dns ?? '8.8.8.8',
'status' => 1 // 1 = Assigned
]);
// 3. Tạo ModuleVmware với IP address vừa tạo
$moduleVmware = ModuleVmware::create([
'name' => $serverName,
@@ -239,7 +240,7 @@ class CreateVirtualMachineJob implements ShouldQueue
'next_payment' => $this->item->order->next_payment ?? 0,
'next_due_date' => $this->item->order->next_due_date ?? null,
'next_invoice' => $this->item->order->next_invoice ?? 0,
'user' => 'root',
'user' => 'Administrator',
'password' => '',
'hostname' => $serverName,
'vmware_id' => $vmId,
@@ -247,7 +248,7 @@ class CreateVirtualMachineJob implements ShouldQueue
'customer_id' => $customer->id,
'status' => 1
]);
Log::info('✅ Lưu dữ liệu VM và IP address thành công', [
'vmware_id' => $vmId,
'module_vmware_id' => $moduleVmware->id,
@@ -256,18 +257,18 @@ class CreateVirtualMachineJob implements ShouldQueue
'name' => $serverName,
'order_item_id' => $this->item->id
]);
// Dispatch AssignIPJob để chạy sau 5 phút
AssignIPJob::dispatch($vmId, $moduleVmware->id, $moduleIpAddress->ip)
->delay(now()->addMinutes(5));
Log::info('✅ Đã dispatch AssignIPJob để chạy sau 5 phút', [
'vm_id' => $vmId,
'module_vmware_id' => $moduleVmware->id,
'assigned_ip' => $moduleIpAddress->ip,
'delay_minutes' => 5
]);
} catch (\Exception $e) {
Log::error('❌ Lỗi khi lưu dữ liệu VM và IP address: ' . $e->getMessage(), [
'vmware_id' => $vmId,
@@ -284,7 +285,7 @@ class CreateVirtualMachineJob implements ShouldQueue
]);
}
}
// Gửi thông báo thành công
$telegram->SendJobRunInfo(
'CreateVirtualMachineJob',
@@ -333,22 +334,22 @@ class CreateVirtualMachineJob implements ShouldQueue
$ipPoolList = IpPool::where('module_network_id', $networkId)
->orderBy('ip_address')
->get();
Log::info('✅ Lấy IP available từ pool', [
'ip_pool_list' => $ipPoolList,
'network_id' => $networkId
]);
if ($ipPoolList->isEmpty()) {
// Nếu không có IP trong pool, trả về IP default
return '0.0.0.0';
}
// Lấy tất cả IP đã được assign trong ModuleIpAddress
$assignedIPs = ModuleIpAddress::where('module_network_id', $networkId)
->pluck('ip')
->toArray();
// Tìm IP đầu tiên chưa được assign
foreach ($ipPoolList as $ipPool) {
if (!in_array($ipPool->ip_address, $assignedIPs)) {
@@ -359,14 +360,14 @@ class CreateVirtualMachineJob implements ShouldQueue
return $ipPool->ip_address;
}
}
// Nếu tất cả IP đã được assign, log warning và trả về IP default
Log::warning('⚠️ Không có IP available trong pool', [
'network_id' => $networkId,
'total_ips_in_pool' => $ipPoolList->count(),
'assigned_ips' => count($assignedIPs)
]);
return '0.0.0.0';
}
@@ -381,21 +382,21 @@ class CreateVirtualMachineJob implements ShouldQueue
if (!$check) {
return 'Login_Again';
}
// Gọi API start VM trực tiếp
$response = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $vCenter->token
])
->post("https://{$vCenter->apiUri}/rest/vcenter/vm/{$vmId}/power/start");
if ($response->status() === 200) {
return [
'error' => false,
'data' => 'success'
];
}
return [
'error' => true,
'data' => $response->body()
@@ -29,10 +29,10 @@ class SyncAllPackage implements ShouldQueue
*/
public function handle()
{
SyncDatacenter::dispatchSync();
SyncHost::dispatchSync();
SyncDatastore::dispatchSync();
SyncNetwork::dispatchSync();
SyncFolder::dispatchSync();
SyncDatacenter::dispatch();
SyncHost::dispatch();
SyncDatastore::dispatch();
SyncNetwork::dispatch();
SyncFolder::dispatch();
}
}
+1 -1
View File
@@ -86,7 +86,7 @@ class SyncNetwork implements ShouldQueue
'name' => $_subItem['name'],
'network' => $_subItem['network'],
'type' => $_subItem['type'],
'ModuleHost_id' => $hostItem->id
'module_host_id' => $hostItem->id
]);
}