Commit e0a3fafb authored by ibuler's avatar ibuler

[Bugfix] 详见trello

parent 3804ab53
# ~*~ coding: utf-8 ~*~ # ~*~ coding: utf-8 ~*~
import json import json
import re
from celery import shared_task from celery import shared_task
from django.core.cache import cache from django.core.cache import cache
...@@ -18,6 +19,7 @@ FORKS = 10 ...@@ -18,6 +19,7 @@ FORKS = 10
TIMEOUT = 60 TIMEOUT = 60
logger = get_logger(__file__) logger = get_logger(__file__)
CACHE_MAX_TIME = 60*60*60 CACHE_MAX_TIME = 60*60*60
disk_pattern = re.compile(r'^hd|sd')
@shared_task @shared_task
...@@ -57,7 +59,7 @@ def set_assets_hardware_info(result, **kwargs): ...@@ -57,7 +59,7 @@ def set_assets_hardware_info(result, **kwargs):
___memory = '%s %s' % capacity_convert('{} MB'.format(info['ansible_memtotal_mb'])) ___memory = '%s %s' % capacity_convert('{} MB'.format(info['ansible_memtotal_mb']))
disk_info = {} disk_info = {}
for dev, dev_info in info['ansible_devices'].items(): for dev, dev_info in info['ansible_devices'].items():
if dev_info['removable'] == '0': if disk_pattern.match(dev) and dev_info['removable'] == '0':
disk_info[dev] = dev_info['size'] disk_info[dev] = dev_info['size']
___disk_total = '%s %s' % sum_capacity(disk_info.values()) ___disk_total = '%s %s' % sum_capacity(disk_info.values())
___disk_info = json.dumps(disk_info) ___disk_info = json.dumps(disk_info)
......
...@@ -16,6 +16,7 @@ logger = get_logger(__file__) ...@@ -16,6 +16,7 @@ logger = get_logger(__file__)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jumpserver.settings') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jumpserver.settings')
from django.conf import settings from django.conf import settings
from django.core.cache import cache
app = Celery('jumpserver') app = Celery('jumpserver')
...@@ -176,6 +177,9 @@ def after_app_shutdown_clean(func): ...@@ -176,6 +177,9 @@ def after_app_shutdown_clean(func):
@worker_ready.connect @worker_ready.connect
def on_app_ready(sender=None, headers=None, body=None, **kwargs): def on_app_ready(sender=None, headers=None, body=None, **kwargs):
if cache.get("CELERY_APP_READY", 0) == 1:
return
cache.set("CELERY_APP_READY", 1, 10)
logger.debug("App ready signal recv") logger.debug("App ready signal recv")
logger.debug("Start need start task: [{}]".format( logger.debug("Start need start task: [{}]".format(
", ".join(__AFTER_APP_READY_RUN_TASKS)) ", ".join(__AFTER_APP_READY_RUN_TASKS))
...@@ -186,6 +190,9 @@ def on_app_ready(sender=None, headers=None, body=None, **kwargs): ...@@ -186,6 +190,9 @@ def on_app_ready(sender=None, headers=None, body=None, **kwargs):
@worker_shutdown.connect @worker_shutdown.connect
def after_app_shutdown(sender=None, headers=None, body=None, **kwargs): def after_app_shutdown(sender=None, headers=None, body=None, **kwargs):
if cache.get("CELERY_APP_SHUTDOWN", 0) == 1:
return
cache.set("CELERY_APP_SHUTDOWN", 1, 10)
from django_celery_beat.models import PeriodicTask from django_celery_beat.models import PeriodicTask
logger.debug("App shutdown signal recv") logger.debug("App shutdown signal recv")
logger.debug("Clean need cleaned period tasks: [{}]".format( logger.debug("Clean need cleaned period tasks: [{}]".format(
......
...@@ -6,9 +6,17 @@ from django.utils.translation import ugettext_lazy as _ ...@@ -6,9 +6,17 @@ from django.utils.translation import ugettext_lazy as _
# from .hands import User, UserGroup, Asset, AssetGroup, SystemUser # from .hands import User, UserGroup, Asset, AssetGroup, SystemUser
from .models import AssetPermission from .models import AssetPermission
from users.models import User
class AssetPermissionForm(forms.ModelForm): class AssetPermissionForm(forms.ModelForm):
users = forms.ModelMultipleChoiceField(
queryset=User.objects.exclude(role=User.ROLE_APP),
widget=forms.SelectMultiple(
attrs={'class': 'select2', 'data-placeholder': _('Select users')},
)
)
class Meta: class Meta:
model = AssetPermission model = AssetPermission
fields = [ fields = [
...@@ -16,9 +24,6 @@ class AssetPermissionForm(forms.ModelForm): ...@@ -16,9 +24,6 @@ class AssetPermissionForm(forms.ModelForm):
'system_users', 'is_active', 'date_expired', 'comment', 'system_users', 'is_active', 'date_expired', 'comment',
] ]
widgets = { widgets = {
'users': forms.SelectMultiple(
attrs={'class': 'select2',
'data-placeholder': _('Select users')}),
'user_groups': forms.SelectMultiple( 'user_groups': forms.SelectMultiple(
attrs={'class': 'select2', attrs={'class': 'select2',
'data-placeholder': _('Select user groups')}), 'data-placeholder': _('Select user groups')}),
......
...@@ -3,15 +3,15 @@ ...@@ -3,15 +3,15 @@
<li class="nav-header"> <li class="nav-header">
<div class="dropdown profile-element"> <div class="dropdown profile-element">
<span> <span>
<img alt="image" class="img-circle" width="48" height="48" src="{{ user.avatar_url }}"/> <img alt="image" class="img-circle" width="48" height="48" src="{{ request.user.avatar_url }}"/>
</span> </span>
<a data-toggle="dropdown" class="dropdown-toggle" href="#"> <a data-toggle="dropdown" class="dropdown-toggle" href="#">
<span class="clear"> <span class="clear">
<span class="block m-t-xs"> <span class="block m-t-xs">
<strong class="font-bold"> {{ user.name }}<span style="color: #8095a8"></span></strong> <strong class="font-bold"> {{ request.user.name }}<span style="color: #8095a8"></span></strong>
</span> </span>
<span class="text-muted text-xs block"> <span class="text-muted text-xs block">
{{ user.get_role_display | default:_('User') }}<b class="caret"></b> {{ request.user.get_role_display | default:_('User') }}<b class="caret"></b>
</span> </span>
</span> </span>
</a> </a>
......
...@@ -7,6 +7,5 @@ class TerminalConfig(AppConfig): ...@@ -7,6 +7,5 @@ class TerminalConfig(AppConfig):
name = 'terminal' name = 'terminal'
def ready(self): def ready(self):
from .signals import on_app_ready from . import signals_handler
on_app_ready.send(self.__class__) return super().ready()
super().ready() \ No newline at end of file
...@@ -7,9 +7,9 @@ from django.utils.translation import ugettext_lazy as _ ...@@ -7,9 +7,9 @@ from django.utils.translation import ugettext_lazy as _
class AbstractSessionCommand(models.Model): class AbstractSessionCommand(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True)
user = models.CharField(max_length=64, verbose_name=_("User")) user = models.CharField(max_length=64, db_index=True, verbose_name=_("User"))
asset = models.CharField(max_length=128, verbose_name=_("Asset")) asset = models.CharField(max_length=128, db_index=True, verbose_name=_("Asset"))
system_user = models.CharField(max_length=64, verbose_name=_("System user")) system_user = models.CharField(max_length=64, db_index=True, verbose_name=_("System user"))
input = models.CharField(max_length=128, db_index=True, verbose_name=_("Input")) input = models.CharField(max_length=128, db_index=True, verbose_name=_("Input"))
output = models.CharField(max_length=1024, blank=True, verbose_name=_("Output")) output = models.CharField(max_length=1024, blank=True, verbose_name=_("Output"))
session = models.CharField(max_length=36, db_index=True, verbose_name=_("Session")) session = models.CharField(max_length=36, db_index=True, verbose_name=_("Session"))
......
...@@ -3,27 +3,28 @@ ...@@ -3,27 +3,28 @@
import threading import threading
import time import time
from celery import shared_task
from django.core.cache import cache from django.core.cache import cache
from django.dispatch import Signal, receiver
from django.db.utils import ProgrammingError, OperationalError from django.db.utils import ProgrammingError, OperationalError
from common.utils import get_logger from common.utils import get_logger
from common.celery import after_app_ready_start, register_as_period_task, \
after_app_shutdown_clean
from .const import ASSETS_CACHE_KEY, USERS_CACHE_KEY, SYSTEM_USER_CACHE_KEY from .const import ASSETS_CACHE_KEY, USERS_CACHE_KEY, SYSTEM_USER_CACHE_KEY
RUNNING = False RUNNING = False
logger = get_logger(__file__) logger = get_logger(__file__)
on_app_ready = Signal()
@shared_task
@receiver(on_app_ready) @register_as_period_task(interval=3600)
def on_app_ready_set_cache(sender, **kwargs): @after_app_ready_start
@after_app_shutdown_clean
def set_session_info_cache():
logger.debug("")
from .utils import get_session_asset_list, get_session_user_list, \ from .utils import get_session_asset_list, get_session_user_list, \
get_session_system_user_list get_session_system_user_list
global RUNNING
def set_cache():
while True:
try: try:
assets = get_session_asset_list() assets = get_session_asset_list()
users = get_session_user_list() users = get_session_user_list()
...@@ -34,16 +35,3 @@ def on_app_ready_set_cache(sender, **kwargs): ...@@ -34,16 +35,3 @@ def on_app_ready_set_cache(sender, **kwargs):
cache.set(SYSTEM_USER_CACHE_KEY, system_users) cache.set(SYSTEM_USER_CACHE_KEY, system_users)
except (ProgrammingError, OperationalError): except (ProgrammingError, OperationalError):
pass pass
finally:
time.sleep(10)
if RUNNING:
return
threads = []
thread = threading.Thread(target=set_cache)
threads.append(thread)
logger.debug("Receive app ready signal: set cache task start")
for t in threads:
t.daemon = True
t.start()
RUNNING = True
...@@ -28,15 +28,15 @@ ...@@ -28,15 +28,15 @@
</div> </div>
</div> </div>
<div class="input-group"> <div class="input-group">
<select class="select2 form-control" name="username"> <select class="select2 form-control" name="user">
<option value="">{% trans 'User' %}</option> <option value="">{% trans 'User' %}</option>
{% for u in user_list %} {% for u in user_list %}
<option value="{{ u }}" {% if u == username %} selected {% endif %}>{{ u }}</option> <option value="{{ u }}" {% if u == user %} selected {% endif %}>{{ u }}</option>
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
<div class="input-group"> <div class="input-group">
<select class="select2 form-control" name="ip"> <select class="select2 form-control" name="asset">
<option value="">{% trans 'Asset' %}</option> <option value="">{% trans 'Asset' %}</option>
{% for a in asset_list %} {% for a in asset_list %}
<option value="{{ a }}" {% if a == asset %} selected {% endif %}>{{ a }}</option> <option value="{{ a }}" {% if a == asset %} selected {% endif %}>{{ a }}</option>
...@@ -68,12 +68,12 @@ ...@@ -68,12 +68,12 @@
<thead> <thead>
<tr> <tr>
<th data-toggle="true">ID</th> <th data-toggle="true">ID</th>
<th>Command</th> <th>{% trans 'Command' %}</th>
<th>Username</th> <th>{% trans 'User' %}</th>
<th>IP</th> <th>{% trans 'Asset' %}</th>
<th>System user</th> <th>{% trans 'System user'%}</th>
<th>Session</th> <th>{% trans 'Session' %}</th>
<th>Datetime</th> <th>{% trans 'Datetime' %}</th>
<th data-hide="all"></th> <th data-hide="all"></th>
</tr> </tr>
</thead> </thead>
......
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
<select class="select2 form-control" name="user"> <select class="select2 form-control" name="user">
<option value="">{% trans 'User' %}</option> <option value="">{% trans 'User' %}</option>
{% for u in user_list %} {% for u in user_list %}
<option value="{{ u }}" {% if u == username %} selected {% endif %}>{{ u }}</option> <option value="{{ u }}" {% if u == user %} selected {% endif %}>{{ u }}</option>
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
......
...@@ -25,6 +25,10 @@ class CommandListView(DatetimeSearchMixin, ListView): ...@@ -25,6 +25,10 @@ class CommandListView(DatetimeSearchMixin, ListView):
date_format = '%m/%d/%Y' date_format = '%m/%d/%Y'
def get_queryset(self): def get_queryset(self):
self.command = self.request.GET.get('command', '')
self.user = self.request.GET.get("user", '')
self.asset = self.request.GET.get('asset', '')
self.system_user = self.request.GET.get('system_user', '')
filter_kwargs = dict() filter_kwargs = dict()
filter_kwargs['date_from'] = self.date_from filter_kwargs['date_from'] = self.date_from
filter_kwargs['date_to'] = self.date_to filter_kwargs['date_to'] = self.date_to
...@@ -36,21 +40,20 @@ class CommandListView(DatetimeSearchMixin, ListView): ...@@ -36,21 +40,20 @@ class CommandListView(DatetimeSearchMixin, ListView):
filter_kwargs['system_user'] = self.system_user filter_kwargs['system_user'] = self.system_user
if self.command: if self.command:
filter_kwargs['input'] = self.command filter_kwargs['input'] = self.command
if filter_kwargs: queryset = command_store.filter(**filter_kwargs)
self.queryset = command_store.filter(**filter_kwargs) return queryset
return self.queryset
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = { context = {
'app': _('Terminal'), 'app': _('Terminal'),
'action': _('Command list'), 'action': _('Command list'),
'user_list': utils.get_user_list_from_cache(), 'user_list': utils.get_session_user_list(),
'asset_list': utils.get_asset_list_from_cache(), 'asset_list': utils.get_session_asset_list(),
'system_user_list': utils.get_system_user_list_from_cache(), 'system_user_list': utils.get_session_system_user_list(),
'command': self.command, 'command': self.command,
'date_from': self.date_from, 'date_from': self.date_from,
'date_to': self.date_to, 'date_to': self.date_to,
'username': self.user, 'user': self.user,
'asset': self.asset, 'asset': self.asset,
'system_user': self.system_user, 'system_user': self.system_user,
} }
......
...@@ -59,7 +59,7 @@ class SessionListView(AdminUserRequiredMixin, DatetimeSearchMixin, ListView): ...@@ -59,7 +59,7 @@ class SessionListView(AdminUserRequiredMixin, DatetimeSearchMixin, ListView):
'system_user_list': utils.get_system_user_list_from_cache(), 'system_user_list': utils.get_system_user_list_from_cache(),
'date_from': self.date_from, 'date_from': self.date_from,
'date_to': self.date_to, 'date_to': self.date_to,
'username': self.user, 'user': self.user,
'asset': self.asset, 'asset': self.asset,
'system_user': self.system_user, 'system_user': self.system_user,
} }
......
...@@ -22,10 +22,14 @@ signer = get_signer() ...@@ -22,10 +22,14 @@ signer = get_signer()
class User(AbstractUser): class User(AbstractUser):
ROLE_ADMIN = 'Admin'
ROLE_USER = 'User'
ROLE_APP = 'App'
ROLE_CHOICES = ( ROLE_CHOICES = (
('Admin', 'Administrator'), (ROLE_ADMIN, 'Administrator'),
('User', 'User'), (ROLE_USER, 'User'),
('App', 'Application') (ROLE_APP, 'Application')
) )
id = models.UUIDField(default=uuid.uuid4, primary_key=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True)
username = models.CharField(max_length=128, unique=True, verbose_name=_('Username')) username = models.CharField(max_length=128, unique=True, verbose_name=_('Username'))
......
...@@ -220,7 +220,7 @@ class LoginLogListView(DatetimeSearchMixin, ListView): ...@@ -220,7 +220,7 @@ class LoginLogListView(DatetimeSearchMixin, ListView):
date_format = '%m/%d/%Y' date_format = '%m/%d/%Y'
def get_queryset(self): def get_queryset(self):
self.username = self.request.GET.get('username', '') self.username = self.request.GET.get('user', '')
self.keyword = self.request.GET.get("keyword", '') self.keyword = self.request.GET.get("keyword", '')
queryset = super().get_queryset() queryset = super().get_queryset()
...@@ -228,7 +228,7 @@ class LoginLogListView(DatetimeSearchMixin, ListView): ...@@ -228,7 +228,7 @@ class LoginLogListView(DatetimeSearchMixin, ListView):
datetime__gt=self.date_from, datetime__lt=self.date_to datetime__gt=self.date_from, datetime__lt=self.date_to
) )
if self.username: if self.username:
queryset = self.queryset.filter(username=self.username) queryset = queryset.filter(username=self.username)
if self.keyword: if self.keyword:
queryset = self.queryset.filter( queryset = self.queryset.filter(
Q(ip__contains=self.keyword) | Q(ip__contains=self.keyword) |
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment