import time
from collections import namedtuple
import psutil
from django.views.generic import TemplateView
from humanize import naturalsize
from sdbs_infra.dashboard.models import Service
class IndexView(TemplateView):
template_name = "index.html"
def get_context_data(self, **kwargs):
return {
'services': Service.objects.all(),
'vps_stats': self.vps_stats()
}
# noinspection PyListCreation
@staticmethod
def vps_stats():
stats = []
stats.append(f"LOAD AVG: {', '.join(map(str, psutil.getloadavg()))}")
memory = psutil.virtual_memory()
stats.append(
f"MEM: {naturalsize(memory.used)}/{naturalsize(memory.total)} ({memory.percent}% USED)"
)
disk = psutil.disk_usage('/')
stats.append(
f"DISK: {naturalsize(disk.used)}/{naturalsize(disk.total)} ({disk.percent}% USED)"
)
uptime = normalize_seconds(time.time() - psutil.boot_time())
stats.append(
f"UPTIME: {int(uptime.days)} days, {int(uptime.hours)} hours, {int(uptime.minutes)} minutes"
)
return " / ".join(map(lambda stat: stat.replace(" ", " "), stats))
def normalize_seconds(seconds: int):
(days, remainder) = divmod(seconds, 86400)
(hours, remainder) = divmod(remainder, 3600)
(minutes, seconds) = divmod(remainder, 60)
return namedtuple("_", ("days", "hours", "minutes", "seconds"))(days, hours, minutes, seconds)