This commit is contained in:
flaskfarm
2022-10-12 01:32:51 +09:00
parent 5b6719c018
commit 751adbbedc
18 changed files with 548 additions and 96 deletions

View File

@@ -2,6 +2,7 @@ import random
import string
from support import SupportDiscord, SupportFile, SupportTelegram
from tool.modal_command import ToolModalCommand
from .setup import *
@@ -33,6 +34,10 @@ class ModuleSetting(PluginModuleBase):
'notify_advaned_use' : 'False',
'notify.yaml': '', #직접 사용하지 않으나 저장 편의상.
'command_text': '',
'celery_start_by_web': 'False', #웹 실행시 celery 실행
'celery_start_command': "celery -A flaskfarm.main.celery worker --loglevel=info --pool=gevent --concurrency=2 --config_filepath={F.config['config_filepath']} --running_type=native",
}
def __init__(self, P):
@@ -57,6 +62,9 @@ class ModuleSetting(PluginModuleBase):
elif page == 'notify':
arg['notify_yaml_filepath'] = F.config['notify_yaml_filepath']
arg['notify.yaml'] = SupportFile.read_file(arg['notify_yaml_filepath'])
elif page == 'celery':
arg['use_celery'] = F.config['use_celery']
arg['running_type'] = F.config['running_type']
return render_template(f'{__package__}_{name}_{page}.html', arg=arg)
except Exception as e:
@@ -113,41 +121,52 @@ class ModuleSetting(PluginModuleBase):
elif command == 'command_run':
ret['msg'] = arg1
pass
elif command == 'celery_execute':
tmp = arg1.replace("{F.config['config_filepath']}", F.config['config_filepath']).replace('{F.config["config_filepath"]}', F.config['config_filepath'])
cmd = [
['msg', f'명령 : {tmp}'],
['msg', ''],
tmp.split(' '),
]
ToolModalCommand.start("Celery 실행", cmd)
return jsonify(ret)
def plugin_load(self):
try:
if F.config['run_flask']:
F.logger.info(f"arg_repeat : {F.config['arg_repeat']}")
F.logger.info(f"arg_repeat : {F.config['arg_repeat']}")
if F.config['run_flask'] == False:
return
F.logger.info(f"arg_repeat : {F.config['arg_repeat']}")
F.logger.info(f"arg_repeat : {F.config['arg_repeat']}")
if F.config['arg_repeat'] == 0 or SystemModelSetting.get('system_start_time') == '':
SystemModelSetting.set('system_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
SystemModelSetting.set('repeat', str(F.config['arg_repeat']))
username = SystemModelSetting.get('web_id')
passwd = SystemModelSetting.get('web_pw')
F.users[username] = User(username, passwd_hash=passwd)
if F.config['arg_repeat'] == 0 or SystemModelSetting.get('system_start_time') == '':
SystemModelSetting.set('system_start_time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
SystemModelSetting.set('repeat', str(F.config['arg_repeat']))
username = SystemModelSetting.get('web_id')
passwd = SystemModelSetting.get('web_pw')
F.users[username] = User(username, passwd_hash=passwd)
self.__set_restart_scheduler()
self.__set_scheduler_check_scheduler()
F.get_recent_version()
self.__set_restart_scheduler()
self.__set_scheduler_check_scheduler()
F.get_recent_version()
notify_yaml_filepath = os.path.join(F.config['path_data'], 'db', 'notify.yaml')
if os.path.exists(notify_yaml_filepath) == False:
import shutil
shutil.copy(
os.path.join(F.config['path_app'], 'files', 'notify.yaml.template'),
notify_yaml_filepath
)
if SystemModelSetting.get_bool('restart_notify'):
from tool import ToolNotify
msg = f"시스템이 시작되었습니다.\n재시작: {F.config['arg_repeat']}"
ToolNotify.send_message(msg, message_id='system_start')
notify_yaml_filepath = os.path.join(F.config['path_data'], 'db', 'notify.yaml')
if os.path.exists(notify_yaml_filepath) == False:
import shutil
shutil.copy(
os.path.join(F.config['path_app'], 'files', 'notify.yaml.template'),
notify_yaml_filepath
)
if SystemModelSetting.get_bool('restart_notify'):
from tool import ToolNotify
msg = f"시스템이 시작되었습니다.\n재시작: {F.config['arg_repeat']}"
ToolNotify.send_message(msg, message_id='system_start')
except Exception as e:
P.logger.error(f'Exception:{str(e)}')
P.logger.error(traceback.format_exc())
def plugin_unload(self):
ToolModalCommand.process_close()
def setting_save_after(self, change_list):
if 'theme' in change_list:

View File

@@ -11,7 +11,7 @@ class ModuleTool(PluginModuleBase):
def __init__(self, P):
super(ModuleTool, self).__init__(P, name=name, first_menu='celery')
super(ModuleTool, self).__init__(P, name=name, first_menu='upload')
def process_menu(self, page, req):

View File

@@ -12,6 +12,7 @@ __menu = {
{'uri': 'menu', 'name': '메뉴 구성'},
{'uri': 'config', 'name': 'config.yaml 파일'},
{'uri': 'export', 'name': 'export.sh 파일'},
{'uri': 'celery', 'name': '비동기 작업(celery)'},
{'uri': 'notify', 'name': '알림'},
],
@@ -22,6 +23,7 @@ __menu = {
'list': [
{'uri': 'setting', 'name': '설정'},
{'uri': 'list', 'name': '로딩 플러그인'},
{'uri': 'all', 'name': '플러그인 목록'},
],
},
{
@@ -29,7 +31,6 @@ __menu = {
'name': '시스템 툴',
'list': [
{'uri': 'upload', 'name': '업로드'},
{'uri': 'celery', 'name': 'celery 테스트'},
{'uri': 'python', 'name': 'Python'},
{'uri': 'db', 'name': 'DB'},
{'uri': 'crypt', 'name': '암호화'},

View File

@@ -0,0 +1,123 @@
{% extends "base.html" %}
{% block content %}
<div>
{{ macros.m_button_group([['globalSettingSaveBtn', '설정 저장'], ['celery_test_btn', 'Celery 테스트']])}}
{{ macros.m_row_start('5') }}
{{ macros.m_row_end() }}
{{ macros.m_hr() }}
<div class="tab-content" id="nav-tabContent">
{{ macros.info_text('use_celery', 'use_celery 값', arg['use_celery']) }}
{{ macros.info_text('running_type', 'running_type 값', arg['running_type']) }}
{{ macros.info_text('_tmp', '설명', "Docker는 celery가 서비스로 동작하기 때문에 설정이 불필요하며 '테스트' 버튼으로 작동 여부 확인만 가능합니다.", desc=['','native로 동작하는 경우 celery 실행을 따로 하지 않고 한번에 실행하기 위한 설정', 'Redis는 설정된 Port로 동작중인 상태여야 함.']) }}
{{ macros.m_hr() }}
<form id='setting' name='setting'>
{{ macros.setting_checkbox('celery_start_by_web', '시작시 celery 실행', value=arg['celery_start_by_web']) }}
{{ macros.setting_input_textarea('celery_start_command', 'celery 실행 명령', desc=['',
'예: celery -A flaskfarm.main.celery worker --loglevel=info --pool=gevent --concurrency=2 --config_filepath="config.yaml파일경로" --running_type=native',
'패키지로 실행시 : -A flaskfarm.main.celery',
'GIT 소스로 실행시 : -A main.celery (현재 작업폴더가 flaskfarm)',
'Linux는 사용자에 따라 export C_FORCE_ROOT=true 필요'
],
value=arg['celery_start_command'], row='5') }}
</form>
{{ macros.setting_buttons([['celery_excute_btn', '실행 테스트']]) }}
</div>
</div>
<script type="text/javascript">
$("body").on('click', '#celery_excute_btn', function(e){
e.preventDefault();
globalSendCommand('celery_execute', $('#celery_start_command').val());
});
$("body").on('click', '#shutdown_btn', function(e){
e.preventDefault();
shutdown_confirm();
});
$("body").on('click', '#celery_test_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/celery_test',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret.ret == 'success') {
$.notify('<strong>'+ ret.data+'</strong>', {
type: 'success'
});
} else if (ret.ret == 'timeout' || ret.ret == 'no_celery') {
$.notify('<strong>'+ ret.data+'</strong>', {
type: 'warning'
});
}
//m_modal(ret)
}
});
});
$("body").on('click', '#ps_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/ps',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
}
});
});
$("body").on('click', '#worker_start_btn', function(e){
e.preventDefault();
$.ajax({
url: '/' + package_name + '/ajax/' + sub + '/worker_start',
type: "POST",
cache: false,
data: {},
dataType: "json",
success: function (ret) {
if (ret.ret == 'success') {
$.notify('<strong>'+ ret.data+'</strong>', {
type: 'success'
});
} else if (ret.ret == 'timeout' || ret.ret == 'no_celery' || ret.ret == 'not_registered') {
$.notify('<strong>'+ ret.data+'</strong>', {
type: 'warning'
});
}
//m_modal(ret)
}
});
});
</script>
{% endblock %}

View File

@@ -13,7 +13,7 @@
<form id='setting' name='setting'>
<div class="tab-content" id="nav-tabContent">
{{ macros.m_tab_content_start('normal', true) }}
{{ macros.setting_checkbox('tool_crypt_use_user_key', '암호화 키 본인키 사용', value=arg['tool_crypt_use_user_key'], desc=['On : 본인 키 사용', '주의) 변경 후 일반설정-인증-로그인 암호를 새로 저장해야 합니다.', 'Off : 앱 고정 키 사용']) }}
{{ macros.setting_checkbox('tool_crypt_use_user_key', '암호화 키 직접 입력', value=arg['tool_crypt_use_user_key'], desc=['On : 본인 키 사용', '주의) 변경 후 일반설정-인증-로그인 암호를 새로 저장해야 합니다.', 'Off : 앱 고정 키 사용']) }}
<div id="tool_crypt_use_user_key_div" class="collapse">
{{ macros.setting_input_text('tool_crypt_user_key', '암호화 키', value=arg['tool_crypt_user_key'], desc=['16진수(숫자, a~e)로 이루어진 32글자. 미만시 앞을 0으로 채움. 초과시 뒤에 무시']) }}
</div>