update fix deadcode, security

This commit is contained in:
baodev0
2026-09-28 08:26:29 +07:00
parent 3af59bd9c5
commit 82080b5b84
452 changed files with 4857 additions and 26289 deletions
@@ -64,19 +64,6 @@ trait ManagesSsh
}
}
public function loginSSH(): bool
{
$conn = $this->LoginAuth();
if ($conn) {
Log::info('✅ Connected to vCenter via SSH successfully');
return true;
}
Log::error('❌ Failed to connect to vCenter via SSH');
return false;
}
// ─── Command variants ────────────────────────────────────────────────────
/**
@@ -0,0 +1,190 @@
<?php
namespace App\Http\Services\vCenter\Concerns;
use App\Support\TlsHttpClientFactory;
use Illuminate\Support\Facades\Log;
trait ReadsVirtualMachineInfo
{
public function getAllVirtualMachine($datacenter = '', $host = '')
{
if ($this->client->checkApiExits()) {
$params = [];
if (!empty($datacenter)) {
$params['filter.datacenters'] = $datacenter;
}
if (!empty($host)) {
$params['filter.hosts'] = $host;
}
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm", $params)->json();
if (!isset($response['type'])) {
return $response['value'];
}
return false;
}
return "Login_Again";
}
public function CheckVirtualMachine($vmware_id = '')
{
if ($this->client->checkApiExits()) {
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id")->json();
if (!isset($response['type'])) {
return $response['value'];
}
return false;
}
return "Login_Again";
}
/**
* Search VM by exact name in vCenter.
* Returns the first matching VM array or null if not found.
*/
public function findVirtualMachineByName(string $vmName): ?array
{
$check = $this->client->checkApiExits();
if (!$check) {
Log::warning('findVirtualMachineByName: API check failed');
return null;
}
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm", [
'filter.names.1' => $vmName,
]);
if (!$response->successful()) {
Log::warning('findVirtualMachineByName: HTTP failed', ['status' => $response->status()]);
return null;
}
$json = $response->json();
if (isset($json['type']) || empty($json['value'])) {
return null;
}
return $json['value'][0] ?? null;
}
public function GetDetailVirtualMachine($vmware_id = ''): array
{
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id")->json();
if (!isset($response['type'])) {
return [
'error' => false,
'data' => $response['value']
];
}
return [
'error' => true,
'message' => $response['value']
];
}
public function GetIPAddressVirtualMachine($vmware_id = ''): array
{
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/guest/identity")->json();
if (!isset($response['type'])) {
return [
'error' => false,
'data' => $response['value']
];
}
return [
'error' => true,
'message' => $response['value']
];
}
public function GetVMStats($vmware_id = ''): array
{
$stats = [
'cpu' => null,
'memory' => null,
'disk' => null,
];
try {
$hardwareResponse = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/hardware")->json();
if (is_array($hardwareResponse) && !isset($hardwareResponse['type']) && isset($hardwareResponse['value'])) {
foreach ($hardwareResponse['value'] as $hardware) {
if (isset($hardware['label']) && $hardware['label'] === 'CPU') {
$stats['cpu'] = [
'cores' => $hardware['spec']['num_cores'] ?? 0,
'cores_per_socket' => $hardware['spec']['cores_per_socket'] ?? 0,
];
}
if (isset($hardware['label']) && $hardware['label'] === 'Memory') {
$stats['memory'] = [
'size_MiB' => $hardware['spec']['size_MiB'] ?? 0,
'size_GB' => round(($hardware['spec']['size_MiB'] ?? 0) / 1024, 2),
];
}
if (isset($hardware['label']) && $hardware['label'] === 'Hard disk') {
$stats['disk'][] = [
'capacity' => $hardware['capacity'] ?? 0,
'capacity_GB' => round(($hardware['capacity'] ?? 0) / (1024 * 1024 * 1024), 2),
];
}
}
}
$guestMemoryResponse = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/guest/memory")->json();
if (is_array($guestMemoryResponse) && !isset($guestMemoryResponse['type']) && isset($guestMemoryResponse['value'])) {
$stats['memory']['used_MiB'] = $guestMemoryResponse['value']['used'] ?? 0;
$stats['memory']['used_GB'] = round(($guestMemoryResponse['value']['used'] ?? 0) / 1024, 2);
$stats['memory']['usage_percent'] = $stats['memory']['size_MiB'] > 0
? round(($guestMemoryResponse['value']['used'] ?? 0) / $stats['memory']['size_MiB'] * 100, 1)
: 0;
}
$guestCpuResponse = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/guest/cpu")->json();
if (is_array($guestCpuResponse) && !isset($guestCpuResponse['type']) && isset($guestCpuResponse['value'])) {
$stats['cpu']['used_percent'] = $guestCpuResponse['value']['used'] ?? 0;
}
return ['error' => false, 'data' => $stats];
} catch (\Exception $e) {
return ['error' => true, 'message' => $e->getMessage(), 'data' => $stats];
}
}
}
@@ -0,0 +1,212 @@
<?php
namespace App\Http\Services\vCenter\Concerns;
use App\Support\TlsHttpClientFactory;
use Illuminate\Support\Facades\Log;
use Exception;
trait UpgradesVirtualMachine
{
public function UpgradeMemoryVirtualMachine($vmware_id = '', $ram = 0): array|string
{
$check = $this->client->checkApiExits();
if ($check) {
$RAMConfig = [
"spec" => [
"size_MiB" => $ram * 1024,
]
];
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->patch("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/hardware/memory", $RAMConfig);
if ($response->status() === 200) {
return [
'error' => false,
'data' => 'success'
];
}
return [
'error' => true,
'data' => $response['value']
];
}
return "Login_Again";
}
public function UpgradeCPUVirtualMachine($vmware_id = '', $cpu = 0): array|string
{
$check = $this->client->checkApiExits();
if ($check) {
$CPUConfig = [
"spec" => [
"cores_per_socket" => 1,
"count" => $cpu
]
];
$response = TlsHttpClientFactory::vCenter()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->patch("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/hardware/cpu", $CPUConfig);
if ($response->status() === 200) {
return [
'error' => false,
'data' => 'success'
];
}
return [
'error' => true,
'data' => $response['value']
];
}
return "Login_Again";
}
public function UpgradeDiskVirtualMachine($product, $disk = 0): array|string
{
$vmware_id = $product->vmware_id;
$check = $this->client->checkApiExits();
if ($check) {
try {
Log::channel('Custom')->info("===================================================================");
Log::channel('Custom')->info("Upgrade Disk with VirtualMachine ID # - $vmware_id");
Log::channel('Custom')->info("\r\n");
$Command = "\$vm = 'VirtualMachine-$vmware_id'; \$disksize = $disk; cd /; C:\CLISave\diskresize.ps1;";
Log::channel('Custom')->info("$Command");
$this->powerShellService->executePowerCLI($Command);
Log::channel('Custom')->info("\r\n");
Log::channel('Custom')->info("After run Command |" . now());
Log::channel('Custom')->info("===================================================================");
return [
'error' => false
];
} catch (\Exception $error) {
Log::channel('Custom')->info("\r\n");
Log::channel('Custom')->info("===================================================================");
Log::channel('Custom')->info("Error Log: ");
Log::channel('Custom')->info($error->getMessage());
Log::channel('Custom')->info("===================================================================");
return [
'error' => true,
'message' => $error->getMessage()
];
}
}
return "Login_Again";
}
private function updateVMHardware($vmId, $addon, $base_cpu, $base_ram): void
{
try {
Log::info("=== BẮT ĐẦU CẬP NHẬT ADDON ===");
$new_cpu = $base_cpu + $addon['cpu'];
$new_ram_mib = ($base_ram + $addon['ram']) * 1024;
if ($addon['cpu'] > 0) {
$this->updateVMCPU($vmId, $new_cpu);
}
if ($addon['ram'] > 0) {
$this->updateVMMemory($vmId, $new_ram_mib);
}
Log::info("=== HOÀN THÀNH CẬP NHẬT ADDON ===");
} catch (Exception $e) {
Log::error("❌ Lỗi khi cập nhật cấu hình phần cứng VM {$vmId}: " . $e->getMessage());
}
}
private function updateVMCPU($vmId, $cpuCount): bool
{
try {
$coresPerSocket = 1;
if ($cpuCount > 1) {
$maxCoresPerSocket = floor($cpuCount / 2);
for ($i = $maxCoresPerSocket; $i >= 1; $i--) {
if ($cpuCount % $i === 0) {
$coresPerSocket = $i;
break;
}
}
if ($coresPerSocket === 1 && $cpuCount > 2) {
$coresPerSocket = $cpuCount;
}
}
$payload = [
'spec' => [
'count' => $cpuCount,
'cores_per_socket' => $coresPerSocket,
'hot_add_enabled' => true
]
];
$response = TlsHttpClientFactory::vCenter()
->timeout(30)
->withHeaders([
'vmware-api-session-id' => $this->client->token,
'Content-Type' => 'application/json',
])
->patch("https://{$this->client->apiUri}/rest/vcenter/vm/{$vmId}/hardware/cpu", $payload);
if ($response->successful()) {
Log::info("✅ API call cập nhật CPU thành công cho VM {$vmId}");
return true;
} else {
Log::error("❌ API call cập nhật CPU thất bại cho VM {$vmId}", [
'status' => $response->status(),
'response' => $response->body()
]);
return false;
}
} catch (Exception $e) {
Log::error("❌ Exception khi cập nhật CPU cho VM {$vmId}: " . $e->getMessage());
return false;
}
}
private function updateVMMemory($vmId, $ramSizeMB): bool
{
try {
$payload = [
'spec' => [
'size_MiB' => $ramSizeMB
]
];
$response = TlsHttpClientFactory::vCenter()
->timeout(30)
->withHeaders([
'vmware-api-session-id' => $this->client->token,
'Content-Type' => 'application/json',
])
->patch("https://{$this->client->apiUri}/rest/vcenter/vm/{$vmId}/hardware/memory", $payload);
if ($response->successful()) {
Log::info("✅ API call cập nhật RAM thành công cho VM {$vmId}");
return true;
} else {
Log::error("❌ API call cập nhật RAM thất bại cho VM {$vmId}", [
'status' => $response->status(),
'response' => $response->body()
]);
return false;
}
} catch (Exception $e) {
Log::error("❌ Exception khi cập nhật RAM cho VM {$vmId}: " . $e->getMessage());
return false;
}
}
}