forked from aaPanel/aaPanel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.py
More file actions
2274 lines (1980 loc) · 82.6 KB
/
task.py
File metadata and controls
2274 lines (1980 loc) · 82.6 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
#!/bin/python
#coding: utf-8
# +-------------------------------------------------------------------
# | aaPanel
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2016 aaPanel(www.aapanel.com) All rights reserved.
# +-------------------------------------------------------------------
# | Author: hwliang <hwl@aapanel.com>
# +-------------------------------------------------------------------
# ------------------------------
# 计划任务
# ------------------------------
# import tracemalloc
# import objgraph
import sys
import os
import logging
from datetime import datetime, timedelta,timezone
from json import dumps, loads
from psutil import Process, pids, cpu_count, cpu_percent, net_io_counters, disk_io_counters, virtual_memory, pids, pid_exists, NoSuchProcess, AccessDenied, ZombieProcess
os.environ['BT_TASK'] = '1'
base_path = "/www/server/panel"
sys.path.insert(0, "/www/server/panel/class/")
if os.path.exists("/www/server/panel/plugin/mail_sys"):
sys.path.insert(1, "/www/server/panel/plugin/mail_sys")
import time
import public
import db
import json
import threading
import panelTask
import process_task
import shutil
from public.hook_import import hook_import
hook_import()
from power_mta.maillog_stat import maillog_event, aggregate_maillogs_task
from power_mta.automations import schedule_automations_forever
from data_v2 import data as data_v2_cls
try:
from BTPanel import cache
except:
cache = None
CURRENT_TASK_VERSION = '1.0.1'
task_obj = panelTask.bt_task()
task_obj.not_web = True
global pre, timeoutCount, logPath, isTask, oldEdate, isCheck
pre = 0
timeoutCount = 0
isCheck = 0
oldEdate = None
logPath = '/tmp/panelExec.log'
isTask = '/tmp/panelTask.pl'
python_bin = None
thread_dict = {}
# def log_malloc():
# snapshot = tracemalloc.take_snapshot()
# top_stats = snapshot.statistics('lineno')
#
# s = 'TOP 50 difference (traced_memory: {} tracemalloc_memory: {})\n'.format(tracemalloc.get_traced_memory(), tracemalloc.get_tracemalloc_memory())
# for stat in top_stats[:50]:
# s += '{}\n'.format(stat)
#
# with open('{}/logs/malloc.log'.format(public.get_panel_path()), 'a') as fp:
# fp.write('[{}]\n'.format(time.strftime('%Y-%m-%d %X')))
# fp.write('{}\n'.format(s))
#
#
# def objgraph_log():
# with open('{}/logs/objgraph.log'.format(public.get_panel_path()), 'a') as fp:
# fp.write('[{}]\n'.format(time.strftime('%Y-%m-%d %X')))
# fp.write('-------------------- SHOW GROWTH --------------------\n')
# objgraph.show_growth(limit=50, file=fp)
# fp.write('\n\n')
#
# fp.write('-------------------- SHOW MOST COMMON TYPES --------------------\n')
# objgraph.show_most_common_types(limit=50, file=fp)
# fp.write('\n\n')
#
#
# def print_malloc_thread():
# time.sleep(60)
# log_malloc()
# objgraph_log()
# print_malloc_thread()
def get_python_bin():
global python_bin
if python_bin: return python_bin
bin_file = '/www/server/panel/pyenv/bin/python'
bin_file2 = '/usr/bin/python'
if os.path.exists(bin_file):
python_bin = bin_file
return bin_file
python_bin = bin_file2
return bin_file2
def WriteFile(filename,s_body,mode='w+'):
"""
写入文件内容
@filename 文件名
@s_body 欲写入的内容
return bool 若文件不存在则尝试自动创建
"""
try:
fp = open(filename, mode)
fp.write(s_body)
fp.close()
return True
except:
try:
fp = open(filename, mode,encoding="utf-8")
fp.write(s_body)
fp.close()
return True
except:
return False
def ReadFile(filename, mode='r'):
"""
读取文件内容
@filename 文件名
return string(bin) 若文件不存在,则返回None
"""
if not os.path.exists(filename):
return False
f_body = None
with open(filename, mode) as fp:
f_body = fp.read()
return f_body
# 下载文件
def DownloadFile(url, filename):
try:
import urllib
import socket
socket.setdefaulttimeout(10)
urllib.urlretrieve(url, filename=filename, reporthook=DownloadHook)
os.system('chown www.www ' + filename)
WriteLogs('done')
except:
WriteLogs('done')
# 下载文件进度回调
def DownloadHook(count, blockSize, totalSize):
global pre
used = count * blockSize
pre1 = int((100.0 * used / totalSize))
if pre == pre1:
return
speed = {'total': totalSize, 'used': used, 'pre': pre}
WriteLogs(dumps(speed))
pre = pre1
# 写输出日志
def WriteLogs(logMsg):
try:
global logPath
with open(logPath, 'w+') as fp:
fp.write(logMsg)
fp.close()
except:
pass
def ExecShell(cmdstring, cwd=None, timeout=None, shell=True, symbol = '&>'):
try:
global logPath
import shlex
import subprocess
import time
sub = subprocess.Popen(cmdstring+ symbol +logPath, 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 startTask():
global isTask,logPath,thread_dict
tip_file = '/dev/shm/.panelTask.pl'
n = 0
tick = 60
while 1:
try:
if os.path.exists(isTask):
with db.Sql() as sql:
sql.table('tasks').where(
"status=?", ('-1',)).setField('status', '0')
taskArr = sql.table('tasks').where("status=?", ('0',)).field('id,type,execstr').order("id asc").select()
for value in taskArr:
start = int(time.time())
if not sql.table('tasks').where("id=?", (value['id'],)).count():
public.writeFile(tip_file, str(int(time.time())))
continue
sql.table('tasks').where("id=?", (value['id'],)).save('status,start', ('-1', start))
if value['type'] == 'download':
argv = value['execstr'].split('|bt|')
DownloadFile(argv[0], argv[1])
elif value['type'] == 'execshell':
ExecShell(value['execstr'])
end = int(time.time())
sql.table('tasks').where("id=?", (value['id'],)).save('status,end', ('1', end))
if(sql.table('tasks').where("status=?", ('0')).count() < 1):
if os.path.exists(isTask):
os.remove(isTask)
sql.close()
taskArr = None
public.writeFile(tip_file, str(int(time.time())))
# 线程检查
n+=1
if n > tick:
run_thread()
n = 0
except:
pass
time.sleep(2)
# 网站到期处理
def siteEdate():
global oldEdate
try:
if not oldEdate:
oldEdate = ReadFile('/www/server/panel/data/edate.pl')
if not oldEdate:
oldEdate = '0000-00-00'
mEdate = time.strftime('%Y-%m-%d', time.localtime())
if oldEdate == mEdate:
return False
oldEdate = mEdate
os.system("nohup " + get_python_bin() + " /www/server/panel/script/site_task.py > /dev/null 2>&1 &")
except Exception as ex:
logging.info(ex)
pass
def GetLoadAverage():
c = os.getloadavg()
data = {}
data['one'] = float(c[0])
data['five'] = float(c[1])
data['fifteen'] = float(c[2])
data['max'] = cpu_count() * 2
data['limit'] = data['max']
data['safe'] = data['max'] * 0.75
return data
# 系统监控任务
def systemTask():
try:
filename = '{}/data/control.conf'.format(base_path)
with db.Sql() as sql:
sql = sql.dbfile('system')
csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
network_sql = '''CREATE TABLE IF NOT EXISTS `network` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`up` INTEGER,
`down` INTEGER,
`total_up` INTEGER,
`total_down` INTEGER,
`down_packets` INTEGER,
`up_packets` INTEGER,
`addtime` INTEGER
)'''
cpuio_sql = '''CREATE TABLE IF NOT EXISTS `cpuio` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` INTEGER,
`mem` INTEGER,
`addtime` INTEGER
)'''
diskio_sql = '''CREATE TABLE IF NOT EXISTS `diskio` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`read_count` INTEGER,
`write_count` INTEGER,
`read_bytes` INTEGER,
`write_bytes` INTEGER,
`read_time` INTEGER,
`write_time` INTEGER,
`addtime` INTEGER
)'''
sql.execute(csql, ())
sql.execute(network_sql, ())
sql.execute(cpuio_sql, ())
sql.execute(diskio_sql, ())
sql.close()
count = 0
reloadNum=0
diskio_1 = diskio_2 = networkInfo = cpuInfo = diskInfo = None
network_up = {}
network_down = {}
cycle = 60
# try:
# from panelDaily import panelDaily
# panelDaily().check_databases()
# except Exception as e:
# logging.info(e)
proc_task_obj = process_task.process_task()
while True:
if not os.path.exists(filename):
time.sleep(10)
continue
day = 30
try:
day = int(ReadFile(filename))
if day < 1:
time.sleep(10)
continue
except:
day = 30
addtime = int(time.time())
deltime = addtime - (day * 86400)
# 取当前CPU Io
tmp = {}
tmp['used'] = proc_task_obj.get_monitor_list(addtime)
tmp['mem'] = GetMemUsed()
cpuInfo = tmp
# 取当前网络Io
networkIo_list = net_io_counters(pernic=True)
tmp = {}
tmp['upTotal'] = 0
tmp['downTotal'] = 0
tmp['up'] = 0
tmp['down'] = 0
tmp['downPackets'] = {}
tmp['upPackets'] = {}
for k in networkIo_list.keys():
networkIo = networkIo_list[k][:4]
if not k in network_up.keys():
network_up[k] = networkIo[0]
network_down[k] = networkIo[1]
tmp['upTotal'] += networkIo[0]
tmp['downTotal'] += networkIo[1]
tmp['downPackets'][k] = round(
float((networkIo[1] - network_down[k]) / 1024)/cycle, 2)
tmp['upPackets'][k] = round(
float((networkIo[0] - network_up[k]) / 1024)/cycle, 2)
tmp['up'] += tmp['upPackets'][k]
tmp['down'] += tmp['downPackets'][k]
network_up[k] = networkIo[0]
network_down[k] = networkIo[1]
# if not networkInfo:
# networkInfo = tmp
# if (tmp['up'] + tmp['down']) > (networkInfo['up'] + networkInfo['down']):
networkInfo = tmp
# 取磁盘Io
disk_ios = True
try:
if os.path.exists('/proc/diskstats'):
diskio_2 = disk_io_counters()
if not diskio_1:
diskio_1 = diskio_2
tmp = {}
tmp['read_count'] = int((diskio_2.read_count - diskio_1.read_count) / cycle)
tmp['write_count'] = int((diskio_2.write_count - diskio_1.write_count) / cycle)
tmp['read_bytes'] = int((diskio_2.read_bytes - diskio_1.read_bytes) / cycle)
tmp['write_bytes'] = int((diskio_2.write_bytes - diskio_1.write_bytes) / cycle)
tmp['read_time'] = int((diskio_2.read_time - diskio_1.read_time) / cycle)
tmp['write_time'] = int((diskio_2.write_time - diskio_1.write_time) / cycle)
if not diskInfo:
diskInfo = tmp
# if (tmp['read_bytes'] + tmp['write_bytes']) > (diskInfo['read_bytes'] + diskInfo['write_bytes']):
diskInfo['read_count'] = tmp['read_count']
diskInfo['write_count'] = tmp['write_count']
diskInfo['read_bytes'] = tmp['read_bytes']
diskInfo['write_bytes'] = tmp['write_bytes']
diskInfo['read_time'] = tmp['read_time']
diskInfo['write_time'] = tmp['write_time']
# logging.info(['read: ',tmp['read_bytes'] / 1024 / 1024,'write: ',tmp['write_bytes'] / 1024 / 1024])
diskio_1 = diskio_2
except:
logging.info(public.get_error_info())
disk_ios = False
try:
sql = db.Sql().dbfile('system')
data = (cpuInfo['used'], cpuInfo['mem'], addtime)
#
sql.table('cpuio').add('pro,mem,addtime', data)
sql.table('cpuio').where("addtime<?", (deltime,)).delete()
data = (networkInfo['up'], networkInfo['down'], networkInfo['upTotal'], networkInfo['downTotal'], dumps(networkInfo['downPackets']), dumps(networkInfo['upPackets']), addtime)
sql.table('network').add('up,down,total_up,total_down,down_packets,up_packets,addtime', data)
sql.table('network').where("addtime<?", (deltime,)).delete()
# logging.info(diskInfo)
if os.path.exists('/proc/diskstats') and disk_ios:
data = (diskInfo['read_count'], diskInfo['write_count'], diskInfo['read_bytes'],diskInfo['write_bytes'], diskInfo['read_time'], diskInfo['write_time'], addtime)
sql.table('diskio').add('read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime', data)
sql.table('diskio').where("addtime<?", (deltime,)).delete()
# LoadAverage
load_average = GetLoadAverage()
lpro = round(
(load_average['one'] / load_average['max']) * 100, 2)
if lpro > 100:
lpro = 100
sql.table('load_average').add('pro,one,five,fifteen,addtime', (lpro, load_average['one'], load_average['five'], load_average['fifteen'], addtime))
sql.table('load_average').where("addtime<?", (deltime,)).delete()
sql.close()
lpro = None
load_average = None
cpuInfo = None
networkInfo = None
diskInfo = None
data = None
count = 0
reloadNum += 1
if reloadNum > 1440:
reloadNum = 0
# 日报数据收集
# if os.path.exists("/www/server/panel/data/start_daily.pl"):
# try:
# from panelDaily import panelDaily
# pd = panelDaily()
# t_now = time.localtime()
# yesterday = time.localtime(time.mktime((
# t_now.tm_year, t_now.tm_mon, t_now.tm_mday-1,
# 0,0,0,0,0,0
# )))
# yes_time_key = pd.get_time_key(yesterday)
# con = ReadFile("/www/server/panel/data/store_app_usage.pl")
# # logging.info(str(con))
# store = False
# if con:
# if con != str(yes_time_key):
# store = True
# else:
# store = True
#
# if store:
# date_str = str(yes_time_key)
# daily_data = pd.get_daily_data_local(date_str)
# if "status" in daily_data.keys():
# if daily_data["status"]:
# score = daily_data["score"]
# if public.M("system").dbfile("system").table("daily").where("time_key=?", (yes_time_key,)).count() == 0:
# public.M("system").dbfile("system").table("daily").add("time_key,evaluate,addtime", (yes_time_key, score, time.time()))
# pd.store_app_usage(yes_time_key)
# WriteFile("/www/server/panel/data/store_app_usage.pl", str(yes_time_key), "w")
# # logging.info("更新应用存储信息:"+str(yes_time_key))
# pd.check_server()
# except Exception as e:
# logging.info("存储应用空间信息错误:"+str(e))
except Exception as ex:
logging.info(str(ex))
del(tmp)
time.sleep(cycle)
count += 1
except Exception as ex:
logging.info(ex)
time.sleep(cycle)
systemTask()
# 取内存使用率
def GetMemUsed():
try:
mem = 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
# 更新 GeoLite2-Country.json
def flush_geoip():
"""
@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:
core = cpu_count()
delay = round(1 / (core if core > 0 else 1), 2)
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 safeModelV2.firewallModel import main as firewall
firewallobj = firewall()
ips_list = json.loads(public.readFile(_ips_path))
if ips_list:
bash = os.path.exists('/usr/bin/apt-get') and not os.path.exists("/etc/redhat-release")
if bash:
btsh_path = "/etc/ufw/btsh"
if not os.path.exists(btsh_path):
os.makedirs(btsh_path)
write_map = {}
for ip_dict in ips_list:
tmp_path = '{}/{}.sh'.format(btsh_path, ip_dict['brief'])
commands = [
f'ipset add {ip_dict["brief"]} {ip}'
for ip in ip_dict.get("ips", [])
if firewallobj.verify_ip(ip)
]
if commands:
script_content = "#!/bin/bash\n" + "\n".join(commands) + "\n"
write_map[tmp_path] = script_content
time.sleep(delay)
for path, content in write_map.items():
public.writeFile(path, content)
time.sleep(0.05)
else:
for ip_dict in ips_list:
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)
time.sleep(delay)
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:
pass
# 检查502错误
def check502():
try:
phpversions = public.get_php_versions()
for version in phpversions:
if version in ['52','5.2']: continue
php_path = '/www/server/php/' + version + '/sbin/php-fpm'
if not os.path.exists(php_path):
continue
if checkPHPVersion(version):
continue
if startPHPVersion(version):
public.WriteLog('PHP daemon',
'PHP-' + version + 'processing exception was detected and has been automatically fixed!',
not_web=True)
except Exception as ex:
logging.info(ex)
# 处理指定PHP版本
def startPHPVersion(version):
try:
fpm = '/etc/init.d/php-fpm-' + version
php_path = '/www/server/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 checkPHPVersion(version): return True
# 尝试重启服务
cgi = '/tmp/php-cgi-' + version + '.sock'
pid = '/www/server/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 checkPHPVersion(version):
return True
# 检查是否正确启动
if os.path.exists(cgi):
return True
return False
except Exception as ex:
logging.info(ex)
return True
# 检查指定PHP版本
def checkPHPVersion(version):
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 = "/phpfpm_"+version+"_status?json"
result = public.request_php(version, uri, '')
loads(result)
return True
except:
logging.info("PHP-{} unreachable detected".format(version))
return False
# 502错误检查线程
def check502Task():
try:
while True:
public.auto_backup_panel()
check502()
sess_expire()
mysql_quota_check()
siteEdate()
flush_geoip()
time.sleep(600)
except Exception as ex:
logging.info(ex)
time.sleep(600)
check502Task()
# MySQL配额检查
def mysql_quota_check():
os.system("nohup " + get_python_bin() +" /www/server/panel/script/mysql_quota.py > /dev/null 2>&1 &")
# session过期处理
def sess_expire():
try:
sess_path = '{}/data/session'.format(base_path)
if not os.path.exists(sess_path): return
s_time = time.time()
f_list = os.listdir(sess_path)
f_num = len(f_list)
for fname in f_list:
filename = '/'.join((sess_path, fname))
fstat = os.stat(filename)
f_time = s_time - fstat.st_mtime
if f_time > 3600:
os.remove(filename)
continue
if fstat.st_size < 256 and len(fname) == 32:
if f_time > 60 or f_num > 30:
os.remove(filename)
continue
del (f_list)
except Exception as ex:
logging.info(str(ex))
# 检查面板证书是否有更新
def check_panel_ssl():
try:
while True:
lets_info = ReadFile("{}/ssl/lets.info".format(base_path))
if not lets_info:
time.sleep(3600)
continue
os.system(get_python_bin() + " {}/script/panel_ssl_task.py > /dev/null".format(base_path))
time.sleep(3600)
except Exception as e:
public.writeFile("/tmp/panelSSL.pl", str(e), "a+")
# 面板进程守护
def daemon_panel11():
cycle = 10
panel_pid_file = "{}/logs/panel.pid".format(public.get_panel_path())
while 1:
time.sleep(cycle)
# 检查pid文件是否存在
if not os.path.exists(panel_pid_file):
continue
# 读取pid文件
panel_pid = public.readFile(panel_pid_file)
if not panel_pid:
logging.info("not pid -- {}".format(panel_pid_file))
service_panel('start')
continue
# 检查进程是否存在
comm_file = "/proc/{}/comm".format(panel_pid)
if not os.path.exists(comm_file):
logging.info("not comm_file-- {}".format(comm_file))
service_panel('start')
continue
# 是否为面板进程
comm = public.readFile(comm_file)
if comm.find('BT-Panel') == -1:
logging.info("not BT-Panel-- {}".format(comm))
service_panel('start')
continue
# # 是否为面板进程
# with open(comm_file, 'r') as f:
# comm = f.read()
# if comm.find('BT-Panel') == -1:
# logging.info("3 not BT-Panel-- {}".format(comm))
# service_panel('start')
# continue
# 查找面板进程并返回PID
def find_panel_pid():
for pid in pids():
try:
p = Process(pid)
if 'BT-Panel' in p.name(): # 假设进程名包含 'BT-Panel'
return pid
except (NoSuchProcess, AccessDenied, ZombieProcess):
continue
return None
# 更新PID文件
def update_pid_file(pid):
pid_file = "{}/logs/panel.pid".format(public.get_panel_path())
try:
with open(pid_file, 'w') as f:
f.write(str(pid))
logging.info(f'Updated panel PID file with PID {pid}')
except Exception as e:
logging.error(f'Error writing to PID file: {e}')
def daemon_panel():
cycle = 10
panel_pid_file = "{}/logs/panel.pid".format(public.get_panel_path())
while True:
time.sleep(cycle)
# 检查PID文件是否存在
if not os.path.exists(panel_pid_file):
logging.info(f'{panel_pid_file} not found, starting panel service...')
continue
panel_pid=""
try:
# 读取PID文件
with open(panel_pid_file, 'r') as file:
panel_pid = file.read()
except Exception as e:
service_panel('start')
continue
if not panel_pid:
logging.info(f'PID is empty in {panel_pid_file}, starting panel service...')
service_panel('start')
continue
panel_pid = panel_pid.strip()
# 检查PID对应的进程是否存在
if not pid_exists(int(panel_pid)):
logging.info(f'PID {panel_pid} not found, attempting to find running panel process...')
panel_pid = find_panel_pid()
if panel_pid:
# 更新PID文件
update_pid_file(panel_pid)
else:
logging.info('No panel process found, starting service...')
service_panel('start')
else:
# 检查进程是否是面板进程
comm_file = f"/proc/{panel_pid}/comm"
if os.path.exists(comm_file):
with open(comm_file, 'r') as file:
comm = file.read()
if not comm or comm.find("BT-Panel") == -1:
logging.info(f'Process {panel_pid} is not a BT-Panel process,comm-{comm} commtype-{type(comm)}')
service_panel('start')
continue
else:
logging.info(f'comm file not found for PID {panel_pid}, restarting service...')
service_panel('start')
def daemon_service():
from script.restart_services import RestartServices, DaemonManager
try:
# remove old deamons
from BTPanel import app
from crontab_v2 import crontab
with app.app_context():
old_deamons = public.M('crontab').where("name Like ?", "[Do not delete]%Daemon").select()
for i in old_deamons:
try:
cron_name = i.get("name")
s_name = cron_name.replace("[Do not delete] ", "").replace(" Daemon", "")
DaemonManager.add_daemon(s_name.lower())
except:
pass
args = public.dict_obj()
args.id = i.get("id")
crontab().DelCrontab(args)
except:
pass
while 1:
RestartServices().main()
time.sleep(10)
def update_panel():
os.system("curl -k https://node.aapanel.com/install/update_7.x_en.sh|bash &")
def service_panel(action='reload'):
if not os.path.exists('{}/init.sh'.format(base_path)):
update_panel()
else:
os.system("nohup bash /www/server/panel/init.sh {} > /dev/null 2>&1 &".format(action))
logging.info("Panel Service: {}".format(action))
# 重启面板服务
def restart_panel_service():
rtips = '{}/data/restart.pl'.format(base_path)
reload_tips = '{}/data/reload.pl'.format(base_path)
while True:
if os.path.exists(rtips):
os.remove(rtips)
service_panel('restart')
if os.path.exists(reload_tips):
os.remove(reload_tips)
service_panel('reload')
time.sleep(1)
# 取面板pid
def get_panel_pid():
try:
pid = ReadFile('/www/server/panel/logs/panel.pid')
if pid:
return int(pid)
for pid in pids():
try:
p = Process(pid)
n = p.cmdline()[-1]
if n.find('runserver') != -1 or n.find('BT-Panel') != -1:
return pid
except:
pass
except:
pass
return None
def HttpGet(url, timeout=6, headers={}):
if sys.version_info[0] == 2:
try:
import urllib2
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req, timeout=timeout,)
return response.read()
except Exception as ex:
logging.info(str(ex))
return str(ex)
else:
try:
import urllib.request
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req, timeout=timeout)
result = response.read()
if type(result) == bytes:
result = result.decode('utf-8')
return result
except Exception as ex:
logging.info("URL: {} => {}".format(url, ex))
return str(ex)
# 定时任务去检测邮件信息
def send_mail_time():
while True:
try:
os.system("nohup " + get_python_bin() +" /www/server/panel/script/mail_task.py > /dev/null 2>&1 &")
time.sleep(180)
except:
time.sleep(360)
send_mail_time()
#5个小时更新一次更新软件列表
def update_software_list():
while True:
try:
import panelPlugin
panelPlugin.panelPlugin().get_cloud_list_status(None)
time.sleep(18000)
except:
time.sleep(1800)
update_software_list()
# 面板消息提醒
def check_panel_msg():
python_bin = get_python_bin()
while True:
os.system('nohup {} /www/server/panel/script/check_msg.py > /dev/null 2>&1 &'.format(python_bin))
time.sleep(3600)
# 面板推送消息
def push_msg():
python_bin = get_python_bin()
while True:
time.sleep(60)
os.system('nohup {} /www/server/panel/script/push_msg.py > /dev/null 2>&1 &'.format(python_bin))
def JavaProDaemons():
'''
@name Java 项目守护进程
@author lkq@aapanel.com
@time 2022-07-19