perf: 补回get_terminal_latest_stat 方法

pull/10097/head
feng 2023-03-29 13:48:51 +08:00 committed by Jiangjie.Bai
parent f214b47306
commit 678df5bf3e
2 changed files with 42 additions and 1 deletions

View File

@ -1,11 +1,12 @@
import uuid
from django.core.cache import cache
from django.db import models
from django.forms.models import model_to_dict
from django.utils.translation import ugettext_lazy as _
from common.utils import get_logger
logger = get_logger(__name__)
@ -21,9 +22,44 @@ class Status(models.Model):
terminal = models.ForeignKey('terminal.Terminal', null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
CACHE_KEY = 'TERMINAL_STATUS_{}'
class Meta:
db_table = 'terminal_status'
get_latest_by = 'date_created'
verbose_name = _("Status")
@classmethod
def get_terminal_latest_stat(cls, terminal):
key = cls.CACHE_KEY.format(terminal.id)
data = cache.get(key)
if not data:
return None
data.pop('terminal', None)
stat = cls(**data)
stat.terminal = terminal
stat.is_alive = terminal.is_alive
stat.keep_one_decimal_place()
return stat
def keep_one_decimal_place(self):
keys = ['cpu_load', 'memory_used', 'disk_used']
for key in keys:
value = getattr(self, key, 0)
if not isinstance(value, (int, float)):
continue
value = '%.1f' % value
setattr(self, key, float(value))
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.terminal.set_alive(ttl=120)
return self.save_to_cache()
def save_to_cache(self):
if not self.terminal:
return
key = self.CACHE_KEY.format(self.terminal.id)
data = model_to_dict(self)
cache.set(key, data, 60 * 3)
return data

View File

@ -1,6 +1,7 @@
import time
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.translation import ugettext_lazy as _
@ -35,6 +36,10 @@ class TerminalStatusMixin:
return False
return time.time() - self.last_stat.date_created.timestamp() < 150
def set_alive(self, ttl=120):
key = self.ALIVE_KEY.format(self.id)
cache.set(key, True, ttl)
class StorageMixin:
command_storage: str