Refactor vCenter snapshot handling and VM operations
- Introduced a new method `resolveVCenterFromProduct` in `SnapshotService` to streamline vCenter resolution from product data. - Updated `CreateSnapshot`, `RemoveSnapshot`, and `RevertSnapshot` jobs to utilize the new vCenter resolution method. - Enhanced the `VmController` to support UUID-based service identification for VM operations. - Added new actions for changing VM IP and RDP port, encapsulating the logic for these operations. - Improved error handling and logging for VM operations, including detailed responses for API consumers. - Removed unnecessary relationships in model queries to optimize performance.
This commit is contained in:
+271
-42
@@ -118,6 +118,49 @@ class vCenter
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lấy thông tin vCenter từ product (ModuleVmware) qua nhiều cách:
|
||||
* 1. Direct relation qua vcenter_id
|
||||
* 2. Qua ipAddress → host → datacenter → vCenter
|
||||
* 3. Qua Service relation (nếu Service có vcenter_id)
|
||||
*
|
||||
* @param \App\Models\ModuleVmware $product
|
||||
* @return \App\Models\vCenter|null
|
||||
*/
|
||||
public function resolveVCenterFromProduct(\App\Models\ModuleVmware $product): ?\App\Models\vCenter
|
||||
{
|
||||
// Cách 1: Ưu tiên quan hệ trực tiếp trên ModuleVmware
|
||||
if ($product->vCenter) {
|
||||
Log::channel('Custom')->debug('resolveVCenter: Found via direct vCenter relation', ['vcenter_id' => $product->vCenter->id]);
|
||||
return $product->vCenter;
|
||||
}
|
||||
|
||||
// Cách 2: Fallback qua ipAddress chain
|
||||
if ($product->ipAddress?->host?->datacenter?->vCenter) {
|
||||
Log::channel('Custom')->debug('resolveVCenter: Found via ipAddress chain');
|
||||
return $product->ipAddress->host->datacenter->vCenter;
|
||||
}
|
||||
|
||||
// Cách 3: Qua Service relation (nếu Service có vcenter_id)
|
||||
// Lấy service đầu tiên liên kết với VM này
|
||||
$service = $product->services()->first();
|
||||
if ($service) {
|
||||
// Load vmware relation với vCenter
|
||||
$service->load('vmware.vCenter');
|
||||
if ($service->vmware?->vCenter) {
|
||||
Log::channel('Custom')->debug('resolveVCenter: Found via Service→Vmware→vCenter');
|
||||
return $service->vmware->vCenter;
|
||||
}
|
||||
}
|
||||
|
||||
Log::channel('Custom')->warning('resolveVCenter: Could not find vCenter for product', [
|
||||
'product_id' => $product->id,
|
||||
'vmware_id' => $product->vmware_id,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getAllHost($datacenter = '')
|
||||
{
|
||||
$check = $this->checkApiExits();
|
||||
@@ -294,27 +337,28 @@ class vCenter
|
||||
if (!$auth) {
|
||||
return "Login_Fail";
|
||||
}
|
||||
|
||||
try {
|
||||
$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;
|
||||
// Build PowerShell command inline
|
||||
$psCommand = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "' .
|
||||
'Import-Module VMware.PowerCLI; ' .
|
||||
'Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false -Scope Session; ' .
|
||||
'$cred = Import-Clixml -Path \'C:\secure\vcenter.cred\'; ' .
|
||||
'Connect-VIServer -Server \'' . $this->apiUri . '\' -Credential $cred; ' .
|
||||
$cmd . '; ' .
|
||||
'Disconnect-VIServer -Confirm:$false" 2>&1';
|
||||
|
||||
Log::channel('Custom')->info('PowerShell Command: ' . substr($psCommand, 0, 200) . '...');
|
||||
|
||||
$out = $auth->exec($psCommand);
|
||||
$err = $auth->getStdError();
|
||||
|
||||
Log::channel('Custom')->info('PowerShell Output length: ' . strlen($out));
|
||||
|
||||
return $out . ($err ? "\n[STDERR]\n" . $err : '');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::channel('Custom')->error('Command Exception: ' . $e->getMessage());
|
||||
return $e->getMessage();
|
||||
}
|
||||
}
|
||||
@@ -573,6 +617,69 @@ PS;
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change IP address of a VM via existing PowerShell scripts.
|
||||
*
|
||||
* Linux → C:\CLISave\changeIPLinux.ps1
|
||||
* Params: -VMName -IP -Gateway -DNS -GuestUser -GuestPassword
|
||||
* Uses: Get-VM -Name $VMName + Invoke-VMScript (requires guest creds)
|
||||
* Returns JSON → parsed via CommandChangePort($cmd, true)
|
||||
*
|
||||
* Windows → C:\CLISave\changeWindows1line.ps1 (legacy inline variable pattern)
|
||||
*
|
||||
* loginServer() MUST be called before this so $this->apiUri / username /
|
||||
* password are set for the Connect-VIServer call inside CommandChangePort.
|
||||
*/
|
||||
public function changeIpVM(
|
||||
string $vmName, // VM display name used with Get-VM -Name
|
||||
string $vmwareId, // VMware ID (used for Windows -Id pattern)
|
||||
string $ipAddress,
|
||||
string $gateway,
|
||||
string $osType,
|
||||
string $guestUser = '',
|
||||
string $guestPassword = '',
|
||||
string $dns = '8.8.8.8',
|
||||
string $hostname = ''
|
||||
): string {
|
||||
$q = fn(string $v) => str_replace("'", "''", $v);
|
||||
|
||||
$isLinux = str_contains(strtolower($osType), 'linux')
|
||||
|| str_contains(strtolower($osType), 'ubuntu')
|
||||
|| str_contains(strtolower($osType), 'centos')
|
||||
|| str_contains(strtolower($osType), 'rocky');
|
||||
|
||||
if ($isLinux) {
|
||||
// changeIPLinux.ps1 param(VMName, IP, Gateway, DNS, GuestUser, GuestPassword)
|
||||
$psFile = "C:\\CLISave\\changeIPLinux.ps1";
|
||||
$Command = "& '{$psFile}'"
|
||||
. " -VMName '" . $q($vmName) . "'"
|
||||
. " -IP '" . $q($ipAddress) . "'"
|
||||
. " -Gateway '" . $q($gateway) . "'"
|
||||
. " -DNS '" . $q($dns) . "'"
|
||||
. " -GuestUser '" . $q($guestUser) . "'"
|
||||
. " -GuestPassword '" . $q($guestPassword) . "'";
|
||||
|
||||
Log::channel('Custom')->info('[changeIpVM:linux] ' . $Command);
|
||||
|
||||
// Script returns JSON → use CommandChangePort with expectJson=true
|
||||
return (string) $this->CommandChangePort($Command, true);
|
||||
}
|
||||
|
||||
// Windows: legacy inline variable pattern → changeWindows1line.ps1
|
||||
$VirtualMachine = "VirtualMachine-$vmwareId";
|
||||
$hn = strtolower($hostname ?: $vmName);
|
||||
$Command = "\$vm = get-vm -Id '{$VirtualMachine}';"
|
||||
. " \$hostname = '{$q($hn)}';"
|
||||
. " \$ipadd = '{$q($ipAddress)}';"
|
||||
. " \$gw = '{$q($gateway)}';"
|
||||
. " \$password = \"'{$q($guestPassword)}'\"; "
|
||||
. " cd /; C:\\CLISave\\changeWindows1line.ps1;";
|
||||
|
||||
Log::channel('Custom')->info('[changeIpVM:windows] ' . $Command);
|
||||
|
||||
return (string) $this->Command($Command);
|
||||
}
|
||||
|
||||
public function loadDatastore($data = [], $host_id = '')
|
||||
{
|
||||
Log::info('[vCenter] loadDatastore()', [
|
||||
@@ -1672,9 +1779,22 @@ PS;
|
||||
public function CreateSnapShot($product, ?string $snapshotName = null): string|array
|
||||
{
|
||||
try {
|
||||
$this->username = $product->ipaddress->host->datacenter->vCenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($product->ipaddress->host->datacenter->vCenter->password);
|
||||
$this->apiUri = $product->ipaddress->host->datacenter->vCenter->host;
|
||||
// Sử dụng helper method để resolve vCenter từ product
|
||||
$vcenter = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenter) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->username = $vcenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($vcenter->password);
|
||||
$this->apiUri = $vcenter->host;
|
||||
|
||||
// Login to get token
|
||||
$loginResult = $this->loginServer($vcenter);
|
||||
if (!$loginResult) {
|
||||
return "Login_Again";
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => true, 'message' => 'Lỗi setup credentials: ' . $e->getMessage()];
|
||||
}
|
||||
@@ -1692,18 +1812,34 @@ PS;
|
||||
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
$Command = "\$vm_name = '$vmware_name';\$name = '$Snapshot'; cd /; C:\CLISave\createsnapshot.ps1;";
|
||||
$Command = "& 'C:\CLISave\createsnapshot.ps1' -vm_name '$vmware_name' -name '$Snapshot'";
|
||||
|
||||
Log::channel('Custom')->info("$Command");
|
||||
|
||||
$this->Command($Command);
|
||||
$cmdResult = $this->Command($Command);
|
||||
|
||||
Log::channel('Custom')->info("Command Result: " . $cmdResult);
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
Log::channel('Custom')->info("After run Command |" . Carbon::now());
|
||||
|
||||
Log::channel('Custom')->info("===================================================================");
|
||||
|
||||
// Check if command failed
|
||||
if (strpos($cmdResult, 'Login_Fail') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'SSH Login to PowerShell server failed'
|
||||
];
|
||||
}
|
||||
|
||||
if (strpos($cmdResult, '[STDERR]') !== false || stripos($cmdResult, 'error') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'PowerShell command failed: ' . $cmdResult
|
||||
];
|
||||
}
|
||||
|
||||
// Clear snapshot cache for this VM
|
||||
$this->clearSnapshotCache($product);
|
||||
|
||||
@@ -1739,9 +1875,16 @@ PS;
|
||||
$startTime = microtime(true);
|
||||
|
||||
try {
|
||||
$this->username = $product->ipaddress->host->datacenter->vCenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($product->ipaddress->host->datacenter->vCenter->password);
|
||||
$this->apiUri = $product->ipaddress->host->datacenter->vCenter->host;
|
||||
// Sử dụng helper method để resolve vCenter từ product
|
||||
$vcenter = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenter) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->username = $vcenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($vcenter->password);
|
||||
$this->apiUri = $vcenter->host;
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => true, 'message' => 'Lỗi setup credentials: ' . $e->getMessage()];
|
||||
}
|
||||
@@ -1919,28 +2062,52 @@ PS;
|
||||
private function callSoap($soapBody, $cookie = null)
|
||||
{
|
||||
$envelope = '<?xml version="1.0" encoding="UTF-8"?>
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:vim25="urn:vim25">
|
||||
' . $soapBody . '
|
||||
</soapenv:Envelope>';
|
||||
|
||||
$headers = [
|
||||
'Content-Type' => 'text/xml; charset=utf-8',
|
||||
'SOAPAction' => 'urn:vim25/2005'
|
||||
$httpHeaders = [
|
||||
'Content-Type: text/xml; charset=utf-8',
|
||||
'SOAPAction: "urn:vim25/6.0"'
|
||||
];
|
||||
|
||||
if ($cookie) {
|
||||
$headers['Cookie'] = $cookie;
|
||||
$httpHeaders[] = "Cookie: {$cookie}";
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
->withHeaders($headers)
|
||||
->post("https://{$this->apiUri}/sdk", $envelope);
|
||||
// Use cURL instead of Laravel Http to avoid HTTP/2 issues with vCenter
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, "https://{$this->apiUri}/sdk");
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $envelope);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_HEADER, true);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
|
||||
|
||||
$responseCookie = $response->header('Set-Cookie');
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
|
||||
$headers = substr($response, 0, $headerSize);
|
||||
$body = substr($response, $headerSize);
|
||||
curl_close($ch);
|
||||
|
||||
// Parse Set-Cookie header
|
||||
$responseCookie = null;
|
||||
if (preg_match('/Set-Cookie:\s*([^\r\n]+)/i', $headers, $matches)) {
|
||||
$responseCookie = trim($matches[1]);
|
||||
}
|
||||
|
||||
Log::channel('Custom')->debug('SOAP call', [
|
||||
'http_code' => $httpCode,
|
||||
'has_cookie' => !empty($responseCookie),
|
||||
'body_preview' => substr($body, 0, 200)
|
||||
]);
|
||||
|
||||
return [
|
||||
'body' => $response->body(),
|
||||
'cookie' => $responseCookie ? $responseCookie : $cookie
|
||||
'body' => $body,
|
||||
'cookie' => $responseCookie ?: $cookie
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1948,8 +2115,22 @@ PS;
|
||||
|
||||
public function RemoveSnapShot($product, $snap = ''): string|array
|
||||
{
|
||||
$this->username = $product->IpAddress->Host->Datacenter->vCenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($product->IpAddress->Host->Datacenter->vCenter->password);
|
||||
// Sử dụng helper method để resolve vCenter từ product
|
||||
$vcenter = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenter) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->username = $vcenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($vcenter->password);
|
||||
|
||||
// Login to get token
|
||||
$loginResult = $this->loginServer($vcenter);
|
||||
if (!$loginResult) {
|
||||
return "Login_Again";
|
||||
}
|
||||
|
||||
$vmware_name = (string) $product->name;
|
||||
$check = $this->checkApiExits();
|
||||
if ($check) {
|
||||
@@ -1961,11 +2142,28 @@ PS;
|
||||
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
$Command = "\$vm_name = '$vmware_name';\$name = '$snap'; cd /; C:\CLISave\deletesnap.ps1;";
|
||||
$Command = "& 'C:\CLISave\deletesnap.ps1' -vm_name '$vmware_name' -name '$snap'";
|
||||
|
||||
Log::channel('Custom')->info("$Command");
|
||||
|
||||
$this->Command($Command);
|
||||
$cmdResult = $this->Command($Command);
|
||||
|
||||
Log::channel('Custom')->info("Command Result: " . $cmdResult);
|
||||
|
||||
// Check if command failed
|
||||
if (strpos($cmdResult, 'Login_Fail') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'SSH Login to PowerShell server failed'
|
||||
];
|
||||
}
|
||||
|
||||
if (strpos($cmdResult, '[STDERR]') !== false || stripos($cmdResult, 'error') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'PowerShell command failed: ' . $cmdResult
|
||||
];
|
||||
}
|
||||
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
@@ -1996,9 +2194,23 @@ PS;
|
||||
|
||||
public function RevertSnapShot($product, $snap = ''): string|array
|
||||
{
|
||||
$this->username = $product->IpAddress->Host->Datacenter->vCenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($product->IpAddress->Host->Datacenter->vCenter->password);
|
||||
$this->apiUri = $product->IpAddress->Host->Datacenter->vCenter->host;
|
||||
// Sử dụng helper method để resolve vCenter từ product
|
||||
$vcenter = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenter) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->username = $vcenter->user;
|
||||
$this->password = SignRSA::DecryptFunc($vcenter->password);
|
||||
$this->apiUri = $vcenter->host;
|
||||
|
||||
// Login to get token
|
||||
$loginResult = $this->loginServer($vcenter);
|
||||
if (!$loginResult) {
|
||||
return "Login_Again";
|
||||
}
|
||||
|
||||
$vmware_name = (string) $product->name;
|
||||
$check = $this->checkApiExits();
|
||||
if ($check) {
|
||||
@@ -2010,11 +2222,28 @@ PS;
|
||||
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
$Command = "\$vm_name = '$vmware_name';\$name = '$snap'; cd /; C:\CLISave\backSnap.ps1;";
|
||||
$Command = "& 'C:\CLISave\backSnap.ps1' -vm_name '$vmware_name' -name '$snap'";
|
||||
|
||||
Log::channel('Custom')->info("$Command");
|
||||
|
||||
$this->Command($Command);
|
||||
$cmdResult = $this->Command($Command);
|
||||
|
||||
Log::channel('Custom')->info("Command Result: " . $cmdResult);
|
||||
|
||||
// Check if command failed
|
||||
if (strpos($cmdResult, 'Login_Fail') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'SSH Login to PowerShell server failed'
|
||||
];
|
||||
}
|
||||
|
||||
if (strpos($cmdResult, '[STDERR]') !== false || stripos($cmdResult, 'error') !== false) {
|
||||
return [
|
||||
'error' => true,
|
||||
'message' => 'PowerShell command failed: ' . $cmdResult
|
||||
];
|
||||
}
|
||||
|
||||
Log::channel('Custom')->info("\r\n");
|
||||
|
||||
|
||||
@@ -17,19 +17,54 @@ class SnapshotService
|
||||
$this->powerShellService = $powerShellService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve vCenter từ product (ModuleVmware) qua nhiều cách:
|
||||
* 1. Direct relation qua vcenter_id
|
||||
* 2. Qua ipAddress → host → datacenter → vCenter
|
||||
* 3. Qua Service relation
|
||||
*/
|
||||
protected function resolveVCenterFromProduct($product): ?\App\Models\vCenter
|
||||
{
|
||||
// Cách 1: Ưu tiên quan hệ trực tiếp trên ModuleVmware
|
||||
if ($product->vCenter) {
|
||||
return $product->vCenter;
|
||||
}
|
||||
|
||||
// Cách 2: Fallback qua ipAddress chain
|
||||
if ($product->ipaddress?->host?->datacenter?->vCenter) {
|
||||
return $product->ipaddress->host->datacenter->vCenter;
|
||||
}
|
||||
|
||||
// Cách 3: Qua Service relation
|
||||
$service = $product->services()->first();
|
||||
if ($service) {
|
||||
$service->load('vmware.vCenter');
|
||||
if ($service->vmware?->vCenter) {
|
||||
return $service->vmware->vCenter;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function CreateSnapShot($product): string|array
|
||||
{
|
||||
try {
|
||||
// Note: credentials setup logic from original vCenter.php seemed redundant with Client logic,
|
||||
// but CreateSnapShot was overwriting $this->username/password.
|
||||
// but CreateSnapShot was overwriting $this->username/password.
|
||||
// Here we assume Client is used, or we need to update Client.
|
||||
// Client stores token. If we need username/password for something else, Client has them now via getters.
|
||||
// But CreateSnapshot used $product->ipaddress...->vCenter->user/password.
|
||||
|
||||
|
||||
// Re-login to ensure we have the right credentials for the vCenter associated with the product
|
||||
$vcenterModel = $product->ipaddress->host->datacenter->vCenter;
|
||||
$vcenterModel = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenterModel) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->client->loginServer($vcenterModel);
|
||||
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => true, 'message' => 'Lỗi setup credentials: ' . $e->getMessage()];
|
||||
}
|
||||
@@ -86,7 +121,12 @@ class SnapshotService
|
||||
// and add the private helpers it depends on.
|
||||
|
||||
try {
|
||||
$vcenterModel = $product->ipaddress->host->datacenter->vCenter;
|
||||
$vcenterModel = $this->resolveVCenterFromProduct($product);
|
||||
|
||||
if (!$vcenterModel) {
|
||||
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
|
||||
}
|
||||
|
||||
$this->client->loginServer($vcenterModel);
|
||||
} catch (\Exception $e) {
|
||||
return ['error' => true, 'message' => 'Lỗi setup credentials: ' . $e->getMessage()];
|
||||
|
||||
Reference in New Issue
Block a user