Add stubs for various Laravel components and scaffolding

- Created stubs for JavaScript and SASS assets.
- Added stubs for channel, command, component, controller, event, factory, job, listener, mail, middleware, migration, model, notification, observer, policy, request, resource, route provider, seeder, and validation rule.
- Implemented scaffolding for configuration, service provider, and Vite integration.
- Included example views for module structure.
- Introduced a module loader for Vite to handle asset paths dynamically.
This commit is contained in:
baodev0
2026-05-29 09:28:08 +07:00
parent fccb0c353a
commit 6bb4a47bfb
89 changed files with 3355 additions and 4560 deletions
File diff suppressed because it is too large Load Diff
+25
View File
@@ -66,4 +66,29 @@ class Client
{
return $this->password;
}
public function SetConfig($data): static
{
$this->username = $data['user'] ?? $data->user;
$this->password = \App\Http\Facade\SignRSA::DecryptFunc($data['password'] ?? $data->password);
return $this;
}
public function resolveVCenterFromProduct(\App\Models\ModuleVmware $product): ?\App\Models\vCenter
{
if ($product->vCenter) {
return $product->vCenter;
}
if ($product->ipAddress?->host?->datacenter?->vCenter) {
return $product->ipAddress->host->datacenter->vCenter;
}
$service = $product->services()->first();
if ($service) {
$service->load('vmware.vCenter');
if ($service->vmware?->vCenter) {
return $service->vmware->vCenter;
}
}
return null;
}
}
@@ -170,4 +170,95 @@ class PowerManagementService
}
return "Login_Again";
}
public function restartVM($product, $vmware_id = ''): array|string
{
try {
$vmId = $vmware_id ?: ($product->vmware_id ?? null);
if (!$vmId) {
return [
'error' => true,
'data' => 'Không tìm thấy vmware_id',
];
}
$vcenter = $product->vCenter ?? null;
if (!$vcenter && isset($product->ipAddress) && $product->ipAddress?->host?->datacenter?->vCenter) {
$vcenter = $product->ipAddress->host->datacenter->vCenter;
}
if (!$vcenter) {
return [
'error' => true,
'data' => 'Không tìm thấy thông tin vCenter cho VM',
];
}
$check = $this->client->loginServer($vcenter);
if (!$check) {
return "Login_Again";
}
$response = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->post("https://{$this->client->apiUri}/rest/vcenter/vm/$vmId/guest/power?action=reboot");
if ($response->status() === 200) {
return [
'error' => false,
'data' => 'success'
];
}
return [
'error' => true,
'data' => $response->json('value') ?? $response->body(),
];
} catch (\Throwable $e) {
return [
'error' => true,
'data' => $e->getMessage(),
];
}
}
public function getVmPowerState($product, string $vmware_id = ''): array|string
{
try {
$vmId = $vmware_id ?: ($product->vmware_id ?? null);
if (!$vmId) {
return ['error' => true, 'data' => 'Không tìm thấy vmware_id'];
}
$vcenter = $product->vCenter ?? null;
if (!$vcenter && $product->ipAddress?->host?->datacenter?->vCenter) {
$vcenter = $product->ipAddress->host->datacenter->vCenter;
}
if (!$vcenter) {
return ['error' => true, 'data' => 'Không tìm thấy thông tin vCenter cho VM'];
}
if (!$this->client->loginServer($vcenter)) {
return 'Login_Again';
}
$response = Http::withoutVerifying()
->withHeaders(['vmware-api-session-id' => $this->client->token])
->timeout(8)
->get("https://{$this->client->apiUri}/rest/vcenter/vm/$vmId/power");
if ($response->successful()) {
$data = $response->json();
return ['error' => false, 'data' => $data['value'] ?? $data];
}
return ['error' => true, 'data' => $response->json('value') ?? 'Không thể lấy trạng thái VM'];
} catch (\Throwable $e) {
return ['error' => true, 'data' => $e->getMessage()];
}
}
}
@@ -267,4 +267,74 @@ PS;
return $data;
}
public function changeIpVM(
string $vmName,
string $vmwareId,
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) {
$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);
return (string) $this->CommandChangePort($Command, true);
}
$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->CommandRSP($Command);
}
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";
$cmd = "Invoke-VMScript -VM '$vmwareId' "
. "-ScriptText \"$ps\" "
. "-ScriptType Powershell "
. "-GuestUser '$guestUser' "
. "-GuestPassword '$guestPassword'";
$output = $this->CommandRSP($cmd);
if (!$output || str_contains($output, 'Login_Fail')) {
return null;
}
if (preg_match('/\b(\d{2,5})\b/', $output, $m)) {
return (int) $m[1];
}
return null;
}
}
@@ -158,6 +158,12 @@ class ResourceService
{
return $this->getAllNetwork($host_id);
}
public function getNetwork($host = ''): array|bool|string
{
return $this->getAllNetwork($host);
}
public function GetFolderByHost($datacenter = '')
{
return \App\Models\ModuleFolder::where('module_datacenter_id', $datacenter)->first();
+134 -1
View File
@@ -5,7 +5,6 @@ namespace App\Http\Services\vCenter;
use App\Support\Cache\CacheKey;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Http\Facade\SignRSA;
class SnapshotService
{
@@ -291,6 +290,140 @@ class SnapshotService
return $list;
}
public function RemoveSnapShot($product, $snap = ''): string|array
{
$vcenter = $this->resolveVCenterFromProduct($product);
if (!$vcenter) {
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
}
$loginResult = $this->client->loginServer($vcenter);
if (!$loginResult) {
return "Login_Again";
}
$vmware_name = (string) $product->name;
$check = $this->client->checkApiExits();
if ($check) {
try {
Log::channel('Custom')->info("===================================================================");
Log::channel('Custom')->info("Remove Snapshot with VirtualMachine Name - $vmware_name - Snap #$snap");
Log::channel('Custom')->info("\r\n");
$Command = "& 'C:\CLISave\deletesnap.ps1' -vm_name '$vmware_name' -name '$snap'";
Log::channel('Custom')->info("$Command");
$cmdResult = $this->powerShellService->executePowerCLI($Command);
Log::channel('Custom')->info("Command Result: " . $cmdResult);
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");
Log::channel('Custom')->info("After run Command |" . now());
Log::channel('Custom')->info("===================================================================");
$this->clearSnapshotCache($product);
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";
}
public function RevertSnapShot($product, $snap = ''): string|array
{
$vcenter = $this->resolveVCenterFromProduct($product);
if (!$vcenter) {
return ['error' => true, 'message' => 'Không tìm thấy thông tin vCenter cho VM'];
}
$loginResult = $this->client->loginServer($vcenter);
if (!$loginResult) {
return "Login_Again";
}
$vmware_name = (string) $product->name;
$check = $this->client->checkApiExits();
if ($check) {
try {
Log::channel('Custom')->info("===================================================================");
Log::channel('Custom')->info("Revert Snapshot with VirtualMachine Name - $vmware_name - Snap #$snap");
Log::channel('Custom')->info("\r\n");
$Command = "& 'C:\CLISave\backSnap.ps1' -vm_name '$vmware_name' -name '$snap'";
Log::channel('Custom')->info("$Command");
$cmdResult = $this->powerShellService->executePowerCLI($Command);
Log::channel('Custom')->info("Command Result: " . $cmdResult);
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");
Log::channel('Custom')->info("After run Command |" . now());
Log::channel('Custom')->info("===================================================================");
$this->clearSnapshotCache($product);
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 callSoap($soapBody, $cookie = null)
{
$curl = curl_init();
@@ -4,6 +4,8 @@ namespace App\Http\Services\vCenter;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Str;
use App\Http\Services\Discord;
use App\Models\ModuleDatastore;
use Exception;
@@ -11,10 +13,12 @@ use Exception;
class VirtualMachineService
{
protected Client $client;
protected PowerShellService $powerShellService;
public function __construct(Client $client)
public function __construct(Client $client, PowerShellService $powerShellService)
{
$this->client = $client;
$this->powerShellService = $powerShellService;
}
public function getAllVirtualMachine($datacenter = '')
@@ -353,4 +357,377 @@ class VirtualMachineService
}
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 = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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];
}
}
public function ConfigNetworkVirtualMachine($vmware_id = '', $config = []): int
{
return Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->patch("https://{$this->client->apiUri}/rest/vcenter/vm/$vmware_id/hardware/ethernet/4000", $config)
->status();
}
public function FindVirtualMachine($name = ''): string|bool
{
$check = $this->client->checkApiExits();
if ($check) {
try {
$response = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get(
"https://{$this->client->apiUri}/rest/vcenter/vm?filter.names.1=$name"
)->json();
} catch (ConnectionException $error) {
return false;
}
if ($response['value']) {
return $response['value'][0]['vm'];
}
return false;
}
return "Login_Again";
}
public function reBuildVPS(string $vmName): array|string
{
if (!$this->client->checkApiExits()) {
return "Login_Again";
}
try {
$response = Http::withoutVerifying()
->withHeaders([
'vmware-api-session-id' => $this->client->token
])
->get("https://{$this->client->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->client->token
])
->get("https://{$this->client->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->powerShellService->executePowerCLI($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()
];
}
}
public function UpgradeMemoryVirtualMachine($vmware_id = '', $ram = 0): array|string
{
$check = $this->client->checkApiExits();
if ($check) {
$RAMConfig = [
"spec" => [
"size_MiB" => $ram * 1024,
]
];
$response = Http::withoutVerifying()
->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 = Http::withoutVerifying()
->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";
}
}