update rm deadcode

This commit is contained in:
baodev0
2026-09-27 11:42:40 +07:00
parent 82a71244ca
commit 3af59bd9c5
129 changed files with 5194 additions and 2698 deletions
+28 -2
View File
@@ -7,6 +7,7 @@ namespace App\Jobs\VirtualMachine;
use App\Actions\VM\ChangeIpVMAction;
use App\Http\Services\Telegram;
use App\Models\ModuleVmware;
use App\Services\VirtualMachine\VmIpReservationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -38,9 +39,11 @@ class ChangeIpVMJob implements ShouldQueue
public readonly string $dns,
public readonly string $guestUser,
public readonly string $guestPassword,
public readonly ?int $newIpPoolId = null,
public readonly ?int $oldIpPoolId = null,
) {}
public function handle(ChangeIpVMAction $action): void
public function handle(ChangeIpVMAction $action, VmIpReservationService $ipReservation): void
{
$vm = ModuleVmware::with([
'vCenter',
@@ -49,6 +52,9 @@ class ChangeIpVMJob implements ShouldQueue
if (!$vm) {
Log::error('[ChangeIpVMJob] ModuleVmware not found', ['module_vmware_id' => $this->moduleVmwareId]);
if ($this->newIpPoolId) {
$ipReservation->releaseByPoolId($this->newIpPoolId);
}
return;
}
@@ -62,6 +68,22 @@ class ChangeIpVMJob implements ShouldQueue
$this->guestPassword,
);
$failed = $raw === 'Login_Again'
|| $raw === 'vCenter_Not_Found'
|| str_starts_with((string) $raw, 'Error:')
|| str_contains((string) $raw, '[STDERR]');
if ($failed) {
if ($this->newIpPoolId) {
$ipReservation->releaseByPoolId($this->newIpPoolId);
}
} else {
$vm->update(['ip' => $this->ipAddress, 'dns' => $this->dns]);
if ($this->oldIpPoolId) {
$ipReservation->releaseByPoolId($this->oldIpPoolId);
}
}
Log::channel('Custom')->info('[ChangeIpVMJob] raw output', [
'module_vmware_id' => $this->moduleVmwareId,
'ip_address' => $this->ipAddress,
@@ -88,7 +110,7 @@ class ChangeIpVMJob implements ShouldQueue
return;
}
if (str_starts_with((string) $raw, 'Error:') || str_contains((string) $raw, '[STDERR]')) {
if ($failed) {
$telegram->SendErrorMessage("❌ Đổi IP thất bại [{$this->osType}]\n"
. "🖥 VM: {$vm->name} ({$vm->vmware_id})\n"
. "📍 IP mới: {$this->ipAddress}\n"
@@ -116,5 +138,9 @@ class ChangeIpVMJob implements ShouldQueue
'ip_address' => $this->ipAddress,
'error' => $e->getMessage(),
]);
if ($this->newIpPoolId) {
app(VmIpReservationService::class)->releaseByPoolId($this->newIpPoolId);
}
}
}
@@ -1,192 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Facade\SignRSA;
use App\Jobs\Mail\SendInformationVirtualMachine;
use App\Models\ModuleVmware;
use App\Models\Setting;
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 ChangePasswordViaSshJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 120;
public function __construct(
public readonly int $moduleVmwareId,
public readonly string $ip,
public readonly string $username,
public readonly string $initialPassword,
public readonly string $newPassword,
) {}
// ─────────────────────────────────────────────────────────────────────────
public function handle(): void
{
Log::info('ChangePasswordViaSshJob: starting', [
'module_vmware_id' => $this->moduleVmwareId,
'ip' => $this->ip,
'username' => $this->username,
]);
$output = $this->runWithRetry();
if ($output === null) {
$this->fail(new \RuntimeException(
"SSH connection to {$this->ip} failed after max attempts"
));
return;
}
Log::info('ChangePasswordViaSshJob: chpasswd output', [
'module_vmware_id' => $this->moduleVmwareId,
'output' => trim($output),
]);
// Update DB
$vm = ModuleVmware::find($this->moduleVmwareId);
if (!$vm) {
Log::error('ChangePasswordViaSshJob: ModuleVmware not found', [
'module_vmware_id' => $this->moduleVmwareId,
]);
return;
}
$vm->update([
'password' => SignRSA::EncryptFunc($this->newPassword),
'plain_password' => $this->newPassword,
]);
$this->sendPasswordEmail($vm);
}
// ─────────────────────────────────────────────────────────────────────────
/**
* Run chpasswd on the remote VM via sshpass + native SSH.
* Retries up to 10 times with 30 s delay (VM may still be booting).
*/
private function runWithRetry(int $maxAttempts = 10, int $sleepSeconds = 30): ?string
{
// Remote bash command: echo 'user:pass' | chpasswd
$credential = $this->username . ':' . $this->newPassword;
$remoteCmd = 'echo ' . escapeshellarg($credential) . ' | chpasswd 2>&1';
$sshCmd = sprintf(
'sshpass -p %s ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 -p 22 %s@%s %s 2>&1',
escapeshellarg($this->initialPassword),
escapeshellarg($this->username),
escapeshellarg($this->ip),
escapeshellarg($remoteCmd),
);
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
$output = shell_exec($sshCmd);
// null = shell_exec failed (command not found, etc.)
// sshpass exits non-zero on connection failure → output contains error text
if ($output !== null && !$this->isSshConnectionError($output)) {
Log::info('ChangePasswordViaSshJob: SSH connected', [
'module_vmware_id' => $this->moduleVmwareId,
'attempt' => $attempt,
]);
return $output;
}
Log::warning('ChangePasswordViaSshJob: SSH not ready, retrying', [
'module_vmware_id' => $this->moduleVmwareId,
'attempt' => $attempt,
'output_preview' => substr((string) $output, 0, 200),
]);
if ($attempt < $maxAttempts) {
sleep($sleepSeconds);
}
}
return null;
}
/**
* Detect SSH connection failures (not auth errors) in sshpass output.
*/
private function isSshConnectionError(string $output): bool
{
$lower = strtolower($output);
return str_contains($lower, 'connection refused')
|| str_contains($lower, 'no route to host')
|| str_contains($lower, 'connection timed out')
|| str_contains($lower, 'host is down')
|| str_contains($lower, 'network is unreachable');
}
// ─────────────────────────────────────────────────────────────────────────
public function failed(\Throwable $e): void
{
Log::error('ChangePasswordViaSshJob: failed', [
'module_vmware_id' => $this->moduleVmwareId,
'ip' => $this->ip,
'error' => $e->getMessage(),
]);
}
// ─────────────────────────────────────────────────────────────────────────
private function sendPasswordEmail(ModuleVmware $vm): void
{
try {
$customer = $vm->customer;
if (!$customer) {
Log::error('ChangePasswordViaSshJob: customer not found', [
'module_vmware_id' => $this->moduleVmwareId,
]);
return;
}
$setting = Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode((string) $setting->value) : null;
$emailData = [
'company_name' => $settingValue->company ?? 'Thế Giới Số',
'company_logo' => $settingValue->logo ?? '',
'client_name' => trim($customer->firstname . ' ' . $customer->lastname),
'product_name' => 'Cloud VPS',
'product_billing' => 'N/A',
'product_price' => 'N/A',
'service_host' => $this->ip,
'service_username' => $this->username,
'service_port' => 22,
'service_password' => $this->newPassword,
'os_name' => ($vm->os?->osGroup?->name ?? '') . ' ' . ($vm->os?->version ?? ''),
'service_due_exp' => $vm->next_due_date ? date('d/m/Y', (int) $vm->next_due_date) : 'N/A',
];
SendInformationVirtualMachine::dispatch($emailData, $customer)
->delay(now()->addSeconds(5));
Log::info('ChangePasswordViaSshJob: email dispatched', [
'module_vmware_id' => $this->moduleVmwareId,
'customer_email' => $customer->email,
]);
} catch (\Throwable $e) {
Log::error('ChangePasswordViaSshJob: email failed: ' . $e->getMessage(), [
'module_vmware_id' => $this->moduleVmwareId,
]);
}
}
}
@@ -20,7 +20,7 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use App\Support\TlsHttpClientFactory;
use Illuminate\Support\Facades\Log;
/**
@@ -309,14 +309,14 @@ class UpdateVmConfigJob implements ShouldQueue
$action = $powerOff ? 'stop' : 'start';
$targetState = $powerOff ? 'POWERED_OFF' : 'POWERED_ON';
Http::withoutVerifying()
TlsHttpClientFactory::vCenter()
->withHeaders(['vmware-api-session-id' => $service->token])
->post("https://{$service->apiUri}/rest/vcenter/vm/{$vmwareId}/power/{$action}");
for ($i = 0; $i < 15; $i++) {
sleep(2);
$state = Http::withoutVerifying()
$state = TlsHttpClientFactory::vCenter()
->withHeaders(['vmware-api-session-id' => $service->token])
->get("https://{$service->apiUri}/rest/vcenter/vm/{$vmwareId}")
->json('value.power_state');