Files
Virtnet.bond/extensions/Servers/Proxmox/Models/Node.php

106 lines
2.8 KiB
PHP

<?php
namespace Paymenter\Extensions\Servers\Proxmox\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Node extends Model
{
protected $table = 'ext_proxmox_nodes';
protected $fillable = [
// Shows to customer
'name',
'notes',
'memory',
'disk',
'cpu',
'location_id',
'storage_location',
'backup_location',
'vnc_enabled',
'is_lxc',
];
protected $casts = [
'is_lxc' => 'boolean',
];
/**
* Get the Proxmox API type path segment for this node (qemu or lxc).
*/
public function vmType(): string
{
return $this->is_lxc ? 'lxc' : 'qemu';
}
public function servers()
{
return $this->hasMany(Server::class);
}
public function ipAddresses()
{
return $this->hasMany(IPAddress::class);
}
public function ipPools()
{
return $this->belongsToMany(IPPool::class, 'ext_proxmox_ip_pool_nodes', 'node_id', 'ip_pool_id');
}
public function location()
{
return $this->belongsTo(Location::class);
}
public function resourcesAvailable()
{
return Cache::remember('proxmox-node-resources-' . $this->id, 30, function () {
$servers = $this->servers()->with('service.product.settings')->get();
$totalMemory = $this->memory;
$totalDisk = $this->disk;
$totalCpu = $this->cpu;
$usedMemory = 0;
$usedDisk = 0;
$usedCpu = 0;
foreach ($servers as $server) {
$productSettings = $server->service->product->settings->keyBy('key');
$usedMemory += (int) ($productSettings->get('memory')?->value ?? 0);
$usedDisk += (int) ($productSettings->get('disk')?->value ?? 0);
$usedCpu += (int) ($productSettings->get('cpu')?->value ?? 0);
}
return [
'memory' => $totalMemory == 0 ? null : $totalMemory - $usedMemory,
'disk' => $totalDisk == 0 ? null : $totalDisk - $usedDisk,
'cpu' => $totalCpu == 0 ? null : $totalCpu - $usedCpu,
];
});
}
public function forgetResourceCache(): void
{
Cache::forget('proxmox-node-resources-' . $this->id);
}
public function canStoreServer($memory, $disk, $cpu)
{
$resources = $this->resourcesAvailable();
if ($resources['memory'] !== null && $resources['memory'] < $memory) {
return false;
}
if ($resources['disk'] !== null && $resources['disk'] < $disk) {
return false;
}
if ($resources['cpu'] !== null && $resources['cpu'] < $cpu) {
return false;
}
return true;
}
}