refactor: implement centralized cache key management and add utility traits for vCenter SSH operations.
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\EmailTemplate;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Template;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class EmailTemplateController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$templates = Template::orderBy('type_id')->orderBy('id')->get();
|
||||
|
||||
return response()->json(['error' => false, 'data' => $templates]);
|
||||
}
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$template = Template::findOrFail($id);
|
||||
|
||||
return response()->json(['error' => false, 'data' => $template]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'type_id' => 'required|integer|min:1',
|
||||
'name' => 'nullable|string|max:100',
|
||||
'subject' => 'nullable|string|max:100',
|
||||
'message' => 'nullable|string',
|
||||
'status' => 'boolean',
|
||||
]);
|
||||
|
||||
$template = DB::transaction(fn () => Template::create($data));
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Thêm email template thành công',
|
||||
'data' => $template,
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$template = Template::findOrFail($id);
|
||||
|
||||
$data = $request->validate([
|
||||
'type_id' => 'sometimes|integer|min:1',
|
||||
'name' => 'sometimes|nullable|string|max:100',
|
||||
'subject' => 'sometimes|nullable|string|max:100',
|
||||
'message' => 'sometimes|nullable|string',
|
||||
'status' => 'sometimes|boolean',
|
||||
]);
|
||||
|
||||
DB::transaction(fn () => $template->update($data));
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Cập nhật email template thành công',
|
||||
'data' => $template->fresh(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
$template = Template::findOrFail($id);
|
||||
|
||||
DB::transaction(fn () => $template->delete());
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'message' => 'Đã xoá email template',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\InfraManagement;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\InfraManagement;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class InfraManagementController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = min((int) $request->get('per_page', 15), 500);
|
||||
$filter = $request->get('filter');
|
||||
$type = $request->get('type');
|
||||
$status = $request->get('status');
|
||||
|
||||
$query = InfraManagement::query()->select([
|
||||
'id', 'name', 'host', 'username', 'token', 'type', 'status',
|
||||
'description', 'meta_data', 'created_at', 'updated_at',
|
||||
]);
|
||||
|
||||
if ($filter) {
|
||||
$query->where(function ($q) use ($filter) {
|
||||
$q->where('name', 'like', "%{$filter}%")
|
||||
->orWhere('host', 'like', "%{$filter}%");
|
||||
});
|
||||
}
|
||||
|
||||
if ($type !== null && $type !== '') {
|
||||
if (is_array($type)) {
|
||||
$query->whereIn('type', $type);
|
||||
} else {
|
||||
$query->where('type', $type);
|
||||
}
|
||||
}
|
||||
|
||||
if ($status !== null && $status !== '') {
|
||||
$query->where('status', filter_var($status, FILTER_VALIDATE_BOOLEAN));
|
||||
}
|
||||
|
||||
$paginator = $query->latest()->paginate($perPage);
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'items' => $paginator->items(),
|
||||
'total' => $paginator->total(),
|
||||
'per_page' => $paginator->perPage(),
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$infra = InfraManagement::select([
|
||||
'id', 'name', 'host', 'username', 'token', 'type', 'status',
|
||||
'description', 'meta_data', 'created_at', 'updated_at',
|
||||
])->find($id);
|
||||
|
||||
if (!$infra) {
|
||||
return response()->json(['error' => true, 'message' => "Không tìm thấy cấu hình #$id"], 404);
|
||||
}
|
||||
|
||||
return response()->json(['error' => false, 'data' => $infra]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'host' => 'required|string|max:255',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'required|string',
|
||||
'token' => 'nullable|string',
|
||||
'type' => 'required|string|in:vcenter,esxi,jumphost',
|
||||
'status' => 'nullable|boolean',
|
||||
'description' => 'nullable|string',
|
||||
'meta_data' => 'nullable|array',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$data = $request->except(['password']);
|
||||
$data['password'] = SignRSA::EncryptFunc($request->password);
|
||||
$data['status'] = $request->boolean('status', true);
|
||||
|
||||
$infra = InfraManagement::create($data);
|
||||
|
||||
// Return without password
|
||||
$infra->makeHidden(['password']);
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json(['error' => false, 'data' => $infra], 201);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$infra = InfraManagement::find($id);
|
||||
|
||||
if (!$infra) {
|
||||
return response()->json(['error' => true, 'message' => "Không tìm thấy cấu hình #$id"], 404);
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'host' => 'required|string|max:255',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'nullable|string',
|
||||
'token' => 'nullable|string',
|
||||
'type' => 'required|string|in:vcenter,esxi,jumphost',
|
||||
'status' => 'nullable|boolean',
|
||||
'description' => 'nullable|string',
|
||||
'meta_data' => 'nullable|array',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$data = $request->except(['password']);
|
||||
$data['status'] = $request->boolean('status', $infra->status);
|
||||
|
||||
if (!empty($request->password)) {
|
||||
$data['password'] = SignRSA::EncryptFunc($request->password);
|
||||
}
|
||||
|
||||
$infra->update($data);
|
||||
$infra->refresh();
|
||||
$infra->makeHidden(['password']);
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json(['error' => false, 'data' => $infra]);
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => true, 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
$infra = InfraManagement::find($id);
|
||||
|
||||
if (!$infra) {
|
||||
return response()->json(['error' => true, 'message' => "Không tìm thấy cấu hình #$id"], 404);
|
||||
}
|
||||
|
||||
$infra->delete();
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã xoá cấu hình thành công']);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ namespace App\Http\Controllers\Api\Admin\Setting;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Models\Setting;
|
||||
use App\Support\Cache\CacheKey;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
@@ -90,7 +91,7 @@ class SettingController extends Controller
|
||||
);
|
||||
|
||||
// Flush mail config cache so new SMTP settings take effect immediately
|
||||
Cache::forget('mail_config');
|
||||
Cache::forget(CacheKey::build('settings', 'mail'));
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
|
||||
@@ -102,7 +102,7 @@ class VPSController extends Controller
|
||||
], 400);
|
||||
}
|
||||
|
||||
$result = $this->vCenterService->restartVM($vps, $vps->vmware_id);
|
||||
$result = $this->vCenterService->StartVirtualMachine($vps, $vps->vmware_id);
|
||||
|
||||
if (is_string($result)) {
|
||||
return response()->json([
|
||||
@@ -114,7 +114,7 @@ class VPSController extends Controller
|
||||
if ($result['error'] ?? true) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => $result['message'] ?? 'Failed to power on VM'
|
||||
'message' => $result['data'] ?? 'Failed to power on VM'
|
||||
], 400);
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ class VPSController extends Controller
|
||||
], 400);
|
||||
}
|
||||
|
||||
$result = $this->vCenterService->restartVM($vps, $vps->vmware_id);
|
||||
$result = $this->vCenterService->ShutdownGuestVirtualMachine($vps, $vps->vmware_id);
|
||||
|
||||
if (is_string($result)) {
|
||||
return response()->json([
|
||||
@@ -159,7 +159,7 @@ class VPSController extends Controller
|
||||
if ($result['error'] ?? true) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => $result['message'] ?? 'Failed to power off VM'
|
||||
'message' => $result['data'] ?? 'Failed to power off VM'
|
||||
], 400);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,11 @@ use App\Http\Controllers\Api\Service\Concerns\ResolvesVm;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Http\Services\vCenter;
|
||||
use App\Jobs\VirtualMachine\ChangeVmPasswordJob;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Os;
|
||||
use App\Models\Service;
|
||||
use App\Services\VmProvisionService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -304,6 +307,94 @@ class VmController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Change Password
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* POST /v1/system/vm-change-password
|
||||
*
|
||||
* Body: { product, current_password, new_password }
|
||||
* Dispatches ChangeVmPasswordJob — returns immediately, runs async.
|
||||
*/
|
||||
public function changePassword(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'product' => ['required'],
|
||||
'current_password' => ['required', 'string'],
|
||||
'new_password' => ['required', 'string', 'min:8'],
|
||||
]);
|
||||
|
||||
$vm = $this->resolveVmById($validated['product'], $request);
|
||||
if ($vm instanceof JsonResponse) {
|
||||
return $vm;
|
||||
}
|
||||
|
||||
// Detect OS family from VM's os_id record
|
||||
$os = $vm->os_id ? Os::with('osGroup')->find($vm->os_id) : null;
|
||||
$osGroupName = strtolower($os?->osGroup?->name ?? '');
|
||||
$osFamily = str_contains($osGroupName, 'windows')
|
||||
? VmProvisionService::OS_WINDOWS
|
||||
: VmProvisionService::OS_LINUX;
|
||||
|
||||
ChangeVmPasswordJob::dispatch(
|
||||
$vm->id,
|
||||
$vm->vmware_id,
|
||||
$osFamily,
|
||||
$validated['new_password'],
|
||||
$validated['current_password'],
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Yêu cầu đổi mật khẩu đã được ghi nhận. Hệ thống sẽ xử lý trong vài phút.',
|
||||
]);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Power State
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* GET /v1/system/vm-power-state?product={id|uuid|vmware_id}
|
||||
*
|
||||
* Calls vSphere REST API directly: GET /rest/vcenter/vm/{vmware_id}/power
|
||||
* Returns: { success: true, data: { state: "POWERED_ON"|"POWERED_OFF"|"SUSPENDED", clean_power_off: bool } }
|
||||
*/
|
||||
public function powerState(Request $request, vCenter $serviceVCenter): JsonResponse
|
||||
{
|
||||
$productId = $request->input('product');
|
||||
if (!$productId) {
|
||||
return response()->json(['success' => false, 'message' => 'Thiếu product id.'], 422);
|
||||
}
|
||||
|
||||
$vm = $this->resolveVmById($productId, $request);
|
||||
if ($vm instanceof JsonResponse) {
|
||||
return $vm;
|
||||
}
|
||||
|
||||
$result = $serviceVCenter->getVmPowerState($vm, $vm->vmware_id);
|
||||
|
||||
if ($result === 'Login_Again') {
|
||||
return response()->json(['success' => false, 'message' => 'Không thể đăng nhập vào vCenter.'], 400);
|
||||
}
|
||||
|
||||
if (is_array($result) && ($result['error'] ?? true)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => $result['data'] ?? 'Không thể lấy trạng thái VM.',
|
||||
], 400);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'state' => $result['data']['state'] ?? null,
|
||||
'clean_power_off' => $result['data']['clean_power_off'] ?? null,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface;
|
||||
use App\Services\ServerService;
|
||||
use Exception;
|
||||
use Illuminate\Support\Carbon;
|
||||
use App\Support\Cache\CacheKey;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -356,19 +357,19 @@ class DomainController extends Controller
|
||||
private function clearDomainCaches($domain): void
|
||||
{
|
||||
try {
|
||||
Cache::forget("domain.{$domain->id}");
|
||||
Cache::forget("domain.{$domain->domain_name}");
|
||||
Cache::forget('domains.all');
|
||||
Cache::forget('domains.filtered');
|
||||
// Clear specific domain keys
|
||||
Cache::forget(CacheKey::build('domain', 'detail', ['id' => $domain->id]));
|
||||
Cache::forget(CacheKey::build('domain', 'detail', ['name' => $domain->domain_name]));
|
||||
Cache::forget(CacheKey::build('domain', 'all'));
|
||||
|
||||
if ($domain->users) {
|
||||
foreach ($domain->users as $user) {
|
||||
Cache::forget("user.{$user->id}.domains");
|
||||
Cache::forget(CacheKey::build('domain', 'user-list', ['user_id' => $user->id]));
|
||||
}
|
||||
}
|
||||
|
||||
if ($domain->dns_manager_server_id) {
|
||||
Cache::forget("server.{$domain->dns_manager_server_id}.domains");
|
||||
Cache::forget(CacheKey::build('domain', 'server-list', ['server_id' => $domain->dns_manager_server_id]));
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
Log::warning('Failed to clear domain caches: ' . $e->getMessage());
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Models\Type;
|
||||
use App\Repositories\Group\GroupRepositoryInterface;
|
||||
use App\Repositories\Log\LogRepositoryInterface;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Support\Cache\CacheKey;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -154,23 +155,19 @@ class GroupController extends Controller
|
||||
/**
|
||||
* Clear all group and product-related caches
|
||||
*/
|
||||
private function clearGroupCaches($typeId)
|
||||
private function clearGroupCaches($typeId): void
|
||||
{
|
||||
// Clear general shop caches
|
||||
Cache::forget('shop_types_with_groups');
|
||||
|
||||
Cache::forget(CacheKey::build('group', 'shop-types'));
|
||||
|
||||
if ($typeId) {
|
||||
// Clear type-specific group cache
|
||||
Cache::forget("groups_type_{$typeId}");
|
||||
|
||||
// Clear all product caches for this type
|
||||
Cache::forget(CacheKey::build('group', 'by-type', ['type_id' => $typeId]));
|
||||
|
||||
$groups = $this->groupRepository->filter(['type_id' => $typeId]);
|
||||
foreach ($groups as $group) {
|
||||
Cache::forget("products_type_{$typeId}_group_{$group->id}");
|
||||
Cache::forget(CacheKey::build('group', 'products', ['type_id' => $typeId, 'group_id' => $group->id]));
|
||||
if ($group->slug) {
|
||||
// Clear paginated product caches for multiple pages
|
||||
for ($page = 1; $page <= 10; $page++) {
|
||||
Cache::forget("group_products_{$group->slug}_page_{$page}");
|
||||
Cache::forget(CacheKey::build('group', 'slug-products', ['page' => $page, 'slug' => $group->slug]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,6 +560,105 @@ class VCenterManagerController extends Controller
|
||||
return response()->json(['error' => true, 'message' => $errorData['value'] ?? $errorData['error_type'] ?? 'Failed to power off VM'], 400);
|
||||
}
|
||||
|
||||
public function restart(Request $request)
|
||||
{
|
||||
$vmId = (int) $request->input('vm_id');
|
||||
|
||||
$vm = VirtualMachines::find($vmId);
|
||||
|
||||
if (!$vm) {
|
||||
return response()->json(['error' => true, 'message' => 'VM not found'], 404);
|
||||
}
|
||||
|
||||
$vmwareId = $vm->vm_id;
|
||||
|
||||
if (!$vmwareId) {
|
||||
return response()->json(['error' => true, 'message' => 'VM VMware ID not found'], 400);
|
||||
}
|
||||
|
||||
$vcenter = $vm->datacenter?->vCenter ?? $vm->host?->datacenter?->vCenter;
|
||||
|
||||
if (!$vcenter) {
|
||||
return response()->json(['error' => true, 'message' => 'vCenter not found'], 400);
|
||||
}
|
||||
|
||||
$vCenterService = new \App\Http\Services\vCenter();
|
||||
|
||||
if (!$vCenterService->loginServer($vcenter)) {
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenterService->token])
|
||||
->post("https://{$vCenterService->apiUri}/rest/vcenter/vm/$vmwareId/power/reset");
|
||||
|
||||
if ($response->status() === 200) {
|
||||
return response()->json(['error' => false, 'message' => 'Restart command sent successfully']);
|
||||
}
|
||||
|
||||
$errorData = $response->json();
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => $errorData['value'] ?? $errorData['error_type'] ?? 'Failed to restart VM',
|
||||
], 400);
|
||||
}
|
||||
|
||||
public function snapshot(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'vm_id' => 'required|integer',
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string|max:1000',
|
||||
]);
|
||||
|
||||
$vmId = (int) $request->input('vm_id');
|
||||
|
||||
$vm = VirtualMachines::find($vmId);
|
||||
|
||||
if (!$vm) {
|
||||
return response()->json(['error' => true, 'message' => 'VM not found'], 404);
|
||||
}
|
||||
|
||||
$vmwareId = $vm->vm_id;
|
||||
|
||||
if (!$vmwareId) {
|
||||
return response()->json(['error' => true, 'message' => 'VM VMware ID not found'], 400);
|
||||
}
|
||||
|
||||
$vcenter = $vm->datacenter?->vCenter ?? $vm->host?->datacenter?->vCenter;
|
||||
|
||||
if (!$vcenter) {
|
||||
return response()->json(['error' => true, 'message' => 'vCenter not found'], 400);
|
||||
}
|
||||
|
||||
$vCenterService = new \App\Http\Services\vCenter();
|
||||
|
||||
if (!$vCenterService->loginServer($vcenter)) {
|
||||
return response()->json(['error' => true, 'message' => 'Cannot login to vCenter'], 400);
|
||||
}
|
||||
|
||||
$response = Http::withoutVerifying()
|
||||
->withHeaders(['vmware-api-session-id' => $vCenterService->token])
|
||||
->post("https://{$vCenterService->apiUri}/rest/vcenter/vm/$vmwareId/snapshot", [
|
||||
'spec' => [
|
||||
'name' => $request->input('name'),
|
||||
'description' => $request->input('description', ''),
|
||||
'memory' => false,
|
||||
'quiesce' => false,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($response->status() === 200) {
|
||||
return response()->json(['error' => false, 'message' => 'Snapshot created successfully']);
|
||||
}
|
||||
|
||||
$errorData = $response->json();
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => $errorData['value'] ?? $errorData['error_type'] ?? 'Failed to create snapshot',
|
||||
], 400);
|
||||
}
|
||||
|
||||
public function getPoweredOffVms()
|
||||
{
|
||||
$vms = VirtualMachines::whereNotNull('vm_id')
|
||||
|
||||
Reference in New Issue
Block a user