jumpserver/apps/ops/ws.py

67 lines
1.9 KiB
Python
Raw Normal View History

import time
2019-10-10 04:47:21 +00:00
import os
import threading
2019-10-10 04:47:21 +00:00
import json
from common.utils import get_logger
from .celery.utils import get_celery_task_log_path
from channels.generic.websocket import JsonWebsocketConsumer
logger = get_logger(__name__)
class CeleryLogWebsocket(JsonWebsocketConsumer):
disconnected = False
def connect(self):
self.accept()
2019-10-10 04:47:21 +00:00
def receive(self, text_data=None, bytes_data=None, **kwargs):
data = json.loads(text_data)
task_id = data.get("task")
if task_id:
self.handle_task(task_id)
def handle_task(self, task_id):
logger.info("Task id: {}".format(task_id))
2019-10-10 04:47:21 +00:00
log_path = get_celery_task_log_path(task_id)
def func():
2019-10-10 04:47:21 +00:00
task_log_f = None
while not self.disconnected:
2019-10-10 04:47:21 +00:00
if not os.path.exists(log_path):
self.send_json({'message': '.', 'task': task_id})
time.sleep(0.5)
continue
self.send_json({'message': '\r\n'})
try:
logger.debug('Task log path: {}'.format(log_path))
task_log_f = open(log_path, 'rb')
2019-10-10 04:47:21 +00:00
break
except OSError:
return
if not task_log_f:
return
2019-10-10 04:47:21 +00:00
while not self.disconnected:
data = task_log_f.readline()
if data:
data = data.replace(b'\n', b'\r\n')
self.send_json({'message': data.decode(errors='ignore'), 'task': task_id})
if data.startswith(b'Task') and data.find(b'succeeded'):
2019-10-10 04:47:21 +00:00
break
time.sleep(0.1)
2019-10-10 04:47:21 +00:00
task_log_f.close()
thread = threading.Thread(target=func)
thread.start()
2019-10-10 04:47:21 +00:00
def disconnect(self, close_code):
self.disconnected = True
self.close()