refactor: implement centralized cache key management and add utility traits for vCenter SSH operations.

This commit is contained in:
pbao9
2026-05-16 16:52:21 +07:00
parent 06dbd54ecd
commit 8a115c5175
36 changed files with 1694 additions and 517 deletions
+107 -36
View File
@@ -2,56 +2,127 @@
namespace App\Services\Cache;
use App\Services\Cache\CacheServiceInterface;
use Closure;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use stdClass;
class CacheService implements CacheServiceInterface
{
protected int $ttl;
private const TTL_SECONDS = [
self::TTL_SHORT => 300, // 5 minutes
self::TTL_MEDIUM => 3600, // 1 hour
self::TTL_LONG => 86400, // 24 hours
];
public function __construct(int $ttl = 60)
{
$this->ttl = $ttl;
}
private const TAGGABLE_DRIVERS = ['redis', 'memcached', 'dynamodb'];
public function putCache(string $prefix, string $key, mixed $value, ?int $ttl = null): void
{
$cacheKey = $this->makeKey($prefix, $key);
Cache::put($cacheKey, $value, $ttl ?? $this->ttl);
}
// -------------------------------------------------------------------------
// Interface implementation
// -------------------------------------------------------------------------
public function getCache(string $prefix, string $key, mixed $default = null): mixed
{
$cacheKey = $this->makeKey($prefix, $key);
return Cache::get($cacheKey, $default);
}
public function remember(
string $key,
Closure $callback,
string $ttl = self::TTL_MEDIUM,
array $tags = [],
): mixed {
$store = $this->resolveStore($tags);
$sentinel = new stdClass();
$cached = $store->get($key, $sentinel);
public function clearCache(string $prefix, string $key): void
{
$cacheKey = $this->makeKey($prefix, $key);
Cache::forget($cacheKey);
}
public function clearCacheByPrefix(string $prefix): void
{
$cachePrefix = config('cache.prefix');
$pattern = $cachePrefix . $prefix . '_*';
$keys = Redis::connection('cache')->keys($pattern);
foreach ($keys as $k) {
Redis::connection('cache')->del($k);
if ($cached !== $sentinel) {
Log::debug("CACHE HIT: {$key}");
return $cached;
}
Log::debug("CACHE MISS: {$key}");
$value = $callback();
$store->put($key, $value, $this->resolveTtl($ttl));
return $value;
}
protected function makeKey(string $prefix, string $key = ''): string
public function put(
string $key,
mixed $value,
string $ttl = self::TTL_MEDIUM,
array $tags = [],
): void {
$this->resolveStore($tags)->put($key, $value, $this->resolveTtl($ttl));
}
public function get(string $key, mixed $default = null): mixed
{
return trim($prefix . '_' . $key, '_');
return Cache::get($key, $default);
}
public function forget(string $key): void
{
Cache::forget($key);
}
public function clearByModule(string $module): void
{
if ($this->supportsTagging()) {
Cache::tags([$module])->flush();
return;
}
$this->scanAndDelete($module);
}
// -------------------------------------------------------------------------
// Internals
// -------------------------------------------------------------------------
private function resolveStore(array $tags): CacheRepository
{
if (!empty($tags) && $this->supportsTagging()) {
return Cache::tags($tags);
}
return Cache::store();
}
/**
* Delete all keys for a module using SCAN (safe for production).
*
* KEYS is O(N) and blocks Redis; SCAN iterates in batches without blocking.
* The pattern matches: {cache_prefix}:{module}:*
*/
private function scanAndDelete(string $module): void
{
$redis = Redis::connection('cache');
$prefix = config('cache.prefix');
$pattern = "{$prefix}:{$module}:*";
$cursor = '0';
do {
$result = $redis->scan($cursor, 'MATCH', $pattern, 'COUNT', 100);
if ($result === false) {
break;
}
[$cursor, $keys] = $result;
foreach ((array) $keys as $key) {
$redis->del($key);
}
} while ((string) $cursor !== '0');
}
private function supportsTagging(): bool
{
return in_array(config('cache.default'), self::TAGGABLE_DRIVERS, strict: true);
}
private function resolveTtl(string $ttl): int
{
return self::TTL_SECONDS[$ttl] ?? self::TTL_SECONDS[self::TTL_MEDIUM];
}
}
+43 -5
View File
@@ -2,10 +2,48 @@
namespace App\Services\Cache;
use Closure;
interface CacheServiceInterface
{
public function putCache(string $prefix, string $key, mixed $value, ?int $ttl = null): void;
public function getCache(string $prefix, string $key, mixed $default = null): mixed;
public function clearCache(string $prefix, string $key): void;
public function clearCacheByPrefix(string $prefix): void;
}
public const TTL_SHORT = 'short'; // 5 minutes
public const TTL_MEDIUM = 'medium'; // 1 hour
public const TTL_LONG = 'long'; // 24 hours
/**
* Return cached value or execute callback and store the result.
* Logs HIT / MISS to debug channel.
*
* @param string[] $tags Optional tag list (only applied when driver supports tagging)
*/
public function remember(
string $key,
Closure $callback,
string $ttl = self::TTL_MEDIUM,
array $tags = [],
): mixed;
/**
* Store a value unconditionally.
*
* @param string[] $tags
*/
public function put(
string $key,
mixed $value,
string $ttl = self::TTL_MEDIUM,
array $tags = [],
): void;
public function get(string $key, mixed $default = null): mixed;
public function forget(string $key): void;
/**
* Invalidate all cache entries belonging to a module.
*
* Uses Cache::tags()->flush() when the driver supports tagging (Redis, Memcached),
* falls back to a Redis SCAN-based deletion otherwise.
*/
public function clearByModule(string $module): void;
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Services;
use App\Services\Cache\CacheServiceInterface;
use App\Support\Cache\CacheKey;
/**
* Example service demonstrating the CacheService + CacheKey pattern.
*
* Cache key format: module:type[:param:value...]
*
* Examples produced:
* students:list:page:1
* students:list:page:2:status:active
* students:detail:id:15
*/
class StudentService
{
private const MODULE = 'students';
public function __construct(
private readonly CacheServiceInterface $cache,
) {}
public function getList(int $page = 1, ?string $status = null): array
{
$params = ['page' => $page];
if ($status !== null) {
$params['status'] = $status;
}
$key = CacheKey::build(self::MODULE, 'list', $params);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchList($page, $status),
ttl: CacheServiceInterface::TTL_MEDIUM,
tags: [self::MODULE],
);
}
public function getDetail(int $id): array
{
$key = CacheKey::build(self::MODULE, 'detail', ['id' => $id]);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchDetail($id),
ttl: CacheServiceInterface::TTL_LONG,
tags: [self::MODULE],
);
}
public function update(int $id, array $_data): void
{
// ... update DB logic ...
// Forget only the stale detail entry
$this->cache->forget(
CacheKey::build(self::MODULE, 'detail', ['id' => $id])
);
// Also bust all list caches for this module
$this->cache->clearByModule(self::MODULE);
}
public function getByIds(array $ids): array
{
// Array params are joined with "," — key: students:bulk:ids:1,2,3
$key = CacheKey::build(self::MODULE, 'bulk', ['ids' => $ids]);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchByIds($ids),
ttl: CacheServiceInterface::TTL_SHORT,
tags: [self::MODULE],
);
}
// -------------------------------------------------------------------------
// Private DB fetch methods (replace with real Eloquent/Repository calls)
// -------------------------------------------------------------------------
private function fetchList(int $_page, ?string $_status): array
{
return []; // replace with Eloquent/Repository query
}
private function fetchDetail(int $_id): array
{
return []; // replace with Eloquent/Repository query
}
private function fetchByIds(array $_ids): array
{
return []; // replace with Eloquent/Repository query
}
}
+76 -5
View File
@@ -34,6 +34,10 @@ final class VsphereHostSshService
private const SCRIPT_VERIFY_LINUX = 'verifyIPLinux.ps1';
private const SCRIPT_VERIFY_WINDOWS = 'verifyIPWindows.ps1';
private const CHANGE_PWD_DIR = 'C:\\CLISave\\changePassword';
private const SCRIPT_CHANGE_PWD_LINUX = 'changePwdLinux.ps1';
private const SCRIPT_CHANGE_PWD_WINDOWS = 'changePwdWindows.ps1';
private const CONNECT_TIMEOUT = 20;
private const MAX_RETRIES = 5;
private const RETRY_DELAY = 5;
@@ -91,8 +95,8 @@ final class VsphereHostSshService
* Assign a static IP to the VM guest OS via PS1 script.
* Calls assignIPLinux.ps1 or assignIPWindows.ps1 in C:\CLISave\AssignIP\.
*
* Windows script params (7): VMName IP MaskBits Gateway DNS GuestUser GuestPassword
* Linux script params (9): VCenter VCUser VCPass VMName IP Gateway DNS GuestUser GuestPassword
* Windows script params (7): VMName IP MaskBits Gateway DNS GuestUser GuestPassword
* Linux script params (10): VCenter VCUser VCPass VMName IP MaskBits Gateway DNS GuestUser GuestPassword
*
* Script output: JSON {"status":"ok"} or {"status":"error","message":"..."}
*/
@@ -127,9 +131,9 @@ final class VsphereHostSshService
$this->warg($guestPassword),
);
} else {
// assignIPLinux.ps1: VCenter VCUser VCPass VMName IP Gateway DNS GuestUser GuestPassword
// assignIPLinux.ps1: VCenter VCUser VCPass VMName IP MaskBits Gateway DNS GuestUser GuestPassword
$remoteCmd = sprintf(
'cd %s && powershell -ExecutionPolicy Bypass -NonInteractive -File %s %s %s %s %s %s %s %s %s %s',
'cd %s && powershell -ExecutionPolicy Bypass -NonInteractive -File %s %s %s %s %s %s %s %s %s %s %s',
self::ASSIGN_DIR,
$script,
$this->warg($vcenterHost),
@@ -137,6 +141,7 @@ final class VsphereHostSshService
$this->warg($vcenterPassword),
$this->warg($vmId),
$this->warg($ip),
$this->warg($cidr),
$this->warg($gateway),
$this->warg($dns),
$this->warg($guestUser),
@@ -272,12 +277,78 @@ final class VsphereHostSshService
);
}
/**
* Customer-initiated VM password change.
*
* Calls changePwdLinux.ps1 / changePwdWindows.ps1 in C:\CLISave\changePassword\.
*
* Param order (matches PS1 declaration):
* $vm vm_id / vmware display name double-quoted
* $password new password single-quoted
* $vcenter_host vCenter host double-quoted
* $vcenter_user vCenter user double-quoted
* $vcenter_password vCenter password single-quoted
* $guest_password current guest password single-quoted
*
* PS1 outputs "SUCCESS" or "ERROR".
*/
public function changePasswordCustomer(
string $vmId,
string $newPassword,
string $currentGuestPassword,
string $osFamily,
string $vcenterHost,
string $vcenterUser,
string $vcenterPassword,
): string {
$script = strtoupper($osFamily) === VmProvisionService::OS_WINDOWS
? self::SCRIPT_CHANGE_PWD_WINDOWS
: self::SCRIPT_CHANGE_PWD_LINUX;
$remoteCmd = sprintf(
'cd %s && powershell -ExecutionPolicy Bypass -NonInteractive -File %s %s %s %s %s %s %s',
self::CHANGE_PWD_DIR,
$script,
$this->warg($vmId),
$this->warg($newPassword),
$this->warg($vcenterHost),
$this->warg($vcenterUser),
$this->warg($vcenterPassword),
$this->warg($currentGuestPassword),
);
Log::info('VsphereHostSshService: changePasswordCustomer', [
'vm_id' => $vmId,
'script' => $script,
'os' => $osFamily,
]);
$output = $this->sshExec($remoteCmd);
Log::info('VsphereHostSshService: changePasswordCustomer output', [
'vm_id' => $vmId,
'output' => trim($output),
]);
return $output;
}
// ─────────────────────────────────────────────────────────────────────────
/**
* Windows cmd.exe safe argument: wrap in double quotes, escape inner double quotes.
* Password charset excludes " and % so wrapping is always safe.
*/
private function warg(string $value): string
{
return '"' . str_replace('"', '\\"', $value) . '"';
}
/**
* Single-quote wrap for passwords — prevents PowerShell variable expansion on $, %, ^ etc.
* Inside a single-quoted PS string, a literal single quote is escaped as ''.
*/
private function sarg(string $value): string
{
return "'" . str_replace("'", "''", $value) . "'";
}
}