This commit is contained in:
pbao9
2026-02-10 16:49:59 +07:00
parent 057353a2e1
commit 3ece85430c
6 changed files with 254 additions and 11514 deletions
@@ -0,0 +1,71 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Services\vCenter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class VpsActionController extends Controller
{
protected $vCenterService;
public function __construct(vCenter $vCenterService)
{
$this->vCenterService = $vCenterService;
}
public function rebuildVps(Request $request)
{
set_time_limit(300); // Increase timeout to 5 minutes for slow vCenter connection
$request->validate([
'vm_name' => 'required|string',
'vcenter_id' => 'required|integer' // We need to know which vCenter to connect to
]);
$vmName = $request->input('vm_name');
$vcenterId = $request->input('vcenter_id');
// Retrieve vCenter details from DB to authenticate
$vcenterModel = \App\Models\vCenter::find($vcenterId);
if (!$vcenterModel) {
return response()->json([
'error' => true,
'message' => 'vCenter ID not found'
], 404);
}
// Authenticate with vCenter
$token = $this->vCenterService->loginServer($vcenterModel);
if (!$token) {
return response()->json([
'error' => true,
'message' => 'Failed to login to vCenter'
], 401);
}
Log::info("API Rebuild VPS requested for VM: {$vmName} on vCenter: {$vcenterModel->host}");
// Call the service function
$result = $this->vCenterService->reBuildVPS($vmName);
if (is_array($result) && isset($result['error']) && $result['error']) {
return response()->json($result, 500);
}
if ($result === "Login_Again") { // Double check handled in service but good to catch
return response()->json([
'error' => true,
'message' => 'Session expired, login again'
], 401);
}
return response()->json([
'error' => false,
'message' => 'Rebuild command executed',
'data' => $result
]);
}
}
+125 -10
View File
@@ -319,16 +319,29 @@ class vCenter
return "Login_Fail";
}
try {
//Action connect to viserver
$action = "powershell.exe; Connect-viserver -Server '$this->apiUri' -User '$this->username' -Password \"'$this->password'\" -SaveCredentials; $cmd";
$psCommand = <<<PS
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "
Import-Module VMware.PowerCLI;
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:\$false;
\$cred = Import-Clixml -Path 'C:\secure\vcenter.cred';
Connect-VIServer -Server '{$this->apiUri}' -Credential \$cred;
$cmd;
Disconnect-VIServer -Confirm:\$false
"
PS;
//Run action
return $auth->exec($action);
} catch (Exception $error) {
return $error->getCode();
$out = $auth->exec($psCommand);
$err = $auth->getStdError();
return $out . ($err ? "\n[STDERR]\n" . $err : '');
} catch (\Exception $e) {
return $e->getMessage();
}
}
private function LoginAuth()
{
@@ -2090,7 +2103,8 @@ PS;
// Kiểm tra hệ điều hành
if (str_contains($this->os, "Windows")) {
$user = $data['user'] ?? 'administartor';
$this->process = new WinRMClient($ip, $user, $password);;
$this->process = new WinRMClient($ip, $user, $password);
;
return $this->process;
}
@@ -2718,8 +2732,8 @@ PS;
/*
* Get Window Remote Port
*/
* Get Window Remote Port
*/
public function getWindowsRdpPort(string $vmwareId, string $guestUser, string $guestPassword): ?int
{
$ps = "(Get-ItemProperty 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -Name PortNumber).PortNumber";
@@ -2742,4 +2756,105 @@ PS;
return null;
}
public function reBuildVPS(string $vmName): array|string
{
if (!$this->checkApiExits()) {
return "Login_Again";
}
try {
$response = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->token
])
->get("https://{$this->apiUri}/rest/vcenter/vm", [
'filter.names' => $vmName
]);
if (!$response->successful()) {
return [
'error' => true,
'message' => 'Failed to search for VM',
'details' => $response->json()
];
}
$vmList = $response->json()['value'] ?? [];
if (empty($vmList)) {
return [
'error' => true,
'message' => "VM not found with name: {$vmName}"
];
}
$vmId = $vmList[0]['vm'];
$detailResponse = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->token
])
->get("https://{$this->apiUri}/rest/vcenter/vm/{$vmId}");
if (!$detailResponse->successful()) {
return [
'error' => true,
'message' => 'Failed to fetch VM details',
'details' => $detailResponse->json()
];
}
$vmData = $detailResponse->json();
$guestOS = $vmData['value']['guest_OS'] ?? 'UNKNOWN';
$scriptPath = '';
$osUpper = strtoupper($guestOS);
if (Str::contains($osUpper, 'WINDOWS')) {
$scriptPath = 'C:\\CLISave\\Windows\\rebuild.ps1';
} elseif (Str::contains($osUpper, ['UBUNTU', 'LINUX', 'CENTOS', 'DEBIAN'])) {
$scriptPath = 'C:\\CLISave\\Ubuntu\\rebuild.ps1';
} else {
return [
'error' => true,
'message' => "Unsupported OS for rebuild: {$guestOS}"
];
}
$scriptDir = dirname($scriptPath);
$scriptFile = basename($scriptPath);
$cmd = "
Write-Output 'STARTING_REBUILD';
\$vm = Get-VM -Name '$vmName';
cd '$scriptDir';
if (Test-Path '.\\$scriptFile') {
Write-Output 'File found, executing...';
& '.\\$scriptFile' | Out-String
} else {
Write-Error 'File NOT FOUND: $scriptPath';
}
Write-Output 'ENDING_REBUILD';
";
$result = $this->Command($cmd);
return [
'error' => false,
'vm_name' => $vmName,
'vm_id' => $vmId,
'os' => $guestOS,
'script' => $scriptPath,
'result' => $result
];
} catch (\Exception $e) {
Log::error("reBuildVPS Exception: " . $e->getMessage());
return [
'error' => true,
'message' => $e->getMessage()
];
}
}
}