-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtask.py
More file actions
3172 lines (2970 loc) · 120 KB
/
task.py
File metadata and controls
3172 lines (2970 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/www/server/panel/pyenv/bin/python3
# coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2016 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: hwliang <hwl@bt.cn>
# +-------------------------------------------------------------------
# ------------------------------
# 面板后台任务
# ------------------------------
import heapq
import sys
import os
import psutil
import json
import time
import shutil
import hashlib
import sqlite3
import threading
import traceback
import subprocess
import pickle
from multiprocessing import Process
from datetime import datetime, timezone, timedelta
from collections import namedtuple
from typing import Optional, Dict, List, Any, Tuple
os.environ['BT_TASK'] = '1'
SETUP_PATH = '/www/server'
PANEL_PATH = '{}/panel'.format(SETUP_PATH)
PY_BIN = os.path.realpath(sys.executable)
TASK_LOG_FILE = '{}/logs/task.log'.format(PANEL_PATH)
EXEC_LOG_PATH = '/tmp/panelExec.log'
def write_file(path: str, content: str, mode='w'):
try:
fp = open(path, mode)
fp.write(content)
fp.close()
return True
except:
try:
fp = open(path, mode, encoding="utf-8")
fp.write(content)
fp.close()
return True
except:
return False
def read_file(filename: str):
fp = None
try:
fp = open(filename, "rb")
f_body_bytes: bytes = fp.read()
f_body = f_body_bytes.decode("utf-8", errors='ignore')
fp.close()
return f_body
except Exception as ex:
return False
finally:
if fp and not fp.closed:
fp.close()
def write_log(*args, _level='INFO', color="debug"):
"""
@name 写入日志
@author hwliang<2021-08-12>
@param *args <any> 要写入到日志文件的信息可以是多个,任意类型
@param _level<string> 日志级别
@param color<string> 日志颜色,可选值:red,green,yellow,blue,purple,cyan,white,gray,black,info,success,warning,warn,err,error,debug,trace,critical,fatal
@return void
"""
color_dict = {
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'purple': '\033[35m',
'cyan': '\033[36m',
'white': '\033[37m',
'gray': '\033[90m',
'black': '\033[30m',
'info': '\033[0m',
'success': '\033[32m',
'warning': '\033[33m',
'warn': '\033[33m',
'err': '\033[31m',
'error': '\033[31m',
'debug': '\033[36m',
'trace': '\033[35m',
'critical': '\033[31m',
'fatal': '\033[31m'
}
_log = []
if color:
color_start = color_dict.get(color.strip().lower(), "")
if color_start:
_log.append(color_start)
_log.append("[{}][{}]".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), _level.upper()))
for _info in args:
try:
if isinstance(_info, (list, tuple)):
_log.append(json.dumps(_info, ensure_ascii=False))
elif isinstance(_info, dict):
_log.append(json.dumps(_info, indent=4, ensure_ascii=False))
else:
_log.append(str(_info))
except:
_log.append(str(_info))
_log.append(" ")
if _log[0].startswith('\033'):
_log.append('\033[0m')
write_file(TASK_LOG_FILE, ''.join(_log) + '\n', mode='a+')
def exec_shell(cmd_string, cwd=None, shell=True):
"""
@name 执行shell命令
@param cmdstring: str 要执行的shell命令
@param cwd: str 执行命令的路径
return int 返回命令执行结果
"""
try:
real_cmd = "{} > {} 2>&1".format(cmd_string, EXEC_LOG_PATH)
sub = subprocess.Popen(real_cmd, cwd=cwd,stdin=subprocess.PIPE, shell=shell, bufsize=4096)
while sub.poll() is None:
time.sleep(0.1)
return sub.returncode
except:
return None
# sys.path.insert(0, PANEL_PATH + '/class')
# import public
# import db
# import panelTask
# import process_task
# import PluginLoader
#
#
# class Task:
# task_obj = None
# pre = 0
# timeout_count = 0
# log_path = '/tmp/panelExec.log'
# is_task = '/tmp/panelTask.pl'
# __api_root_url = 'https://api.bt.cn'
# _check_url = __api_root_url + '/panel/get_soft_list_status'
# end_time = None
# is_check = 0
# python_bin = None
# thread_dict = {}
# setup_path = None
# panel_path = None
# old_edate = None
# log_file = None
# __path_error = None
# __error_html = None
#
# # 系统监控相关属性
# diskio_1 = None
# diskio_2 = None
# networkInfo = None
# cpuInfo = None
# diskInfo = None
# network_up = {}
# network_down = {}
# cycle = 60
# last_delete_time = 0
# # 实例化进程监控对象
# proc_task_obj = None
#
# def __init__(self) -> None:
# if not self.task_obj: self.task_obj = panelTask.bt_task()
# if not self.python_bin: self.python_bin = public.get_python_bin()
# if not self.setup_path: self.setup_path = public.get_setup_path()
# if not self.panel_path: self.panel_path = public.get_panel_path()
# if not self.log_file: self.log_file = self.panel_path + '/logs/task.log'
# if not self.__path_error: self.__path_error = self.panel_path + '/data/error_pl.pl'
# if not self.__error_html: self.__error_html = self.panel_path + '/BTPanel/templates/default/block_error.html'
# if not self.proc_task_obj: self.proc_task_obj = process_task.process_task()
#
# def write_log(self, *args, _level='INFO', color="debug"):
# '''
# @name 写入日志
# @author hwliang<2021-08-12>
# @param *args <any> 要写入到日志文件的信息可以是多个,任意类型
# @param _level<string> 日志级别
# @param color<string> 日志颜色,可选值:red,green,yellow,blue,purple,cyan,white,gray,black,info,success,warning,warn,err,error,debug,trace,critical,fatal
# @return void
# '''
#
# color_start = ''
# color_end = ''
# color_dict = {
# 'red': '\033[31m',
# 'green': '\033[32m',
# 'yellow': '\033[33m',
# 'blue': '\033[34m',
# 'purple': '\033[35m',
# 'cyan': '\033[36m',
# 'white': '\033[37m',
# 'gray': '\033[90m',
# 'black': '\033[30m',
# 'info': '\033[0m',
# 'success': '\033[32m',
# 'warning': '\033[33m',
# 'warn': '\033[33m',
# 'err': '\033[31m',
# 'error': '\033[31m',
# 'debug': '\033[36m',
# 'trace': '\033[35m',
# 'critical': '\033[31m',
# 'fatal': '\033[31m'
# }
# if color:
# color = color.strip().lower()
# if color in color_dict:
# color_start = color_dict[color]
# color_end = '\033[0m'
#
# log_body = "{}[{}][{}]".format(color_start, public.format_date(), _level.upper())
# for _info in args:
# try:
# if type(_info) == dict:
# _info = json.dumps(_info, indent=4, ensure_ascii=False)
# elif type(_info) == list:
# _info = json.dumps(_info, ensure_ascii=False)
# elif type(_info) == tuple:
# _info = json.dumps(_info, ensure_ascii=False)
# except:
# _info = str(_info)
#
# log_body += " {}".format(_info)
#
# log_body += "{}\n".format(color_end)
# # print(log_body.strip())
# public.WriteFile(self.log_file, log_body, 'a+')
#
# def exec_shell(self, cmdstring, cwd=None, timeout=None, shell=True):
# '''
# @name 执行shell命令
# @param cmdstring: str 要执行的shell命令
# @param cwd: str 执行命令的路径
# @param timeout: int 超时时间
# @param shell: bool 是否使用shell
# return int 返回命令执行结果
# '''
# try:
# import subprocess
# import time
# sub = subprocess.Popen(cmdstring + ' > ' + self.log_path + ' 2>&1', cwd=cwd,
# stdin=subprocess.PIPE, shell=shell, bufsize=4096)
#
# while sub.poll() is None:
# time.sleep(0.1)
#
# return sub.returncode
# except:
# return None
#
# def get_soft_name_of_version(self, name):
# '''
# @name 获取软件名称和版本
# @param name<string> 软件名称
# @return tuple(string, string) 返回软件名称和版本
# '''
# if name.find('Docker') != -1:
# return ('docker', '1.0')
# return_default = ('', '')
# arr1 = name.split('[')
# if len(arr1) < 2:
# return return_default
# arr2 = arr1[1].split(']')
# if len(arr2) < 2:
# return return_default
# arr3 = arr2[0].split('-')
# if len(arr3) < 2:
# return return_default
#
# soft_name = arr3[0]
# soft_version = arr3[1]
# if soft_name == 'php':
# soft_version = soft_version.replace('.', '')
# return (soft_name, soft_version)
#
# def check_install_status(self, name):
# '''
# @name 检查软件是否安装成功
# @param name<string> 软件名称
# @return tuple(bool, string) 返回是否安装成功和安装信息
# '''
# return_default = (1, '安装成功')
# try:
# # 获取软件名称和版本
# soft_name, soft_version = self.get_soft_name_of_version(name)
# if not soft_name or not soft_version:
# return return_default
#
# # 获取安装检查配置
# install_config = public.read_config('install_check')
# if not install_config:
# return return_default
#
# if soft_name not in install_config:
# return return_default
#
# if os.path.exists("/www/server/panel/install/{}_not_support.pl".format(soft_name)):
# return (0, '不兼容此系统!请点详情说明!')
#
# if os.path.exists("/www/server/panel/install/{}_mem_kill.pl".format(soft_name)):
# return (0, '内存不足安装异常!请点详情说明!')
#
# soft_config = install_config[soft_name]
#
# def replace_all(data):
# '''
# @name 替换所有变量
# @param data<string> 需要替换的字符串
# @return string 替换后的字符串
# '''
# if not data:
# return data
# if data.find('{') == -1:
# return data
# # 替换安装路径
# data = data.replace('{SetupPath}', self.setup_path)
# # 替换版本号
# data = data.replace('{Version}', soft_version)
# # 替换主机名
# if data.find("{Host") != -1:
# host_name = public.get_hostname()
# host = host_name.split('.')[0]
# data = data.replace("{Hostname}", host_name)
# data = data.replace("{Host}", host)
# return data
#
# # 检查文件是否存在
# if 'files_exists' in soft_config:
# for fname in soft_config['files_exists']:
# filename = replace_all(fname)
# if not os.path.exists(filename):
# return (0, '安装失败,文件不存在:{}'.format(filename))
#
# # 检查pid文件是否有效
# if 'pid' in soft_config and soft_config['pid']:
# pid_file = replace_all(soft_config['pid'])
# if not os.path.exists(pid_file):
# return (0, '启动失败,pid文件不存在:{}'.format(pid_file))
# pid = public.readFile(pid_file)
# if not pid:
# return (0, '启动失败,pid文件为空:{}'.format(pid_file))
# proc_file = '/proc/{}/cmdline'.format(pid.strip())
# if not os.path.exists(proc_file):
# return (0, '启动失败,指定PID: {}({}) 进程不存在'.format(pid_file, pid))
#
# # 执行命令检查
# if 'cmd' in soft_config:
# for cmd in soft_config['cmd']:
# res = '\n'.join(public.ExecShell(replace_all(cmd['exec'])))
# if res.find(replace_all(cmd['success'])) == -1:
# return (0, '{}服务启动状态异常'.format(soft_name))
# except:
# pass
#
# return return_default
#
# def task_table_rep(self):
# '''
# @name 修复任务表
# @param None
# '''
# task_obj = public.M('tasks')
# res = task_obj.query("SELECT count(*) FROM sqlite_master where type='table' and name='tasks' and sql like '%msg%'")
# if res and res[0][0] == 0:
# task_obj.execute("ALTER TABLE tasks ADD COLUMN msg TEXT DEFAULT '安装成功'", ())
# res = task_obj.query("SELECT count(*) FROM sqlite_master where type='table' and name='tasks' and sql like '%install_status%'")
# if res and res[0][0] == 0:
# task_obj.execute("ALTER TABLE tasks ADD COLUMN install_status INTEGER DEFAULT 1", ())
# task_obj.close()
#
# def save_installed_msg(self, task_id):
# '''
# @name 保存安装脚本执行日志
# @param task_id<int> 任务ID
# @return None
# '''
# try:
# from panel_msg.msg_file import message_mgr
#
# msg = message_mgr.get_by_task_id(task_id)
# if msg is None:
# return None
# else:
# msg.title = "正在" + msg.title[2:]
# msg.sub["file_name"] = "/tmp/panelExec.log"
# msg.sub["install_status"] = "正在" + msg.sub["install_status"][2:]
# msg.sub["status"] = 1
# msg.read = False
# msg.read_time = 0
#
# res = msg.save_to_file()
# return msg
# except:
# return public.get_error_info()
#
# def update_installed_msg(self, msg):
# '''
# @name 更新安装脚本执行日志
# @param msg<Message> 消息对象
# @return None
# '''
# try:
# import shutil
# logs_dir = public.get_panel_path() + "/logs/installed"
# if not os.path.exists(logs_dir):
# os.makedirs(logs_dir, 0o600)
#
# filename = logs_dir + "/{}_{}.log".format(msg.sub["soft_name"], int(time.time()))
# if os.path.exists(self.log_path):
# shutil.copyfile(self.log_path, filename)
# msg.sub["file_name"] = filename
# msg.sub["install_status"] = msg.sub["install_status"][2:] + "结束"
# msg.sub["status"] = 2
# msg.read = False
# msg.title = msg.title[2:] + "已结束"
# msg.read_time = 0
#
# msg.save_to_file()
# except:
# public.writeFile("{}/logs/task.error".format(self.panel_path), public.get_error_info())
#
# def task_end(self, value):
# '''
# @name 任务结束处理
# @param value<dict> 任务信息
# @return None
# '''
# # 安装PHP后需要重新加载PHP环境
# if value['execstr'].find('install php') != -1:
# os.system("{} {}/tools.py phpenv".format(self.python_bin, self.panel_path))
# elif value['execstr'].find('install nginx') != -1:
# # 修复nginx配置文件到支持当前安装的nginx版本
# os.system("{} {}/script/nginx_conf_rep.py".format(self.python_bin, self.panel_path))
#
# # 任务队列
# def startTask(self):
# '''
# @name 开始任务队列
# @param None
# '''
# tip_file = '/dev/shm/.panelTask.pl'
# self.task_table_rep()
# n = 0
# tasks_obj = None
# while 1:
# try:
# if os.path.exists(self.is_task):
# tasks_obj = public.M('tasks')
# # 重置所有任务状态
# tasks_obj.where("status=?", ('-1',)).setField('status', '0')
#
# # 获取所有未执行的任务
# taskArr = tasks_obj.where("status=?", ('0',)).field('id,name,type,execstr').order("id asc").select()
#
# # 逐个执行任务
# for value in taskArr:
#
# # 检查关键目录是否可写
# public.check_sys_write()
#
# # 检查任务类型是否为shell执行
# if value['type'] != 'execshell': continue
#
# # 检查任务是否存在
# if not tasks_obj.where("id=?", (value['id'],)).count():
# public.writeFile(tip_file, str(int(time.time())))
# continue
#
# # 写入状态和任务开始时间
# start = int(time.time())
# tasks_obj.where("id=?", (value['id'],)).save('status,start', ('-1', start))
#
# # 保存安装日志
# msg = self.save_installed_msg(value["id"])
#
# # 执行任务
# self.write_log("正在执行任务: {}".format(value['name']))
#
# self.exec_shell(value['execstr'])
#
# # 处理任务结束事件
# self.task_end(value)
#
# # 检查软件是否安装成功
# end = int(time.time())
# install_status, install_msg = self.check_install_status(value['name'])
#
# self.write_log("任务执行结果: {},".format(install_msg), "耗时: {}秒".format(end - start))
#
# # 写入任务结束状态到数据库
# status_code = 1
#
# tasks_obj.where("id=?", (value['id'],)).save('status,end,msg,install_status', (status_code, end, install_msg, install_status))
#
# # 更新安装日志
# self.update_installed_msg(msg)
#
# # 移除任务标记文件
# if (tasks_obj.where("status=?", ('0')).count() < 1):
# if os.path.exists(self.is_task):
# os.remove(self.is_task)
#
# # 重置系统加固状态
# public.start_syssafe()
#
# # 写入任务循环标记
# public.writeFile(tip_file, str(int(time.time())))
#
# # 线程检查
# n += 1
# if n > 60:
# self.run_thread()
# n = 0
# except:
# pass
# finally:
# if tasks_obj:
# tasks_obj.close()
# tasks_obj = None
#
# time.sleep(2)
#
# # 定时任务去检测邮件信息
# def send_mail_time(self):
# self.write_log("启动邮件发送定时任务")
# time.sleep(60)
# while True:
# try:
# os.system("nohup {} {}/script/mail_task.py > /dev/null 2>&1 &".format(self.python_bin, self.panel_path))
# time.sleep(59)
# except:
# time.sleep(59)
# self.send_mail_time()
#
# def get_mac_address(self):
# '''
# @name 获取MAC地址
# @return string
# '''
# import uuid
# mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
# return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])
#
# def get_user_info(self):
# user_file = '{}/data/userInfo.json'.format(self.panel_path)
# if not os.path.exists(user_file): return {}
# userInfo = {}
# try:
# userTmp = json.loads(public.readFile(user_file))
# if not 'serverid' in userTmp or len(userTmp['serverid']) != 64:
# return userInfo
# userInfo['uid'] = userTmp['uid']
# userInfo['address'] = userTmp['address']
# userInfo['access_key'] = userTmp['access_key']
# userInfo['username'] = userTmp['username']
# userInfo['serverid'] = userTmp['serverid']
# userInfo['oem'] = public.get_oem_name()
# userInfo['o'] = userInfo['oem']
# userInfo['mac'] = self.get_mac_address()
# except:
# pass
# return userInfo
#
# # 获取云端帐户状态
# def get_cloud_list_status(self):
# '''
# @name 获取云端软件列表状态
# @return str or bool
# '''
# try:
# pdata = public.get_user_info()
# if not pdata: return False
# if pdata['uid'] == -1: return False
# pdata['mac'] = self.get_mac_address()
# list_body = self.HttpPost(self._check_url, pdata)
# if not list_body: return False
#
# list_body = json.loads(list_body)
# if not list_body['status']:
# public.writeFile(self.__path_error, "error")
# msg = '''{% extends "layout.html" %}
# {% block content %}
# <div class="main-content pb55" style="min-height: 525px;">
# <div class="container-fluid">
# <div class="site_table_view bgw mtb15 pd15 text-center">
# <div style="padding:50px">
# <h1 class="h3"></h1>
# '''
# msg += list_body['title'] + list_body['body']
# msg += '''
# </div>
# </div>
# </div>
# </div>
# {% endblock %}
# {% block scripts %}
# {% endblock %}'''
# public.writeFile(self.__error_html, msg)
# return '3'
# else:
# if os.path.exists(self.__path_error):
# os.remove(self.__path_error)
# if os.path.exists(self.__error_html):
# os.remove(self.__error_html)
# return '2'
# except Exception as ex:
# self.write_log(ex)
# if os.path.exists(self.__path_error): os.remove(self.__path_error)
# if os.path.exists(self.__error_html): os.remove(self.__error_html)
# return '1'
#
# # 5个小时更新一次更新软件列表
# def update_software_list(self):
# '''
# @name 更新软件列表
# @return void
# '''
# self.write_log("启动软件列表定时更新")
# time.sleep(120)
# while True:
# try:
# self.get_cloud_list_status()
# time.sleep(18000)
# except Exception as ex:
# self.write_log(ex)
# time.sleep(1800)
# self.update_software_list()
#
# # 面板消息提醒
# def check_panel_msg(self):
# '''
# @name 面板消息提醒
# @return None
# '''
# self.write_log("启动面板消息提醒")
# time.sleep(120)
# while True:
# #统计ssh的错误次数
# PluginLoader.module_run("syslog", "task_ssh_error_count", public.dict_obj())
# os.system('nohup {} {}/script/check_msg.py > /dev/null 2>&1 &'.format(self.python_bin, self.panel_path))
# time.sleep(3000)
#
# # 面板推送消息
# def push_msg(self):
# '''
# @name 面板推送消息
# @return None
# '''
# self.write_log("启动面板推送消息")
# time.sleep(120)
# while True:
# time.sleep(60)
# os.system('nohup {} {}/script/push_msg.py > /dev/null 2>&1 &'.format(self.python_bin, self.panel_path))
#
#
# def total_load_msg(self):
# '''
# @name 面板负载均衡统计任务
# @return None
# '''
# self.write_log("面板负载均衡统计任务")
# time.sleep(120)
# while True:
# time.sleep(60*5)
# os.system('nohup {} {}/script/total_load_msg.py > /dev/null 2>&1 &'.format(self.python_bin, self.panel_path))
#
# def node_monitor(self):
# self.write_log("启动 <节点监控任务>")
# time.sleep(10)
# while True:
# time.sleep(120)
# os.system('nohup {} {}/script/node_monitor.py > /dev/null 2>&1 &'.format(self.python_bin, self.panel_path))
#
# def ProLog(self):
# '''
# @name 项目日志清理
# @return None
# '''
# path_list = ["{}/go_project/vhost/logs".format(self.setup_path), "/var/tmp/springboot/vhost/logs/"]
# try:
# for i2 in path_list:
# if os.path.exists(i2):
# for dir in os.listdir(i2):
# dir = os.path.join(i2, dir)
# # 判断当前目录是否为文件夹
# if os.path.isfile(dir):
# if dir.endswith(".log"):
# # 文件大于500M的时候则清空文件
# if os.stat(dir).st_size > 200000000:
# public.ExecShell("echo ''>{}".format(dir))
# except:
# pass
#
# def ProDadmons(self):
# '''
# @name 项目守护进程
# @author
# '''
# n = 30
# self.write_log("启动项目守护进程")
# while 1:
# n += 1
# if n >= 30:
# n = 1
# self.ProLog()
# self.wait_daemon_time()
# os.system("nohup {} {}/script/project_daemon.py > /dev/null 2>&1 &".format(self.python_bin, self.panel_path))
#
# def wait_daemon_time(self):
# '''
# @name 等待守护进程时间
# @return None
# '''
# last_time_out = self.get_daemon_time()
# use_time = 0
# while use_time < last_time_out:
# time.sleep(5)
# use_time += 5
# new_time_out = self.get_daemon_time()
# if new_time_out != last_time_out:
# if use_time > new_time_out:
# break
# else:
# last_time_out = new_time_out
#
# def get_daemon_time(self):
# '''
# @name 获取守护进程时间
# @return int
# '''
# daemon_time_file = os.path.join(self.panel_path, 'data/daemon_time.pl')
# if os.path.exists(daemon_time_file):
# time_out = int(public.readFile(daemon_time_file))
# if time_out < 10:
# time_out = 10
# if time_out > 30 * 60:
# time_out = 30 * 60
# else:
# time_out = 120
# return time_out
#
# def process_task_thread(self):
# '''
# @name 进程监控
# @auther hwliang
# '''
# time.sleep(60)
# # 进程流量监控,如果文件:/www/server/panel/data/is_net_task.pl 或 /www/server/panel/data/control.conf不存在,则不监控进程流量
# is_net_task = self.panel_path + '/data/is_net_task.pl'
# control_file = self.panel_path + '/data/control.conf'
# if not os.path.exists(is_net_task) or not os.path.exists(control_file):
# return
# self.write_log("启动进程流量监控")
# net_task_obj = process_task.process_network_total()
# net_task_obj.start()
#
# def check_database_quota(self):
# '''
# @name 数据库配额检查
# @return None
# '''
# get = public.dict_obj()
# get.model_index = "project"
# self.write_log("启动数据库配额检查")
# while True:
# num = PluginLoader.module_run("quota", "database_quota_check", get)
# if num == 0:
# break
# time.sleep(60)
#
# # 取内存使用率
# def GetMemUsed(self):
# '''
# @name 获取内存使用率
# @return float
# '''
# try:
# mem = psutil.virtual_memory()
# memInfo = {'memTotal': mem.total / 1024 / 1024, 'memFree': mem.free / 1024 / 1024,
# 'memBuffers': mem.buffers / 1024 / 1024, 'memCached': mem.cached / 1024 / 1024}
# tmp = memInfo['memTotal'] - memInfo['memFree'] - \
# memInfo['memBuffers'] - memInfo['memCached']
# tmp1 = memInfo['memTotal'] / 100
# return (tmp / tmp1)
# except:
# return 1
#
# # 检查502错误
# def check502(self):
# '''
# @name 检查PHP导致的502错误
# @return None
# '''
# try:
# phpversions = public.get_php_versions()
# for version in phpversions:
# if version in ['52', '5.2']: continue
# php_path = self.setup_path + '/php/' + version + '/sbin/php-fpm'
# if not os.path.exists(php_path):
# continue
# if self.checkPHPVersion(version):
# continue
# if self.startPHPVersion(version):
# public.WriteLog('PHP守护程序', '检测到PHP-' + version + '处理异常,已自动修复!', not_web=True)
# self.write_log('PHP守护程序', '检测到PHP-' + version + '处理异常,已自动修复!', 'ERROR', 'red')
# except Exception as ex:
# self.write_log(ex)
#
# # 处理指定PHP版本
# def startPHPVersion(self, version):
# '''
# @name 修复指定PHP版本服务状态
# @param version<string> PHP版本
# @return bool
# '''
# try:
# fpm = '/etc/init.d/php-fpm-' + version
# php_path = self.setup_path + '/php/' + version + '/sbin/php-fpm'
# if not os.path.exists(php_path):
# if os.path.exists(fpm):
# os.remove(fpm)
# return False
#
# # 尝试重载服务
# os.system(fpm + ' start')
# os.system(fpm + ' reload')
# if self.checkPHPVersion(version):
# return True
#
# # 尝试重启服务
# cgi = '/tmp/php-cgi-' + version + '.sock'
# pid = self.setup_path + '/php/' + version + '/var/run/php-fpm.pid'
# os.system('pkill -9 php-fpm-' + version)
# time.sleep(0.5)
# if os.path.exists(cgi):
# os.remove(cgi)
# if os.path.exists(pid):
# os.remove(pid)
# os.system(fpm + ' start')
# if self.checkPHPVersion(version):
# return True
# # 检查是否正确启动
# if os.path.exists(cgi):
# return True
# return False
# except Exception as ex:
# self.write_log(ex)
# return True
#
# # 检查指定PHP版本
# def checkPHPVersion(self, version):
# '''
# @name 检查指定PHP版本服务状态
# @param version<string> PHP版本
# @return bool
# '''
# try:
# cgi_file = '/tmp/php-cgi-{}.sock'.format(version)
# if os.path.exists(cgi_file):
# init_file = '/etc/init.d/php-fpm-{}'.format(version)
# if os.path.exists(init_file):
# init_body = public.ReadFile(init_file)
# if not init_body: return True
# uri = "http://127.0.0.1/phpfpm_" + version + "_status?json"
# result = self.HttpGet(uri)
# json.loads(result)
# return True
# except:
# self.write_log("检测到PHP-{}无法访问".format(version))
# return False
#
# """
# @name 检查当前节点是否可用
# """
#
# def check_node_status(self):
# try:
# node_path = '{}/data/node_url.pl'.format(self.panel_path)
# if not os.path.exists(node_path):
# return False
#
# mtime = os.path.getmtime(node_path)
# if time.time() - mtime < 86400:
# return False
# self.write_log("更新节点状态")
# os.system("nohup {} {}/script/reload_check.py auth_day > /dev/null 2>&1 &".format(self.python_bin, self.panel_path))
# except:
# pass
#
# # 2024/5/21 下午5:32 更新 GeoLite2-Country.json
# def flush_geoip(self):
#
# '''
# @name 检测如果大小小于3M或大于1个月则更新
# @author wzz <2024/5/21 下午5:33>
# @param "data":{"参数名":""} <数据类型> 参数描述
# @return dict{"status":True/False,"msg":"提示信息"}
# '''
# _ips_path = "/www/server/panel/data/firewall/GeoLite2-Country.json"
# m_time_file = "/www/server/panel/data/firewall/geoip_mtime.pl"
#
# if not os.path.exists(_ips_path):
# os.system("mkdir -p /www/server/panel/data/firewall")
# os.system("touch {}".format(_ips_path))
#
# try:
# if not os.path.exists(_ips_path):
# public.downloadFile('{}/install/lib/{}'.format(public.get_url(), os.path.basename(_ips_path)), _ips_path)
# public.writeFile(m_time_file, str(int(time.time())))
# return
#
# _ips_size = os.path.getsize(_ips_path)
# if os.path.exists(m_time_file):
# _ips_mtime = int(public.readFile(m_time_file))
# else:
# _ips_mtime = 0
#
# if _ips_size < 3145728 or time.time() - _ips_mtime > 2592000:
# os.system("rm -f {}".format(_ips_path))
# os.system("rm -f {}".format(m_time_file))
# public.downloadFile('{}/install/lib/{}'.format(public.get_url(), os.path.basename(_ips_path)), _ips_path)
# public.writeFile(m_time_file, str(int(time.time())))
#
# if os.path.exists(_ips_path):
# try:
# import json
# from xml.etree.ElementTree import ElementTree, Element
# from safeModel.firewallModel import main as firewall
#
# firewallobj = firewall()
# ips_list = json.loads(public.readFile(_ips_path))
# if ips_list:
# for ip_dict in ips_list:
# if os.path.exists('/usr/bin/apt-get') and not os.path.exists("/etc/redhat-release"):
# btsh_path = "/etc/ufw/btsh"
# if not os.path.exists(btsh_path):
# os.makedirs(btsh_path)
# tmp_path = '{}/{}.sh'.format(btsh_path, ip_dict['brief'])
# if os.path.exists(tmp_path):
# public.writeFile(tmp_path, "")
#
# _string = "#!/bin/bash\n"
# for ip in ip_dict['ips']:
# if firewallobj.verify_ip(ip):
# _string = _string + 'ipset add ' + ip_dict['brief'] + ' ' + ip + '\n'
# public.writeFile(tmp_path, _string)
# else:
# xml_path = "/etc/firewalld/ipsets/{}.xml.old".format(ip_dict['brief'])
# xml_body = """<?xml version="1.0" encoding="utf-8"?>
# <ipset type="hash:net">
# <option name="maxelem" value="1000000"/>
# </ipset>
# """
# if os.path.exists(xml_path):
# public.writeFile(xml_path, xml_body)
# else:
# os.makedirs(os.path.dirname(xml_path), exist_ok=True)
# public.writeFile(xml_path, xml_body)
#
# tree = ElementTree()
# tree.parse(xml_path)
# root = tree.getroot()
# for ip in ip_dict['ips']:
# if firewallobj.verify_ip(ip):
# entry = Element("entry")
# entry.text = ip
# root.append(entry)
#
# firewallobj.format(root)
# tree.write(xml_path, 'utf-8', xml_declaration=True)
# except:
# pass
# except:
# try:
# public.downloadFile('{}/install/lib/{}'.format(public.get_url(), os.path.basename(_ips_path)), _ips_path)
# public.writeFile(m_time_file, str(int(time.time())))
# except: